entities
listlengths
1
8.61k
max_stars_repo_path
stringlengths
7
172
max_stars_repo_name
stringlengths
5
89
max_stars_count
int64
0
82k
content
stringlengths
14
1.05M
id
stringlengths
2
6
new_content
stringlengths
15
1.05M
modified
bool
1 class
references
stringlengths
29
1.05M
[ { "context": "#\n###*\n@module joukou-fbpp/protocols/index\n@author Fabian Cook <fabian.cook@joukou.com>\n###\nComponentProtocol = ", "end": 617, "score": 0.9998667240142822, "start": 606, "tag": "NAME", "value": "Fabian Cook" }, { "context": " joukou-fbpp/protocols/index\n@author Fa...
src/protocols/index.coffee
joukou/joukou-flow
0
### Copyright 2014 Joukou Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ### ###* @module joukou-fbpp/protocols/index @author Fabian Cook <fabian.cook@joukou.com> ### ComponentProtocol = require( './component' ) GraphProtocol = require( './graph' ) GeneralProtocol = require( './general' ) NetworkProtocol = require( './network' ) RuntimeProtocol = require( './runtime' ) module.exports = component: ComponentProtocol graph: GraphProtocol general: GeneralProtocol network: NetworkProtocol runtime: RuntimeProtocol
31313
### Copyright 2014 Joukou Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ### ###* @module joukou-fbpp/protocols/index @author <NAME> <<EMAIL>> ### ComponentProtocol = require( './component' ) GraphProtocol = require( './graph' ) GeneralProtocol = require( './general' ) NetworkProtocol = require( './network' ) RuntimeProtocol = require( './runtime' ) module.exports = component: ComponentProtocol graph: GraphProtocol general: GeneralProtocol network: NetworkProtocol runtime: RuntimeProtocol
true
### Copyright 2014 Joukou Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ### ###* @module joukou-fbpp/protocols/index @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> ### ComponentProtocol = require( './component' ) GraphProtocol = require( './graph' ) GeneralProtocol = require( './general' ) NetworkProtocol = require( './network' ) RuntimeProtocol = require( './runtime' ) module.exports = component: ComponentProtocol graph: GraphProtocol general: GeneralProtocol network: NetworkProtocol runtime: RuntimeProtocol
[ { "context": "##\n##\n## Forked from Jeff Mott's CryptoJS\n##\n## https://code.google.com/p/cryp", "end": 30, "score": 0.9998815655708313, "start": 21, "tag": "NAME", "value": "Jeff Mott" } ]
node_modules/triplesec/src/sha512.iced
gallizoltan/warpwallet
157
## ## ## Forked from Jeff Mott's CryptoJS ## ## https://code.google.com/p/crypto-js/ ## {X64Word,X64WordArray} = require './wordarray' {Hasher} = require './algbase' #======================================================================= class Global convert : (raw) -> (new X64Word(raw[i],raw[i+1]) for i in [0...raw.length] by 2) constructor : -> @K = @convert [ 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817 ] @I = new X64WordArray @convert [ 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1, 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179 ] @W = (new X64Word(0,0) for i in [0...80]) #======================================================================= glbl = new Global() #======================================================================= exports.SHA512 = class SHA512 extends Hasher @blockSize : 1024/32 blockSize : SHA512.blockSize @output_size : 512/8 output_size : SHA512.output_size _doReset : () -> @_hash = glbl.I.clone() _doProcessBlock : (M, offset) -> # Shortcuts H = @_hash.words W = glbl.W H0 = H[0] H1 = H[1] H2 = H[2] H3 = H[3] H4 = H[4] H5 = H[5] H6 = H[6] H7 = H[7] H0h = H0.high H0l = H0.low H1h = H1.high H1l = H1.low H2h = H2.high H2l = H2.low H3h = H3.high H3l = H3.low H4h = H4.high H4l = H4.low H5h = H5.high H5l = H5.low H6h = H6.high H6l = H6.low H7h = H7.high H7l = H7.low # Working variables ah = H0h al = H0l bh = H1h bl = H1l ch = H2h cl = H2l dh = H3h dl = H3l eh = H4h el = H4l fh = H5h fl = H5l gh = H6h gl = H6l hh = H7h hl = H7l # Rounds for i in [0...80] # Shortcut Wi = W[i] # Extend message if (i < 16) Wih = Wi.high = M[offset + i * 2] | 0 Wil = Wi.low = M[offset + i * 2 + 1] | 0 else # Gamma0 gamma0x = W[i - 15] gamma0xh = gamma0x.high gamma0xl = gamma0x.low gamma0h = ((gamma0xh >>> 1) | (gamma0xl << 31)) ^ ((gamma0xh >>> 8) | (gamma0xl << 24)) ^ (gamma0xh >>> 7) gamma0l = ((gamma0xl >>> 1) | (gamma0xh << 31)) ^ ((gamma0xl >>> 8) | (gamma0xh << 24)) ^ ((gamma0xl >>> 7) | (gamma0xh << 25)) # Gamma1 gamma1x = W[i - 2] gamma1xh = gamma1x.high gamma1xl = gamma1x.low gamma1h = ((gamma1xh >>> 19) | (gamma1xl << 13)) ^ ((gamma1xh << 3) | (gamma1xl >>> 29)) ^ (gamma1xh >>> 6) gamma1l = ((gamma1xl >>> 19) | (gamma1xh << 13)) ^ ((gamma1xl << 3) | (gamma1xh >>> 29)) ^ ((gamma1xl >>> 6) | (gamma1xh << 26)) # W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] Wi7 = W[i - 7] Wi7h = Wi7.high Wi7l = Wi7.low Wi16 = W[i - 16] Wi16h = Wi16.high Wi16l = Wi16.low Wil = gamma0l + Wi7l Wih = gamma0h + Wi7h + (if (Wil >>> 0) < (gamma0l >>> 0) then 1 else 0) Wil = Wil + gamma1l Wih = Wih + gamma1h + (if (Wil >>> 0) < (gamma1l >>> 0) then 1 else 0) Wil = Wil + Wi16l Wih = Wih + Wi16h + (if (Wil >>> 0) < (Wi16l >>> 0) then 1 else 0) Wi.high = Wih Wi.low = Wil chh = (eh & fh) ^ (~eh & gh) chl = (el & fl) ^ (~el & gl) majh = (ah & bh) ^ (ah & ch) ^ (bh & ch) majl = (al & bl) ^ (al & cl) ^ (bl & cl) sigma0h = ((ah >>> 28) | (al << 4)) ^ ((ah << 30) | (al >>> 2)) ^ ((ah << 25) | (al >>> 7)) sigma0l = ((al >>> 28) | (ah << 4)) ^ ((al << 30) | (ah >>> 2)) ^ ((al << 25) | (ah >>> 7)) sigma1h = ((eh >>> 14) | (el << 18)) ^ ((eh >>> 18) | (el << 14)) ^ ((eh << 23) | (el >>> 9)) sigma1l = ((el >>> 14) | (eh << 18)) ^ ((el >>> 18) | (eh << 14)) ^ ((el << 23) | (eh >>> 9)) # t1 = h + sigma1 + ch + K[i] + W[i] Ki = glbl.K[i] Kih = Ki.high Kil = Ki.low t1l = hl + sigma1l t1h = hh + sigma1h + (if (t1l >>> 0) < (hl >>> 0) then 1 else 0) t1l = t1l + chl t1h = t1h + chh + (if (t1l >>> 0) < (chl >>> 0) then 1 else 0) t1l = t1l + Kil t1h = t1h + Kih + (if (t1l >>> 0) < (Kil >>> 0) then 1 else 0) t1l = t1l + Wil t1h = t1h + Wih + (if (t1l >>> 0) < (Wil >>> 0) then 1 else 0) # t2 = sigma0 + maj t2l = sigma0l + majl t2h = sigma0h + majh + (if (t2l >>> 0) < (sigma0l >>> 0) then 1 else 0) # Update working variables hh = gh hl = gl gh = fh gl = fl fh = eh fl = el el = (dl + t1l) | 0 eh = (dh + t1h + (if (el >>> 0) < (dl >>> 0) then 1 else 0)) | 0 dh = ch dl = cl ch = bh cl = bl bh = ah bl = al al = (t1l + t2l) | 0 ah = (t1h + t2h + (if (al >>> 0) < (t1l >>> 0) then 1 else 0)) | 0 # Intermediate hash value H0l = H0.low = (H0l + al) H0.high = (H0h + ah + (if (H0l >>> 0) < (al >>> 0) then 1 else 0)) H1l = H1.low = (H1l + bl) H1.high = (H1h + bh + (if (H1l >>> 0) < (bl >>> 0) then 1 else 0)) H2l = H2.low = (H2l + cl) H2.high = (H2h + ch + (if (H2l >>> 0) < (cl >>> 0) then 1 else 0)) H3l = H3.low = (H3l + dl) H3.high = (H3h + dh + (if (H3l >>> 0) < (dl >>> 0) then 1 else 0)) H4l = H4.low = (H4l + el) H4.high = (H4h + eh + (if (H4l >>> 0) < (el >>> 0) then 1 else 0)) H5l = H5.low = (H5l + fl) H5.high = (H5h + fh + (if (H5l >>> 0) < (fl >>> 0) then 1 else 0)) H6l = H6.low = (H6l + gl) H6.high = (H6h + gh + (if (H6l >>> 0) < (gl >>> 0) then 1 else 0)) H7l = H7.low = (H7l + hl) H7.high = (H7h + hh + (if (H7l >>> 0) < (hl >>> 0) then 1 else 0)) _doFinalize: () -> # Shortcuts dataWords = @_data.words nBitsTotal = @_nDataBytes * 8 nBitsLeft = @_data.sigBytes * 8 # Add padding dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32) dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 30] = Math.floor(nBitsTotal / 0x100000000) dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 31] = nBitsTotal @_data.sigBytes = dataWords.length * 4 # Hash final blocks @_process() # Convert hash to 32-bit word array and return @_hash.toX32() copy_to : (obj) -> super obj obj._hash = @_hash.clone() clone : -> out = new SHA512() @copy_to out out #======================================================================= exports.transform = (x) -> out = (new SHA512).finalize x x.scrub() out #=======================================================================
210340
## ## ## Forked from <NAME>'s CryptoJS ## ## https://code.google.com/p/crypto-js/ ## {X64Word,X64WordArray} = require './wordarray' {Hasher} = require './algbase' #======================================================================= class Global convert : (raw) -> (new X64Word(raw[i],raw[i+1]) for i in [0...raw.length] by 2) constructor : -> @K = @convert [ 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817 ] @I = new X64WordArray @convert [ 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1, 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179 ] @W = (new X64Word(0,0) for i in [0...80]) #======================================================================= glbl = new Global() #======================================================================= exports.SHA512 = class SHA512 extends Hasher @blockSize : 1024/32 blockSize : SHA512.blockSize @output_size : 512/8 output_size : SHA512.output_size _doReset : () -> @_hash = glbl.I.clone() _doProcessBlock : (M, offset) -> # Shortcuts H = @_hash.words W = glbl.W H0 = H[0] H1 = H[1] H2 = H[2] H3 = H[3] H4 = H[4] H5 = H[5] H6 = H[6] H7 = H[7] H0h = H0.high H0l = H0.low H1h = H1.high H1l = H1.low H2h = H2.high H2l = H2.low H3h = H3.high H3l = H3.low H4h = H4.high H4l = H4.low H5h = H5.high H5l = H5.low H6h = H6.high H6l = H6.low H7h = H7.high H7l = H7.low # Working variables ah = H0h al = H0l bh = H1h bl = H1l ch = H2h cl = H2l dh = H3h dl = H3l eh = H4h el = H4l fh = H5h fl = H5l gh = H6h gl = H6l hh = H7h hl = H7l # Rounds for i in [0...80] # Shortcut Wi = W[i] # Extend message if (i < 16) Wih = Wi.high = M[offset + i * 2] | 0 Wil = Wi.low = M[offset + i * 2 + 1] | 0 else # Gamma0 gamma0x = W[i - 15] gamma0xh = gamma0x.high gamma0xl = gamma0x.low gamma0h = ((gamma0xh >>> 1) | (gamma0xl << 31)) ^ ((gamma0xh >>> 8) | (gamma0xl << 24)) ^ (gamma0xh >>> 7) gamma0l = ((gamma0xl >>> 1) | (gamma0xh << 31)) ^ ((gamma0xl >>> 8) | (gamma0xh << 24)) ^ ((gamma0xl >>> 7) | (gamma0xh << 25)) # Gamma1 gamma1x = W[i - 2] gamma1xh = gamma1x.high gamma1xl = gamma1x.low gamma1h = ((gamma1xh >>> 19) | (gamma1xl << 13)) ^ ((gamma1xh << 3) | (gamma1xl >>> 29)) ^ (gamma1xh >>> 6) gamma1l = ((gamma1xl >>> 19) | (gamma1xh << 13)) ^ ((gamma1xl << 3) | (gamma1xh >>> 29)) ^ ((gamma1xl >>> 6) | (gamma1xh << 26)) # W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] Wi7 = W[i - 7] Wi7h = Wi7.high Wi7l = Wi7.low Wi16 = W[i - 16] Wi16h = Wi16.high Wi16l = Wi16.low Wil = gamma0l + Wi7l Wih = gamma0h + Wi7h + (if (Wil >>> 0) < (gamma0l >>> 0) then 1 else 0) Wil = Wil + gamma1l Wih = Wih + gamma1h + (if (Wil >>> 0) < (gamma1l >>> 0) then 1 else 0) Wil = Wil + Wi16l Wih = Wih + Wi16h + (if (Wil >>> 0) < (Wi16l >>> 0) then 1 else 0) Wi.high = Wih Wi.low = Wil chh = (eh & fh) ^ (~eh & gh) chl = (el & fl) ^ (~el & gl) majh = (ah & bh) ^ (ah & ch) ^ (bh & ch) majl = (al & bl) ^ (al & cl) ^ (bl & cl) sigma0h = ((ah >>> 28) | (al << 4)) ^ ((ah << 30) | (al >>> 2)) ^ ((ah << 25) | (al >>> 7)) sigma0l = ((al >>> 28) | (ah << 4)) ^ ((al << 30) | (ah >>> 2)) ^ ((al << 25) | (ah >>> 7)) sigma1h = ((eh >>> 14) | (el << 18)) ^ ((eh >>> 18) | (el << 14)) ^ ((eh << 23) | (el >>> 9)) sigma1l = ((el >>> 14) | (eh << 18)) ^ ((el >>> 18) | (eh << 14)) ^ ((el << 23) | (eh >>> 9)) # t1 = h + sigma1 + ch + K[i] + W[i] Ki = glbl.K[i] Kih = Ki.high Kil = Ki.low t1l = hl + sigma1l t1h = hh + sigma1h + (if (t1l >>> 0) < (hl >>> 0) then 1 else 0) t1l = t1l + chl t1h = t1h + chh + (if (t1l >>> 0) < (chl >>> 0) then 1 else 0) t1l = t1l + Kil t1h = t1h + Kih + (if (t1l >>> 0) < (Kil >>> 0) then 1 else 0) t1l = t1l + Wil t1h = t1h + Wih + (if (t1l >>> 0) < (Wil >>> 0) then 1 else 0) # t2 = sigma0 + maj t2l = sigma0l + majl t2h = sigma0h + majh + (if (t2l >>> 0) < (sigma0l >>> 0) then 1 else 0) # Update working variables hh = gh hl = gl gh = fh gl = fl fh = eh fl = el el = (dl + t1l) | 0 eh = (dh + t1h + (if (el >>> 0) < (dl >>> 0) then 1 else 0)) | 0 dh = ch dl = cl ch = bh cl = bl bh = ah bl = al al = (t1l + t2l) | 0 ah = (t1h + t2h + (if (al >>> 0) < (t1l >>> 0) then 1 else 0)) | 0 # Intermediate hash value H0l = H0.low = (H0l + al) H0.high = (H0h + ah + (if (H0l >>> 0) < (al >>> 0) then 1 else 0)) H1l = H1.low = (H1l + bl) H1.high = (H1h + bh + (if (H1l >>> 0) < (bl >>> 0) then 1 else 0)) H2l = H2.low = (H2l + cl) H2.high = (H2h + ch + (if (H2l >>> 0) < (cl >>> 0) then 1 else 0)) H3l = H3.low = (H3l + dl) H3.high = (H3h + dh + (if (H3l >>> 0) < (dl >>> 0) then 1 else 0)) H4l = H4.low = (H4l + el) H4.high = (H4h + eh + (if (H4l >>> 0) < (el >>> 0) then 1 else 0)) H5l = H5.low = (H5l + fl) H5.high = (H5h + fh + (if (H5l >>> 0) < (fl >>> 0) then 1 else 0)) H6l = H6.low = (H6l + gl) H6.high = (H6h + gh + (if (H6l >>> 0) < (gl >>> 0) then 1 else 0)) H7l = H7.low = (H7l + hl) H7.high = (H7h + hh + (if (H7l >>> 0) < (hl >>> 0) then 1 else 0)) _doFinalize: () -> # Shortcuts dataWords = @_data.words nBitsTotal = @_nDataBytes * 8 nBitsLeft = @_data.sigBytes * 8 # Add padding dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32) dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 30] = Math.floor(nBitsTotal / 0x100000000) dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 31] = nBitsTotal @_data.sigBytes = dataWords.length * 4 # Hash final blocks @_process() # Convert hash to 32-bit word array and return @_hash.toX32() copy_to : (obj) -> super obj obj._hash = @_hash.clone() clone : -> out = new SHA512() @copy_to out out #======================================================================= exports.transform = (x) -> out = (new SHA512).finalize x x.scrub() out #=======================================================================
true
## ## ## Forked from PI:NAME:<NAME>END_PI's CryptoJS ## ## https://code.google.com/p/crypto-js/ ## {X64Word,X64WordArray} = require './wordarray' {Hasher} = require './algbase' #======================================================================= class Global convert : (raw) -> (new X64Word(raw[i],raw[i+1]) for i in [0...raw.length] by 2) constructor : -> @K = @convert [ 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817 ] @I = new X64WordArray @convert [ 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1, 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179 ] @W = (new X64Word(0,0) for i in [0...80]) #======================================================================= glbl = new Global() #======================================================================= exports.SHA512 = class SHA512 extends Hasher @blockSize : 1024/32 blockSize : SHA512.blockSize @output_size : 512/8 output_size : SHA512.output_size _doReset : () -> @_hash = glbl.I.clone() _doProcessBlock : (M, offset) -> # Shortcuts H = @_hash.words W = glbl.W H0 = H[0] H1 = H[1] H2 = H[2] H3 = H[3] H4 = H[4] H5 = H[5] H6 = H[6] H7 = H[7] H0h = H0.high H0l = H0.low H1h = H1.high H1l = H1.low H2h = H2.high H2l = H2.low H3h = H3.high H3l = H3.low H4h = H4.high H4l = H4.low H5h = H5.high H5l = H5.low H6h = H6.high H6l = H6.low H7h = H7.high H7l = H7.low # Working variables ah = H0h al = H0l bh = H1h bl = H1l ch = H2h cl = H2l dh = H3h dl = H3l eh = H4h el = H4l fh = H5h fl = H5l gh = H6h gl = H6l hh = H7h hl = H7l # Rounds for i in [0...80] # Shortcut Wi = W[i] # Extend message if (i < 16) Wih = Wi.high = M[offset + i * 2] | 0 Wil = Wi.low = M[offset + i * 2 + 1] | 0 else # Gamma0 gamma0x = W[i - 15] gamma0xh = gamma0x.high gamma0xl = gamma0x.low gamma0h = ((gamma0xh >>> 1) | (gamma0xl << 31)) ^ ((gamma0xh >>> 8) | (gamma0xl << 24)) ^ (gamma0xh >>> 7) gamma0l = ((gamma0xl >>> 1) | (gamma0xh << 31)) ^ ((gamma0xl >>> 8) | (gamma0xh << 24)) ^ ((gamma0xl >>> 7) | (gamma0xh << 25)) # Gamma1 gamma1x = W[i - 2] gamma1xh = gamma1x.high gamma1xl = gamma1x.low gamma1h = ((gamma1xh >>> 19) | (gamma1xl << 13)) ^ ((gamma1xh << 3) | (gamma1xl >>> 29)) ^ (gamma1xh >>> 6) gamma1l = ((gamma1xl >>> 19) | (gamma1xh << 13)) ^ ((gamma1xl << 3) | (gamma1xh >>> 29)) ^ ((gamma1xl >>> 6) | (gamma1xh << 26)) # W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] Wi7 = W[i - 7] Wi7h = Wi7.high Wi7l = Wi7.low Wi16 = W[i - 16] Wi16h = Wi16.high Wi16l = Wi16.low Wil = gamma0l + Wi7l Wih = gamma0h + Wi7h + (if (Wil >>> 0) < (gamma0l >>> 0) then 1 else 0) Wil = Wil + gamma1l Wih = Wih + gamma1h + (if (Wil >>> 0) < (gamma1l >>> 0) then 1 else 0) Wil = Wil + Wi16l Wih = Wih + Wi16h + (if (Wil >>> 0) < (Wi16l >>> 0) then 1 else 0) Wi.high = Wih Wi.low = Wil chh = (eh & fh) ^ (~eh & gh) chl = (el & fl) ^ (~el & gl) majh = (ah & bh) ^ (ah & ch) ^ (bh & ch) majl = (al & bl) ^ (al & cl) ^ (bl & cl) sigma0h = ((ah >>> 28) | (al << 4)) ^ ((ah << 30) | (al >>> 2)) ^ ((ah << 25) | (al >>> 7)) sigma0l = ((al >>> 28) | (ah << 4)) ^ ((al << 30) | (ah >>> 2)) ^ ((al << 25) | (ah >>> 7)) sigma1h = ((eh >>> 14) | (el << 18)) ^ ((eh >>> 18) | (el << 14)) ^ ((eh << 23) | (el >>> 9)) sigma1l = ((el >>> 14) | (eh << 18)) ^ ((el >>> 18) | (eh << 14)) ^ ((el << 23) | (eh >>> 9)) # t1 = h + sigma1 + ch + K[i] + W[i] Ki = glbl.K[i] Kih = Ki.high Kil = Ki.low t1l = hl + sigma1l t1h = hh + sigma1h + (if (t1l >>> 0) < (hl >>> 0) then 1 else 0) t1l = t1l + chl t1h = t1h + chh + (if (t1l >>> 0) < (chl >>> 0) then 1 else 0) t1l = t1l + Kil t1h = t1h + Kih + (if (t1l >>> 0) < (Kil >>> 0) then 1 else 0) t1l = t1l + Wil t1h = t1h + Wih + (if (t1l >>> 0) < (Wil >>> 0) then 1 else 0) # t2 = sigma0 + maj t2l = sigma0l + majl t2h = sigma0h + majh + (if (t2l >>> 0) < (sigma0l >>> 0) then 1 else 0) # Update working variables hh = gh hl = gl gh = fh gl = fl fh = eh fl = el el = (dl + t1l) | 0 eh = (dh + t1h + (if (el >>> 0) < (dl >>> 0) then 1 else 0)) | 0 dh = ch dl = cl ch = bh cl = bl bh = ah bl = al al = (t1l + t2l) | 0 ah = (t1h + t2h + (if (al >>> 0) < (t1l >>> 0) then 1 else 0)) | 0 # Intermediate hash value H0l = H0.low = (H0l + al) H0.high = (H0h + ah + (if (H0l >>> 0) < (al >>> 0) then 1 else 0)) H1l = H1.low = (H1l + bl) H1.high = (H1h + bh + (if (H1l >>> 0) < (bl >>> 0) then 1 else 0)) H2l = H2.low = (H2l + cl) H2.high = (H2h + ch + (if (H2l >>> 0) < (cl >>> 0) then 1 else 0)) H3l = H3.low = (H3l + dl) H3.high = (H3h + dh + (if (H3l >>> 0) < (dl >>> 0) then 1 else 0)) H4l = H4.low = (H4l + el) H4.high = (H4h + eh + (if (H4l >>> 0) < (el >>> 0) then 1 else 0)) H5l = H5.low = (H5l + fl) H5.high = (H5h + fh + (if (H5l >>> 0) < (fl >>> 0) then 1 else 0)) H6l = H6.low = (H6l + gl) H6.high = (H6h + gh + (if (H6l >>> 0) < (gl >>> 0) then 1 else 0)) H7l = H7.low = (H7l + hl) H7.high = (H7h + hh + (if (H7l >>> 0) < (hl >>> 0) then 1 else 0)) _doFinalize: () -> # Shortcuts dataWords = @_data.words nBitsTotal = @_nDataBytes * 8 nBitsLeft = @_data.sigBytes * 8 # Add padding dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32) dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 30] = Math.floor(nBitsTotal / 0x100000000) dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 31] = nBitsTotal @_data.sigBytes = dataWords.length * 4 # Hash final blocks @_process() # Convert hash to 32-bit word array and return @_hash.toX32() copy_to : (obj) -> super obj obj._hash = @_hash.clone() clone : -> out = new SHA512() @copy_to out out #======================================================================= exports.transform = (x) -> out = (new SHA512).finalize x x.scrub() out #=======================================================================
[ { "context": "defg\")\n expect(client.accessToken).to.equal \"abcdefg\"\n\n describe \"#deauthorize()\", ->\n it \"should ", "end": 1064, "score": 0.5355660915374756, "start": 1057, "tag": "KEY", "value": "abcdefg" }, { "context": "ssToken property\", ->\n client.access...
test/spec/readmill/client.coffee
aron/annotator.readmill.js
0
describe "Client", -> jQuery = Annotator.$ Client = Annotator.Readmill.Client client = null fakeDeferred = null beforeEach -> client = new Client clientId: "12345" fakeDeferred = sinon.stub new jQuery.Deferred() sinon.stub(jQuery, "ajax").returns fakeDeferred afterEach -> jQuery.ajax.restore() it "should create a new instance of Client", -> expect(client).to.be.an.instanceof Client it "should allow the @apiEndpoint to be overridden", -> target = new Client clientId: "12345", apiEndpoint: "http://localhost:8000" expect(target.apiEndpoint).to.equal "http://localhost:8000" it "should throw an exception if options.clientId is not provided", -> target = -> new Client() expect(target).to.throw Error describe "#request()", -> it "should call jQuery.ajax()", -> client.request(url: "") expect(jQuery.ajax).was.called() describe "#authorize()", -> it "should set the @accessToken property", -> client.authorize("abcdefg") expect(client.accessToken).to.equal "abcdefg" describe "#deauthorize()", -> it "should remove the @accessToken property", -> client.accessToken = "abcdefg" client.deauthorize() expect(client.accessToken).to.equal(null) describe "#isAuthorized()", -> it "should return true if @accessToken is present", -> client.accessToken = "abcdefg" expect(client.isAuthorized()).to.be.true it "should return false if @accessToken is not present", -> expect(client.isAuthorized()).to.be.false
60149
describe "Client", -> jQuery = Annotator.$ Client = Annotator.Readmill.Client client = null fakeDeferred = null beforeEach -> client = new Client clientId: "12345" fakeDeferred = sinon.stub new jQuery.Deferred() sinon.stub(jQuery, "ajax").returns fakeDeferred afterEach -> jQuery.ajax.restore() it "should create a new instance of Client", -> expect(client).to.be.an.instanceof Client it "should allow the @apiEndpoint to be overridden", -> target = new Client clientId: "12345", apiEndpoint: "http://localhost:8000" expect(target.apiEndpoint).to.equal "http://localhost:8000" it "should throw an exception if options.clientId is not provided", -> target = -> new Client() expect(target).to.throw Error describe "#request()", -> it "should call jQuery.ajax()", -> client.request(url: "") expect(jQuery.ajax).was.called() describe "#authorize()", -> it "should set the @accessToken property", -> client.authorize("abcdefg") expect(client.accessToken).to.equal "<KEY>" describe "#deauthorize()", -> it "should remove the @accessToken property", -> client.accessToken = "<KEY>" client.deauthorize() expect(client.accessToken).to.equal(null) describe "#isAuthorized()", -> it "should return true if @accessToken is present", -> client.accessToken = "<KEY>" expect(client.isAuthorized()).to.be.true it "should return false if @accessToken is not present", -> expect(client.isAuthorized()).to.be.false
true
describe "Client", -> jQuery = Annotator.$ Client = Annotator.Readmill.Client client = null fakeDeferred = null beforeEach -> client = new Client clientId: "12345" fakeDeferred = sinon.stub new jQuery.Deferred() sinon.stub(jQuery, "ajax").returns fakeDeferred afterEach -> jQuery.ajax.restore() it "should create a new instance of Client", -> expect(client).to.be.an.instanceof Client it "should allow the @apiEndpoint to be overridden", -> target = new Client clientId: "12345", apiEndpoint: "http://localhost:8000" expect(target.apiEndpoint).to.equal "http://localhost:8000" it "should throw an exception if options.clientId is not provided", -> target = -> new Client() expect(target).to.throw Error describe "#request()", -> it "should call jQuery.ajax()", -> client.request(url: "") expect(jQuery.ajax).was.called() describe "#authorize()", -> it "should set the @accessToken property", -> client.authorize("abcdefg") expect(client.accessToken).to.equal "PI:KEY:<KEY>END_PI" describe "#deauthorize()", -> it "should remove the @accessToken property", -> client.accessToken = "PI:KEY:<KEY>END_PI" client.deauthorize() expect(client.accessToken).to.equal(null) describe "#isAuthorized()", -> it "should return true if @accessToken is present", -> client.accessToken = "PI:KEY:<KEY>END_PI" expect(client.isAuthorized()).to.be.true it "should return false if @accessToken is not present", -> expect(client.isAuthorized()).to.be.false
[ { "context": " is rendered\"\n\n # Page Title\n document.title = \"Lauren Craig\"\n # if Blog.settings.title\n # document.title ", "end": 195, "score": 0.987507700920105, "start": 183, "tag": "NAME", "value": "Lauren Craig" }, { "context": "<meta>', { property: 'twitter:creator...
_source/client/templates/pages/blog/entry.coffee
jbaxleyiii/laurencraig.com
0
Template.blogShow.helpers isAdmin: -> Session.get "canEditPost" Template.blogShow.onRendered -> console.log "blogShow is rendered" # Page Title document.title = "Lauren Craig" # if Blog.settings.title # document.title += " | #{Blog.settings.title}" Meteor.call "isBlogAuthorized", @id, (err, authorized) => if authorized Session.set "canEditPost", authorized Template.pinterest.onRendered -> return unless @data @autorun -> template = Template.instance() data = Template.currentData() preferred_url = data.url || location.origin + location.pathname url = encodeURIComponent preferred_url description = encodeURIComponent data.pinterest?.description || data.description href = "http://www.pinterest.com/pin/create/button/?url=#{url}&media=#{data.media}&description=#{description}" template.$('[data-share]').attr 'href', href Template.twitter.onRendered -> return unless @data @autorun -> template = Template.instance() data = Template.currentData() $('meta[property^="twitter:"]').remove() if data.thumbnail if typeof data.thumbnail is "function" img = data.thumbnail() else img = data.thumbnail if img if not /^http(s?):\/\/+/.test(img) img = location.origin + img # # Twitter cards # $('<meta>', { property: 'twitter:card', content: 'summary' }).appendTo 'head' # What should go here? #$('<meta>', { property: 'twitter:site', content: '' }).appendTo 'head' # if data.author $('<meta>', { property: 'twitter:creator', content: "laurnec" }).appendTo 'head' description = data.excerpt || data.description $('<meta>', { property: 'twitter:url', content: location.origin + location.pathname }).appendTo 'head' $('<meta>', { property: 'twitter:title', content: "#{data.title}" }).appendTo 'head' $('<meta>', { property: 'twitter:description', content: description }).appendTo 'head' $('<meta>', { property: 'twitter:image', content: img }).appendTo 'head' # # Twitter share button # preferred_url = data.url || location.origin + location.pathname url = encodeURIComponent preferred_url base = "https://twitter.com/intent/tweet" text = encodeURIComponent data.twitter?.title || data.title href = base + "?url=" + url + "&text=" + text # if data.author href += "&via=" + "laurnec" template.$("[data-share]").attr "href", href Template.facebook.onRendered -> return unless @data @autorun -> template = Template.instance() data = Template.currentData() $('meta[property^="og:"]').remove() # # OpenGraph tags # description = data.facebook?.description || data.excerpt || data.description || data.summary url = data.url || location.origin + location.pathname title = data.title $('<meta>', { property: 'og:type', content: 'article' }).appendTo 'head' $('<meta>', { property: 'og:site_name', content: location.hostname }).appendTo 'head' $('<meta>', { property: 'og:url', content: url }).appendTo 'head' $('<meta>', { property: 'og:title', content: title }).appendTo 'head' $('<meta>', { property: 'og:description', content: description }).appendTo 'head' if data.thumbnail if typeof data.thumbnail == "function" img = data.thumbnail() else img = data.thumbnail if img if not /^http(s?):\/\/+/.test(img) img = location.origin + img $('<meta>', { property: 'og:image', content: img }).appendTo 'head' url = encodeURIComponent url base = "https://www.facebook.com/sharer/sharer.php" title = encodeURIComponent title summary = encodeURIComponent description href = base + "?s=100&p[url]=" + url + "&p[title]=" + title + "&p[summary]=" + summary if img href += "&p[images][0]=" + encodeURIComponent img template.$("[data-share]").attr "href", href Template.blogShow.events "click a#edit-post": (event, template) -> event.preventDefault() postId = Post.first({slug: Router.current().params.slug})._id Router.go "blogAdminEdit", {id: postId} Template.disqus.onRendered -> if Blog.settings.comments.disqusShortname # Don"t load the Disqus embed.js into the DOM more than once if window.DISQUS # If we"ve already loaded, call reset instead. This will find the correct # thread for the current page URL. See: # http://help.disqus.com/customer/portal/articles/472107-using-disqus-on-ajax-sites post = @data window.DISQUS.reset reload: true config: -> @page.identifier = post.id @page.title = post.title @page.url = window.location.href else disqus_shortname = Blog.settings.comments.disqusShortname disqus_identifier = @data.id disqus_title = @data.title disqus_url = window.location.href disqus_developer = 1 dsq = document.createElement("script") dsq.type = "text/javascript" dsq.async = true dsq.src = "//" + disqus_shortname + ".disqus.com/embed.js" (document.getElementsByTagName("head")[0] or document.getElementsByTagName("body")[0]).appendChild dsq Template.disqus.helpers useDisqus: -> Blog.settings.comments.disqusShortname
83760
Template.blogShow.helpers isAdmin: -> Session.get "canEditPost" Template.blogShow.onRendered -> console.log "blogShow is rendered" # Page Title document.title = "<NAME>" # if Blog.settings.title # document.title += " | #{Blog.settings.title}" Meteor.call "isBlogAuthorized", @id, (err, authorized) => if authorized Session.set "canEditPost", authorized Template.pinterest.onRendered -> return unless @data @autorun -> template = Template.instance() data = Template.currentData() preferred_url = data.url || location.origin + location.pathname url = encodeURIComponent preferred_url description = encodeURIComponent data.pinterest?.description || data.description href = "http://www.pinterest.com/pin/create/button/?url=#{url}&media=#{data.media}&description=#{description}" template.$('[data-share]').attr 'href', href Template.twitter.onRendered -> return unless @data @autorun -> template = Template.instance() data = Template.currentData() $('meta[property^="twitter:"]').remove() if data.thumbnail if typeof data.thumbnail is "function" img = data.thumbnail() else img = data.thumbnail if img if not /^http(s?):\/\/+/.test(img) img = location.origin + img # # Twitter cards # $('<meta>', { property: 'twitter:card', content: 'summary' }).appendTo 'head' # What should go here? #$('<meta>', { property: 'twitter:site', content: '' }).appendTo 'head' # if data.author $('<meta>', { property: 'twitter:creator', content: "laurnec" }).appendTo 'head' description = data.excerpt || data.description $('<meta>', { property: 'twitter:url', content: location.origin + location.pathname }).appendTo 'head' $('<meta>', { property: 'twitter:title', content: "#{data.title}" }).appendTo 'head' $('<meta>', { property: 'twitter:description', content: description }).appendTo 'head' $('<meta>', { property: 'twitter:image', content: img }).appendTo 'head' # # Twitter share button # preferred_url = data.url || location.origin + location.pathname url = encodeURIComponent preferred_url base = "https://twitter.com/intent/tweet" text = encodeURIComponent data.twitter?.title || data.title href = base + "?url=" + url + "&text=" + text # if data.author href += "&via=" + "laurnec" template.$("[data-share]").attr "href", href Template.facebook.onRendered -> return unless @data @autorun -> template = Template.instance() data = Template.currentData() $('meta[property^="og:"]').remove() # # OpenGraph tags # description = data.facebook?.description || data.excerpt || data.description || data.summary url = data.url || location.origin + location.pathname title = data.title $('<meta>', { property: 'og:type', content: 'article' }).appendTo 'head' $('<meta>', { property: 'og:site_name', content: location.hostname }).appendTo 'head' $('<meta>', { property: 'og:url', content: url }).appendTo 'head' $('<meta>', { property: 'og:title', content: title }).appendTo 'head' $('<meta>', { property: 'og:description', content: description }).appendTo 'head' if data.thumbnail if typeof data.thumbnail == "function" img = data.thumbnail() else img = data.thumbnail if img if not /^http(s?):\/\/+/.test(img) img = location.origin + img $('<meta>', { property: 'og:image', content: img }).appendTo 'head' url = encodeURIComponent url base = "https://www.facebook.com/sharer/sharer.php" title = encodeURIComponent title summary = encodeURIComponent description href = base + "?s=100&p[url]=" + url + "&p[title]=" + title + "&p[summary]=" + summary if img href += "&p[images][0]=" + encodeURIComponent img template.$("[data-share]").attr "href", href Template.blogShow.events "click a#edit-post": (event, template) -> event.preventDefault() postId = Post.first({slug: Router.current().params.slug})._id Router.go "blogAdminEdit", {id: postId} Template.disqus.onRendered -> if Blog.settings.comments.disqusShortname # Don"t load the Disqus embed.js into the DOM more than once if window.DISQUS # If we"ve already loaded, call reset instead. This will find the correct # thread for the current page URL. See: # http://help.disqus.com/customer/portal/articles/472107-using-disqus-on-ajax-sites post = @data window.DISQUS.reset reload: true config: -> @page.identifier = post.id @page.title = post.title @page.url = window.location.href else disqus_shortname = Blog.settings.comments.disqusShortname disqus_identifier = @data.id disqus_title = @data.title disqus_url = window.location.href disqus_developer = 1 dsq = document.createElement("script") dsq.type = "text/javascript" dsq.async = true dsq.src = "//" + disqus_shortname + ".disqus.com/embed.js" (document.getElementsByTagName("head")[0] or document.getElementsByTagName("body")[0]).appendChild dsq Template.disqus.helpers useDisqus: -> Blog.settings.comments.disqusShortname
true
Template.blogShow.helpers isAdmin: -> Session.get "canEditPost" Template.blogShow.onRendered -> console.log "blogShow is rendered" # Page Title document.title = "PI:NAME:<NAME>END_PI" # if Blog.settings.title # document.title += " | #{Blog.settings.title}" Meteor.call "isBlogAuthorized", @id, (err, authorized) => if authorized Session.set "canEditPost", authorized Template.pinterest.onRendered -> return unless @data @autorun -> template = Template.instance() data = Template.currentData() preferred_url = data.url || location.origin + location.pathname url = encodeURIComponent preferred_url description = encodeURIComponent data.pinterest?.description || data.description href = "http://www.pinterest.com/pin/create/button/?url=#{url}&media=#{data.media}&description=#{description}" template.$('[data-share]').attr 'href', href Template.twitter.onRendered -> return unless @data @autorun -> template = Template.instance() data = Template.currentData() $('meta[property^="twitter:"]').remove() if data.thumbnail if typeof data.thumbnail is "function" img = data.thumbnail() else img = data.thumbnail if img if not /^http(s?):\/\/+/.test(img) img = location.origin + img # # Twitter cards # $('<meta>', { property: 'twitter:card', content: 'summary' }).appendTo 'head' # What should go here? #$('<meta>', { property: 'twitter:site', content: '' }).appendTo 'head' # if data.author $('<meta>', { property: 'twitter:creator', content: "laurnec" }).appendTo 'head' description = data.excerpt || data.description $('<meta>', { property: 'twitter:url', content: location.origin + location.pathname }).appendTo 'head' $('<meta>', { property: 'twitter:title', content: "#{data.title}" }).appendTo 'head' $('<meta>', { property: 'twitter:description', content: description }).appendTo 'head' $('<meta>', { property: 'twitter:image', content: img }).appendTo 'head' # # Twitter share button # preferred_url = data.url || location.origin + location.pathname url = encodeURIComponent preferred_url base = "https://twitter.com/intent/tweet" text = encodeURIComponent data.twitter?.title || data.title href = base + "?url=" + url + "&text=" + text # if data.author href += "&via=" + "laurnec" template.$("[data-share]").attr "href", href Template.facebook.onRendered -> return unless @data @autorun -> template = Template.instance() data = Template.currentData() $('meta[property^="og:"]').remove() # # OpenGraph tags # description = data.facebook?.description || data.excerpt || data.description || data.summary url = data.url || location.origin + location.pathname title = data.title $('<meta>', { property: 'og:type', content: 'article' }).appendTo 'head' $('<meta>', { property: 'og:site_name', content: location.hostname }).appendTo 'head' $('<meta>', { property: 'og:url', content: url }).appendTo 'head' $('<meta>', { property: 'og:title', content: title }).appendTo 'head' $('<meta>', { property: 'og:description', content: description }).appendTo 'head' if data.thumbnail if typeof data.thumbnail == "function" img = data.thumbnail() else img = data.thumbnail if img if not /^http(s?):\/\/+/.test(img) img = location.origin + img $('<meta>', { property: 'og:image', content: img }).appendTo 'head' url = encodeURIComponent url base = "https://www.facebook.com/sharer/sharer.php" title = encodeURIComponent title summary = encodeURIComponent description href = base + "?s=100&p[url]=" + url + "&p[title]=" + title + "&p[summary]=" + summary if img href += "&p[images][0]=" + encodeURIComponent img template.$("[data-share]").attr "href", href Template.blogShow.events "click a#edit-post": (event, template) -> event.preventDefault() postId = Post.first({slug: Router.current().params.slug})._id Router.go "blogAdminEdit", {id: postId} Template.disqus.onRendered -> if Blog.settings.comments.disqusShortname # Don"t load the Disqus embed.js into the DOM more than once if window.DISQUS # If we"ve already loaded, call reset instead. This will find the correct # thread for the current page URL. See: # http://help.disqus.com/customer/portal/articles/472107-using-disqus-on-ajax-sites post = @data window.DISQUS.reset reload: true config: -> @page.identifier = post.id @page.title = post.title @page.url = window.location.href else disqus_shortname = Blog.settings.comments.disqusShortname disqus_identifier = @data.id disqus_title = @data.title disqus_url = window.location.href disqus_developer = 1 dsq = document.createElement("script") dsq.type = "text/javascript" dsq.async = true dsq.src = "//" + disqus_shortname + ".disqus.com/embed.js" (document.getElementsByTagName("head")[0] or document.getElementsByTagName("body")[0]).appendChild dsq Template.disqus.helpers useDisqus: -> Blog.settings.comments.disqusShortname
[ { "context": " \n# Copyright 2011 - 2013 Mark Masse (OSS project WRML.org) \n# ", "end": 824, "score": 0.9997885823249817, "start": 814, "tag": "NAME", "value": "Mark Masse" } ]
wrmldoc/js/app/config/marionette/renderer.coffee
wrml/wrml
47
# # WRML - Web Resource Modeling Language # __ __ ______ __ __ __ # /\ \ _ \ \ /\ == \ /\ "-./ \ /\ \ # \ \ \/ ".\ \\ \ __< \ \ \-./\ \\ \ \____ # \ \__/".~\_\\ \_\ \_\\ \_\ \ \_\\ \_____\ # \/_/ \/_/ \/_/ /_/ \/_/ \/_/ \/_____/ # # http://www.wrml.org # # Copyright 2011 - 2013 Mark Masse (OSS project WRML.org) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # CoffeeScript do (Marionette) -> _.extend Marionette.Renderer, lookups: ["apps/", "components/"] render: (template, data) -> # TODO: Is this needed to support embedded templates? # if (template.startsWith("#")) # Marionette.Renderer.render(template, data) # return ecoTemplate = @getEcoTemplate(template) throw "Template #{template} not found!" unless ecoTemplate ecoTemplate(data) getEcoTemplate: (template) -> for path in [template, template.split("/").insertAt(-1, "templates").join("/")] for lookup in @lookups ecoTemplate = ecoTemplates[lookup + path] return ecoTemplate if ecoTemplate
85496
# # WRML - Web Resource Modeling Language # __ __ ______ __ __ __ # /\ \ _ \ \ /\ == \ /\ "-./ \ /\ \ # \ \ \/ ".\ \\ \ __< \ \ \-./\ \\ \ \____ # \ \__/".~\_\\ \_\ \_\\ \_\ \ \_\\ \_____\ # \/_/ \/_/ \/_/ /_/ \/_/ \/_/ \/_____/ # # http://www.wrml.org # # Copyright 2011 - 2013 <NAME> (OSS project WRML.org) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # CoffeeScript do (Marionette) -> _.extend Marionette.Renderer, lookups: ["apps/", "components/"] render: (template, data) -> # TODO: Is this needed to support embedded templates? # if (template.startsWith("#")) # Marionette.Renderer.render(template, data) # return ecoTemplate = @getEcoTemplate(template) throw "Template #{template} not found!" unless ecoTemplate ecoTemplate(data) getEcoTemplate: (template) -> for path in [template, template.split("/").insertAt(-1, "templates").join("/")] for lookup in @lookups ecoTemplate = ecoTemplates[lookup + path] return ecoTemplate if ecoTemplate
true
# # WRML - Web Resource Modeling Language # __ __ ______ __ __ __ # /\ \ _ \ \ /\ == \ /\ "-./ \ /\ \ # \ \ \/ ".\ \\ \ __< \ \ \-./\ \\ \ \____ # \ \__/".~\_\\ \_\ \_\\ \_\ \ \_\\ \_____\ # \/_/ \/_/ \/_/ /_/ \/_/ \/_/ \/_____/ # # http://www.wrml.org # # Copyright 2011 - 2013 PI:NAME:<NAME>END_PI (OSS project WRML.org) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # CoffeeScript do (Marionette) -> _.extend Marionette.Renderer, lookups: ["apps/", "components/"] render: (template, data) -> # TODO: Is this needed to support embedded templates? # if (template.startsWith("#")) # Marionette.Renderer.render(template, data) # return ecoTemplate = @getEcoTemplate(template) throw "Template #{template} not found!" unless ecoTemplate ecoTemplate(data) getEcoTemplate: (template) -> for path in [template, template.split("/").insertAt(-1, "templates").join("/")] for lookup in @lookups ecoTemplate = ecoTemplates[lookup + path] return ecoTemplate if ecoTemplate
[ { "context": " not adding a path suffix?\n new_key = \"#{kind} #{direction}-#{arity}-#{cell}-#{path}\"\n else\n new", "end": 12678, "score": 0.9077970385551453, "start": 12657, "tag": "KEY", "value": "kind} #{direction}-#{" }, { "context": "\n new_ke...
bokehjs/src/coffee/models/layouts/box.coffee
andreagrant/bokehDev
1
_ = require "underscore" {EQ, GE, Strength, Variable, WEAK_EQ} = require "../../core/layout/solver" p = require "../../core/properties" LayoutDOM = require "./layout_dom" class BoxView extends LayoutDOM.View className: "bk-grid" get_height: () -> children = @model.get_layoutable_children() child_heights = _.map(children, ((child) -> child._height._value)) if @model._horizontal height = _.reduce(child_heights, ((a, b) -> Math.max(a, b))) else height = _.reduce(child_heights, ((a, b) -> a + b)) return height get_width: () -> children = @model.get_layoutable_children() child_widths = _.map(children, ((child) -> child._width._value)) if @model._horizontal width = _.reduce(child_widths, ((a, b) -> a + b)) else width = _.reduce(child_widths, ((a, b) -> Math.max(a, b))) return width class Box extends LayoutDOM.Model default_view: BoxView constructor: (attrs, options) -> super(attrs, options) # for children that want to be the same size # as other children, make them all equal to these @_child_equal_size_width = new Variable() @_child_equal_size_height = new Variable() # these are passed up to our parent after basing # them on the child box-equal-size vars @_box_equal_size_top = new Variable() @_box_equal_size_bottom = new Variable() @_box_equal_size_left = new Variable() @_box_equal_size_right = new Variable() # these are passed up to our parent after basing # them on the child box-cell-align vars @_box_cell_align_top = new Variable() @_box_cell_align_bottom = new Variable() @_box_cell_align_left = new Variable() @_box_cell_align_right = new Variable() @define { children: [ p.Array, [] ] } @internal { spacing: [ p.Number, 6 ] } @override { responsive: 'fixed' } get_layoutable_children: () -> @get('children') variables_updated: () -> # Use trigger to force re-render for child in @get_layoutable_children() child.trigger('change') @trigger('change') get_edit_variables: () -> edit_variables = super() for child in @get_layoutable_children() edit_variables = edit_variables.concat(child.get_edit_variables()) return edit_variables get_constrained_variables: () -> constrained_variables = super() constrained_variables = _.extend(constrained_variables, { 'box-equal-size-top' : @_box_equal_size_top 'box-equal-size-bottom' : @_box_equal_size_bottom 'box-equal-size-left' : @_box_equal_size_left 'box-equal-size-right' : @_box_equal_size_right 'box-cell-align-top' : @_box_cell_align_top 'box-cell-align-bottom' : @_box_cell_align_bottom 'box-cell-align-left' : @_box_cell_align_left 'box-cell-align-right' : @_box_cell_align_right }) return constrained_variables get_constraints: () -> # Note we don't got and get constraints from _layout_dom parent. constraints = [] children = @get_layoutable_children() if children.length == 0 # No need to continue further if there are no children. Children sure do # make life a lot more complicated. return constraints for child in children # Test it's layoutable @_test_layoutable(child) vars = child.get_constrained_variables() var_keys = _.keys(vars) # Make total widget sizes fill the orthogonal direction # TODO(bird) Can't we make this shorter by using span which has already picked a # dominant direction (we'd just also need to set a doc_span) rect = @_child_rect(vars) if @_horizontal if @_has_var('height', var_keys) constraints.push(EQ(rect.height, [ -1, @_height ])) else if @_has_var('width', var_keys) constraints.push(EQ(rect.width, [ -1, @_width ])) # Add equal-size constraint # - A child's "interesting area" (like the plot area) is the same size as the previous child # (a child can opt out of this by not returning the box-equal-size variables) if @_horizontal if @_has_var(['box-equal-size-left', 'box-equal-size-right', 'width'], var_keys) constraints.push(EQ([-1, vars['box-equal-size-left']], [-1, vars['box-equal-size-right']], vars['width'], @_child_equal_size_width)) else if @_has_var(['box-equal-size-top', 'box-equal-size-bottom', 'height'], var_keys) constraints.push(EQ([-1, vars['box-equal-size-top']], [-1, vars['box-equal-size-bottom']], vars['height'], @_child_equal_size_height)) # Pull child constraints up recursively constraints = constraints.concat(child.get_constraints()) # TODO(bird) - This is the second time we loop through children last = @_info(children[0].get_constrained_variables()) constraints.push(EQ(last.span.start, 0)) for i in [1...children.length] next = @_info(children[i].get_constrained_variables()) # Each child's start equals the previous child's end (unless we have a fixed layout # in which case size may not be available) if last.span.size constraints.push(EQ(last.span.start, last.span.size, [-1, next.span.start])) # The whitespace at end of one child + start of next must equal the box spacing. # This must be a weak constraint because it can conflict with aligning the # alignable edges in each child. Alignment is generally more important visually than spacing. constraints.push(WEAK_EQ(last.whitespace.after, next.whitespace.before, 0 - @spacing)) # If we can't satisfy the whitespace being equal to box spacing, we should fix # it (align things) by increasing rather than decreasing the whitespace. constraints.push(GE(last.whitespace.after, next.whitespace.before, 0 - @spacing)) last = next # Child's side has to stick to the end of the box if @_horizontal if @_has_var('width', var_keys) constraints.push(EQ(last.span.start, last.span.size, [-1, @_width])) else if @_has_var('height', var_keys) constraints.push(EQ(last.span.start, last.span.size, [-1, @_height])) # align outermost edges in both dimensions constraints = constraints.concat(@_align_outer_edges_constraints(true)) # horizontal=true constraints = constraints.concat(@_align_outer_edges_constraints(false)) # line up edges in same-arity boxes constraints = constraints.concat(@_align_inner_cell_edges_constraints()) # build our equal-size bounds from the child ones constraints = constraints.concat(@_box_equal_size_bounds(true)) # horizontal=true constraints = constraints.concat(@_box_equal_size_bounds(false)) # propagate cell alignment (between same-arity boxes) up the hierarchy constraints = constraints.concat(@_box_cell_align_bounds(true)) # horizontal=true constraints = constraints.concat(@_box_cell_align_bounds(false)) # build our whitespace from the child ones constraints = constraints.concat(@_box_whitespace(true)) # horizontal=true constraints = constraints.concat(@_box_whitespace(false)) return constraints _has_var: (look_up, var_keys) -> # Convenience wrapper on an underscore method to # keep code in get_constraints cleaner if typeof look_up is 'string' look_up_list = [look_up] else look_up_list = look_up return _.every(look_up_list, (x) -> x in var_keys) _test_layoutable: (child) -> required_constrained_variables = [ 'origin-x', 'origin-y', 'whitespace-top', 'whitespace-right', 'whitespace-bottom', 'whitespace-left' ] if not child.get_constrained_variables? throw new Error("#{child} is missing get_constrained_variables method") vars = child.get_constrained_variables() for key in required_constrained_variables if key not in _.keys(vars) throw new Error("#{child} is missing constrained_variable #{key}") if not vars[key] instanceof Variable throw new Error("#{child} #{key} is not a solver Variable") return true _child_rect: (vars) -> width = vars['width'] height = vars['height'] [x, y] = [vars['origin-x'], vars['origin-y']] return {x: x, y: y, width: width, height: height} _span: (rect) -> # return [coordinate, size] pair in box-aligned direction if @_horizontal {start: rect.x, size: rect.width} else {start: rect.y, size: rect.height} _info: (vars) -> if @_horizontal whitespace = {before: vars['whitespace-left'], after: vars['whitespace-right']} else whitespace = {before: vars['whitespace-top'], after: vars['whitespace-bottom']} span = @_span(@_child_rect(vars)) return {span: span, whitespace: whitespace} _flatten_cell_edge_variables: (horizontal) -> # All alignment happens in terms of the # box-cell-align-{left,right,top,bottom} variables. We add # "path" information to variables so we know which ones align, # where the "path" includes the box arity and box cell we went # through. # # If we have a row of three plots, we should align the top and # bottom variables between the three plots. # # The flattened dictionary in this case (for the top and left # only) should be: # # box-cell-align-top : [ 3 vars ] # box-cell-align-bottom : [ 3 vars ] # # We don't do left/right starting from a row, and left/right # edges have nothing to align with here. # # Now say we have a row of three columns, each with three # plots (3x3 = 9). We should align the top/bottom variables # across the top three, middle three, and bottom three plots, # as if those groupings were rows. We do this by flattening # starting from the row first, which gets us a dictionary only # of top/bottom variables. # # box-cell-align-top col-3-0- : [ 3 plots from top of columns ] # box-cell-align-top col-3-1- : [ 3 plots from middle of columns ] # box-cell-align-top col-3-2- : [ 3 plots from bottom of columns ] # # "col-3-1-" = 3-cell column, cell index 1. # # In three later, separate calls to # _align_inner_cell_edges_constraints() on each column, we'll # get the left/right variables: # # box-cell-align-left : [ 3 left-column plots ] # box-cell-align-left : [ 3 middle-column plots ] # box-cell-align-left : [ 3 right-column plots ] # # Now add another nesting - we have a row of three columns, # each with three rows, each with three plots. This is # arranged 3x9 = 27. # # box-cell-align-top col-3-0- : [ 9 plots from top rows of columns ] # box-cell-align-top col-3-1- : [ 9 plots from middle rows of columns ] # box-cell-align-top col-3-2- : [ 9 plots from bottom rows of columns ] # # When we make the _align_inner_cell_edges_constraints() calls on each of the three # columns, each column will return row-pathed values # # box-cell-align-left row-3-0-: [ 3 plots in left column of left column ] # box-cell-align-left row-3-1-: [ 3 plots in middle column of left column ] # box-cell-align-left row-3-2-: [ 3 plots in right column of left column ] # ... same for the middle and right columns # # Anyway in essence what we do is that we add only rows to the # path to left/right variables, and only columns to the path # to top/bottom variables. # # If we nest yet another level we would finally get paths with # multiple rows or multiple columns in them. if horizontal relevant_edges = Box._top_bottom_inner_cell_edge_variables else relevant_edges = Box._left_right_inner_cell_edge_variables add_path = horizontal != @_horizontal children = @get_layoutable_children() arity = children.length flattened = {} cell = 0 for child in children if child instanceof Box cell_vars = child._flatten_cell_edge_variables(horizontal) else cell_vars = {} all_vars = child.get_constrained_variables() for name in relevant_edges if name of all_vars cell_vars[name] = [all_vars[name]] for key, variables of cell_vars if add_path parsed = key.split(" ") kind = parsed[0] if parsed.length > 1 path = parsed[1] else path = "" if @_horizontal direction = "row" else direction = "col" # TODO should we "ignore" arity-1 boxes potentially by not adding a path suffix? new_key = "#{kind} #{direction}-#{arity}-#{cell}-#{path}" else new_key = key if new_key of flattened flattened[new_key] = flattened[new_key].concat(variables) else flattened[new_key] = variables cell = cell + 1 return flattened # This should only be called on the toplevel box (twice, # once with horizontal=true and once with horizontal=false) _align_inner_cell_edges_constraints: () -> constraints = [] if @_is_root flattened = @_flatten_cell_edge_variables(@_horizontal) for key, variables of flattened if variables.length > 1 #console.log("constraining ", key, " ", variables) last = variables[0] for i in [1...variables.length] constraints.push(EQ(variables[i], [-1, last])) return constraints # returns a two-item array where each item is a list of edge # children from the start and end respectively _find_edge_leaves: (horizontal) -> children = @get_layoutable_children() # console.log(" finding edge leaves in #{children.length}-#{@type}, " + # "our orientation #{@_horizontal} finding #{horizontal} children ", children) leaves = [ [] , [] ] if children.length > 0 if @_horizontal == horizontal # note start and end may be the same start = children[0] end = children[children.length - 1] if start instanceof Box leaves[0] = leaves[0].concat(start._find_edge_leaves(horizontal)[0]) else leaves[0].push(start) if end instanceof Box leaves[1] = leaves[1].concat(end._find_edge_leaves(horizontal)[1]) else leaves[1].push(end) else # if we are a column and someone wants the horizontal edges, # we return the horizontal edges from all of our children for child in children if child instanceof Box child_leaves = child._find_edge_leaves(horizontal) leaves[0] = leaves[0].concat(child_leaves[0]) leaves[1] = leaves[1].concat(child_leaves[1]) else leaves[0].push(child) leaves[1].push(child) # console.log(" start leaves ", _.map(leaves[0], (leaf) -> leaf.id)) # console.log(" end leaves ", _.map(leaves[1], (leaf) -> leaf.id)) return leaves _align_outer_edges_constraints: (horizontal) -> # console.log("#{if horizontal then 'horizontal' else 'vertical'} outer edge constraints in #{@get_layoutable_children().length}-#{@type}") [start_leaves, end_leaves] = @_find_edge_leaves(horizontal) if horizontal start_variable = 'on-edge-align-left' end_variable = 'on-edge-align-right' else start_variable = 'on-edge-align-top' end_variable = 'on-edge-align-bottom' collect_vars = (leaves, name) -> #console.log("collecting #{name} in ", leaves) edges = [] for leaf in leaves vars = leaf.get_constrained_variables() if name of vars edges.push(vars[name]) #vars[name]['_debug'] = "#{name} from #{leaf.id}" edges start_edges = collect_vars(start_leaves, start_variable) end_edges = collect_vars(end_leaves, end_variable) result = [] add_all_equal = (edges) -> if edges.length > 1 first = edges[0] for i in [1...edges.length] edge = edges[i] #console.log(" constraining #{first._debug} == #{edge._debug}") result.push(EQ([-1, first], edge)) null # prevent coffeescript from making a tmp array add_all_equal(start_edges) add_all_equal(end_edges) # console.log("computed constraints ", result) return result _box_insets_from_child_insets: (horizontal, child_variable_prefix, our_variable_prefix, minimum) -> [start_leaves, end_leaves] = @_find_edge_leaves(horizontal) if horizontal start_variable = "#{child_variable_prefix}-left" end_variable = "#{child_variable_prefix}-right" our_start = @["#{our_variable_prefix}_left"] our_end = @["#{our_variable_prefix}_right"] else start_variable = "#{child_variable_prefix}-top" end_variable = "#{child_variable_prefix}-bottom" our_start = @["#{our_variable_prefix}_top"] our_end = @["#{our_variable_prefix}_bottom"] result = [] add_constraints = (ours, leaves, name) -> edges = [] for leaf in leaves vars = leaf.get_constrained_variables() if name of vars if minimum result.push(GE([-1, ours], vars[name])) else result.push(EQ([-1, ours], vars[name])) null # prevent coffeescript from making a tmp array add_constraints(our_start, start_leaves, start_variable) add_constraints(our_end, end_leaves, end_variable) return result _box_equal_size_bounds: (horizontal) -> # false = box bounds equal all outer child bounds exactly @_box_insets_from_child_insets(horizontal, 'box-equal-size', '_box_equal_size', false) _box_cell_align_bounds: (horizontal) -> # false = box bounds equal all outer child bounds exactly @_box_insets_from_child_insets(horizontal, 'box-cell-align', '_box_cell_align', false) _box_whitespace: (horizontal) -> # true = box whitespace must be the minimum of child # whitespaces (i.e. distance from box edge to the outermost # child pixels) @_box_insets_from_child_insets(horizontal, 'whitespace', '_whitespace', true) @_left_right_inner_cell_edge_variables = [ 'box-cell-align-left', 'box-cell-align-right' ] @_top_bottom_inner_cell_edge_variables = [ 'box-cell-align-top', 'box-cell-align-bottom' ] module.exports = Model: Box View: BoxView
88422
_ = require "underscore" {EQ, GE, Strength, Variable, WEAK_EQ} = require "../../core/layout/solver" p = require "../../core/properties" LayoutDOM = require "./layout_dom" class BoxView extends LayoutDOM.View className: "bk-grid" get_height: () -> children = @model.get_layoutable_children() child_heights = _.map(children, ((child) -> child._height._value)) if @model._horizontal height = _.reduce(child_heights, ((a, b) -> Math.max(a, b))) else height = _.reduce(child_heights, ((a, b) -> a + b)) return height get_width: () -> children = @model.get_layoutable_children() child_widths = _.map(children, ((child) -> child._width._value)) if @model._horizontal width = _.reduce(child_widths, ((a, b) -> a + b)) else width = _.reduce(child_widths, ((a, b) -> Math.max(a, b))) return width class Box extends LayoutDOM.Model default_view: BoxView constructor: (attrs, options) -> super(attrs, options) # for children that want to be the same size # as other children, make them all equal to these @_child_equal_size_width = new Variable() @_child_equal_size_height = new Variable() # these are passed up to our parent after basing # them on the child box-equal-size vars @_box_equal_size_top = new Variable() @_box_equal_size_bottom = new Variable() @_box_equal_size_left = new Variable() @_box_equal_size_right = new Variable() # these are passed up to our parent after basing # them on the child box-cell-align vars @_box_cell_align_top = new Variable() @_box_cell_align_bottom = new Variable() @_box_cell_align_left = new Variable() @_box_cell_align_right = new Variable() @define { children: [ p.Array, [] ] } @internal { spacing: [ p.Number, 6 ] } @override { responsive: 'fixed' } get_layoutable_children: () -> @get('children') variables_updated: () -> # Use trigger to force re-render for child in @get_layoutable_children() child.trigger('change') @trigger('change') get_edit_variables: () -> edit_variables = super() for child in @get_layoutable_children() edit_variables = edit_variables.concat(child.get_edit_variables()) return edit_variables get_constrained_variables: () -> constrained_variables = super() constrained_variables = _.extend(constrained_variables, { 'box-equal-size-top' : @_box_equal_size_top 'box-equal-size-bottom' : @_box_equal_size_bottom 'box-equal-size-left' : @_box_equal_size_left 'box-equal-size-right' : @_box_equal_size_right 'box-cell-align-top' : @_box_cell_align_top 'box-cell-align-bottom' : @_box_cell_align_bottom 'box-cell-align-left' : @_box_cell_align_left 'box-cell-align-right' : @_box_cell_align_right }) return constrained_variables get_constraints: () -> # Note we don't got and get constraints from _layout_dom parent. constraints = [] children = @get_layoutable_children() if children.length == 0 # No need to continue further if there are no children. Children sure do # make life a lot more complicated. return constraints for child in children # Test it's layoutable @_test_layoutable(child) vars = child.get_constrained_variables() var_keys = _.keys(vars) # Make total widget sizes fill the orthogonal direction # TODO(bird) Can't we make this shorter by using span which has already picked a # dominant direction (we'd just also need to set a doc_span) rect = @_child_rect(vars) if @_horizontal if @_has_var('height', var_keys) constraints.push(EQ(rect.height, [ -1, @_height ])) else if @_has_var('width', var_keys) constraints.push(EQ(rect.width, [ -1, @_width ])) # Add equal-size constraint # - A child's "interesting area" (like the plot area) is the same size as the previous child # (a child can opt out of this by not returning the box-equal-size variables) if @_horizontal if @_has_var(['box-equal-size-left', 'box-equal-size-right', 'width'], var_keys) constraints.push(EQ([-1, vars['box-equal-size-left']], [-1, vars['box-equal-size-right']], vars['width'], @_child_equal_size_width)) else if @_has_var(['box-equal-size-top', 'box-equal-size-bottom', 'height'], var_keys) constraints.push(EQ([-1, vars['box-equal-size-top']], [-1, vars['box-equal-size-bottom']], vars['height'], @_child_equal_size_height)) # Pull child constraints up recursively constraints = constraints.concat(child.get_constraints()) # TODO(bird) - This is the second time we loop through children last = @_info(children[0].get_constrained_variables()) constraints.push(EQ(last.span.start, 0)) for i in [1...children.length] next = @_info(children[i].get_constrained_variables()) # Each child's start equals the previous child's end (unless we have a fixed layout # in which case size may not be available) if last.span.size constraints.push(EQ(last.span.start, last.span.size, [-1, next.span.start])) # The whitespace at end of one child + start of next must equal the box spacing. # This must be a weak constraint because it can conflict with aligning the # alignable edges in each child. Alignment is generally more important visually than spacing. constraints.push(WEAK_EQ(last.whitespace.after, next.whitespace.before, 0 - @spacing)) # If we can't satisfy the whitespace being equal to box spacing, we should fix # it (align things) by increasing rather than decreasing the whitespace. constraints.push(GE(last.whitespace.after, next.whitespace.before, 0 - @spacing)) last = next # Child's side has to stick to the end of the box if @_horizontal if @_has_var('width', var_keys) constraints.push(EQ(last.span.start, last.span.size, [-1, @_width])) else if @_has_var('height', var_keys) constraints.push(EQ(last.span.start, last.span.size, [-1, @_height])) # align outermost edges in both dimensions constraints = constraints.concat(@_align_outer_edges_constraints(true)) # horizontal=true constraints = constraints.concat(@_align_outer_edges_constraints(false)) # line up edges in same-arity boxes constraints = constraints.concat(@_align_inner_cell_edges_constraints()) # build our equal-size bounds from the child ones constraints = constraints.concat(@_box_equal_size_bounds(true)) # horizontal=true constraints = constraints.concat(@_box_equal_size_bounds(false)) # propagate cell alignment (between same-arity boxes) up the hierarchy constraints = constraints.concat(@_box_cell_align_bounds(true)) # horizontal=true constraints = constraints.concat(@_box_cell_align_bounds(false)) # build our whitespace from the child ones constraints = constraints.concat(@_box_whitespace(true)) # horizontal=true constraints = constraints.concat(@_box_whitespace(false)) return constraints _has_var: (look_up, var_keys) -> # Convenience wrapper on an underscore method to # keep code in get_constraints cleaner if typeof look_up is 'string' look_up_list = [look_up] else look_up_list = look_up return _.every(look_up_list, (x) -> x in var_keys) _test_layoutable: (child) -> required_constrained_variables = [ 'origin-x', 'origin-y', 'whitespace-top', 'whitespace-right', 'whitespace-bottom', 'whitespace-left' ] if not child.get_constrained_variables? throw new Error("#{child} is missing get_constrained_variables method") vars = child.get_constrained_variables() for key in required_constrained_variables if key not in _.keys(vars) throw new Error("#{child} is missing constrained_variable #{key}") if not vars[key] instanceof Variable throw new Error("#{child} #{key} is not a solver Variable") return true _child_rect: (vars) -> width = vars['width'] height = vars['height'] [x, y] = [vars['origin-x'], vars['origin-y']] return {x: x, y: y, width: width, height: height} _span: (rect) -> # return [coordinate, size] pair in box-aligned direction if @_horizontal {start: rect.x, size: rect.width} else {start: rect.y, size: rect.height} _info: (vars) -> if @_horizontal whitespace = {before: vars['whitespace-left'], after: vars['whitespace-right']} else whitespace = {before: vars['whitespace-top'], after: vars['whitespace-bottom']} span = @_span(@_child_rect(vars)) return {span: span, whitespace: whitespace} _flatten_cell_edge_variables: (horizontal) -> # All alignment happens in terms of the # box-cell-align-{left,right,top,bottom} variables. We add # "path" information to variables so we know which ones align, # where the "path" includes the box arity and box cell we went # through. # # If we have a row of three plots, we should align the top and # bottom variables between the three plots. # # The flattened dictionary in this case (for the top and left # only) should be: # # box-cell-align-top : [ 3 vars ] # box-cell-align-bottom : [ 3 vars ] # # We don't do left/right starting from a row, and left/right # edges have nothing to align with here. # # Now say we have a row of three columns, each with three # plots (3x3 = 9). We should align the top/bottom variables # across the top three, middle three, and bottom three plots, # as if those groupings were rows. We do this by flattening # starting from the row first, which gets us a dictionary only # of top/bottom variables. # # box-cell-align-top col-3-0- : [ 3 plots from top of columns ] # box-cell-align-top col-3-1- : [ 3 plots from middle of columns ] # box-cell-align-top col-3-2- : [ 3 plots from bottom of columns ] # # "col-3-1-" = 3-cell column, cell index 1. # # In three later, separate calls to # _align_inner_cell_edges_constraints() on each column, we'll # get the left/right variables: # # box-cell-align-left : [ 3 left-column plots ] # box-cell-align-left : [ 3 middle-column plots ] # box-cell-align-left : [ 3 right-column plots ] # # Now add another nesting - we have a row of three columns, # each with three rows, each with three plots. This is # arranged 3x9 = 27. # # box-cell-align-top col-3-0- : [ 9 plots from top rows of columns ] # box-cell-align-top col-3-1- : [ 9 plots from middle rows of columns ] # box-cell-align-top col-3-2- : [ 9 plots from bottom rows of columns ] # # When we make the _align_inner_cell_edges_constraints() calls on each of the three # columns, each column will return row-pathed values # # box-cell-align-left row-3-0-: [ 3 plots in left column of left column ] # box-cell-align-left row-3-1-: [ 3 plots in middle column of left column ] # box-cell-align-left row-3-2-: [ 3 plots in right column of left column ] # ... same for the middle and right columns # # Anyway in essence what we do is that we add only rows to the # path to left/right variables, and only columns to the path # to top/bottom variables. # # If we nest yet another level we would finally get paths with # multiple rows or multiple columns in them. if horizontal relevant_edges = Box._top_bottom_inner_cell_edge_variables else relevant_edges = Box._left_right_inner_cell_edge_variables add_path = horizontal != @_horizontal children = @get_layoutable_children() arity = children.length flattened = {} cell = 0 for child in children if child instanceof Box cell_vars = child._flatten_cell_edge_variables(horizontal) else cell_vars = {} all_vars = child.get_constrained_variables() for name in relevant_edges if name of all_vars cell_vars[name] = [all_vars[name]] for key, variables of cell_vars if add_path parsed = key.split(" ") kind = parsed[0] if parsed.length > 1 path = parsed[1] else path = "" if @_horizontal direction = "row" else direction = "col" # TODO should we "ignore" arity-1 boxes potentially by not adding a path suffix? new_key = "#{<KEY>arity}-<KEY>cell}-<KEY>path<KEY>}" else new_key = key if new_key of flattened flattened[new_key] = flattened[new_key].concat(variables) else flattened[new_key] = variables cell = cell + 1 return flattened # This should only be called on the toplevel box (twice, # once with horizontal=true and once with horizontal=false) _align_inner_cell_edges_constraints: () -> constraints = [] if @_is_root flattened = @_flatten_cell_edge_variables(@_horizontal) for key, variables of flattened if variables.length > 1 #console.log("constraining ", key, " ", variables) last = variables[0] for i in [1...variables.length] constraints.push(EQ(variables[i], [-1, last])) return constraints # returns a two-item array where each item is a list of edge # children from the start and end respectively _find_edge_leaves: (horizontal) -> children = @get_layoutable_children() # console.log(" finding edge leaves in #{children.length}-#{@type}, " + # "our orientation #{@_horizontal} finding #{horizontal} children ", children) leaves = [ [] , [] ] if children.length > 0 if @_horizontal == horizontal # note start and end may be the same start = children[0] end = children[children.length - 1] if start instanceof Box leaves[0] = leaves[0].concat(start._find_edge_leaves(horizontal)[0]) else leaves[0].push(start) if end instanceof Box leaves[1] = leaves[1].concat(end._find_edge_leaves(horizontal)[1]) else leaves[1].push(end) else # if we are a column and someone wants the horizontal edges, # we return the horizontal edges from all of our children for child in children if child instanceof Box child_leaves = child._find_edge_leaves(horizontal) leaves[0] = leaves[0].concat(child_leaves[0]) leaves[1] = leaves[1].concat(child_leaves[1]) else leaves[0].push(child) leaves[1].push(child) # console.log(" start leaves ", _.map(leaves[0], (leaf) -> leaf.id)) # console.log(" end leaves ", _.map(leaves[1], (leaf) -> leaf.id)) return leaves _align_outer_edges_constraints: (horizontal) -> # console.log("#{if horizontal then 'horizontal' else 'vertical'} outer edge constraints in #{@get_layoutable_children().length}-#{@type}") [start_leaves, end_leaves] = @_find_edge_leaves(horizontal) if horizontal start_variable = 'on-edge-align-left' end_variable = 'on-edge-align-right' else start_variable = 'on-edge-align-top' end_variable = 'on-edge-align-bottom' collect_vars = (leaves, name) -> #console.log("collecting #{name} in ", leaves) edges = [] for leaf in leaves vars = leaf.get_constrained_variables() if name of vars edges.push(vars[name]) #vars[name]['_debug'] = "#{name} from #{leaf.id}" edges start_edges = collect_vars(start_leaves, start_variable) end_edges = collect_vars(end_leaves, end_variable) result = [] add_all_equal = (edges) -> if edges.length > 1 first = edges[0] for i in [1...edges.length] edge = edges[i] #console.log(" constraining #{first._debug} == #{edge._debug}") result.push(EQ([-1, first], edge)) null # prevent coffeescript from making a tmp array add_all_equal(start_edges) add_all_equal(end_edges) # console.log("computed constraints ", result) return result _box_insets_from_child_insets: (horizontal, child_variable_prefix, our_variable_prefix, minimum) -> [start_leaves, end_leaves] = @_find_edge_leaves(horizontal) if horizontal start_variable = "#{child_variable_prefix}-left" end_variable = "#{child_variable_prefix}-right" our_start = @["#{our_variable_prefix}_left"] our_end = @["#{our_variable_prefix}_right"] else start_variable = "#{child_variable_prefix}-top" end_variable = "#{child_variable_prefix}-bottom" our_start = @["#{our_variable_prefix}_top"] our_end = @["#{our_variable_prefix}_bottom"] result = [] add_constraints = (ours, leaves, name) -> edges = [] for leaf in leaves vars = leaf.get_constrained_variables() if name of vars if minimum result.push(GE([-1, ours], vars[name])) else result.push(EQ([-1, ours], vars[name])) null # prevent coffeescript from making a tmp array add_constraints(our_start, start_leaves, start_variable) add_constraints(our_end, end_leaves, end_variable) return result _box_equal_size_bounds: (horizontal) -> # false = box bounds equal all outer child bounds exactly @_box_insets_from_child_insets(horizontal, 'box-equal-size', '_box_equal_size', false) _box_cell_align_bounds: (horizontal) -> # false = box bounds equal all outer child bounds exactly @_box_insets_from_child_insets(horizontal, 'box-cell-align', '_box_cell_align', false) _box_whitespace: (horizontal) -> # true = box whitespace must be the minimum of child # whitespaces (i.e. distance from box edge to the outermost # child pixels) @_box_insets_from_child_insets(horizontal, 'whitespace', '_whitespace', true) @_left_right_inner_cell_edge_variables = [ 'box-cell-align-left', 'box-cell-align-right' ] @_top_bottom_inner_cell_edge_variables = [ 'box-cell-align-top', 'box-cell-align-bottom' ] module.exports = Model: Box View: BoxView
true
_ = require "underscore" {EQ, GE, Strength, Variable, WEAK_EQ} = require "../../core/layout/solver" p = require "../../core/properties" LayoutDOM = require "./layout_dom" class BoxView extends LayoutDOM.View className: "bk-grid" get_height: () -> children = @model.get_layoutable_children() child_heights = _.map(children, ((child) -> child._height._value)) if @model._horizontal height = _.reduce(child_heights, ((a, b) -> Math.max(a, b))) else height = _.reduce(child_heights, ((a, b) -> a + b)) return height get_width: () -> children = @model.get_layoutable_children() child_widths = _.map(children, ((child) -> child._width._value)) if @model._horizontal width = _.reduce(child_widths, ((a, b) -> a + b)) else width = _.reduce(child_widths, ((a, b) -> Math.max(a, b))) return width class Box extends LayoutDOM.Model default_view: BoxView constructor: (attrs, options) -> super(attrs, options) # for children that want to be the same size # as other children, make them all equal to these @_child_equal_size_width = new Variable() @_child_equal_size_height = new Variable() # these are passed up to our parent after basing # them on the child box-equal-size vars @_box_equal_size_top = new Variable() @_box_equal_size_bottom = new Variable() @_box_equal_size_left = new Variable() @_box_equal_size_right = new Variable() # these are passed up to our parent after basing # them on the child box-cell-align vars @_box_cell_align_top = new Variable() @_box_cell_align_bottom = new Variable() @_box_cell_align_left = new Variable() @_box_cell_align_right = new Variable() @define { children: [ p.Array, [] ] } @internal { spacing: [ p.Number, 6 ] } @override { responsive: 'fixed' } get_layoutable_children: () -> @get('children') variables_updated: () -> # Use trigger to force re-render for child in @get_layoutable_children() child.trigger('change') @trigger('change') get_edit_variables: () -> edit_variables = super() for child in @get_layoutable_children() edit_variables = edit_variables.concat(child.get_edit_variables()) return edit_variables get_constrained_variables: () -> constrained_variables = super() constrained_variables = _.extend(constrained_variables, { 'box-equal-size-top' : @_box_equal_size_top 'box-equal-size-bottom' : @_box_equal_size_bottom 'box-equal-size-left' : @_box_equal_size_left 'box-equal-size-right' : @_box_equal_size_right 'box-cell-align-top' : @_box_cell_align_top 'box-cell-align-bottom' : @_box_cell_align_bottom 'box-cell-align-left' : @_box_cell_align_left 'box-cell-align-right' : @_box_cell_align_right }) return constrained_variables get_constraints: () -> # Note we don't got and get constraints from _layout_dom parent. constraints = [] children = @get_layoutable_children() if children.length == 0 # No need to continue further if there are no children. Children sure do # make life a lot more complicated. return constraints for child in children # Test it's layoutable @_test_layoutable(child) vars = child.get_constrained_variables() var_keys = _.keys(vars) # Make total widget sizes fill the orthogonal direction # TODO(bird) Can't we make this shorter by using span which has already picked a # dominant direction (we'd just also need to set a doc_span) rect = @_child_rect(vars) if @_horizontal if @_has_var('height', var_keys) constraints.push(EQ(rect.height, [ -1, @_height ])) else if @_has_var('width', var_keys) constraints.push(EQ(rect.width, [ -1, @_width ])) # Add equal-size constraint # - A child's "interesting area" (like the plot area) is the same size as the previous child # (a child can opt out of this by not returning the box-equal-size variables) if @_horizontal if @_has_var(['box-equal-size-left', 'box-equal-size-right', 'width'], var_keys) constraints.push(EQ([-1, vars['box-equal-size-left']], [-1, vars['box-equal-size-right']], vars['width'], @_child_equal_size_width)) else if @_has_var(['box-equal-size-top', 'box-equal-size-bottom', 'height'], var_keys) constraints.push(EQ([-1, vars['box-equal-size-top']], [-1, vars['box-equal-size-bottom']], vars['height'], @_child_equal_size_height)) # Pull child constraints up recursively constraints = constraints.concat(child.get_constraints()) # TODO(bird) - This is the second time we loop through children last = @_info(children[0].get_constrained_variables()) constraints.push(EQ(last.span.start, 0)) for i in [1...children.length] next = @_info(children[i].get_constrained_variables()) # Each child's start equals the previous child's end (unless we have a fixed layout # in which case size may not be available) if last.span.size constraints.push(EQ(last.span.start, last.span.size, [-1, next.span.start])) # The whitespace at end of one child + start of next must equal the box spacing. # This must be a weak constraint because it can conflict with aligning the # alignable edges in each child. Alignment is generally more important visually than spacing. constraints.push(WEAK_EQ(last.whitespace.after, next.whitespace.before, 0 - @spacing)) # If we can't satisfy the whitespace being equal to box spacing, we should fix # it (align things) by increasing rather than decreasing the whitespace. constraints.push(GE(last.whitespace.after, next.whitespace.before, 0 - @spacing)) last = next # Child's side has to stick to the end of the box if @_horizontal if @_has_var('width', var_keys) constraints.push(EQ(last.span.start, last.span.size, [-1, @_width])) else if @_has_var('height', var_keys) constraints.push(EQ(last.span.start, last.span.size, [-1, @_height])) # align outermost edges in both dimensions constraints = constraints.concat(@_align_outer_edges_constraints(true)) # horizontal=true constraints = constraints.concat(@_align_outer_edges_constraints(false)) # line up edges in same-arity boxes constraints = constraints.concat(@_align_inner_cell_edges_constraints()) # build our equal-size bounds from the child ones constraints = constraints.concat(@_box_equal_size_bounds(true)) # horizontal=true constraints = constraints.concat(@_box_equal_size_bounds(false)) # propagate cell alignment (between same-arity boxes) up the hierarchy constraints = constraints.concat(@_box_cell_align_bounds(true)) # horizontal=true constraints = constraints.concat(@_box_cell_align_bounds(false)) # build our whitespace from the child ones constraints = constraints.concat(@_box_whitespace(true)) # horizontal=true constraints = constraints.concat(@_box_whitespace(false)) return constraints _has_var: (look_up, var_keys) -> # Convenience wrapper on an underscore method to # keep code in get_constraints cleaner if typeof look_up is 'string' look_up_list = [look_up] else look_up_list = look_up return _.every(look_up_list, (x) -> x in var_keys) _test_layoutable: (child) -> required_constrained_variables = [ 'origin-x', 'origin-y', 'whitespace-top', 'whitespace-right', 'whitespace-bottom', 'whitespace-left' ] if not child.get_constrained_variables? throw new Error("#{child} is missing get_constrained_variables method") vars = child.get_constrained_variables() for key in required_constrained_variables if key not in _.keys(vars) throw new Error("#{child} is missing constrained_variable #{key}") if not vars[key] instanceof Variable throw new Error("#{child} #{key} is not a solver Variable") return true _child_rect: (vars) -> width = vars['width'] height = vars['height'] [x, y] = [vars['origin-x'], vars['origin-y']] return {x: x, y: y, width: width, height: height} _span: (rect) -> # return [coordinate, size] pair in box-aligned direction if @_horizontal {start: rect.x, size: rect.width} else {start: rect.y, size: rect.height} _info: (vars) -> if @_horizontal whitespace = {before: vars['whitespace-left'], after: vars['whitespace-right']} else whitespace = {before: vars['whitespace-top'], after: vars['whitespace-bottom']} span = @_span(@_child_rect(vars)) return {span: span, whitespace: whitespace} _flatten_cell_edge_variables: (horizontal) -> # All alignment happens in terms of the # box-cell-align-{left,right,top,bottom} variables. We add # "path" information to variables so we know which ones align, # where the "path" includes the box arity and box cell we went # through. # # If we have a row of three plots, we should align the top and # bottom variables between the three plots. # # The flattened dictionary in this case (for the top and left # only) should be: # # box-cell-align-top : [ 3 vars ] # box-cell-align-bottom : [ 3 vars ] # # We don't do left/right starting from a row, and left/right # edges have nothing to align with here. # # Now say we have a row of three columns, each with three # plots (3x3 = 9). We should align the top/bottom variables # across the top three, middle three, and bottom three plots, # as if those groupings were rows. We do this by flattening # starting from the row first, which gets us a dictionary only # of top/bottom variables. # # box-cell-align-top col-3-0- : [ 3 plots from top of columns ] # box-cell-align-top col-3-1- : [ 3 plots from middle of columns ] # box-cell-align-top col-3-2- : [ 3 plots from bottom of columns ] # # "col-3-1-" = 3-cell column, cell index 1. # # In three later, separate calls to # _align_inner_cell_edges_constraints() on each column, we'll # get the left/right variables: # # box-cell-align-left : [ 3 left-column plots ] # box-cell-align-left : [ 3 middle-column plots ] # box-cell-align-left : [ 3 right-column plots ] # # Now add another nesting - we have a row of three columns, # each with three rows, each with three plots. This is # arranged 3x9 = 27. # # box-cell-align-top col-3-0- : [ 9 plots from top rows of columns ] # box-cell-align-top col-3-1- : [ 9 plots from middle rows of columns ] # box-cell-align-top col-3-2- : [ 9 plots from bottom rows of columns ] # # When we make the _align_inner_cell_edges_constraints() calls on each of the three # columns, each column will return row-pathed values # # box-cell-align-left row-3-0-: [ 3 plots in left column of left column ] # box-cell-align-left row-3-1-: [ 3 plots in middle column of left column ] # box-cell-align-left row-3-2-: [ 3 plots in right column of left column ] # ... same for the middle and right columns # # Anyway in essence what we do is that we add only rows to the # path to left/right variables, and only columns to the path # to top/bottom variables. # # If we nest yet another level we would finally get paths with # multiple rows or multiple columns in them. if horizontal relevant_edges = Box._top_bottom_inner_cell_edge_variables else relevant_edges = Box._left_right_inner_cell_edge_variables add_path = horizontal != @_horizontal children = @get_layoutable_children() arity = children.length flattened = {} cell = 0 for child in children if child instanceof Box cell_vars = child._flatten_cell_edge_variables(horizontal) else cell_vars = {} all_vars = child.get_constrained_variables() for name in relevant_edges if name of all_vars cell_vars[name] = [all_vars[name]] for key, variables of cell_vars if add_path parsed = key.split(" ") kind = parsed[0] if parsed.length > 1 path = parsed[1] else path = "" if @_horizontal direction = "row" else direction = "col" # TODO should we "ignore" arity-1 boxes potentially by not adding a path suffix? new_key = "#{PI:KEY:<KEY>END_PIarity}-PI:KEY:<KEY>END_PIcell}-PI:KEY:<KEY>END_PIpathPI:KEY:<KEY>END_PI}" else new_key = key if new_key of flattened flattened[new_key] = flattened[new_key].concat(variables) else flattened[new_key] = variables cell = cell + 1 return flattened # This should only be called on the toplevel box (twice, # once with horizontal=true and once with horizontal=false) _align_inner_cell_edges_constraints: () -> constraints = [] if @_is_root flattened = @_flatten_cell_edge_variables(@_horizontal) for key, variables of flattened if variables.length > 1 #console.log("constraining ", key, " ", variables) last = variables[0] for i in [1...variables.length] constraints.push(EQ(variables[i], [-1, last])) return constraints # returns a two-item array where each item is a list of edge # children from the start and end respectively _find_edge_leaves: (horizontal) -> children = @get_layoutable_children() # console.log(" finding edge leaves in #{children.length}-#{@type}, " + # "our orientation #{@_horizontal} finding #{horizontal} children ", children) leaves = [ [] , [] ] if children.length > 0 if @_horizontal == horizontal # note start and end may be the same start = children[0] end = children[children.length - 1] if start instanceof Box leaves[0] = leaves[0].concat(start._find_edge_leaves(horizontal)[0]) else leaves[0].push(start) if end instanceof Box leaves[1] = leaves[1].concat(end._find_edge_leaves(horizontal)[1]) else leaves[1].push(end) else # if we are a column and someone wants the horizontal edges, # we return the horizontal edges from all of our children for child in children if child instanceof Box child_leaves = child._find_edge_leaves(horizontal) leaves[0] = leaves[0].concat(child_leaves[0]) leaves[1] = leaves[1].concat(child_leaves[1]) else leaves[0].push(child) leaves[1].push(child) # console.log(" start leaves ", _.map(leaves[0], (leaf) -> leaf.id)) # console.log(" end leaves ", _.map(leaves[1], (leaf) -> leaf.id)) return leaves _align_outer_edges_constraints: (horizontal) -> # console.log("#{if horizontal then 'horizontal' else 'vertical'} outer edge constraints in #{@get_layoutable_children().length}-#{@type}") [start_leaves, end_leaves] = @_find_edge_leaves(horizontal) if horizontal start_variable = 'on-edge-align-left' end_variable = 'on-edge-align-right' else start_variable = 'on-edge-align-top' end_variable = 'on-edge-align-bottom' collect_vars = (leaves, name) -> #console.log("collecting #{name} in ", leaves) edges = [] for leaf in leaves vars = leaf.get_constrained_variables() if name of vars edges.push(vars[name]) #vars[name]['_debug'] = "#{name} from #{leaf.id}" edges start_edges = collect_vars(start_leaves, start_variable) end_edges = collect_vars(end_leaves, end_variable) result = [] add_all_equal = (edges) -> if edges.length > 1 first = edges[0] for i in [1...edges.length] edge = edges[i] #console.log(" constraining #{first._debug} == #{edge._debug}") result.push(EQ([-1, first], edge)) null # prevent coffeescript from making a tmp array add_all_equal(start_edges) add_all_equal(end_edges) # console.log("computed constraints ", result) return result _box_insets_from_child_insets: (horizontal, child_variable_prefix, our_variable_prefix, minimum) -> [start_leaves, end_leaves] = @_find_edge_leaves(horizontal) if horizontal start_variable = "#{child_variable_prefix}-left" end_variable = "#{child_variable_prefix}-right" our_start = @["#{our_variable_prefix}_left"] our_end = @["#{our_variable_prefix}_right"] else start_variable = "#{child_variable_prefix}-top" end_variable = "#{child_variable_prefix}-bottom" our_start = @["#{our_variable_prefix}_top"] our_end = @["#{our_variable_prefix}_bottom"] result = [] add_constraints = (ours, leaves, name) -> edges = [] for leaf in leaves vars = leaf.get_constrained_variables() if name of vars if minimum result.push(GE([-1, ours], vars[name])) else result.push(EQ([-1, ours], vars[name])) null # prevent coffeescript from making a tmp array add_constraints(our_start, start_leaves, start_variable) add_constraints(our_end, end_leaves, end_variable) return result _box_equal_size_bounds: (horizontal) -> # false = box bounds equal all outer child bounds exactly @_box_insets_from_child_insets(horizontal, 'box-equal-size', '_box_equal_size', false) _box_cell_align_bounds: (horizontal) -> # false = box bounds equal all outer child bounds exactly @_box_insets_from_child_insets(horizontal, 'box-cell-align', '_box_cell_align', false) _box_whitespace: (horizontal) -> # true = box whitespace must be the minimum of child # whitespaces (i.e. distance from box edge to the outermost # child pixels) @_box_insets_from_child_insets(horizontal, 'whitespace', '_whitespace', true) @_left_right_inner_cell_edge_variables = [ 'box-cell-align-left', 'box-cell-align-right' ] @_top_bottom_inner_cell_edge_variables = [ 'box-cell-align-top', 'box-cell-align-bottom' ] module.exports = Model: Box View: BoxView
[ { "context": "\nnikita = require '@nikitajs/core/lib'\n{tags, config} = require './test'\nthey ", "end": 28, "score": 0.7816126942634583, "start": 26, "tag": "USERNAME", "value": "js" }, { "context": "/$basearch/\n gpgcheck=1\n gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY...
packages/tools/test/repo.coffee
adaltas/node-nikita
31
nikita = require '@nikitajs/core/lib' {tags, config} = require './test' they = require('mocha-they')(config) return unless tags.tools_repo describe 'tools.repo', -> @timeout 200000 they 'Write with source option', ({ssh}) -> nikita $ssh: ssh $tmpdir: true , ({metadata: {tmpdir}}) -> @fs.mkdir "#{tmpdir}/repo" @file target: "#{tmpdir}/CentOS.repo" content: """ [base] name=CentOS-$releasever - Base mirrorlist=http://localhost?release=$releasever&arch=$basearch&repo=os&infra=$infra baseurl=http://localhost/centos/$releasever/os/$basearch/ gpgcheck=1 gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7 """ {$status} = await @tools.repo source: "#{tmpdir}/CentOS.repo" target: "#{tmpdir}/repo/centos.repo" $status.should.be.true() {$status} = await @tools.repo source: "#{tmpdir}/CentOS.repo" target: "#{tmpdir}/repo/centos.repo" {$status} = await $status.should.be.false() @fs.assert "#{tmpdir}/repo/centos.repo" they 'Write with content option', ({ssh}) -> nikita $ssh: ssh $tmpdir: true , ({metadata: {tmpdir}}) -> @fs.mkdir "#{tmpdir}/repo" {$status} = await @tools.repo target: "#{tmpdir}/repo/centos.repo" content: 'base': 'name':'CentOS-$releasever - Base' 'baseurl':'http://mirror.centos.org/centos/$releasever/os/$basearch/' 'gpgcheck':'0' $status.should.be.true() {$status} = await @tools.repo target: "#{tmpdir}/repo/centos.repo" content: 'base': 'name':'CentOS-$releasever - Base' 'baseurl':'http://mirror.centos.org/centos/$releasever/os/$basearch/' 'gpgcheck':'0' $status.should.be.false() @fs.assert target: "#{tmpdir}/repo/centos.repo" content: '[base]\nname = CentOS-$releasever - Base\nbaseurl = http://mirror.centos.org/centos/$releasever/os/$basearch/\ngpgcheck = 0\n' they 'delete files with clean option', ({ssh}) -> nikita $ssh: ssh $tmpdir: true , ({metadata: {tmpdir}}) -> await @file target: "#{tmpdir}/source/CentOS.repo" content: """ [base] name=CentOS-$releasever - Base mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=os&infra=$infra baseurl=http://mirror.centos.org/centos/$releasever/os/$basearch/ gpgcheck=1 gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7 """ await @tools.repo source: "#{tmpdir}/source/CentOS.repo" target: "#{tmpdir}/target/CentOS.repo" {$status} = await @tools.repo source: "#{tmpdir}/source/CentOS.repo" target: "#{tmpdir}/target/CentOS.repo" clean: 'test*' $status.should.be.false() await @file.touch target: "#{tmpdir}/target/test.repo" {$status} = await @tools.repo source: "#{tmpdir}/source/CentOS.repo" target: "#{tmpdir}/target/CentOS.repo" clean: "test*" $status.should.be.true() await @fs.assert target: "#{tmpdir}/target/test.repo" not: true they 'Download GPG Keys option', ({ssh}) -> nikita $ssh: ssh $tmpdir: true , ({metadata: {tmpdir}}) -> await @file target: "#{tmpdir}/linuxtech.repo" content: """ [linuxtech-release] name=LinuxTECH.NET el6 main repo baseurl=http://linuxsoft.cern.ch/linuxtech/el6/release/ mirrorlist=http://pkgrepo.linuxtech.net/el6/release/mirrorlist.txt mirrorlist_expire=7d enabled=1 gpgcheck=1 gpgkey=http://pkgrepo.linuxtech.net/el6/release/RPM-GPG-KEY-LinuxTECH.NET """ await @tools.repo source: "#{tmpdir}/linuxtech.repo" gpg_dir: "#{tmpdir}" update: false await @fs.assert "#{tmpdir}/RPM-GPG-KEY-LinuxTECH.NET" they 'Download repo from remote location', ({ssh}) -> nikita $ssh: ssh , -> await @fs.remove '/etc/yum.repos.d/linuxtech.repo' {$status} = await @tools.repo source: "http://pkgrepo.linuxtech.net/el6/release/linuxtech.repo" $status.should.be.true() {$status} = await @tools.repo source: "http://pkgrepo.linuxtech.net/el6/release/linuxtech.repo" $status.should.be.false() await @fs.assert '/etc/yum.repos.d/linuxtech.repo' they 'Do Not update Package', ({ssh}) -> nikita $ssh: ssh , -> await @fs.remove '/etc/yum.repos.d/mongodb.repo' await @service.remove 'mongodb-org-shell' {$status} = await @tools.repo target: '/etc/yum.repos.d/mongodb.repo' content: 'mongodb-org-3.2': 'name':'MongoDB Repository' 'baseurl':'https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/3.2/x86_64/' 'gpgcheck':'1' 'enabled':'1' 'gpgkey':'https://www.mongodb.org/static/pgp/server-3.2.asc' await @service.install name: 'mongodb-org-shell' await @execute command: "mongo --version | grep shell | awk '{ print $4 }' | grep '3.2'" {$status} = await @tools.repo target: '/etc/yum.repos.d/mongodb.repo' content: 'mongodb-org-3.4': 'name':'MongoDB Repository' 'baseurl':'https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/3.4/x86_64/' 'gpgcheck':'1' 'enabled':'1' 'gpgkey':'https://www.mongodb.org/static/pgp/server-3.4.asc' $status.should.be.true() {$status} = await @tools.repo target: '/etc/yum.repos.d/mongodb.repo' content: 'mongodb-org-3.4': 'name':'MongoDB Repository' 'baseurl':'https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/3.4/x86_64/' 'gpgcheck':'1' 'enabled':'1' 'gpgkey':'https://www.mongodb.org/static/pgp/server-3.4.asc' $status.should.be.false() await @execute command: "mongo --version | grep shell | awk '{ print $4 }' | grep '3.2'" they 'Update Package', ({ssh}) -> nikita $ssh: ssh , -> await @fs.remove '/etc/yum.repos.d/mongodb.repo' await @fs.remove '/etc/pki/rpm-gpg/server-3.2.asc' await @fs.remove '/etc/pki/rpm-gpg/server-3.4.asc' await @service.remove 'mongodb-org-shell' await @tools.repo target: '/etc/yum.repos.d/mongodb.repo' content: 'mongodb-org-3.2': 'name':'MongoDB Repository' 'baseurl':'https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/3.2/x86_64/' 'gpgcheck':'1' 'enabled':'1' 'gpgkey':'https://www.mongodb.org/static/pgp/server-3.2.asc' await @service.install name: 'mongodb-org-shell' await @execute command: "mongo --version | grep shell | awk '{ print $4 }' | grep '3.2'" {$status} = await @tools.repo target: '/etc/yum.repos.d/mongodb.repo' update: true content: 'mongodb-org-3.4': 'name':'MongoDB Repository' 'baseurl':'https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/3.4/x86_64/' 'gpgcheck':'1' 'enabled':'1' 'gpgkey':'https://www.mongodb.org/static/pgp/server-3.4.asc' $status.should.be.true() {$status} = await @tools.repo target: '/etc/yum.repos.d/mongodb.repo' update: true content: 'mongodb-org-3.4': 'name':'MongoDB Repository' 'baseurl':'https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/3.4/x86_64/' 'gpgcheck':'1' 'enabled':'1' 'gpgkey':'https://www.mongodb.org/static/pgp/server-3.4.asc' $status.should.be.false() await @execute command: "mongo --version | grep shell | awk '{ print $4 }' | grep '3.4'"
201498
nikita = require '@nikitajs/core/lib' {tags, config} = require './test' they = require('mocha-they')(config) return unless tags.tools_repo describe 'tools.repo', -> @timeout 200000 they 'Write with source option', ({ssh}) -> nikita $ssh: ssh $tmpdir: true , ({metadata: {tmpdir}}) -> @fs.mkdir "#{tmpdir}/repo" @file target: "#{tmpdir}/CentOS.repo" content: """ [base] name=CentOS-$releasever - Base mirrorlist=http://localhost?release=$releasever&arch=$basearch&repo=os&infra=$infra baseurl=http://localhost/centos/$releasever/os/$basearch/ gpgcheck=1 gpgkey=file:///<KEY> """ {$status} = await @tools.repo source: "#{tmpdir}/CentOS.repo" target: "#{tmpdir}/repo/centos.repo" $status.should.be.true() {$status} = await @tools.repo source: "#{tmpdir}/CentOS.repo" target: "#{tmpdir}/repo/centos.repo" {$status} = await $status.should.be.false() @fs.assert "#{tmpdir}/repo/centos.repo" they 'Write with content option', ({ssh}) -> nikita $ssh: ssh $tmpdir: true , ({metadata: {tmpdir}}) -> @fs.mkdir "#{tmpdir}/repo" {$status} = await @tools.repo target: "#{tmpdir}/repo/centos.repo" content: 'base': 'name':'CentOS-$releasever - Base' 'baseurl':'http://mirror.centos.org/centos/$releasever/os/$basearch/' 'gpgcheck':'0' $status.should.be.true() {$status} = await @tools.repo target: "#{tmpdir}/repo/centos.repo" content: 'base': 'name':'CentOS-$releasever - Base' 'baseurl':'http://mirror.centos.org/centos/$releasever/os/$basearch/' 'gpgcheck':'0' $status.should.be.false() @fs.assert target: "#{tmpdir}/repo/centos.repo" content: '[base]\nname = CentOS-$releasever - Base\nbaseurl = http://mirror.centos.org/centos/$releasever/os/$basearch/\ngpgcheck = 0\n' they 'delete files with clean option', ({ssh}) -> nikita $ssh: ssh $tmpdir: true , ({metadata: {tmpdir}}) -> await @file target: "#{tmpdir}/source/CentOS.repo" content: """ [base] name=CentOS-$releasever - Base mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=os&infra=$infra baseurl=http://mirror.centos.org/centos/$releasever/os/$basearch/ gpgcheck=1 gpgkey=file:///<KEY> """ await @tools.repo source: "#{tmpdir}/source/CentOS.repo" target: "#{tmpdir}/target/CentOS.repo" {$status} = await @tools.repo source: "#{tmpdir}/source/CentOS.repo" target: "#{tmpdir}/target/CentOS.repo" clean: 'test*' $status.should.be.false() await @file.touch target: "#{tmpdir}/target/test.repo" {$status} = await @tools.repo source: "#{tmpdir}/source/CentOS.repo" target: "#{tmpdir}/target/CentOS.repo" clean: "test*" $status.should.be.true() await @fs.assert target: "#{tmpdir}/target/test.repo" not: true they 'Download GPG Keys option', ({ssh}) -> nikita $ssh: ssh $tmpdir: true , ({metadata: {tmpdir}}) -> await @file target: "#{tmpdir}/linuxtech.repo" content: """ [linuxtech-release] name=LinuxTECH.NET el6 main repo baseurl=http://linuxsoft.cern.ch/linuxtech/el6/release/ mirrorlist=http://pkgrepo.linuxtech.net/el6/release/mirrorlist.txt mirrorlist_expire=7d enabled=1 gpgcheck=1 gpgkey=http://pkgrepo.linuxtech.net/el6/release/RPM-GPG-KEY-LinuxTECH.NET """ await @tools.repo source: "#{tmpdir}/linuxtech.repo" gpg_dir: "#{tmpdir}" update: false await @fs.assert "#{tmpdir}/RPM-GPG-KEY-LinuxTECH.NET" they 'Download repo from remote location', ({ssh}) -> nikita $ssh: ssh , -> await @fs.remove '/etc/yum.repos.d/linuxtech.repo' {$status} = await @tools.repo source: "http://pkgrepo.linuxtech.net/el6/release/linuxtech.repo" $status.should.be.true() {$status} = await @tools.repo source: "http://pkgrepo.linuxtech.net/el6/release/linuxtech.repo" $status.should.be.false() await @fs.assert '/etc/yum.repos.d/linuxtech.repo' they 'Do Not update Package', ({ssh}) -> nikita $ssh: ssh , -> await @fs.remove '/etc/yum.repos.d/mongodb.repo' await @service.remove 'mongodb-org-shell' {$status} = await @tools.repo target: '/etc/yum.repos.d/mongodb.repo' content: 'mongodb-org-3.2': 'name':'MongoDB Repository' 'baseurl':'https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/3.2/x86_64/' 'gpgcheck':'1' 'enabled':'1' 'gpgkey':'https://www.mongodb.org/static/<KEY>/server<KEY>-3.2.<KEY>' await @service.install name: 'mongodb-org-shell' await @execute command: "mongo --version | grep shell | awk '{ print $4 }' | grep '3.2'" {$status} = await @tools.repo target: '/etc/yum.repos.d/mongodb.repo' content: 'mongodb-org-3.4': 'name':'MongoDB Repository' 'baseurl':'https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/3.4/x86_64/' 'gpgcheck':'1' 'enabled':'1' 'gpgkey':'https<KEY>://www.mongodb.org/static/<KEY>server-3.4.asc' $status.should.be.true() {$status} = await @tools.repo target: '/etc/yum.repos.d/mongodb.repo' content: 'mongodb-org-3.4': 'name':'MongoDB Repository' 'baseurl':'https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/3.4/x86_64/' 'gpgcheck':'1' 'enabled':'1' 'gpgkey':'https<KEY>://www.mongodb.org/static/<KEY>server-3.4.<KEY>' $status.should.be.false() await @execute command: "mongo --version | grep shell | awk '{ print $4 }' | grep '3.2'" they 'Update Package', ({ssh}) -> nikita $ssh: ssh , -> await @fs.remove '/etc/yum.repos.d/mongodb.repo' await @fs.remove '/etc/pki/rpm-gpg/server-3.2.asc' await @fs.remove '/etc/pki/rpm-gpg/server-3.4.asc' await @service.remove 'mongodb-org-shell' await @tools.repo target: '/etc/yum.repos.d/mongodb.repo' content: 'mongodb-org-3.2': 'name':'MongoDB Repository' 'baseurl':'https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/3.2/x86_64/' 'gpgcheck':'1' 'enabled':'1' 'gpgkey':'https://www.mongodb.org/static/pgp/server-3.2.asc' await @service.install name: 'mongodb-org-shell' await @execute command: "mongo --version | grep shell | awk '{ print $4 }' | grep '3.2'" {$status} = await @tools.repo target: '/etc/yum.repos.d/mongodb.repo' update: true content: 'mongodb-org-3.4': 'name':'MongoDB Repository' 'baseurl':'https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/3.4/x86_64/' 'gpgcheck':'1' 'enabled':'1' 'gpgkey':'https://www.mongodb.org/static/pgp/server-3.4.asc' $status.should.be.true() {$status} = await @tools.repo target: '/etc/yum.repos.d/mongodb.repo' update: true content: 'mongodb-org-3.4': 'name':'MongoDB Repository' 'baseurl':'https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/3.4/x86_64/' 'gpgcheck':'1' 'enabled':'1' 'gpgkey':'https://www.mongodb.org/static/pgp/server-3.4.asc' $status.should.be.false() await @execute command: "mongo --version | grep shell | awk '{ print $4 }' | grep '3.4'"
true
nikita = require '@nikitajs/core/lib' {tags, config} = require './test' they = require('mocha-they')(config) return unless tags.tools_repo describe 'tools.repo', -> @timeout 200000 they 'Write with source option', ({ssh}) -> nikita $ssh: ssh $tmpdir: true , ({metadata: {tmpdir}}) -> @fs.mkdir "#{tmpdir}/repo" @file target: "#{tmpdir}/CentOS.repo" content: """ [base] name=CentOS-$releasever - Base mirrorlist=http://localhost?release=$releasever&arch=$basearch&repo=os&infra=$infra baseurl=http://localhost/centos/$releasever/os/$basearch/ gpgcheck=1 gpgkey=file:///PI:KEY:<KEY>END_PI """ {$status} = await @tools.repo source: "#{tmpdir}/CentOS.repo" target: "#{tmpdir}/repo/centos.repo" $status.should.be.true() {$status} = await @tools.repo source: "#{tmpdir}/CentOS.repo" target: "#{tmpdir}/repo/centos.repo" {$status} = await $status.should.be.false() @fs.assert "#{tmpdir}/repo/centos.repo" they 'Write with content option', ({ssh}) -> nikita $ssh: ssh $tmpdir: true , ({metadata: {tmpdir}}) -> @fs.mkdir "#{tmpdir}/repo" {$status} = await @tools.repo target: "#{tmpdir}/repo/centos.repo" content: 'base': 'name':'CentOS-$releasever - Base' 'baseurl':'http://mirror.centos.org/centos/$releasever/os/$basearch/' 'gpgcheck':'0' $status.should.be.true() {$status} = await @tools.repo target: "#{tmpdir}/repo/centos.repo" content: 'base': 'name':'CentOS-$releasever - Base' 'baseurl':'http://mirror.centos.org/centos/$releasever/os/$basearch/' 'gpgcheck':'0' $status.should.be.false() @fs.assert target: "#{tmpdir}/repo/centos.repo" content: '[base]\nname = CentOS-$releasever - Base\nbaseurl = http://mirror.centos.org/centos/$releasever/os/$basearch/\ngpgcheck = 0\n' they 'delete files with clean option', ({ssh}) -> nikita $ssh: ssh $tmpdir: true , ({metadata: {tmpdir}}) -> await @file target: "#{tmpdir}/source/CentOS.repo" content: """ [base] name=CentOS-$releasever - Base mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=os&infra=$infra baseurl=http://mirror.centos.org/centos/$releasever/os/$basearch/ gpgcheck=1 gpgkey=file:///PI:KEY:<KEY>END_PI """ await @tools.repo source: "#{tmpdir}/source/CentOS.repo" target: "#{tmpdir}/target/CentOS.repo" {$status} = await @tools.repo source: "#{tmpdir}/source/CentOS.repo" target: "#{tmpdir}/target/CentOS.repo" clean: 'test*' $status.should.be.false() await @file.touch target: "#{tmpdir}/target/test.repo" {$status} = await @tools.repo source: "#{tmpdir}/source/CentOS.repo" target: "#{tmpdir}/target/CentOS.repo" clean: "test*" $status.should.be.true() await @fs.assert target: "#{tmpdir}/target/test.repo" not: true they 'Download GPG Keys option', ({ssh}) -> nikita $ssh: ssh $tmpdir: true , ({metadata: {tmpdir}}) -> await @file target: "#{tmpdir}/linuxtech.repo" content: """ [linuxtech-release] name=LinuxTECH.NET el6 main repo baseurl=http://linuxsoft.cern.ch/linuxtech/el6/release/ mirrorlist=http://pkgrepo.linuxtech.net/el6/release/mirrorlist.txt mirrorlist_expire=7d enabled=1 gpgcheck=1 gpgkey=http://pkgrepo.linuxtech.net/el6/release/RPM-GPG-KEY-LinuxTECH.NET """ await @tools.repo source: "#{tmpdir}/linuxtech.repo" gpg_dir: "#{tmpdir}" update: false await @fs.assert "#{tmpdir}/RPM-GPG-KEY-LinuxTECH.NET" they 'Download repo from remote location', ({ssh}) -> nikita $ssh: ssh , -> await @fs.remove '/etc/yum.repos.d/linuxtech.repo' {$status} = await @tools.repo source: "http://pkgrepo.linuxtech.net/el6/release/linuxtech.repo" $status.should.be.true() {$status} = await @tools.repo source: "http://pkgrepo.linuxtech.net/el6/release/linuxtech.repo" $status.should.be.false() await @fs.assert '/etc/yum.repos.d/linuxtech.repo' they 'Do Not update Package', ({ssh}) -> nikita $ssh: ssh , -> await @fs.remove '/etc/yum.repos.d/mongodb.repo' await @service.remove 'mongodb-org-shell' {$status} = await @tools.repo target: '/etc/yum.repos.d/mongodb.repo' content: 'mongodb-org-3.2': 'name':'MongoDB Repository' 'baseurl':'https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/3.2/x86_64/' 'gpgcheck':'1' 'enabled':'1' 'gpgkey':'https://www.mongodb.org/static/PI:KEY:<KEY>END_PI/serverPI:KEY:<KEY>END_PI-3.2.PI:KEY:<KEY>END_PI' await @service.install name: 'mongodb-org-shell' await @execute command: "mongo --version | grep shell | awk '{ print $4 }' | grep '3.2'" {$status} = await @tools.repo target: '/etc/yum.repos.d/mongodb.repo' content: 'mongodb-org-3.4': 'name':'MongoDB Repository' 'baseurl':'https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/3.4/x86_64/' 'gpgcheck':'1' 'enabled':'1' 'gpgkey':'httpsPI:KEY:<KEY>END_PI://www.mongodb.org/static/PI:KEY:<KEY>END_PIserver-3.4.asc' $status.should.be.true() {$status} = await @tools.repo target: '/etc/yum.repos.d/mongodb.repo' content: 'mongodb-org-3.4': 'name':'MongoDB Repository' 'baseurl':'https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/3.4/x86_64/' 'gpgcheck':'1' 'enabled':'1' 'gpgkey':'httpsPI:KEY:<KEY>END_PI://www.mongodb.org/static/PI:KEY:<KEY>END_PIserver-3.4.PI:KEY:<KEY>END_PI' $status.should.be.false() await @execute command: "mongo --version | grep shell | awk '{ print $4 }' | grep '3.2'" they 'Update Package', ({ssh}) -> nikita $ssh: ssh , -> await @fs.remove '/etc/yum.repos.d/mongodb.repo' await @fs.remove '/etc/pki/rpm-gpg/server-3.2.asc' await @fs.remove '/etc/pki/rpm-gpg/server-3.4.asc' await @service.remove 'mongodb-org-shell' await @tools.repo target: '/etc/yum.repos.d/mongodb.repo' content: 'mongodb-org-3.2': 'name':'MongoDB Repository' 'baseurl':'https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/3.2/x86_64/' 'gpgcheck':'1' 'enabled':'1' 'gpgkey':'https://www.mongodb.org/static/pgp/server-3.2.asc' await @service.install name: 'mongodb-org-shell' await @execute command: "mongo --version | grep shell | awk '{ print $4 }' | grep '3.2'" {$status} = await @tools.repo target: '/etc/yum.repos.d/mongodb.repo' update: true content: 'mongodb-org-3.4': 'name':'MongoDB Repository' 'baseurl':'https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/3.4/x86_64/' 'gpgcheck':'1' 'enabled':'1' 'gpgkey':'https://www.mongodb.org/static/pgp/server-3.4.asc' $status.should.be.true() {$status} = await @tools.repo target: '/etc/yum.repos.d/mongodb.repo' update: true content: 'mongodb-org-3.4': 'name':'MongoDB Repository' 'baseurl':'https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/3.4/x86_64/' 'gpgcheck':'1' 'enabled':'1' 'gpgkey':'https://www.mongodb.org/static/pgp/server-3.4.asc' $status.should.be.false() await @execute command: "mongo --version | grep shell | awk '{ print $4 }' | grep '3.4'"
[ { "context": " on jQuery UI\n###\n\nlast_name_options =\n id: 'last_name' # the parser name\n ", "end": 103, "score": 0.9880213737487793, "start": 94, "tag": "NAME", "value": "last_name" } ]
app/assets/javascripts/messages/messages_show_table.js.coffee
andyl/BAMRU-Private
1
### Used to sort photos (drag & drop) Relies on jQuery UI ### last_name_options = id: 'last_name' # the parser name is: (s) -> false # disable standard parser type: 'text' # either text or numeric format: (s) -> (new MemberName(s)).last_name() # the sort key (last name) sort_opts = headers: 0: {sorter: 'last_name'} 4: {sorter: false } filter_params = filterContainer: "#filter-box" filterClearContainer: "#filter-clear-button" filterColumns: [0,1,2,3] columns: ["recipient", "updated", "read", "rsvp"] save_msg_sort_to_cookie = (sort_spec) -> spec_string = JSON.stringify(sort_spec) createCookie("msg_sort", spec_string) window.read_msg_sort_from_cookie = -> string = readCookie("msg_sort") if (string == null) then null else JSON.parse(string) $(document).ready -> $.tablesorter.addParser last_name_options sort_spec = read_msg_sort_from_cookie() sort_opts['sortList'] = sort_spec unless sort_spec == null $("#myTable").tablesorter(sort_opts).bind "sortEnd", (sorter) -> save_msg_sort_to_cookie(sorter.target.config.sortList) $("#myTable").tablesorterFilter(filter_params) $("#filter-box").focus() $(document).ready -> $('#clearsort').click -> eraseCookie("msg_sort") refresh_url = window.location.href.split(/[?#]/, 1) window.location.assign(refresh_url)
142653
### Used to sort photos (drag & drop) Relies on jQuery UI ### last_name_options = id: '<NAME>' # the parser name is: (s) -> false # disable standard parser type: 'text' # either text or numeric format: (s) -> (new MemberName(s)).last_name() # the sort key (last name) sort_opts = headers: 0: {sorter: 'last_name'} 4: {sorter: false } filter_params = filterContainer: "#filter-box" filterClearContainer: "#filter-clear-button" filterColumns: [0,1,2,3] columns: ["recipient", "updated", "read", "rsvp"] save_msg_sort_to_cookie = (sort_spec) -> spec_string = JSON.stringify(sort_spec) createCookie("msg_sort", spec_string) window.read_msg_sort_from_cookie = -> string = readCookie("msg_sort") if (string == null) then null else JSON.parse(string) $(document).ready -> $.tablesorter.addParser last_name_options sort_spec = read_msg_sort_from_cookie() sort_opts['sortList'] = sort_spec unless sort_spec == null $("#myTable").tablesorter(sort_opts).bind "sortEnd", (sorter) -> save_msg_sort_to_cookie(sorter.target.config.sortList) $("#myTable").tablesorterFilter(filter_params) $("#filter-box").focus() $(document).ready -> $('#clearsort').click -> eraseCookie("msg_sort") refresh_url = window.location.href.split(/[?#]/, 1) window.location.assign(refresh_url)
true
### Used to sort photos (drag & drop) Relies on jQuery UI ### last_name_options = id: 'PI:NAME:<NAME>END_PI' # the parser name is: (s) -> false # disable standard parser type: 'text' # either text or numeric format: (s) -> (new MemberName(s)).last_name() # the sort key (last name) sort_opts = headers: 0: {sorter: 'last_name'} 4: {sorter: false } filter_params = filterContainer: "#filter-box" filterClearContainer: "#filter-clear-button" filterColumns: [0,1,2,3] columns: ["recipient", "updated", "read", "rsvp"] save_msg_sort_to_cookie = (sort_spec) -> spec_string = JSON.stringify(sort_spec) createCookie("msg_sort", spec_string) window.read_msg_sort_from_cookie = -> string = readCookie("msg_sort") if (string == null) then null else JSON.parse(string) $(document).ready -> $.tablesorter.addParser last_name_options sort_spec = read_msg_sort_from_cookie() sort_opts['sortList'] = sort_spec unless sort_spec == null $("#myTable").tablesorter(sort_opts).bind "sortEnd", (sorter) -> save_msg_sort_to_cookie(sorter.target.config.sortList) $("#myTable").tablesorterFilter(filter_params) $("#filter-box").focus() $(document).ready -> $('#clearsort').click -> eraseCookie("msg_sort") refresh_url = window.location.href.split(/[?#]/, 1) window.location.assign(refresh_url)
[ { "context": "'\n values: [\n ['Toyota', 100]\n ['Honda', 80]\n ['Mazda', 70]\n ['Prius', 10]", "end": 158, "score": 0.6245457530021667, "start": 153, "tag": "NAME", "value": "Honda" }, { "context": " ['Toyota', 100]\n ['Honda', 80]\n ['M...
examples/src/app-bar-horizontal.coffee
robinfhu/forest-d3
58
chart = new ForestD3.BarChart '#example' data = [ key: 'series1' label: 'Long' color: '#555' values: [ ['Toyota', 100] ['Honda', 80] ['Mazda', 70] ['Prius', 10] ['Ford F150', 87] ['Hyundai', 23.4] ['Chrysler', 1] ['Lincoln', 102] ['Accord', -60] ['Hummer', -5.6] ['Dodge', -11] ] ] chart.data(data).render() chart.sortBy((d)-> d[1]) sortDir = 0 document.getElementById('sort-button').addEventListener 'click', -> chart.sortDirection(if sortDir is 0 then 'asc' else 'desc').render() sortDir = 1 - sortDir
193918
chart = new ForestD3.BarChart '#example' data = [ key: 'series1' label: 'Long' color: '#555' values: [ ['Toyota', 100] ['<NAME>', 80] ['<NAME>', 70] ['<NAME>', 10] ['Ford F150', 87] ['<NAME>', 23.4] ['<NAME>', 1] ['<NAME>', 102] ['<NAME>', -60] ['<NAME>', -5.6] ['<NAME>', -11] ] ] chart.data(data).render() chart.sortBy((d)-> d[1]) sortDir = 0 document.getElementById('sort-button').addEventListener 'click', -> chart.sortDirection(if sortDir is 0 then 'asc' else 'desc').render() sortDir = 1 - sortDir
true
chart = new ForestD3.BarChart '#example' data = [ key: 'series1' label: 'Long' color: '#555' values: [ ['Toyota', 100] ['PI:NAME:<NAME>END_PI', 80] ['PI:NAME:<NAME>END_PI', 70] ['PI:NAME:<NAME>END_PI', 10] ['Ford F150', 87] ['PI:NAME:<NAME>END_PI', 23.4] ['PI:NAME:<NAME>END_PI', 1] ['PI:NAME:<NAME>END_PI', 102] ['PI:NAME:<NAME>END_PI', -60] ['PI:NAME:<NAME>END_PI', -5.6] ['PI:NAME:<NAME>END_PI', -11] ] ] chart.data(data).render() chart.sortBy((d)-> d[1]) sortDir = 0 document.getElementById('sort-button').addEventListener 'click', -> chart.sortDirection(if sortDir is 0 then 'asc' else 'desc').render() sortDir = 1 - sortDir
[ { "context": "name: 'me'\ncycleMarkers: [\n\t{\n\t\ttype: 'greedy'\n\t\tvalue: 'ac", "end": 9, "score": 0.5842705368995667, "start": 7, "tag": "NAME", "value": "me" } ]
commands/commands/me.cson
Czaplicki/mcfunction-support-data
0
name: 'me' cycleMarkers: [ { type: 'greedy' value: 'action' } ]
55348
name: '<NAME>' cycleMarkers: [ { type: 'greedy' value: 'action' } ]
true
name: 'PI:NAME:<NAME>END_PI' cycleMarkers: [ { type: 'greedy' value: 'action' } ]
[ { "context": "ow.fbAsyncInit = ->\n FB.init({\n appId : '719174448253674',\n xfbml : true,\n version : 'v2.8'\n", "end": 318, "score": 0.9531831741333008, "start": 303, "tag": "KEY", "value": "719174448253674" } ]
focas-web/app/assets/javascripts/home.coffee
MoonCheesez/focas-web
0
# Place all the behaviors and hooks related to the matching controller here. # All this logic will automatically be available in application.js. # You can use CoffeeScript in this file: http://coffeescript.org/ facebook_button = "#facebook-login" window.fbAsyncInit = -> FB.init({ appId : '719174448253674', xfbml : true, version : 'v2.8' }) FB.getLoginStatus((response) -> if response.status == "connected" display_quote() else $(facebook_button).show() ) PageScript = document.getElementsByTagName("script")[0] return if document.getElementById("FBScript") FBScript = document.createElement("script") FBScript.id = "FBScript" FBScript.async = true FBScript.src = "//connect.facebook.net/en_US/all.js" PageScript.parentNode.insertBefore(FBScript, PageScript) window.login = -> r = (response) -> if response.authResponse display_quote() FB.login(r, {scope: 'user_posts,publish_actions'}) window.display_quote = -> $("#login").fadeOut(1000) $("#background").addClass("blur") $("#quote").fadeIn(1000) start_tracking() window.out_of_focus = -> $("#background").removeClass("blur") $("#quote").addClass("blur") window.in_focus = -> $("#background").addClass("blur") $("#quote").removeClass("blur") send_message = (m) -> FB.api('/me/feed', 'post', {message: m}, (response) -> return response ) start_tracking = -> eventHandler = (e) -> prevType = $(this).data("prevType") if prevType != e.type switch (e.type) when "blur" send_message("Slacking off, motivate me to carry on.") out_of_focus() break when "focus" send_message("Working hard, do not disturb.") in_focus() break $(this).data("prevType", e.type) $(window).on("blur focus", eventHandler)
12002
# Place all the behaviors and hooks related to the matching controller here. # All this logic will automatically be available in application.js. # You can use CoffeeScript in this file: http://coffeescript.org/ facebook_button = "#facebook-login" window.fbAsyncInit = -> FB.init({ appId : '<KEY>', xfbml : true, version : 'v2.8' }) FB.getLoginStatus((response) -> if response.status == "connected" display_quote() else $(facebook_button).show() ) PageScript = document.getElementsByTagName("script")[0] return if document.getElementById("FBScript") FBScript = document.createElement("script") FBScript.id = "FBScript" FBScript.async = true FBScript.src = "//connect.facebook.net/en_US/all.js" PageScript.parentNode.insertBefore(FBScript, PageScript) window.login = -> r = (response) -> if response.authResponse display_quote() FB.login(r, {scope: 'user_posts,publish_actions'}) window.display_quote = -> $("#login").fadeOut(1000) $("#background").addClass("blur") $("#quote").fadeIn(1000) start_tracking() window.out_of_focus = -> $("#background").removeClass("blur") $("#quote").addClass("blur") window.in_focus = -> $("#background").addClass("blur") $("#quote").removeClass("blur") send_message = (m) -> FB.api('/me/feed', 'post', {message: m}, (response) -> return response ) start_tracking = -> eventHandler = (e) -> prevType = $(this).data("prevType") if prevType != e.type switch (e.type) when "blur" send_message("Slacking off, motivate me to carry on.") out_of_focus() break when "focus" send_message("Working hard, do not disturb.") in_focus() break $(this).data("prevType", e.type) $(window).on("blur focus", eventHandler)
true
# Place all the behaviors and hooks related to the matching controller here. # All this logic will automatically be available in application.js. # You can use CoffeeScript in this file: http://coffeescript.org/ facebook_button = "#facebook-login" window.fbAsyncInit = -> FB.init({ appId : 'PI:KEY:<KEY>END_PI', xfbml : true, version : 'v2.8' }) FB.getLoginStatus((response) -> if response.status == "connected" display_quote() else $(facebook_button).show() ) PageScript = document.getElementsByTagName("script")[0] return if document.getElementById("FBScript") FBScript = document.createElement("script") FBScript.id = "FBScript" FBScript.async = true FBScript.src = "//connect.facebook.net/en_US/all.js" PageScript.parentNode.insertBefore(FBScript, PageScript) window.login = -> r = (response) -> if response.authResponse display_quote() FB.login(r, {scope: 'user_posts,publish_actions'}) window.display_quote = -> $("#login").fadeOut(1000) $("#background").addClass("blur") $("#quote").fadeIn(1000) start_tracking() window.out_of_focus = -> $("#background").removeClass("blur") $("#quote").addClass("blur") window.in_focus = -> $("#background").addClass("blur") $("#quote").removeClass("blur") send_message = (m) -> FB.api('/me/feed', 'post', {message: m}, (response) -> return response ) start_tracking = -> eventHandler = (e) -> prevType = $(this).data("prevType") if prevType != e.type switch (e.type) when "blur" send_message("Slacking off, motivate me to carry on.") out_of_focus() break when "focus" send_message("Working hard, do not disturb.") in_focus() break $(this).data("prevType", e.type) $(window).on("blur focus", eventHandler)
[ { "context": "##############\n# Title: Base View Class\n# Author: kevin@wintr.us @ WINTR\n#########################################", "end": 108, "score": 0.9998986124992371, "start": 94, "tag": "EMAIL", "value": "kevin@wintr.us" }, { "context": "Title: Base View Class\n# Author: k...
source/javascripts/views/supers/View.coffee
WikiEducationFoundation/WikiEduWizard
1
######################################################### # Title: Base View Class # Author: kevin@wintr.us @ WINTR ######################################################### require('../../helpers/ViewHelper') class View extends Backbone.View ###//-------------------------------------- //+ PUBLIC PROPERTIES / CONSTANTS //--------------------------------------### # # @private # template: -> # # @private # getRenderData: -> ###//-------------------------------------- //+ INHERITED / OVERRIDES //--------------------------------------### # # @private # initialize: -> @render = _.bind( @render, @ ) # # @private # render: -> @$el.html( @template( @getRenderData() ) ) @afterRender() return @ # # @private # afterRender: -> ###//-------------------------------------- //+ PUBLIC METHODS / GETTERS / SETTERS //--------------------------------------### ###//-------------------------------------- //+ EVENT HANDLERS //--------------------------------------### ###//-------------------------------------- //+ PRIVATE AND PROTECTED METHODS //--------------------------------------### module.exports = View
98475
######################################################### # Title: Base View Class # Author: <EMAIL> @ WINTR ######################################################### require('../../helpers/ViewHelper') class View extends Backbone.View ###//-------------------------------------- //+ PUBLIC PROPERTIES / CONSTANTS //--------------------------------------### # # @private # template: -> # # @private # getRenderData: -> ###//-------------------------------------- //+ INHERITED / OVERRIDES //--------------------------------------### # # @private # initialize: -> @render = _.bind( @render, @ ) # # @private # render: -> @$el.html( @template( @getRenderData() ) ) @afterRender() return @ # # @private # afterRender: -> ###//-------------------------------------- //+ PUBLIC METHODS / GETTERS / SETTERS //--------------------------------------### ###//-------------------------------------- //+ EVENT HANDLERS //--------------------------------------### ###//-------------------------------------- //+ PRIVATE AND PROTECTED METHODS //--------------------------------------### module.exports = View
true
######################################################### # Title: Base View Class # Author: PI:EMAIL:<EMAIL>END_PI @ WINTR ######################################################### require('../../helpers/ViewHelper') class View extends Backbone.View ###//-------------------------------------- //+ PUBLIC PROPERTIES / CONSTANTS //--------------------------------------### # # @private # template: -> # # @private # getRenderData: -> ###//-------------------------------------- //+ INHERITED / OVERRIDES //--------------------------------------### # # @private # initialize: -> @render = _.bind( @render, @ ) # # @private # render: -> @$el.html( @template( @getRenderData() ) ) @afterRender() return @ # # @private # afterRender: -> ###//-------------------------------------- //+ PUBLIC METHODS / GETTERS / SETTERS //--------------------------------------### ###//-------------------------------------- //+ EVENT HANDLERS //--------------------------------------### ###//-------------------------------------- //+ PRIVATE AND PROTECTED METHODS //--------------------------------------### module.exports = View
[ { "context": "ns(\"subscription\")').remove()\n $('span:contains(\"root@inbound.listboxer.com\")').remove()\n $('a:contains(\"click\")').remove()\n", "end": 446, "score": 0.9999004006385803, "start": 420, "tag": "EMAIL", "value": "root@inbound.listboxer.com" } ]
app/assets/javascripts/posts.coffee
rileygelwicks/listboxer
0
# Place all the behaviors and hooks related to the matching controller here. # All this logic will automatically be available in application.js. # You can use CoffeeScript in this file: http://coffeescript.org/ $(document).on "page:change", -> $('.unsubscribe').remove() $('a:contains("Unsubscribe")').remove() $('a:contains("unsubscribe")').remove() $('a:contains("subscription")').remove() $('span:contains("root@inbound.listboxer.com")').remove() $('a:contains("click")').remove()
2275
# Place all the behaviors and hooks related to the matching controller here. # All this logic will automatically be available in application.js. # You can use CoffeeScript in this file: http://coffeescript.org/ $(document).on "page:change", -> $('.unsubscribe').remove() $('a:contains("Unsubscribe")').remove() $('a:contains("unsubscribe")').remove() $('a:contains("subscription")').remove() $('span:contains("<EMAIL>")').remove() $('a:contains("click")').remove()
true
# Place all the behaviors and hooks related to the matching controller here. # All this logic will automatically be available in application.js. # You can use CoffeeScript in this file: http://coffeescript.org/ $(document).on "page:change", -> $('.unsubscribe').remove() $('a:contains("Unsubscribe")').remove() $('a:contains("unsubscribe")').remove() $('a:contains("subscription")').remove() $('span:contains("PI:EMAIL:<EMAIL>END_PI")').remove() $('a:contains("click")').remove()
[ { "context": "n CoffeeScript are not global by default\n\nname = \"Phil\"\n\n# Get access to the element with the id csoutpu", "end": 553, "score": 0.9964296221733093, "start": 549, "tag": "NAME", "value": "Phil" }, { "context": "<br>\")\n\n# ---------- STRINGS ----------\n\nfName = ...
banas-coffeescript/part-one.coffee
trevorfenner/programming-paradigms-example-code
2
# I'll use the NodeJS compiler to process CoffeeScript so download Node if you # don't have it here https://nodejs.org/en/ # Then in your terminal install CoffeeScript by typing # npm install -g coffee-script # You compile to a JS file with the same name but the js extension with # coffee --compile cstut.coffee # To auto compile use this in the terminal coffee -wc *.coffee ### Multiline Comment ### # ---------- INTRO ---------- # There is no var or semicolons in CoffeeScript # Variables in CoffeeScript are not global by default name = "Phil" # Get access to the element with the id csoutput csOutput = document.getElementById("csoutput") # Assign this string with the variable to it # Use double quotes for Interpolation csOutput.innerHTML = "Hello #{name}<br>" # ---------- VARIABLES ---------- # The data types are string, number, boolean, array, object, undefined # and null aString = "I'm a String" csOutput.insertAdjacentHTML('beforeend', 'aString is a String<br>') if typeof aString is 'string' largestNum = Number.MAX_VALUE smallestNum = Number.MIN_VALUE largeNumStr = "The largest number is #{largestNum}<br>" smallNumStr = "The smallest number is #{smallestNum}<br>" csOutput.insertAdjacentHTML('beforeend', largeNumStr) csOutput.insertAdjacentHTML('beforeend', smallNumStr) areYouHappy = no # Booleans have the value of (true, yes, or on) or (false, no, or off) csOutput.insertAdjacentHTML('beforeend', 'areYouHappy is a Boolean<br>') if typeof areYouHappy is 'boolean' # ---------- MATH ---------- csOutput.insertAdjacentHTML('beforeend', "5 + 2 = #{5 + 2}<br>") csOutput.insertAdjacentHTML('beforeend', "5 - 2 = #{5 - 2}<br>") csOutput.insertAdjacentHTML('beforeend', "5 * 2 = #{5 * 2}<br>") csOutput.insertAdjacentHTML('beforeend', "5 / 2 = #{5 / 2}<br>") csOutput.insertAdjacentHTML('beforeend', "5 % 2 = #{5 % 2}<br>") # CS has 16 digits of precision precisionTest = 0.1000000000000001; csOutput.insertAdjacentHTML('beforeend', "Precision : #{precisionTest + 0.10000000000000011}<br>") # Round to 2 digits balance = 1563.87 csOutput.insertAdjacentHTML('beforeend', "Monthly Payment = #{(balance/12).toFixed(2)}<br>") # Shortcut for adding 1 randNum = 5 csOutput.insertAdjacentHTML('beforeend', "randNum++ = #{randNum++}<br>") csOutput.insertAdjacentHTML('beforeend', "++randNum = #{++randNum}<br>") # Shortcut for subtracting 1 randNum = 5 csOutput.insertAdjacentHTML('beforeend', "randNum-- = #{randNum--}<br>") csOutput.insertAdjacentHTML('beforeend', "--randNum = #{--randNum}<br>") # Order of operations csOutput.insertAdjacentHTML('beforeend', "3 + 2 * 5 = #{3 + 2 * 5}<br>") csOutput.insertAdjacentHTML('beforeend', "(3 + 2) * 5 = #{(3 + 2) * 5}<br>") # Math properties and functions csOutput.insertAdjacentHTML('beforeend', "Math.E = #{Math.E}<br>") csOutput.insertAdjacentHTML('beforeend', "Math.PI = #{Math.PI}<br>") csOutput.insertAdjacentHTML('beforeend', "Math.abs(-8) = #{Math.abs(-8)}<br>") csOutput.insertAdjacentHTML('beforeend', "Math.cbrt(1000) = #{Math.cbrt(1000)}<br>") csOutput.insertAdjacentHTML('beforeend', "Math.ceil(6.45) = #{Math.ceil(6.45)}<br>") csOutput.insertAdjacentHTML('beforeend', "Math.floor(6.45) = #{Math.floor(6.45)}<br>") csOutput.insertAdjacentHTML('beforeend', "Math.round(6.45) = #{Math.round(6.45)}<br>") csOutput.insertAdjacentHTML('beforeend', "Math.log(10) = #{Math.log(10)}<br>") csOutput.insertAdjacentHTML('beforeend', "Math.log10(10) = #{Math.log10(10)}<br>") csOutput.insertAdjacentHTML('beforeend', "Math.pow(4,2) = #{Math.pow(4,2)}<br>") csOutput.insertAdjacentHTML('beforeend', "Math.sqrt(1000) = #{Math.sqrt(1000)}<br>") # Generate a random number randNum = Math.floor(Math.random() * 100) + 1 csOutput.insertAdjacentHTML('beforeend', "Random Number = #{randNum}<br>") # ---------- STRINGS ---------- fName = "Derek" lName = "Banas" # You can combine Strings with a + csOutput.insertAdjacentHTML('beforeend', fName + " " + lName + "<br>") longString = "This is a long string that goes on forever" # Get the String length csOutput.insertAdjacentHTML('beforeend', "String Length : #{longString.length}<br>") # Get the index of a matching string csOutput.insertAdjacentHTML('beforeend', "Index of string : #{longString.indexOf("goes")}<br>") # Get a character at an index csOutput.insertAdjacentHTML('beforeend', "Index 8 : #{longString.charAt(8)}<br>") # Get a substring csOutput.insertAdjacentHTML('beforeend', "Word at 27 : #{longString.slice(27,31)}<br>") # Get everything after an index csOutput.insertAdjacentHTML('beforeend', "After 27 : #{longString.slice(27)}<br>") # Replace a string with another longString = longString.replace("forever", "and on forever ") csOutput.insertAdjacentHTML('beforeend', "New String : #{longString}<br>") # Convert a string into an Array strArray = longString.split(" ") # Output an array for x in strArray csOutput.insertAdjacentHTML('beforeend', "#{x}<br>") # Trim whitespace longString = longString.trim() # Convert to all uppercase csOutput.insertAdjacentHTML('beforeend', "#{longString.toUpperCase()}<br>") # Convert to all lowercase csOutput.insertAdjacentHTML('beforeend', "#{longString.toLowerCase()}<br>") # ---------- CONDITIONALS ---------- # If works like JavaScript except with indentation and not curly brackets # Comparison operators are ==, !=, >, <, >=, <= # == and != in CS is the same as === and !== in JS age = 3 if age >= 18 # Insert text either beforebegin or beforeend csOutput.insertAdjacentHTML('beforeend', 'You can Vote<br>') if (age >= 16) csOutput.insertAdjacentHTML('beforeend', 'You can Drive also<br>') else if (age >= 16) csOutput.insertAdjacentHTML('beforeend', 'You can Drive<br>') else csOutput.insertAdjacentHTML('beforeend', 'You\'ll be 16 soon<br>') # Unless executes if the test returns false unless (age >= 19) csOutput.insertAdjacentHTML('beforeend', 'You are in school<br>') else csOutput.insertAdjacentHTML('beforeend', 'You may go to college<br>') # Logical operators are &&, || and ! hsGrad = true if !(age > 4) || (age > 65) csOutput.insertAdjacentHTML('beforeend', 'You don\'t go to school<br>') else if (age >= 5) && (age <= 6) csOutput.insertAdjacentHTML('beforeend', 'Go to Kindergarten<br>') else if (age > 6) && (age <= 18) schoolGrade = "Go to Grade #{age - 5}<br>" csOutput.insertAdjacentHTML('beforeend', schoolGrade) else csOutput.insertAdjacentHTML('beforeend', 'Go to Work<br>') # Ternary operator votingAge = if age > 18 then true else false csOutput.insertAdjacentHTML('beforeend', "Can Vote : #{votingAge}<br>") # Switch childAge = 7 switch childAge when 5 then csOutput.insertAdjacentHTML('beforeend', 'Go to Kindergarten<br>') when 6, 7, 8, 9, 10 then csOutput.insertAdjacentHTML('beforeend', 'Go to Elementary School<br>') else csOutput.insertAdjacentHTML('beforeend', 'Go to Someplace<br>') # Do something if the variable has a value if age? csOutput.insertAdjacentHTML('beforeend', "#{age} years old<br>") # The existential operator can also assign 1 value if it exists or # another if not chicken = null chickenName = chicken ? "Fred" csOutput.insertAdjacentHTML('beforeend', "Chickens Name : #{chickenName}<br>") # We can stack conditions hat = "Winter Hat" coat = "Winter Coat" gloves = null # Only execute if we have a hat and coat # If null output '?' instead of null if hat? and coat? csOutput.insertAdjacentHTML('beforeend', "#{hat} #{coat} #{gloves ? '?'}<br>")
87876
# I'll use the NodeJS compiler to process CoffeeScript so download Node if you # don't have it here https://nodejs.org/en/ # Then in your terminal install CoffeeScript by typing # npm install -g coffee-script # You compile to a JS file with the same name but the js extension with # coffee --compile cstut.coffee # To auto compile use this in the terminal coffee -wc *.coffee ### Multiline Comment ### # ---------- INTRO ---------- # There is no var or semicolons in CoffeeScript # Variables in CoffeeScript are not global by default name = "<NAME>" # Get access to the element with the id csoutput csOutput = document.getElementById("csoutput") # Assign this string with the variable to it # Use double quotes for Interpolation csOutput.innerHTML = "Hello #{name}<br>" # ---------- VARIABLES ---------- # The data types are string, number, boolean, array, object, undefined # and null aString = "I'm a String" csOutput.insertAdjacentHTML('beforeend', 'aString is a String<br>') if typeof aString is 'string' largestNum = Number.MAX_VALUE smallestNum = Number.MIN_VALUE largeNumStr = "The largest number is #{largestNum}<br>" smallNumStr = "The smallest number is #{smallestNum}<br>" csOutput.insertAdjacentHTML('beforeend', largeNumStr) csOutput.insertAdjacentHTML('beforeend', smallNumStr) areYouHappy = no # Booleans have the value of (true, yes, or on) or (false, no, or off) csOutput.insertAdjacentHTML('beforeend', 'areYouHappy is a Boolean<br>') if typeof areYouHappy is 'boolean' # ---------- MATH ---------- csOutput.insertAdjacentHTML('beforeend', "5 + 2 = #{5 + 2}<br>") csOutput.insertAdjacentHTML('beforeend', "5 - 2 = #{5 - 2}<br>") csOutput.insertAdjacentHTML('beforeend', "5 * 2 = #{5 * 2}<br>") csOutput.insertAdjacentHTML('beforeend', "5 / 2 = #{5 / 2}<br>") csOutput.insertAdjacentHTML('beforeend', "5 % 2 = #{5 % 2}<br>") # CS has 16 digits of precision precisionTest = 0.1000000000000001; csOutput.insertAdjacentHTML('beforeend', "Precision : #{precisionTest + 0.10000000000000011}<br>") # Round to 2 digits balance = 1563.87 csOutput.insertAdjacentHTML('beforeend', "Monthly Payment = #{(balance/12).toFixed(2)}<br>") # Shortcut for adding 1 randNum = 5 csOutput.insertAdjacentHTML('beforeend', "randNum++ = #{randNum++}<br>") csOutput.insertAdjacentHTML('beforeend', "++randNum = #{++randNum}<br>") # Shortcut for subtracting 1 randNum = 5 csOutput.insertAdjacentHTML('beforeend', "randNum-- = #{randNum--}<br>") csOutput.insertAdjacentHTML('beforeend', "--randNum = #{--randNum}<br>") # Order of operations csOutput.insertAdjacentHTML('beforeend', "3 + 2 * 5 = #{3 + 2 * 5}<br>") csOutput.insertAdjacentHTML('beforeend', "(3 + 2) * 5 = #{(3 + 2) * 5}<br>") # Math properties and functions csOutput.insertAdjacentHTML('beforeend', "Math.E = #{Math.E}<br>") csOutput.insertAdjacentHTML('beforeend', "Math.PI = #{Math.PI}<br>") csOutput.insertAdjacentHTML('beforeend', "Math.abs(-8) = #{Math.abs(-8)}<br>") csOutput.insertAdjacentHTML('beforeend', "Math.cbrt(1000) = #{Math.cbrt(1000)}<br>") csOutput.insertAdjacentHTML('beforeend', "Math.ceil(6.45) = #{Math.ceil(6.45)}<br>") csOutput.insertAdjacentHTML('beforeend', "Math.floor(6.45) = #{Math.floor(6.45)}<br>") csOutput.insertAdjacentHTML('beforeend', "Math.round(6.45) = #{Math.round(6.45)}<br>") csOutput.insertAdjacentHTML('beforeend', "Math.log(10) = #{Math.log(10)}<br>") csOutput.insertAdjacentHTML('beforeend', "Math.log10(10) = #{Math.log10(10)}<br>") csOutput.insertAdjacentHTML('beforeend', "Math.pow(4,2) = #{Math.pow(4,2)}<br>") csOutput.insertAdjacentHTML('beforeend', "Math.sqrt(1000) = #{Math.sqrt(1000)}<br>") # Generate a random number randNum = Math.floor(Math.random() * 100) + 1 csOutput.insertAdjacentHTML('beforeend', "Random Number = #{randNum}<br>") # ---------- STRINGS ---------- fName = "<NAME>" lName = "<NAME>" # You can combine Strings with a + csOutput.insertAdjacentHTML('beforeend', fName + " " + lName + "<br>") longString = "This is a long string that goes on forever" # Get the String length csOutput.insertAdjacentHTML('beforeend', "String Length : #{longString.length}<br>") # Get the index of a matching string csOutput.insertAdjacentHTML('beforeend', "Index of string : #{longString.indexOf("goes")}<br>") # Get a character at an index csOutput.insertAdjacentHTML('beforeend', "Index 8 : #{longString.charAt(8)}<br>") # Get a substring csOutput.insertAdjacentHTML('beforeend', "Word at 27 : #{longString.slice(27,31)}<br>") # Get everything after an index csOutput.insertAdjacentHTML('beforeend', "After 27 : #{longString.slice(27)}<br>") # Replace a string with another longString = longString.replace("forever", "and on forever ") csOutput.insertAdjacentHTML('beforeend', "New String : #{longString}<br>") # Convert a string into an Array strArray = longString.split(" ") # Output an array for x in strArray csOutput.insertAdjacentHTML('beforeend', "#{x}<br>") # Trim whitespace longString = longString.trim() # Convert to all uppercase csOutput.insertAdjacentHTML('beforeend', "#{longString.toUpperCase()}<br>") # Convert to all lowercase csOutput.insertAdjacentHTML('beforeend', "#{longString.toLowerCase()}<br>") # ---------- CONDITIONALS ---------- # If works like JavaScript except with indentation and not curly brackets # Comparison operators are ==, !=, >, <, >=, <= # == and != in CS is the same as === and !== in JS age = 3 if age >= 18 # Insert text either beforebegin or beforeend csOutput.insertAdjacentHTML('beforeend', 'You can Vote<br>') if (age >= 16) csOutput.insertAdjacentHTML('beforeend', 'You can Drive also<br>') else if (age >= 16) csOutput.insertAdjacentHTML('beforeend', 'You can Drive<br>') else csOutput.insertAdjacentHTML('beforeend', 'You\'ll be 16 soon<br>') # Unless executes if the test returns false unless (age >= 19) csOutput.insertAdjacentHTML('beforeend', 'You are in school<br>') else csOutput.insertAdjacentHTML('beforeend', 'You may go to college<br>') # Logical operators are &&, || and ! hsGrad = true if !(age > 4) || (age > 65) csOutput.insertAdjacentHTML('beforeend', 'You don\'t go to school<br>') else if (age >= 5) && (age <= 6) csOutput.insertAdjacentHTML('beforeend', 'Go to Kindergarten<br>') else if (age > 6) && (age <= 18) schoolGrade = "Go to Grade #{age - 5}<br>" csOutput.insertAdjacentHTML('beforeend', schoolGrade) else csOutput.insertAdjacentHTML('beforeend', 'Go to Work<br>') # Ternary operator votingAge = if age > 18 then true else false csOutput.insertAdjacentHTML('beforeend', "Can Vote : #{votingAge}<br>") # Switch childAge = 7 switch childAge when 5 then csOutput.insertAdjacentHTML('beforeend', 'Go to Kindergarten<br>') when 6, 7, 8, 9, 10 then csOutput.insertAdjacentHTML('beforeend', 'Go to Elementary School<br>') else csOutput.insertAdjacentHTML('beforeend', 'Go to Someplace<br>') # Do something if the variable has a value if age? csOutput.insertAdjacentHTML('beforeend', "#{age} years old<br>") # The existential operator can also assign 1 value if it exists or # another if not chicken = null chickenName = chicken ? "<NAME>" csOutput.insertAdjacentHTML('beforeend', "Chickens Name : #{chickenName}<br>") # We can stack conditions hat = "Winter Hat" coat = "Winter Coat" gloves = null # Only execute if we have a hat and coat # If null output '?' instead of null if hat? and coat? csOutput.insertAdjacentHTML('beforeend', "#{hat} #{coat} #{gloves ? '?'}<br>")
true
# I'll use the NodeJS compiler to process CoffeeScript so download Node if you # don't have it here https://nodejs.org/en/ # Then in your terminal install CoffeeScript by typing # npm install -g coffee-script # You compile to a JS file with the same name but the js extension with # coffee --compile cstut.coffee # To auto compile use this in the terminal coffee -wc *.coffee ### Multiline Comment ### # ---------- INTRO ---------- # There is no var or semicolons in CoffeeScript # Variables in CoffeeScript are not global by default name = "PI:NAME:<NAME>END_PI" # Get access to the element with the id csoutput csOutput = document.getElementById("csoutput") # Assign this string with the variable to it # Use double quotes for Interpolation csOutput.innerHTML = "Hello #{name}<br>" # ---------- VARIABLES ---------- # The data types are string, number, boolean, array, object, undefined # and null aString = "I'm a String" csOutput.insertAdjacentHTML('beforeend', 'aString is a String<br>') if typeof aString is 'string' largestNum = Number.MAX_VALUE smallestNum = Number.MIN_VALUE largeNumStr = "The largest number is #{largestNum}<br>" smallNumStr = "The smallest number is #{smallestNum}<br>" csOutput.insertAdjacentHTML('beforeend', largeNumStr) csOutput.insertAdjacentHTML('beforeend', smallNumStr) areYouHappy = no # Booleans have the value of (true, yes, or on) or (false, no, or off) csOutput.insertAdjacentHTML('beforeend', 'areYouHappy is a Boolean<br>') if typeof areYouHappy is 'boolean' # ---------- MATH ---------- csOutput.insertAdjacentHTML('beforeend', "5 + 2 = #{5 + 2}<br>") csOutput.insertAdjacentHTML('beforeend', "5 - 2 = #{5 - 2}<br>") csOutput.insertAdjacentHTML('beforeend', "5 * 2 = #{5 * 2}<br>") csOutput.insertAdjacentHTML('beforeend', "5 / 2 = #{5 / 2}<br>") csOutput.insertAdjacentHTML('beforeend', "5 % 2 = #{5 % 2}<br>") # CS has 16 digits of precision precisionTest = 0.1000000000000001; csOutput.insertAdjacentHTML('beforeend', "Precision : #{precisionTest + 0.10000000000000011}<br>") # Round to 2 digits balance = 1563.87 csOutput.insertAdjacentHTML('beforeend', "Monthly Payment = #{(balance/12).toFixed(2)}<br>") # Shortcut for adding 1 randNum = 5 csOutput.insertAdjacentHTML('beforeend', "randNum++ = #{randNum++}<br>") csOutput.insertAdjacentHTML('beforeend', "++randNum = #{++randNum}<br>") # Shortcut for subtracting 1 randNum = 5 csOutput.insertAdjacentHTML('beforeend', "randNum-- = #{randNum--}<br>") csOutput.insertAdjacentHTML('beforeend', "--randNum = #{--randNum}<br>") # Order of operations csOutput.insertAdjacentHTML('beforeend', "3 + 2 * 5 = #{3 + 2 * 5}<br>") csOutput.insertAdjacentHTML('beforeend', "(3 + 2) * 5 = #{(3 + 2) * 5}<br>") # Math properties and functions csOutput.insertAdjacentHTML('beforeend', "Math.E = #{Math.E}<br>") csOutput.insertAdjacentHTML('beforeend', "Math.PI = #{Math.PI}<br>") csOutput.insertAdjacentHTML('beforeend', "Math.abs(-8) = #{Math.abs(-8)}<br>") csOutput.insertAdjacentHTML('beforeend', "Math.cbrt(1000) = #{Math.cbrt(1000)}<br>") csOutput.insertAdjacentHTML('beforeend', "Math.ceil(6.45) = #{Math.ceil(6.45)}<br>") csOutput.insertAdjacentHTML('beforeend', "Math.floor(6.45) = #{Math.floor(6.45)}<br>") csOutput.insertAdjacentHTML('beforeend', "Math.round(6.45) = #{Math.round(6.45)}<br>") csOutput.insertAdjacentHTML('beforeend', "Math.log(10) = #{Math.log(10)}<br>") csOutput.insertAdjacentHTML('beforeend', "Math.log10(10) = #{Math.log10(10)}<br>") csOutput.insertAdjacentHTML('beforeend', "Math.pow(4,2) = #{Math.pow(4,2)}<br>") csOutput.insertAdjacentHTML('beforeend', "Math.sqrt(1000) = #{Math.sqrt(1000)}<br>") # Generate a random number randNum = Math.floor(Math.random() * 100) + 1 csOutput.insertAdjacentHTML('beforeend', "Random Number = #{randNum}<br>") # ---------- STRINGS ---------- fName = "PI:NAME:<NAME>END_PI" lName = "PI:NAME:<NAME>END_PI" # You can combine Strings with a + csOutput.insertAdjacentHTML('beforeend', fName + " " + lName + "<br>") longString = "This is a long string that goes on forever" # Get the String length csOutput.insertAdjacentHTML('beforeend', "String Length : #{longString.length}<br>") # Get the index of a matching string csOutput.insertAdjacentHTML('beforeend', "Index of string : #{longString.indexOf("goes")}<br>") # Get a character at an index csOutput.insertAdjacentHTML('beforeend', "Index 8 : #{longString.charAt(8)}<br>") # Get a substring csOutput.insertAdjacentHTML('beforeend', "Word at 27 : #{longString.slice(27,31)}<br>") # Get everything after an index csOutput.insertAdjacentHTML('beforeend', "After 27 : #{longString.slice(27)}<br>") # Replace a string with another longString = longString.replace("forever", "and on forever ") csOutput.insertAdjacentHTML('beforeend', "New String : #{longString}<br>") # Convert a string into an Array strArray = longString.split(" ") # Output an array for x in strArray csOutput.insertAdjacentHTML('beforeend', "#{x}<br>") # Trim whitespace longString = longString.trim() # Convert to all uppercase csOutput.insertAdjacentHTML('beforeend', "#{longString.toUpperCase()}<br>") # Convert to all lowercase csOutput.insertAdjacentHTML('beforeend', "#{longString.toLowerCase()}<br>") # ---------- CONDITIONALS ---------- # If works like JavaScript except with indentation and not curly brackets # Comparison operators are ==, !=, >, <, >=, <= # == and != in CS is the same as === and !== in JS age = 3 if age >= 18 # Insert text either beforebegin or beforeend csOutput.insertAdjacentHTML('beforeend', 'You can Vote<br>') if (age >= 16) csOutput.insertAdjacentHTML('beforeend', 'You can Drive also<br>') else if (age >= 16) csOutput.insertAdjacentHTML('beforeend', 'You can Drive<br>') else csOutput.insertAdjacentHTML('beforeend', 'You\'ll be 16 soon<br>') # Unless executes if the test returns false unless (age >= 19) csOutput.insertAdjacentHTML('beforeend', 'You are in school<br>') else csOutput.insertAdjacentHTML('beforeend', 'You may go to college<br>') # Logical operators are &&, || and ! hsGrad = true if !(age > 4) || (age > 65) csOutput.insertAdjacentHTML('beforeend', 'You don\'t go to school<br>') else if (age >= 5) && (age <= 6) csOutput.insertAdjacentHTML('beforeend', 'Go to Kindergarten<br>') else if (age > 6) && (age <= 18) schoolGrade = "Go to Grade #{age - 5}<br>" csOutput.insertAdjacentHTML('beforeend', schoolGrade) else csOutput.insertAdjacentHTML('beforeend', 'Go to Work<br>') # Ternary operator votingAge = if age > 18 then true else false csOutput.insertAdjacentHTML('beforeend', "Can Vote : #{votingAge}<br>") # Switch childAge = 7 switch childAge when 5 then csOutput.insertAdjacentHTML('beforeend', 'Go to Kindergarten<br>') when 6, 7, 8, 9, 10 then csOutput.insertAdjacentHTML('beforeend', 'Go to Elementary School<br>') else csOutput.insertAdjacentHTML('beforeend', 'Go to Someplace<br>') # Do something if the variable has a value if age? csOutput.insertAdjacentHTML('beforeend', "#{age} years old<br>") # The existential operator can also assign 1 value if it exists or # another if not chicken = null chickenName = chicken ? "PI:NAME:<NAME>END_PI" csOutput.insertAdjacentHTML('beforeend', "Chickens Name : #{chickenName}<br>") # We can stack conditions hat = "Winter Hat" coat = "Winter Coat" gloves = null # Only execute if we have a hat and coat # If null output '?' instead of null if hat? and coat? csOutput.insertAdjacentHTML('beforeend', "#{hat} #{coat} #{gloves ? '?'}<br>")
[ { "context": "parameter', ->\n gapi.server.setApiKey 'AIzaSyB14Ua7k5_wusxHTQEH3sqmglO7MHjHPCI'\n config = require '../lib/config.coff", "end": 538, "score": 0.9997689723968506, "start": 499, "tag": "KEY", "value": "AIzaSyB14Ua7k5_wusxHTQEH3sqmglO7MHjHPCI" }, { "...
static/node_modules/gapi/test/gapi.coffee
nohharri/chator
4
describe 'requiring gapi module', -> it 'should contain the server namespace', -> gapi = require '../index' gapi.should.have.property 'server' describe 'server namespace', -> it 'shoud contain the setApiKey function', -> gapi.server.should.have.property 'setApiKey' gapi.server.setApiKey.should.be.a 'function' describe 'calling setApiKey', -> it 'should set config.api.key to the value of first parameter', -> gapi.server.setApiKey 'AIzaSyB14Ua7k5_wusxHTQEH3sqmglO7MHjHPCI' config = require '../lib/config.coffee' config.api.key.should.equal 'AIzaSyB14Ua7k5_wusxHTQEH3sqmglO7MHjHPCI' it 'should contain the load function', -> gapi.server.should.have.property 'load' gapi.server.load.should.be.a 'function'
176447
describe 'requiring gapi module', -> it 'should contain the server namespace', -> gapi = require '../index' gapi.should.have.property 'server' describe 'server namespace', -> it 'shoud contain the setApiKey function', -> gapi.server.should.have.property 'setApiKey' gapi.server.setApiKey.should.be.a 'function' describe 'calling setApiKey', -> it 'should set config.api.key to the value of first parameter', -> gapi.server.setApiKey '<KEY>' config = require '../lib/config.coffee' config.api.key.should.equal '<KEY>' it 'should contain the load function', -> gapi.server.should.have.property 'load' gapi.server.load.should.be.a 'function'
true
describe 'requiring gapi module', -> it 'should contain the server namespace', -> gapi = require '../index' gapi.should.have.property 'server' describe 'server namespace', -> it 'shoud contain the setApiKey function', -> gapi.server.should.have.property 'setApiKey' gapi.server.setApiKey.should.be.a 'function' describe 'calling setApiKey', -> it 'should set config.api.key to the value of first parameter', -> gapi.server.setApiKey 'PI:KEY:<KEY>END_PI' config = require '../lib/config.coffee' config.api.key.should.equal 'PI:KEY:<KEY>END_PI' it 'should contain the load function', -> gapi.server.should.have.property 'load' gapi.server.load.should.be.a 'function'
[ { "context": " 'completions': [\n 'Funktionalitéit:'\n 'Hannergrond:'\n 'Beispill:'\n 'Szenario:'\n 'Plan", "end": 104, "score": 0.9664037227630615, "start": 93, "tag": "NAME", "value": "Hannergrond" }, { "context": " 'Plang vum Szenario:'\n 'Beispiller:...
settings/language-gherkin_lu.cson
mackoj/language-gherkin-i18n
17
'.text.gherkin.feature.lu': 'editor': 'completions': [ 'Funktionalitéit:' 'Hannergrond:' 'Beispill:' 'Szenario:' 'Plang vum Szenario:' 'Beispiller:' 'ugeholl ' 'wann ' 'dann ' 'awer ' 'mä ' 'an ' 'a ' ] 'increaseIndentPattern': 'Beispill: .*' 'Szenario: .*' 'commentStart': '# '
45190
'.text.gherkin.feature.lu': 'editor': 'completions': [ 'Funktionalitéit:' '<NAME>:' 'Beispill:' 'Szenario:' 'Plang vum Szenario:' 'Beispiller:' '<NAME> ' '<NAME> ' '<NAME> ' '<NAME> ' 'm<NAME> ' 'an ' 'a ' ] 'increaseIndentPattern': 'Beispill: .*' 'Szenario: .*' 'commentStart': '# '
true
'.text.gherkin.feature.lu': 'editor': 'completions': [ 'Funktionalitéit:' 'PI:NAME:<NAME>END_PI:' 'Beispill:' 'Szenario:' 'Plang vum Szenario:' 'Beispiller:' 'PI:NAME:<NAME>END_PI ' 'PI:NAME:<NAME>END_PI ' 'PI:NAME:<NAME>END_PI ' 'PI:NAME:<NAME>END_PI ' 'mPI:NAME:<NAME>END_PI ' 'an ' 'a ' ] 'increaseIndentPattern': 'Beispill: .*' 'Szenario: .*' 'commentStart': '# '
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.9956865310668945, "start": 12, "tag": "NAME", "value": "Joyent" }, { "context": "urn\n)\ngotUpgrade = false\nsrv.listen common.PORT, \"127.0.0.1\", ->\n options =\n port: ...
test/simple/test-http-upgrade-agent.coffee
lxe/io.coffee
0
# Copyright Joyent, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. # Verify that the 'upgrade' header causes an 'upgrade' event to be emitted to # the HTTP client. This test uses a raw TCP server to better control server # behavior. common = require("../common") assert = require("assert") http = require("http") net = require("net") # Create a TCP server srv = net.createServer((c) -> data = "" c.on "data", (d) -> data += d.toString("utf8") c.write "HTTP/1.1 101\r\n" c.write "hello: world\r\n" c.write "connection: upgrade\r\n" c.write "upgrade: websocket\r\n" c.write "\r\n" c.write "nurtzo" return c.on "end", -> c.end() return return ) gotUpgrade = false srv.listen common.PORT, "127.0.0.1", -> options = port: common.PORT host: "127.0.0.1" headers: upgrade: "websocket" name = options.host + ":" + options.port req = http.request(options) req.end() req.on "upgrade", (res, socket, upgradeHead) -> # XXX: This test isn't fantastic, as it assumes that the entire response # from the server will arrive in a single data callback assert.equal upgradeHead, "nurtzo" console.log res.headers expectedHeaders = hello: "world" connection: "upgrade" upgrade: "websocket" assert.deepEqual expectedHeaders, res.headers # Make sure this request got removed from the pool. assert not http.globalAgent.sockets.hasOwnProperty(name) req.on "close", -> socket.end() srv.close() gotUpgrade = true return return return process.on "exit", -> assert.ok gotUpgrade return
138154
# Copyright <NAME>, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. # Verify that the 'upgrade' header causes an 'upgrade' event to be emitted to # the HTTP client. This test uses a raw TCP server to better control server # behavior. common = require("../common") assert = require("assert") http = require("http") net = require("net") # Create a TCP server srv = net.createServer((c) -> data = "" c.on "data", (d) -> data += d.toString("utf8") c.write "HTTP/1.1 101\r\n" c.write "hello: world\r\n" c.write "connection: upgrade\r\n" c.write "upgrade: websocket\r\n" c.write "\r\n" c.write "nurtzo" return c.on "end", -> c.end() return return ) gotUpgrade = false srv.listen common.PORT, "127.0.0.1", -> options = port: common.PORT host: "127.0.0.1" headers: upgrade: "websocket" name = options.host + ":" + options.port req = http.request(options) req.end() req.on "upgrade", (res, socket, upgradeHead) -> # XXX: This test isn't fantastic, as it assumes that the entire response # from the server will arrive in a single data callback assert.equal upgradeHead, "nurtzo" console.log res.headers expectedHeaders = hello: "world" connection: "upgrade" upgrade: "websocket" assert.deepEqual expectedHeaders, res.headers # Make sure this request got removed from the pool. assert not http.globalAgent.sockets.hasOwnProperty(name) req.on "close", -> socket.end() srv.close() gotUpgrade = true return return return process.on "exit", -> assert.ok gotUpgrade return
true
# Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. # Verify that the 'upgrade' header causes an 'upgrade' event to be emitted to # the HTTP client. This test uses a raw TCP server to better control server # behavior. common = require("../common") assert = require("assert") http = require("http") net = require("net") # Create a TCP server srv = net.createServer((c) -> data = "" c.on "data", (d) -> data += d.toString("utf8") c.write "HTTP/1.1 101\r\n" c.write "hello: world\r\n" c.write "connection: upgrade\r\n" c.write "upgrade: websocket\r\n" c.write "\r\n" c.write "nurtzo" return c.on "end", -> c.end() return return ) gotUpgrade = false srv.listen common.PORT, "127.0.0.1", -> options = port: common.PORT host: "127.0.0.1" headers: upgrade: "websocket" name = options.host + ":" + options.port req = http.request(options) req.end() req.on "upgrade", (res, socket, upgradeHead) -> # XXX: This test isn't fantastic, as it assumes that the entire response # from the server will arrive in a single data callback assert.equal upgradeHead, "nurtzo" console.log res.headers expectedHeaders = hello: "world" connection: "upgrade" upgrade: "websocket" assert.deepEqual expectedHeaders, res.headers # Make sure this request got removed from the pool. assert not http.globalAgent.sockets.hasOwnProperty(name) req.on "close", -> socket.end() srv.close() gotUpgrade = true return return return process.on "exit", -> assert.ok gotUpgrade return
[ { "context": "], (bot, message) ->\n bot.reply message, 'Sorry <@' + message.user + '>, I don\\'t understand. \\n'\n ", "end": 1882, "score": 0.5833470821380615, "start": 1882, "tag": "USERNAME", "value": "" }, { "context": "pboophq.com/'\n# text: text\n# color: '#7CD197'\n...
index.coffee
chusi/beatbeat
0
Botkit = require('botkit') stats = require('measured').createCollection() heartbeats = require('heartbeats') HEART_REGISTER_COUNT = 4 HEART_MISSED_BEAT_ALERT_AFTER=3 ### check out http://davestevens.github.io/slack-message-builder/ ### # Expect a SLACK_TOKEN environment variable slackToken = process.env.SLACK_TOKEN if !slackToken console.error 'SLACK_TOKEN is required!' process.exit 1 controller = Botkit.slackbot() bot = controller.spawn token: slackToken debug: true bot.startRTM (err, bot, payload) -> if err then throw new Error('Could not connect to Slack') controller.on 'bot_channel_join', (bot, message) -> bot.reply message, 'I\'m here!' controller.hears '.*beat (.*)', ['ambient', 'mention', 'direct_message', 'direct_mention'], (bot, message) -> beat = message.match[1] if beat of heartbeats.hearts is true pulse = heartbeats.hearts[beat].pulse('beat') pulse.beat() else if beat of stats.toJSON() is false bot.reply message, '<@' + message.user + '> thnx for checking in your first beat of ' + beat else if stats.toJSON()[beat].count is HEART_REGISTER_COUNT rate = register_beat beat, stats.toJSON()[beat] bot.reply message, '<@' + message.user + '> time to create heartbeat for ' + beat + ' with rate ' + rate #else # bot.reply message, 'debug: doing nothing' stats.meter(beat).mark(); controller.hears 'stats', ['direct_message', 'direct_mention'], (bot, message) -> bot.reply message, "your stats: " + JSON.stringify(stats.toJSON(), null, 4) controller.hears 'help', ['direct_message', 'direct_mention'], (bot, message) -> help = 'I will respond to the following messages: \n' + '`beat` <name>\n' + '`stats` to see some internal stats\n' + '`bot help` to see this again.' bot.reply message, help controller.hears '.*', ['direct_message', 'direct_mention'], (bot, message) -> bot.reply message, 'Sorry <@' + message.user + '>, I don\'t understand. \n' return register_beat = (name, stat) -> rate = Math.ceil(1/stat.mean) console.log "going to register autobeat ", name, rate, "rate?", beat = heartbeats.createHeart(rate * 1000, name) beat.createPulse('beat') beat.createEvent 1, (heartbeat, last) -> #console.log "event heartbeat", heartbeat, this.heart console.log "missed beats?", this.heart.pulse('beat').missedBeats, "lag", this.heart.pulse('beat').lag if this.heart.pulse('beat').missedBeats > HEART_MISSED_BEAT_ALERT_AFTER bot.say text: '<!channel> HUSTON, we are missing beats (' + this.heart.pulse('beat').missedBeats + ') for ' + name channel: 'C0P5UTCFN' # reset stuff this.heart.kill() delete heartbeats.hearts[name] stats.meter(name).end() #.unref() #FIXME: this is a hack delete stats._metrics[name] rate # # controller.hears [ 'attachment' ], ['direct_message', 'direct_mention'], (bot, message) -> # text = 'Beep Beep Boop is a ridiculously simple hosting platform for your Slackbots.' # attachments = [ { # fallback: text # pretext: 'We bring bots to life. :sunglasses: :thumbsup:' # title: 'Host, deploy and share your bot in seconds.' # image_url: 'https://storage.googleapis.com/beepboophq/_assets/bot-1.22f6fb.png' # title_link: 'https://beepboophq.com/' # text: text # color: '#7CD197' # } ] # bot.reply message, { attachments: attachments }, (err, resp) -> # console.log err, resp
216064
Botkit = require('botkit') stats = require('measured').createCollection() heartbeats = require('heartbeats') HEART_REGISTER_COUNT = 4 HEART_MISSED_BEAT_ALERT_AFTER=3 ### check out http://davestevens.github.io/slack-message-builder/ ### # Expect a SLACK_TOKEN environment variable slackToken = process.env.SLACK_TOKEN if !slackToken console.error 'SLACK_TOKEN is required!' process.exit 1 controller = Botkit.slackbot() bot = controller.spawn token: slackToken debug: true bot.startRTM (err, bot, payload) -> if err then throw new Error('Could not connect to Slack') controller.on 'bot_channel_join', (bot, message) -> bot.reply message, 'I\'m here!' controller.hears '.*beat (.*)', ['ambient', 'mention', 'direct_message', 'direct_mention'], (bot, message) -> beat = message.match[1] if beat of heartbeats.hearts is true pulse = heartbeats.hearts[beat].pulse('beat') pulse.beat() else if beat of stats.toJSON() is false bot.reply message, '<@' + message.user + '> thnx for checking in your first beat of ' + beat else if stats.toJSON()[beat].count is HEART_REGISTER_COUNT rate = register_beat beat, stats.toJSON()[beat] bot.reply message, '<@' + message.user + '> time to create heartbeat for ' + beat + ' with rate ' + rate #else # bot.reply message, 'debug: doing nothing' stats.meter(beat).mark(); controller.hears 'stats', ['direct_message', 'direct_mention'], (bot, message) -> bot.reply message, "your stats: " + JSON.stringify(stats.toJSON(), null, 4) controller.hears 'help', ['direct_message', 'direct_mention'], (bot, message) -> help = 'I will respond to the following messages: \n' + '`beat` <name>\n' + '`stats` to see some internal stats\n' + '`bot help` to see this again.' bot.reply message, help controller.hears '.*', ['direct_message', 'direct_mention'], (bot, message) -> bot.reply message, 'Sorry <@' + message.user + '>, I don\'t understand. \n' return register_beat = (name, stat) -> rate = Math.ceil(1/stat.mean) console.log "going to register autobeat ", name, rate, "rate?", beat = heartbeats.createHeart(rate * 1000, name) beat.createPulse('beat') beat.createEvent 1, (heartbeat, last) -> #console.log "event heartbeat", heartbeat, this.heart console.log "missed beats?", this.heart.pulse('beat').missedBeats, "lag", this.heart.pulse('beat').lag if this.heart.pulse('beat').missedBeats > HEART_MISSED_BEAT_ALERT_AFTER bot.say text: '<!channel> HUSTON, we are missing beats (' + this.heart.pulse('beat').missedBeats + ') for ' + name channel: 'C0P5UTCFN' # reset stuff this.heart.kill() delete heartbeats.hearts[name] stats.meter(name).end() #.unref() #FIXME: this is a hack delete stats._metrics[name] rate # # controller.hears [ 'attachment' ], ['direct_message', 'direct_mention'], (bot, message) -> # text = 'Beep Beep Boop is a ridiculously simple hosting platform for your Slackbots.' # attachments = [ { # fallback: text # pretext: 'We bring bots to life. :sunglasses: :thumbsup:' # title: 'Host, deploy and share your bot in seconds.' # image_url: 'https://storage.googleapis.com/beepboophq/_assets/bot-1.22f6fb.png' # title_link: 'https://beepboophq.com/' # text: text # color: '#7CD1<PASSWORD>' # } ] # bot.reply message, { attachments: attachments }, (err, resp) -> # console.log err, resp
true
Botkit = require('botkit') stats = require('measured').createCollection() heartbeats = require('heartbeats') HEART_REGISTER_COUNT = 4 HEART_MISSED_BEAT_ALERT_AFTER=3 ### check out http://davestevens.github.io/slack-message-builder/ ### # Expect a SLACK_TOKEN environment variable slackToken = process.env.SLACK_TOKEN if !slackToken console.error 'SLACK_TOKEN is required!' process.exit 1 controller = Botkit.slackbot() bot = controller.spawn token: slackToken debug: true bot.startRTM (err, bot, payload) -> if err then throw new Error('Could not connect to Slack') controller.on 'bot_channel_join', (bot, message) -> bot.reply message, 'I\'m here!' controller.hears '.*beat (.*)', ['ambient', 'mention', 'direct_message', 'direct_mention'], (bot, message) -> beat = message.match[1] if beat of heartbeats.hearts is true pulse = heartbeats.hearts[beat].pulse('beat') pulse.beat() else if beat of stats.toJSON() is false bot.reply message, '<@' + message.user + '> thnx for checking in your first beat of ' + beat else if stats.toJSON()[beat].count is HEART_REGISTER_COUNT rate = register_beat beat, stats.toJSON()[beat] bot.reply message, '<@' + message.user + '> time to create heartbeat for ' + beat + ' with rate ' + rate #else # bot.reply message, 'debug: doing nothing' stats.meter(beat).mark(); controller.hears 'stats', ['direct_message', 'direct_mention'], (bot, message) -> bot.reply message, "your stats: " + JSON.stringify(stats.toJSON(), null, 4) controller.hears 'help', ['direct_message', 'direct_mention'], (bot, message) -> help = 'I will respond to the following messages: \n' + '`beat` <name>\n' + '`stats` to see some internal stats\n' + '`bot help` to see this again.' bot.reply message, help controller.hears '.*', ['direct_message', 'direct_mention'], (bot, message) -> bot.reply message, 'Sorry <@' + message.user + '>, I don\'t understand. \n' return register_beat = (name, stat) -> rate = Math.ceil(1/stat.mean) console.log "going to register autobeat ", name, rate, "rate?", beat = heartbeats.createHeart(rate * 1000, name) beat.createPulse('beat') beat.createEvent 1, (heartbeat, last) -> #console.log "event heartbeat", heartbeat, this.heart console.log "missed beats?", this.heart.pulse('beat').missedBeats, "lag", this.heart.pulse('beat').lag if this.heart.pulse('beat').missedBeats > HEART_MISSED_BEAT_ALERT_AFTER bot.say text: '<!channel> HUSTON, we are missing beats (' + this.heart.pulse('beat').missedBeats + ') for ' + name channel: 'C0P5UTCFN' # reset stuff this.heart.kill() delete heartbeats.hearts[name] stats.meter(name).end() #.unref() #FIXME: this is a hack delete stats._metrics[name] rate # # controller.hears [ 'attachment' ], ['direct_message', 'direct_mention'], (bot, message) -> # text = 'Beep Beep Boop is a ridiculously simple hosting platform for your Slackbots.' # attachments = [ { # fallback: text # pretext: 'We bring bots to life. :sunglasses: :thumbsup:' # title: 'Host, deploy and share your bot in seconds.' # image_url: 'https://storage.googleapis.com/beepboophq/_assets/bot-1.22f6fb.png' # title_link: 'https://beepboophq.com/' # text: text # color: '#7CD1PI:PASSWORD:<PASSWORD>END_PI' # } ] # bot.reply message, { attachments: attachments }, (err, resp) -> # console.log err, resp
[ { "context": "###\nPDFFont - embeds fonts in PDF documents\nBy Devon Govett\n###\n\nTTFFont = require './font/ttf'\nAFMFont = req", "end": 59, "score": 0.9998771548271179, "start": 47, "tag": "NAME", "value": "Devon Govett" } ]
lib/font.coffee
blend/pdfkit
11
### PDFFont - embeds fonts in PDF documents By Devon Govett ### TTFFont = require './font/ttf' AFMFont = require './font/afm' Subset = require './font/subset' fs = require 'fs' class PDFFont constructor: (@document, src, family, @id) -> if typeof src is 'string' if src of STANDARD_FONTS @isAFM = true @font = new AFMFont STANDARD_FONTS[src]() @registerAFM src return else if /\.(ttf|ttc)$/i.test src @font = TTFFont.open src, family else if /\.dfont$/i.test src @font = TTFFont.fromDFont src, family else throw new Error 'Not a supported font format or standard PDF font.' else if Buffer.isBuffer(src) @font = TTFFont.fromBuffer src, family else if src instanceof Uint8Array @font = TTFFont.fromBuffer new Buffer(src), family else if src instanceof ArrayBuffer @font = TTFFont.fromBuffer new Buffer(new Uint8Array(src)), family else throw new Error 'Not a supported font format or standard PDF font.' # create a subset for the font and register @subset = new Subset @font @registerTTF() # This insanity is so browserify can inline the font files STANDARD_FONTS = "Courier": -> fs.readFileSync __dirname + "/font/data/Courier.afm", 'utf8' "Courier-Bold": -> fs.readFileSync __dirname + "/font/data/Courier-Bold.afm", 'utf8' "Courier-Oblique": -> fs.readFileSync __dirname + "/font/data/Courier-Oblique.afm", 'utf8' "Courier-BoldOblique": -> fs.readFileSync __dirname + "/font/data/Courier-BoldOblique.afm", 'utf8' "Helvetica": -> fs.readFileSync __dirname + "/font/data/Helvetica.afm", 'utf8' "Helvetica-Bold": -> fs.readFileSync __dirname + "/font/data/Helvetica-Bold.afm", 'utf8' "Helvetica-Oblique": -> fs.readFileSync __dirname + "/font/data/Helvetica-Oblique.afm", 'utf8' "Helvetica-BoldOblique": -> fs.readFileSync __dirname + "/font/data/Helvetica-BoldOblique.afm", 'utf8' "Times-Roman": -> fs.readFileSync __dirname + "/font/data/Times-Roman.afm", 'utf8' "Times-Bold": -> fs.readFileSync __dirname + "/font/data/Times-Bold.afm", 'utf8' "Times-Italic": -> fs.readFileSync __dirname + "/font/data/Times-Italic.afm", 'utf8' "Times-BoldItalic": -> fs.readFileSync __dirname + "/font/data/Times-BoldItalic.afm", 'utf8' "Symbol": -> fs.readFileSync __dirname + "/font/data/Symbol.afm", 'utf8' "ZapfDingbats": -> fs.readFileSync __dirname + "/font/data/ZapfDingbats.afm", 'utf8' use: (characters) -> @subset?.use characters embed: -> return if @embedded or not @dictionary? if @isAFM @embedAFM() else @embedTTF() @embedded = true encode: (text) -> if @isAFM @font.encodeText text else @subset?.encodeText(text) or text ref: -> @dictionary ?= @document.ref() registerTTF: -> @name = @font.name.postscriptName @scaleFactor = 1000.0 / @font.head.unitsPerEm @bbox = (Math.round e * @scaleFactor for e in @font.bbox) @stemV = 0 # not sure how to compute this for true-type fonts... if @font.post.exists raw = @font.post.italic_angle hi = raw >> 16 low = raw & 0xFF hi = -((hi ^ 0xFFFF) + 1) if hi & 0x8000 isnt 0 @italicAngle = +"#{hi}.#{low}" else @italicAngle = 0 @ascender = Math.round @font.ascender * @scaleFactor @decender = Math.round @font.decender * @scaleFactor @lineGap = Math.round @font.lineGap * @scaleFactor @capHeight = (@font.os2.exists and @font.os2.capHeight) or @ascender @xHeight = (@font.os2.exists and @font.os2.xHeight) or 0 @familyClass = (@font.os2.exists and @font.os2.familyClass or 0) >> 8 @isSerif = @familyClass in [1,2,3,4,5,7] @isScript = @familyClass is 10 @flags = 0 @flags |= 1 << 0 if @font.post.isFixedPitch @flags |= 1 << 1 if @isSerif @flags |= 1 << 3 if @isScript @flags |= 1 << 6 if @italicAngle isnt 0 @flags |= 1 << 5 # assume the font is nonsymbolic... throw new Error 'No unicode cmap for font' if not @font.cmap.unicode embedTTF: -> data = @subset.encode() fontfile = @document.ref() fontfile.write data fontfile.data.Length1 = fontfile.uncompressedLength fontfile.end() descriptor = @document.ref Type: 'FontDescriptor' FontName: @subset.postscriptName FontFile2: fontfile FontBBox: @bbox Flags: @flags StemV: @stemV ItalicAngle: @italicAngle Ascent: @ascender Descent: @decender CapHeight: @capHeight XHeight: @xHeight descriptor.end() firstChar = +Object.keys(@subset.cmap)[0] charWidths = for code, glyph of @subset.cmap Math.round @font.widthOfGlyph(glyph) cmap = @document.ref() cmap.end toUnicodeCmap(@subset.subset) @dictionary.data = Type: 'Font' BaseFont: @subset.postscriptName Subtype: 'TrueType' FontDescriptor: descriptor FirstChar: firstChar LastChar: firstChar + charWidths.length - 1 Widths: charWidths Encoding: 'MacRomanEncoding' ToUnicode: cmap @dictionary.end() toUnicodeCmap = (map) -> unicodeMap = ''' /CIDInit /ProcSet findresource begin 12 dict begin begincmap /CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def /CMapName /Adobe-Identity-UCS def /CMapType 2 def 1 begincodespacerange <00><ff> endcodespacerange ''' codes = Object.keys(map).sort (a, b) -> a - b range = [] for code in codes if range.length >= 100 unicodeMap += "\n#{range.length} beginbfchar\n#{range.join('\n')}\nendbfchar" range = [] unicode = ('0000' + map[code].toString(16)).slice(-4) code = (+code).toString(16) range.push "<#{code}><#{unicode}>" unicodeMap += "\n#{range.length} beginbfchar\n#{range.join('\n')}\nendbfchar\n" if range.length unicodeMap += ''' endcmap CMapName currentdict /CMap defineresource pop end end ''' registerAFM: (@name) -> {@ascender,@decender,@bbox,@lineGap} = @font embedAFM: -> @dictionary.data = Type: 'Font' BaseFont: @name Subtype: 'Type1' Encoding: 'WinAnsiEncoding' @dictionary.end() widthOfString: (string, size) -> string = '' + string width = 0 for i in [0...string.length] charCode = string.charCodeAt(i) width += @font.widthOfGlyph(@font.characterToGlyph(charCode)) or 0 scale = size / 1000 return width * scale lineHeight: (size, includeGap = false) -> gap = if includeGap then @lineGap else 0 (@ascender + gap - @decender) / 1000 * size module.exports = PDFFont
142068
### PDFFont - embeds fonts in PDF documents By <NAME> ### TTFFont = require './font/ttf' AFMFont = require './font/afm' Subset = require './font/subset' fs = require 'fs' class PDFFont constructor: (@document, src, family, @id) -> if typeof src is 'string' if src of STANDARD_FONTS @isAFM = true @font = new AFMFont STANDARD_FONTS[src]() @registerAFM src return else if /\.(ttf|ttc)$/i.test src @font = TTFFont.open src, family else if /\.dfont$/i.test src @font = TTFFont.fromDFont src, family else throw new Error 'Not a supported font format or standard PDF font.' else if Buffer.isBuffer(src) @font = TTFFont.fromBuffer src, family else if src instanceof Uint8Array @font = TTFFont.fromBuffer new Buffer(src), family else if src instanceof ArrayBuffer @font = TTFFont.fromBuffer new Buffer(new Uint8Array(src)), family else throw new Error 'Not a supported font format or standard PDF font.' # create a subset for the font and register @subset = new Subset @font @registerTTF() # This insanity is so browserify can inline the font files STANDARD_FONTS = "Courier": -> fs.readFileSync __dirname + "/font/data/Courier.afm", 'utf8' "Courier-Bold": -> fs.readFileSync __dirname + "/font/data/Courier-Bold.afm", 'utf8' "Courier-Oblique": -> fs.readFileSync __dirname + "/font/data/Courier-Oblique.afm", 'utf8' "Courier-BoldOblique": -> fs.readFileSync __dirname + "/font/data/Courier-BoldOblique.afm", 'utf8' "Helvetica": -> fs.readFileSync __dirname + "/font/data/Helvetica.afm", 'utf8' "Helvetica-Bold": -> fs.readFileSync __dirname + "/font/data/Helvetica-Bold.afm", 'utf8' "Helvetica-Oblique": -> fs.readFileSync __dirname + "/font/data/Helvetica-Oblique.afm", 'utf8' "Helvetica-BoldOblique": -> fs.readFileSync __dirname + "/font/data/Helvetica-BoldOblique.afm", 'utf8' "Times-Roman": -> fs.readFileSync __dirname + "/font/data/Times-Roman.afm", 'utf8' "Times-Bold": -> fs.readFileSync __dirname + "/font/data/Times-Bold.afm", 'utf8' "Times-Italic": -> fs.readFileSync __dirname + "/font/data/Times-Italic.afm", 'utf8' "Times-BoldItalic": -> fs.readFileSync __dirname + "/font/data/Times-BoldItalic.afm", 'utf8' "Symbol": -> fs.readFileSync __dirname + "/font/data/Symbol.afm", 'utf8' "ZapfDingbats": -> fs.readFileSync __dirname + "/font/data/ZapfDingbats.afm", 'utf8' use: (characters) -> @subset?.use characters embed: -> return if @embedded or not @dictionary? if @isAFM @embedAFM() else @embedTTF() @embedded = true encode: (text) -> if @isAFM @font.encodeText text else @subset?.encodeText(text) or text ref: -> @dictionary ?= @document.ref() registerTTF: -> @name = @font.name.postscriptName @scaleFactor = 1000.0 / @font.head.unitsPerEm @bbox = (Math.round e * @scaleFactor for e in @font.bbox) @stemV = 0 # not sure how to compute this for true-type fonts... if @font.post.exists raw = @font.post.italic_angle hi = raw >> 16 low = raw & 0xFF hi = -((hi ^ 0xFFFF) + 1) if hi & 0x8000 isnt 0 @italicAngle = +"#{hi}.#{low}" else @italicAngle = 0 @ascender = Math.round @font.ascender * @scaleFactor @decender = Math.round @font.decender * @scaleFactor @lineGap = Math.round @font.lineGap * @scaleFactor @capHeight = (@font.os2.exists and @font.os2.capHeight) or @ascender @xHeight = (@font.os2.exists and @font.os2.xHeight) or 0 @familyClass = (@font.os2.exists and @font.os2.familyClass or 0) >> 8 @isSerif = @familyClass in [1,2,3,4,5,7] @isScript = @familyClass is 10 @flags = 0 @flags |= 1 << 0 if @font.post.isFixedPitch @flags |= 1 << 1 if @isSerif @flags |= 1 << 3 if @isScript @flags |= 1 << 6 if @italicAngle isnt 0 @flags |= 1 << 5 # assume the font is nonsymbolic... throw new Error 'No unicode cmap for font' if not @font.cmap.unicode embedTTF: -> data = @subset.encode() fontfile = @document.ref() fontfile.write data fontfile.data.Length1 = fontfile.uncompressedLength fontfile.end() descriptor = @document.ref Type: 'FontDescriptor' FontName: @subset.postscriptName FontFile2: fontfile FontBBox: @bbox Flags: @flags StemV: @stemV ItalicAngle: @italicAngle Ascent: @ascender Descent: @decender CapHeight: @capHeight XHeight: @xHeight descriptor.end() firstChar = +Object.keys(@subset.cmap)[0] charWidths = for code, glyph of @subset.cmap Math.round @font.widthOfGlyph(glyph) cmap = @document.ref() cmap.end toUnicodeCmap(@subset.subset) @dictionary.data = Type: 'Font' BaseFont: @subset.postscriptName Subtype: 'TrueType' FontDescriptor: descriptor FirstChar: firstChar LastChar: firstChar + charWidths.length - 1 Widths: charWidths Encoding: 'MacRomanEncoding' ToUnicode: cmap @dictionary.end() toUnicodeCmap = (map) -> unicodeMap = ''' /CIDInit /ProcSet findresource begin 12 dict begin begincmap /CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def /CMapName /Adobe-Identity-UCS def /CMapType 2 def 1 begincodespacerange <00><ff> endcodespacerange ''' codes = Object.keys(map).sort (a, b) -> a - b range = [] for code in codes if range.length >= 100 unicodeMap += "\n#{range.length} beginbfchar\n#{range.join('\n')}\nendbfchar" range = [] unicode = ('0000' + map[code].toString(16)).slice(-4) code = (+code).toString(16) range.push "<#{code}><#{unicode}>" unicodeMap += "\n#{range.length} beginbfchar\n#{range.join('\n')}\nendbfchar\n" if range.length unicodeMap += ''' endcmap CMapName currentdict /CMap defineresource pop end end ''' registerAFM: (@name) -> {@ascender,@decender,@bbox,@lineGap} = @font embedAFM: -> @dictionary.data = Type: 'Font' BaseFont: @name Subtype: 'Type1' Encoding: 'WinAnsiEncoding' @dictionary.end() widthOfString: (string, size) -> string = '' + string width = 0 for i in [0...string.length] charCode = string.charCodeAt(i) width += @font.widthOfGlyph(@font.characterToGlyph(charCode)) or 0 scale = size / 1000 return width * scale lineHeight: (size, includeGap = false) -> gap = if includeGap then @lineGap else 0 (@ascender + gap - @decender) / 1000 * size module.exports = PDFFont
true
### PDFFont - embeds fonts in PDF documents By PI:NAME:<NAME>END_PI ### TTFFont = require './font/ttf' AFMFont = require './font/afm' Subset = require './font/subset' fs = require 'fs' class PDFFont constructor: (@document, src, family, @id) -> if typeof src is 'string' if src of STANDARD_FONTS @isAFM = true @font = new AFMFont STANDARD_FONTS[src]() @registerAFM src return else if /\.(ttf|ttc)$/i.test src @font = TTFFont.open src, family else if /\.dfont$/i.test src @font = TTFFont.fromDFont src, family else throw new Error 'Not a supported font format or standard PDF font.' else if Buffer.isBuffer(src) @font = TTFFont.fromBuffer src, family else if src instanceof Uint8Array @font = TTFFont.fromBuffer new Buffer(src), family else if src instanceof ArrayBuffer @font = TTFFont.fromBuffer new Buffer(new Uint8Array(src)), family else throw new Error 'Not a supported font format or standard PDF font.' # create a subset for the font and register @subset = new Subset @font @registerTTF() # This insanity is so browserify can inline the font files STANDARD_FONTS = "Courier": -> fs.readFileSync __dirname + "/font/data/Courier.afm", 'utf8' "Courier-Bold": -> fs.readFileSync __dirname + "/font/data/Courier-Bold.afm", 'utf8' "Courier-Oblique": -> fs.readFileSync __dirname + "/font/data/Courier-Oblique.afm", 'utf8' "Courier-BoldOblique": -> fs.readFileSync __dirname + "/font/data/Courier-BoldOblique.afm", 'utf8' "Helvetica": -> fs.readFileSync __dirname + "/font/data/Helvetica.afm", 'utf8' "Helvetica-Bold": -> fs.readFileSync __dirname + "/font/data/Helvetica-Bold.afm", 'utf8' "Helvetica-Oblique": -> fs.readFileSync __dirname + "/font/data/Helvetica-Oblique.afm", 'utf8' "Helvetica-BoldOblique": -> fs.readFileSync __dirname + "/font/data/Helvetica-BoldOblique.afm", 'utf8' "Times-Roman": -> fs.readFileSync __dirname + "/font/data/Times-Roman.afm", 'utf8' "Times-Bold": -> fs.readFileSync __dirname + "/font/data/Times-Bold.afm", 'utf8' "Times-Italic": -> fs.readFileSync __dirname + "/font/data/Times-Italic.afm", 'utf8' "Times-BoldItalic": -> fs.readFileSync __dirname + "/font/data/Times-BoldItalic.afm", 'utf8' "Symbol": -> fs.readFileSync __dirname + "/font/data/Symbol.afm", 'utf8' "ZapfDingbats": -> fs.readFileSync __dirname + "/font/data/ZapfDingbats.afm", 'utf8' use: (characters) -> @subset?.use characters embed: -> return if @embedded or not @dictionary? if @isAFM @embedAFM() else @embedTTF() @embedded = true encode: (text) -> if @isAFM @font.encodeText text else @subset?.encodeText(text) or text ref: -> @dictionary ?= @document.ref() registerTTF: -> @name = @font.name.postscriptName @scaleFactor = 1000.0 / @font.head.unitsPerEm @bbox = (Math.round e * @scaleFactor for e in @font.bbox) @stemV = 0 # not sure how to compute this for true-type fonts... if @font.post.exists raw = @font.post.italic_angle hi = raw >> 16 low = raw & 0xFF hi = -((hi ^ 0xFFFF) + 1) if hi & 0x8000 isnt 0 @italicAngle = +"#{hi}.#{low}" else @italicAngle = 0 @ascender = Math.round @font.ascender * @scaleFactor @decender = Math.round @font.decender * @scaleFactor @lineGap = Math.round @font.lineGap * @scaleFactor @capHeight = (@font.os2.exists and @font.os2.capHeight) or @ascender @xHeight = (@font.os2.exists and @font.os2.xHeight) or 0 @familyClass = (@font.os2.exists and @font.os2.familyClass or 0) >> 8 @isSerif = @familyClass in [1,2,3,4,5,7] @isScript = @familyClass is 10 @flags = 0 @flags |= 1 << 0 if @font.post.isFixedPitch @flags |= 1 << 1 if @isSerif @flags |= 1 << 3 if @isScript @flags |= 1 << 6 if @italicAngle isnt 0 @flags |= 1 << 5 # assume the font is nonsymbolic... throw new Error 'No unicode cmap for font' if not @font.cmap.unicode embedTTF: -> data = @subset.encode() fontfile = @document.ref() fontfile.write data fontfile.data.Length1 = fontfile.uncompressedLength fontfile.end() descriptor = @document.ref Type: 'FontDescriptor' FontName: @subset.postscriptName FontFile2: fontfile FontBBox: @bbox Flags: @flags StemV: @stemV ItalicAngle: @italicAngle Ascent: @ascender Descent: @decender CapHeight: @capHeight XHeight: @xHeight descriptor.end() firstChar = +Object.keys(@subset.cmap)[0] charWidths = for code, glyph of @subset.cmap Math.round @font.widthOfGlyph(glyph) cmap = @document.ref() cmap.end toUnicodeCmap(@subset.subset) @dictionary.data = Type: 'Font' BaseFont: @subset.postscriptName Subtype: 'TrueType' FontDescriptor: descriptor FirstChar: firstChar LastChar: firstChar + charWidths.length - 1 Widths: charWidths Encoding: 'MacRomanEncoding' ToUnicode: cmap @dictionary.end() toUnicodeCmap = (map) -> unicodeMap = ''' /CIDInit /ProcSet findresource begin 12 dict begin begincmap /CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def /CMapName /Adobe-Identity-UCS def /CMapType 2 def 1 begincodespacerange <00><ff> endcodespacerange ''' codes = Object.keys(map).sort (a, b) -> a - b range = [] for code in codes if range.length >= 100 unicodeMap += "\n#{range.length} beginbfchar\n#{range.join('\n')}\nendbfchar" range = [] unicode = ('0000' + map[code].toString(16)).slice(-4) code = (+code).toString(16) range.push "<#{code}><#{unicode}>" unicodeMap += "\n#{range.length} beginbfchar\n#{range.join('\n')}\nendbfchar\n" if range.length unicodeMap += ''' endcmap CMapName currentdict /CMap defineresource pop end end ''' registerAFM: (@name) -> {@ascender,@decender,@bbox,@lineGap} = @font embedAFM: -> @dictionary.data = Type: 'Font' BaseFont: @name Subtype: 'Type1' Encoding: 'WinAnsiEncoding' @dictionary.end() widthOfString: (string, size) -> string = '' + string width = 0 for i in [0...string.length] charCode = string.charCodeAt(i) width += @font.widthOfGlyph(@font.characterToGlyph(charCode)) or 0 scale = size / 1000 return width * scale lineHeight: (size, includeGap = false) -> gap = if includeGap then @lineGap else 0 (@ascender + gap - @decender) / 1000 * size module.exports = PDFFont
[ { "context": "# Copyright (c) 2014 Riceball LEE, MIT License\nErrors = require(\"abs", "end": 33, "score": 0.9998021125793457, "start": 21, "tag": "NAME", "value": "Riceball LEE" } ]
src/nosql-stream.coffee
snowyu/nosql-stream
1
# Copyright (c) 2014 Riceball LEE, MIT License Errors = require("abstract-object/Error") #AbstractNoSQL = require("abstract-nosql") #inherits = require("abstract-object/lib/util/inherits") #inheritsDirectly = require("abstract-object/lib/util/inheritsDirectly") #isInheritedFrom = require("abstract-object/lib/util/isInheritedFrom") isFunction = require("abstract-object/lib/util/isFunction") extend = require("abstract-object/lib/util/_extend") InvalidArgumentError = Errors.InvalidArgumentError ReadStream = require("./read-stream") WriteStream = require("./write-stream") module.exports = class StreamNoSQL #inherits StreamNoSQL, AbstractNoSQL constructor: (aClass)-> if (this not instanceof StreamNoSQL) if isFunction aClass if not aClass::readStream extend aClass::, StreamNoSQL:: return aClass throw new InvalidArgumentError("this class has been already streamable.") throw new InvalidArgumentError("please use StreamNoSQLTo(aClass) to add streamable to a database class.") readStream: (options, makeData)-> opt = extend({}, @_options, options) ReadStream @, opt, makeData createReadStream: @::readStream valueStream: (options, makeData)-> opt = extend({}, options) opt.keys = false @readStream opt, makeData createValueStream: @::valueStream keyStream: (options, makeData)-> opt = extend({}, options) opt.values = false @readStream opt, makeData createKeyStream: @::keyStream writeStream: (options)-> opt = extend({}, @_options, options) WriteStream @, opt createWriteStream: @::writeStream
4479
# Copyright (c) 2014 <NAME>, MIT License Errors = require("abstract-object/Error") #AbstractNoSQL = require("abstract-nosql") #inherits = require("abstract-object/lib/util/inherits") #inheritsDirectly = require("abstract-object/lib/util/inheritsDirectly") #isInheritedFrom = require("abstract-object/lib/util/isInheritedFrom") isFunction = require("abstract-object/lib/util/isFunction") extend = require("abstract-object/lib/util/_extend") InvalidArgumentError = Errors.InvalidArgumentError ReadStream = require("./read-stream") WriteStream = require("./write-stream") module.exports = class StreamNoSQL #inherits StreamNoSQL, AbstractNoSQL constructor: (aClass)-> if (this not instanceof StreamNoSQL) if isFunction aClass if not aClass::readStream extend aClass::, StreamNoSQL:: return aClass throw new InvalidArgumentError("this class has been already streamable.") throw new InvalidArgumentError("please use StreamNoSQLTo(aClass) to add streamable to a database class.") readStream: (options, makeData)-> opt = extend({}, @_options, options) ReadStream @, opt, makeData createReadStream: @::readStream valueStream: (options, makeData)-> opt = extend({}, options) opt.keys = false @readStream opt, makeData createValueStream: @::valueStream keyStream: (options, makeData)-> opt = extend({}, options) opt.values = false @readStream opt, makeData createKeyStream: @::keyStream writeStream: (options)-> opt = extend({}, @_options, options) WriteStream @, opt createWriteStream: @::writeStream
true
# Copyright (c) 2014 PI:NAME:<NAME>END_PI, MIT License Errors = require("abstract-object/Error") #AbstractNoSQL = require("abstract-nosql") #inherits = require("abstract-object/lib/util/inherits") #inheritsDirectly = require("abstract-object/lib/util/inheritsDirectly") #isInheritedFrom = require("abstract-object/lib/util/isInheritedFrom") isFunction = require("abstract-object/lib/util/isFunction") extend = require("abstract-object/lib/util/_extend") InvalidArgumentError = Errors.InvalidArgumentError ReadStream = require("./read-stream") WriteStream = require("./write-stream") module.exports = class StreamNoSQL #inherits StreamNoSQL, AbstractNoSQL constructor: (aClass)-> if (this not instanceof StreamNoSQL) if isFunction aClass if not aClass::readStream extend aClass::, StreamNoSQL:: return aClass throw new InvalidArgumentError("this class has been already streamable.") throw new InvalidArgumentError("please use StreamNoSQLTo(aClass) to add streamable to a database class.") readStream: (options, makeData)-> opt = extend({}, @_options, options) ReadStream @, opt, makeData createReadStream: @::readStream valueStream: (options, makeData)-> opt = extend({}, options) opt.keys = false @readStream opt, makeData createValueStream: @::valueStream keyStream: (options, makeData)-> opt = extend({}, options) opt.values = false @readStream opt, makeData createKeyStream: @::keyStream writeStream: (options)-> opt = extend({}, @_options, options) WriteStream @, opt createWriteStream: @::writeStream
[ { "context": "#\n# ngQuickDate\n# by Adam Albrecht\n# http://adamalbrecht.com\n#\n# Source Code: https:", "end": 34, "score": 0.9998999834060669, "start": 21, "tag": "NAME", "value": "Adam Albrecht" }, { "context": "malbrecht.com\n#\n# Source Code: https://github.com/adamalbrecht/ngQ...
src/ng-quick-date.coffee
sree93/ngQuickDate
0
# # ngQuickDate # by Adam Albrecht # http://adamalbrecht.com # # Source Code: https://github.com/adamalbrecht/ngQuickDate # # Compatible with Angular 1.2.0+ # app = angular.module("ngQuickDate", []) app.provider "ngQuickDateDefaults", -> { options: { dateFormat: 'M/d/yyyy' timeFormat: 'h:mm a' labelFormat: null placeholder: 'Click to Set Date' hoverText: null buttonIconHtml: null closeButtonHtml: '&times;' nextLinkHtml: 'Next &rarr;' prevLinkHtml: '&larr; Prev' disableTimepicker: false disableClearButton: false disableTodayButton: false dateText: "Date" timeText: "Time" clearText: "Clear" todayText: "Today" okText: "OK" defaultTime: null dayAbbreviations: ["Su", "M", "Tu", "W", "Th", "F", "Sa"] dateFilter: null parseDateFunction: (str) -> seconds = Date.parse(str) if isNaN(seconds) return null else new Date(seconds) } $get: -> @options set: (keyOrHash, value) -> if typeof(keyOrHash) == 'object' for k, v of keyOrHash @options[k] = v else @options[keyOrHash] = value } app.directive "quickDatepicker", ['ngQuickDateDefaults', '$filter', '$sce', (ngQuickDateDefaults, $filter, $sce) -> restrict: "EA" require: "?ngModel" scope: dateFilter: '=?' onChange: "&" required: '@' replace: true link: (scope, element, attrs, ngModelCtrl) -> # INITIALIZE VARIABLES AND CONFIGURATION # ================================ initialize = -> setConfigOptions() # Setup configuration variables scope.toggleCalendar(false) # Make sure it is closed initially scope.weeks = [] # Nested Array of visible weeks / days in the popup scope.inputDate = null # Date inputted into the date text input field scope.inputTime = null # Time inputted into the time text input field scope.invalid = true if typeof(attrs.initValue) == 'string' ngModelCtrl.$setViewValue(attrs.initValue) setCalendarDate() refreshView() # Copy various configuration options from the default configuration to scope setConfigOptions = -> for key, value of ngQuickDateDefaults if key.match(/[Hh]tml/) scope[key] = $sce.trustAsHtml(ngQuickDateDefaults[key] || "") else if !scope[key] && attrs[key] scope[key] = attrs[key] else if !scope[key] scope[key] = ngQuickDateDefaults[key] if !scope.labelFormat scope.labelFormat = scope.dateFormat unless scope.disableTimepicker scope.labelFormat += " " + scope.timeFormat if attrs.iconClass && attrs.iconClass.length scope.buttonIconHtml = $sce.trustAsHtml("<i ng-show='iconClass' class='#{attrs.iconClass}'></i>") # VIEW SETUP # ================================ # This code listens for clicks both on the entire document and the popup. # If a click on the document is received but not on the popup, the popup # should be closed datepickerClicked = false window.document.addEventListener 'click', (event) -> if scope.calendarShown && ! datepickerClicked scope.toggleCalendar(false) scope.$apply() datepickerClicked = false angular.element(element[0])[0].addEventListener 'click', (event) -> datepickerClicked = true # SCOPE MANIPULATION Methods # ================================ # Refresh the calendar, the input dates, and the button date refreshView = -> date = if ngModelCtrl.$modelValue then parseDateString(ngModelCtrl.$modelValue) else null setupCalendarView() setInputFieldValues(date) scope.mainButtonStr = if date then $filter('date')(date, scope.labelFormat) else scope.placeholder scope.invalid = ngModelCtrl.$invalid # Set the values used in the 2 input fields setInputFieldValues = (val) -> if val? scope.inputDate = $filter('date')(val, scope.dateFormat) scope.inputTime = $filter('date')(val, scope.timeFormat) else scope.inputDate = null scope.inputTime = null # Set the date that is used by the calendar to determine which month to show # Defaults to the current month setCalendarDate = (val=null) -> d = if val? then new Date(val) else new Date() if (d.toString() == "Invalid Date") d = new Date() d.setDate(1) scope.calendarDate = new Date(d) # Setup the data needed by the table that makes up the calendar in the popup # Uses scope.calendarDate to decide which month to show setupCalendarView = -> offset = scope.calendarDate.getDay() daysInMonth = getDaysInMonth(scope.calendarDate.getFullYear(), scope.calendarDate.getMonth()) numRows = Math.ceil((offset + daysInMonth) / 7) weeks = [] curDate = new Date(scope.calendarDate) curDate.setDate(curDate.getDate() + (offset * -1)) for row in [0..(numRows-1)] weeks.push([]) for day in [0..6] d = new Date(curDate) if scope.defaultTime time = scope.defaultTime.split(':') d.setHours(time[0] || 0) d.setMinutes(time[1] || 0) d.setSeconds(time[2] || 0) selected = ngModelCtrl.$modelValue && d && datesAreEqual(d, ngModelCtrl.$modelValue) today = datesAreEqual(d, new Date()) weeks[row].push({ date: d selected: selected disabled: if (typeof(scope.dateFilter) == 'function') then !scope.dateFilter(d) else false other: d.getMonth() != scope.calendarDate.getMonth() today: today }) curDate.setDate(curDate.getDate() + 1) scope.weeks = weeks # PARSERS AND FORMATTERS # ================================= # When the model is set from within the datepicker, this will be run # before passing it to the model. ngModelCtrl.$parsers.push((viewVal) -> if scope.required && !viewVal? ngModelCtrl.$setValidity('required', false); null else if angular.isDate(viewVal) ngModelCtrl.$setValidity('required', true); viewVal else if angular.isString(viewVal) ngModelCtrl.$setValidity('required', true); scope.parseDateFunction(viewVal) else null ) # When the model is set from outside the datepicker, this will be run # before passing it to the datepicker ngModelCtrl.$formatters.push((modelVal) -> if angular.isDate(modelVal) modelVal else if angular.isString(modelVal) scope.parseDateFunction(modelVal) else undefined ) # HELPER METHODS # ================================= dateToString = (date, format) -> $filter('date')(date, format) stringToDate = (date) -> if typeof date == 'string' parseDateString(date) else date parseDateString = ngQuickDateDefaults.parseDateFunction datesAreEqual = (d1, d2, compareTimes=false) -> if compareTimes (d1 - d2) == 0 else d1 = stringToDate(d1); d2 = stringToDate(d2); d1 && d2 && (d1.getYear() == d2.getYear()) && (d1.getMonth() == d2.getMonth()) && (d1.getDate() == d2.getDate()) datesAreEqualToMinute = (d1, d2) -> return false unless d1 && d2 parseInt(d1.getTime() / 60000) == parseInt(d2.getTime() / 60000) getDaysInMonth = (year, month) -> [31, (if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) then 29 else 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month] # DATA WATCHES # ================================== # Called when the model is updated from outside the datepicker ngModelCtrl.$render = -> setCalendarDate(ngModelCtrl.$viewValue) refreshView() # Called when the model is updated from inside the datepicker, # either by clicking a calendar date, setting an input, etc ngModelCtrl.$viewChangeListeners.unshift -> setCalendarDate(ngModelCtrl.$viewValue) refreshView() if scope.onChange scope.onChange() # When the popup is toggled open, select the date input scope.$watch 'calendarShown', (newVal, oldVal) -> if newVal dateInput = angular.element(element[0].querySelector(".quickdate-date-input"))[0] dateInput.select() # VIEW ACTIONS # ================================== scope.toggleCalendar = (show) -> if isFinite(show) scope.calendarShown = show else scope.calendarShown = not scope.calendarShown # Select a new model date. This is called in 3 situations: # * Clicking a day on the calendar or from the `selectDateFromInput` # * Changing the date or time inputs, which call the `selectDateFromInput` method, which calls this method. # * The clear button is clicked scope.selectDate = (date, closeCalendar=true) -> changed = (!ngModelCtrl.$viewValue && date) || (ngModelCtrl.$viewValue && !date) || ((date && ngModelCtrl.$viewValue) && (date.getTime() != ngModelCtrl.$viewValue.getTime())) if typeof(scope.dateFilter) == 'function' && !scope.dateFilter(date) return false ngModelCtrl.$setViewValue(date) if closeCalendar scope.toggleCalendar(false) true # This is triggered when the date or time inputs have a blur or enter event. scope.selectDateFromInput = (closeCalendar=false) -> try tmpDate = parseDateString(scope.inputDate) if !tmpDate throw 'Invalid Date' if !scope.disableTimepicker && scope.inputTime and scope.inputTime.length and tmpDate tmpTime = if scope.disableTimepicker then '00:00:00' else scope.inputTime tmpDateAndTime = parseDateString("#{scope.inputDate} #{tmpTime}") if !tmpDateAndTime throw 'Invalid Time' tmpDate = tmpDateAndTime unless datesAreEqualToMinute(ngModelCtrl.$viewValue, tmpDate) if !scope.selectDate(tmpDate, false) throw 'Invalid Date' if closeCalendar scope.toggleCalendar(false) scope.inputDateErr = false scope.inputTimeErr = false catch err if err == 'Invalid Date' scope.inputDateErr = true else if err == 'Invalid Time' scope.inputTimeErr = true # When tab is pressed from the date input and the timepicker # is disabled, close the popup scope.onDateInputTab = -> if scope.disableTimepicker scope.toggleCalendar(false) true # When tab is pressed from the time input, close the popup scope.onTimeInputTab = -> scope.toggleCalendar(false) true # View the next and previous months in the calendar popup scope.nextMonth = -> setCalendarDate(new Date(new Date(scope.calendarDate).setMonth(scope.calendarDate.getMonth() + 1))) refreshView() scope.prevMonth = -> setCalendarDate(new Date(new Date(scope.calendarDate).setMonth(scope.calendarDate.getMonth() - 1))) refreshView() # Set the date model to null scope.clear = -> scope.selectDate(null, true) scope.today = -> scope.selectDate(new Date(), true) initialize() # TEMPLATE # ================================================================ template: """ <div class='quickdate'> <a href='' ng-focus='toggleCalendar(true)' ng-click='toggleCalendar(true)' class='quickdate-button' title='{{hoverText}}'><div ng-hide='iconClass' ng-bind-html='buttonIconHtml'></div>{{mainButtonStr}}</a> <div class='quickdate-popup' ng-class='{open: calendarShown}'> <a href='' tabindex='-1' class='quickdate-close' ng-click='toggleCalendar()'><div ng-bind-html='closeButtonHtml'></div></a> <div class='quickdate-text-inputs'> <div class='quickdate-input-wrapper'> <label>{{dateText}}</label> <input class='quickdate-date-input' ng-class="{'ng-invalid': inputDateErr, 'form-control': true}" name='inputDate' type='text' ng-model='inputDate' placeholder='1/1/2013' ng-enter="selectDateFromInput(true)" ng-blur="selectDateFromInput(false)" on-tab='onDateInputTab()' /> </div> <div class='quickdate-input-wrapper' ng-hide='disableTimepicker'> <label>{{timeText}}</label> <input class='quickdate-time-input' ng-class="{'ng-invalid': inputTimeErr, 'form-control': true}" name='inputTime' type='text' ng-model='inputTime' placeholder='12:00 PM' ng-enter="selectDateFromInput(true)" ng-blur="selectDateFromInput(false)" on-tab='onTimeInputTab()'> </div> </div> <div class='quickdate-calendar-header'> <a href='' class='quickdate-prev-month quickdate-action-link' tabindex='-1' ng-click='prevMonth()'><div ng-bind-html='prevLinkHtml'></div></a> <span class='quickdate-month'>{{calendarDate | date:'MMMM yyyy'}}</span> <a href='' class='quickdate-next-month quickdate-action-link' ng-click='nextMonth()' tabindex='-1' ><div ng-bind-html='nextLinkHtml'></div></a> </div> <table class='quickdate-calendar'> <thead> <tr> <th ng-repeat='day in dayAbbreviations'>{{day}}</th> </tr> </thead> <tbody> <tr ng-repeat='week in weeks'> <td ng-mousedown='selectDate(day.date, false, true)' ng-click='$event.preventDefault()' ng-class='{"other-month": day.other, "disabled-date": day.disabled, "selected": day.selected, "is-today": day.today}' ng-repeat='day in week'>{{day.date | date:'d'}}</td> </tr> </tbody> </table> <div class='quickdate-popup-footer'> <a href='' class='btn btn-sm btn-danger' tabindex='-1' ng-hide='disableClearButton' ng-click='clear()'>{{clearText}}</a> <a href='' class='btn btn-sm btn-primary' tabindex='-1' ng-hide='disableTodayButton' ng-click='today()'>{{todayText}}</a> <a href='' class='btn btn-sm btn-primary' tabindex='-1' ng-click='toggleCalendar(false)'>{{okText}}</a> </div> </div> </div> """ ] app.directive 'ngEnter', -> (scope, element, attr) -> element.bind 'keydown keypress', (e) -> if (e.which == 13) scope.$apply(attr.ngEnter) e.preventDefault() app.directive 'onTab', -> restrict: 'A', link: (scope, element, attr) -> element.bind 'keydown keypress', (e) -> if (e.which == 9) && !e.shiftKey scope.$apply(attr.onTab)
20627
# # ngQuickDate # by <NAME> # http://adamalbrecht.com # # Source Code: https://github.com/adamalbrecht/ngQuickDate # # Compatible with Angular 1.2.0+ # app = angular.module("ngQuickDate", []) app.provider "ngQuickDateDefaults", -> { options: { dateFormat: 'M/d/yyyy' timeFormat: 'h:mm a' labelFormat: null placeholder: 'Click to Set Date' hoverText: null buttonIconHtml: null closeButtonHtml: '&times;' nextLinkHtml: 'Next &rarr;' prevLinkHtml: '&larr; Prev' disableTimepicker: false disableClearButton: false disableTodayButton: false dateText: "Date" timeText: "Time" clearText: "Clear" todayText: "Today" okText: "OK" defaultTime: null dayAbbreviations: ["Su", "M", "Tu", "W", "Th", "F", "Sa"] dateFilter: null parseDateFunction: (str) -> seconds = Date.parse(str) if isNaN(seconds) return null else new Date(seconds) } $get: -> @options set: (keyOrHash, value) -> if typeof(keyOrHash) == 'object' for k, v of keyOrHash @options[k] = v else @options[keyOrHash] = value } app.directive "quickDatepicker", ['ngQuickDateDefaults', '$filter', '$sce', (ngQuickDateDefaults, $filter, $sce) -> restrict: "EA" require: "?ngModel" scope: dateFilter: '=?' onChange: "&" required: '@' replace: true link: (scope, element, attrs, ngModelCtrl) -> # INITIALIZE VARIABLES AND CONFIGURATION # ================================ initialize = -> setConfigOptions() # Setup configuration variables scope.toggleCalendar(false) # Make sure it is closed initially scope.weeks = [] # Nested Array of visible weeks / days in the popup scope.inputDate = null # Date inputted into the date text input field scope.inputTime = null # Time inputted into the time text input field scope.invalid = true if typeof(attrs.initValue) == 'string' ngModelCtrl.$setViewValue(attrs.initValue) setCalendarDate() refreshView() # Copy various configuration options from the default configuration to scope setConfigOptions = -> for key, value of ngQuickDateDefaults if key.match(/[Hh]tml/) scope[key] = $sce.trustAsHtml(ngQuickDateDefaults[key] || "") else if !scope[key] && attrs[key] scope[key] = attrs[key] else if !scope[key] scope[key] = ngQuickDateDefaults[key] if !scope.labelFormat scope.labelFormat = scope.dateFormat unless scope.disableTimepicker scope.labelFormat += " " + scope.timeFormat if attrs.iconClass && attrs.iconClass.length scope.buttonIconHtml = $sce.trustAsHtml("<i ng-show='iconClass' class='#{attrs.iconClass}'></i>") # VIEW SETUP # ================================ # This code listens for clicks both on the entire document and the popup. # If a click on the document is received but not on the popup, the popup # should be closed datepickerClicked = false window.document.addEventListener 'click', (event) -> if scope.calendarShown && ! datepickerClicked scope.toggleCalendar(false) scope.$apply() datepickerClicked = false angular.element(element[0])[0].addEventListener 'click', (event) -> datepickerClicked = true # SCOPE MANIPULATION Methods # ================================ # Refresh the calendar, the input dates, and the button date refreshView = -> date = if ngModelCtrl.$modelValue then parseDateString(ngModelCtrl.$modelValue) else null setupCalendarView() setInputFieldValues(date) scope.mainButtonStr = if date then $filter('date')(date, scope.labelFormat) else scope.placeholder scope.invalid = ngModelCtrl.$invalid # Set the values used in the 2 input fields setInputFieldValues = (val) -> if val? scope.inputDate = $filter('date')(val, scope.dateFormat) scope.inputTime = $filter('date')(val, scope.timeFormat) else scope.inputDate = null scope.inputTime = null # Set the date that is used by the calendar to determine which month to show # Defaults to the current month setCalendarDate = (val=null) -> d = if val? then new Date(val) else new Date() if (d.toString() == "Invalid Date") d = new Date() d.setDate(1) scope.calendarDate = new Date(d) # Setup the data needed by the table that makes up the calendar in the popup # Uses scope.calendarDate to decide which month to show setupCalendarView = -> offset = scope.calendarDate.getDay() daysInMonth = getDaysInMonth(scope.calendarDate.getFullYear(), scope.calendarDate.getMonth()) numRows = Math.ceil((offset + daysInMonth) / 7) weeks = [] curDate = new Date(scope.calendarDate) curDate.setDate(curDate.getDate() + (offset * -1)) for row in [0..(numRows-1)] weeks.push([]) for day in [0..6] d = new Date(curDate) if scope.defaultTime time = scope.defaultTime.split(':') d.setHours(time[0] || 0) d.setMinutes(time[1] || 0) d.setSeconds(time[2] || 0) selected = ngModelCtrl.$modelValue && d && datesAreEqual(d, ngModelCtrl.$modelValue) today = datesAreEqual(d, new Date()) weeks[row].push({ date: d selected: selected disabled: if (typeof(scope.dateFilter) == 'function') then !scope.dateFilter(d) else false other: d.getMonth() != scope.calendarDate.getMonth() today: today }) curDate.setDate(curDate.getDate() + 1) scope.weeks = weeks # PARSERS AND FORMATTERS # ================================= # When the model is set from within the datepicker, this will be run # before passing it to the model. ngModelCtrl.$parsers.push((viewVal) -> if scope.required && !viewVal? ngModelCtrl.$setValidity('required', false); null else if angular.isDate(viewVal) ngModelCtrl.$setValidity('required', true); viewVal else if angular.isString(viewVal) ngModelCtrl.$setValidity('required', true); scope.parseDateFunction(viewVal) else null ) # When the model is set from outside the datepicker, this will be run # before passing it to the datepicker ngModelCtrl.$formatters.push((modelVal) -> if angular.isDate(modelVal) modelVal else if angular.isString(modelVal) scope.parseDateFunction(modelVal) else undefined ) # HELPER METHODS # ================================= dateToString = (date, format) -> $filter('date')(date, format) stringToDate = (date) -> if typeof date == 'string' parseDateString(date) else date parseDateString = ngQuickDateDefaults.parseDateFunction datesAreEqual = (d1, d2, compareTimes=false) -> if compareTimes (d1 - d2) == 0 else d1 = stringToDate(d1); d2 = stringToDate(d2); d1 && d2 && (d1.getYear() == d2.getYear()) && (d1.getMonth() == d2.getMonth()) && (d1.getDate() == d2.getDate()) datesAreEqualToMinute = (d1, d2) -> return false unless d1 && d2 parseInt(d1.getTime() / 60000) == parseInt(d2.getTime() / 60000) getDaysInMonth = (year, month) -> [31, (if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) then 29 else 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month] # DATA WATCHES # ================================== # Called when the model is updated from outside the datepicker ngModelCtrl.$render = -> setCalendarDate(ngModelCtrl.$viewValue) refreshView() # Called when the model is updated from inside the datepicker, # either by clicking a calendar date, setting an input, etc ngModelCtrl.$viewChangeListeners.unshift -> setCalendarDate(ngModelCtrl.$viewValue) refreshView() if scope.onChange scope.onChange() # When the popup is toggled open, select the date input scope.$watch 'calendarShown', (newVal, oldVal) -> if newVal dateInput = angular.element(element[0].querySelector(".quickdate-date-input"))[0] dateInput.select() # VIEW ACTIONS # ================================== scope.toggleCalendar = (show) -> if isFinite(show) scope.calendarShown = show else scope.calendarShown = not scope.calendarShown # Select a new model date. This is called in 3 situations: # * Clicking a day on the calendar or from the `selectDateFromInput` # * Changing the date or time inputs, which call the `selectDateFromInput` method, which calls this method. # * The clear button is clicked scope.selectDate = (date, closeCalendar=true) -> changed = (!ngModelCtrl.$viewValue && date) || (ngModelCtrl.$viewValue && !date) || ((date && ngModelCtrl.$viewValue) && (date.getTime() != ngModelCtrl.$viewValue.getTime())) if typeof(scope.dateFilter) == 'function' && !scope.dateFilter(date) return false ngModelCtrl.$setViewValue(date) if closeCalendar scope.toggleCalendar(false) true # This is triggered when the date or time inputs have a blur or enter event. scope.selectDateFromInput = (closeCalendar=false) -> try tmpDate = parseDateString(scope.inputDate) if !tmpDate throw 'Invalid Date' if !scope.disableTimepicker && scope.inputTime and scope.inputTime.length and tmpDate tmpTime = if scope.disableTimepicker then '00:00:00' else scope.inputTime tmpDateAndTime = parseDateString("#{scope.inputDate} #{tmpTime}") if !tmpDateAndTime throw 'Invalid Time' tmpDate = tmpDateAndTime unless datesAreEqualToMinute(ngModelCtrl.$viewValue, tmpDate) if !scope.selectDate(tmpDate, false) throw 'Invalid Date' if closeCalendar scope.toggleCalendar(false) scope.inputDateErr = false scope.inputTimeErr = false catch err if err == 'Invalid Date' scope.inputDateErr = true else if err == 'Invalid Time' scope.inputTimeErr = true # When tab is pressed from the date input and the timepicker # is disabled, close the popup scope.onDateInputTab = -> if scope.disableTimepicker scope.toggleCalendar(false) true # When tab is pressed from the time input, close the popup scope.onTimeInputTab = -> scope.toggleCalendar(false) true # View the next and previous months in the calendar popup scope.nextMonth = -> setCalendarDate(new Date(new Date(scope.calendarDate).setMonth(scope.calendarDate.getMonth() + 1))) refreshView() scope.prevMonth = -> setCalendarDate(new Date(new Date(scope.calendarDate).setMonth(scope.calendarDate.getMonth() - 1))) refreshView() # Set the date model to null scope.clear = -> scope.selectDate(null, true) scope.today = -> scope.selectDate(new Date(), true) initialize() # TEMPLATE # ================================================================ template: """ <div class='quickdate'> <a href='' ng-focus='toggleCalendar(true)' ng-click='toggleCalendar(true)' class='quickdate-button' title='{{hoverText}}'><div ng-hide='iconClass' ng-bind-html='buttonIconHtml'></div>{{mainButtonStr}}</a> <div class='quickdate-popup' ng-class='{open: calendarShown}'> <a href='' tabindex='-1' class='quickdate-close' ng-click='toggleCalendar()'><div ng-bind-html='closeButtonHtml'></div></a> <div class='quickdate-text-inputs'> <div class='quickdate-input-wrapper'> <label>{{dateText}}</label> <input class='quickdate-date-input' ng-class="{'ng-invalid': inputDateErr, 'form-control': true}" name='inputDate' type='text' ng-model='inputDate' placeholder='1/1/2013' ng-enter="selectDateFromInput(true)" ng-blur="selectDateFromInput(false)" on-tab='onDateInputTab()' /> </div> <div class='quickdate-input-wrapper' ng-hide='disableTimepicker'> <label>{{timeText}}</label> <input class='quickdate-time-input' ng-class="{'ng-invalid': inputTimeErr, 'form-control': true}" name='inputTime' type='text' ng-model='inputTime' placeholder='12:00 PM' ng-enter="selectDateFromInput(true)" ng-blur="selectDateFromInput(false)" on-tab='onTimeInputTab()'> </div> </div> <div class='quickdate-calendar-header'> <a href='' class='quickdate-prev-month quickdate-action-link' tabindex='-1' ng-click='prevMonth()'><div ng-bind-html='prevLinkHtml'></div></a> <span class='quickdate-month'>{{calendarDate | date:'MMMM yyyy'}}</span> <a href='' class='quickdate-next-month quickdate-action-link' ng-click='nextMonth()' tabindex='-1' ><div ng-bind-html='nextLinkHtml'></div></a> </div> <table class='quickdate-calendar'> <thead> <tr> <th ng-repeat='day in dayAbbreviations'>{{day}}</th> </tr> </thead> <tbody> <tr ng-repeat='week in weeks'> <td ng-mousedown='selectDate(day.date, false, true)' ng-click='$event.preventDefault()' ng-class='{"other-month": day.other, "disabled-date": day.disabled, "selected": day.selected, "is-today": day.today}' ng-repeat='day in week'>{{day.date | date:'d'}}</td> </tr> </tbody> </table> <div class='quickdate-popup-footer'> <a href='' class='btn btn-sm btn-danger' tabindex='-1' ng-hide='disableClearButton' ng-click='clear()'>{{clearText}}</a> <a href='' class='btn btn-sm btn-primary' tabindex='-1' ng-hide='disableTodayButton' ng-click='today()'>{{todayText}}</a> <a href='' class='btn btn-sm btn-primary' tabindex='-1' ng-click='toggleCalendar(false)'>{{okText}}</a> </div> </div> </div> """ ] app.directive 'ngEnter', -> (scope, element, attr) -> element.bind 'keydown keypress', (e) -> if (e.which == 13) scope.$apply(attr.ngEnter) e.preventDefault() app.directive 'onTab', -> restrict: 'A', link: (scope, element, attr) -> element.bind 'keydown keypress', (e) -> if (e.which == 9) && !e.shiftKey scope.$apply(attr.onTab)
true
# # ngQuickDate # by PI:NAME:<NAME>END_PI # http://adamalbrecht.com # # Source Code: https://github.com/adamalbrecht/ngQuickDate # # Compatible with Angular 1.2.0+ # app = angular.module("ngQuickDate", []) app.provider "ngQuickDateDefaults", -> { options: { dateFormat: 'M/d/yyyy' timeFormat: 'h:mm a' labelFormat: null placeholder: 'Click to Set Date' hoverText: null buttonIconHtml: null closeButtonHtml: '&times;' nextLinkHtml: 'Next &rarr;' prevLinkHtml: '&larr; Prev' disableTimepicker: false disableClearButton: false disableTodayButton: false dateText: "Date" timeText: "Time" clearText: "Clear" todayText: "Today" okText: "OK" defaultTime: null dayAbbreviations: ["Su", "M", "Tu", "W", "Th", "F", "Sa"] dateFilter: null parseDateFunction: (str) -> seconds = Date.parse(str) if isNaN(seconds) return null else new Date(seconds) } $get: -> @options set: (keyOrHash, value) -> if typeof(keyOrHash) == 'object' for k, v of keyOrHash @options[k] = v else @options[keyOrHash] = value } app.directive "quickDatepicker", ['ngQuickDateDefaults', '$filter', '$sce', (ngQuickDateDefaults, $filter, $sce) -> restrict: "EA" require: "?ngModel" scope: dateFilter: '=?' onChange: "&" required: '@' replace: true link: (scope, element, attrs, ngModelCtrl) -> # INITIALIZE VARIABLES AND CONFIGURATION # ================================ initialize = -> setConfigOptions() # Setup configuration variables scope.toggleCalendar(false) # Make sure it is closed initially scope.weeks = [] # Nested Array of visible weeks / days in the popup scope.inputDate = null # Date inputted into the date text input field scope.inputTime = null # Time inputted into the time text input field scope.invalid = true if typeof(attrs.initValue) == 'string' ngModelCtrl.$setViewValue(attrs.initValue) setCalendarDate() refreshView() # Copy various configuration options from the default configuration to scope setConfigOptions = -> for key, value of ngQuickDateDefaults if key.match(/[Hh]tml/) scope[key] = $sce.trustAsHtml(ngQuickDateDefaults[key] || "") else if !scope[key] && attrs[key] scope[key] = attrs[key] else if !scope[key] scope[key] = ngQuickDateDefaults[key] if !scope.labelFormat scope.labelFormat = scope.dateFormat unless scope.disableTimepicker scope.labelFormat += " " + scope.timeFormat if attrs.iconClass && attrs.iconClass.length scope.buttonIconHtml = $sce.trustAsHtml("<i ng-show='iconClass' class='#{attrs.iconClass}'></i>") # VIEW SETUP # ================================ # This code listens for clicks both on the entire document and the popup. # If a click on the document is received but not on the popup, the popup # should be closed datepickerClicked = false window.document.addEventListener 'click', (event) -> if scope.calendarShown && ! datepickerClicked scope.toggleCalendar(false) scope.$apply() datepickerClicked = false angular.element(element[0])[0].addEventListener 'click', (event) -> datepickerClicked = true # SCOPE MANIPULATION Methods # ================================ # Refresh the calendar, the input dates, and the button date refreshView = -> date = if ngModelCtrl.$modelValue then parseDateString(ngModelCtrl.$modelValue) else null setupCalendarView() setInputFieldValues(date) scope.mainButtonStr = if date then $filter('date')(date, scope.labelFormat) else scope.placeholder scope.invalid = ngModelCtrl.$invalid # Set the values used in the 2 input fields setInputFieldValues = (val) -> if val? scope.inputDate = $filter('date')(val, scope.dateFormat) scope.inputTime = $filter('date')(val, scope.timeFormat) else scope.inputDate = null scope.inputTime = null # Set the date that is used by the calendar to determine which month to show # Defaults to the current month setCalendarDate = (val=null) -> d = if val? then new Date(val) else new Date() if (d.toString() == "Invalid Date") d = new Date() d.setDate(1) scope.calendarDate = new Date(d) # Setup the data needed by the table that makes up the calendar in the popup # Uses scope.calendarDate to decide which month to show setupCalendarView = -> offset = scope.calendarDate.getDay() daysInMonth = getDaysInMonth(scope.calendarDate.getFullYear(), scope.calendarDate.getMonth()) numRows = Math.ceil((offset + daysInMonth) / 7) weeks = [] curDate = new Date(scope.calendarDate) curDate.setDate(curDate.getDate() + (offset * -1)) for row in [0..(numRows-1)] weeks.push([]) for day in [0..6] d = new Date(curDate) if scope.defaultTime time = scope.defaultTime.split(':') d.setHours(time[0] || 0) d.setMinutes(time[1] || 0) d.setSeconds(time[2] || 0) selected = ngModelCtrl.$modelValue && d && datesAreEqual(d, ngModelCtrl.$modelValue) today = datesAreEqual(d, new Date()) weeks[row].push({ date: d selected: selected disabled: if (typeof(scope.dateFilter) == 'function') then !scope.dateFilter(d) else false other: d.getMonth() != scope.calendarDate.getMonth() today: today }) curDate.setDate(curDate.getDate() + 1) scope.weeks = weeks # PARSERS AND FORMATTERS # ================================= # When the model is set from within the datepicker, this will be run # before passing it to the model. ngModelCtrl.$parsers.push((viewVal) -> if scope.required && !viewVal? ngModelCtrl.$setValidity('required', false); null else if angular.isDate(viewVal) ngModelCtrl.$setValidity('required', true); viewVal else if angular.isString(viewVal) ngModelCtrl.$setValidity('required', true); scope.parseDateFunction(viewVal) else null ) # When the model is set from outside the datepicker, this will be run # before passing it to the datepicker ngModelCtrl.$formatters.push((modelVal) -> if angular.isDate(modelVal) modelVal else if angular.isString(modelVal) scope.parseDateFunction(modelVal) else undefined ) # HELPER METHODS # ================================= dateToString = (date, format) -> $filter('date')(date, format) stringToDate = (date) -> if typeof date == 'string' parseDateString(date) else date parseDateString = ngQuickDateDefaults.parseDateFunction datesAreEqual = (d1, d2, compareTimes=false) -> if compareTimes (d1 - d2) == 0 else d1 = stringToDate(d1); d2 = stringToDate(d2); d1 && d2 && (d1.getYear() == d2.getYear()) && (d1.getMonth() == d2.getMonth()) && (d1.getDate() == d2.getDate()) datesAreEqualToMinute = (d1, d2) -> return false unless d1 && d2 parseInt(d1.getTime() / 60000) == parseInt(d2.getTime() / 60000) getDaysInMonth = (year, month) -> [31, (if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) then 29 else 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month] # DATA WATCHES # ================================== # Called when the model is updated from outside the datepicker ngModelCtrl.$render = -> setCalendarDate(ngModelCtrl.$viewValue) refreshView() # Called when the model is updated from inside the datepicker, # either by clicking a calendar date, setting an input, etc ngModelCtrl.$viewChangeListeners.unshift -> setCalendarDate(ngModelCtrl.$viewValue) refreshView() if scope.onChange scope.onChange() # When the popup is toggled open, select the date input scope.$watch 'calendarShown', (newVal, oldVal) -> if newVal dateInput = angular.element(element[0].querySelector(".quickdate-date-input"))[0] dateInput.select() # VIEW ACTIONS # ================================== scope.toggleCalendar = (show) -> if isFinite(show) scope.calendarShown = show else scope.calendarShown = not scope.calendarShown # Select a new model date. This is called in 3 situations: # * Clicking a day on the calendar or from the `selectDateFromInput` # * Changing the date or time inputs, which call the `selectDateFromInput` method, which calls this method. # * The clear button is clicked scope.selectDate = (date, closeCalendar=true) -> changed = (!ngModelCtrl.$viewValue && date) || (ngModelCtrl.$viewValue && !date) || ((date && ngModelCtrl.$viewValue) && (date.getTime() != ngModelCtrl.$viewValue.getTime())) if typeof(scope.dateFilter) == 'function' && !scope.dateFilter(date) return false ngModelCtrl.$setViewValue(date) if closeCalendar scope.toggleCalendar(false) true # This is triggered when the date or time inputs have a blur or enter event. scope.selectDateFromInput = (closeCalendar=false) -> try tmpDate = parseDateString(scope.inputDate) if !tmpDate throw 'Invalid Date' if !scope.disableTimepicker && scope.inputTime and scope.inputTime.length and tmpDate tmpTime = if scope.disableTimepicker then '00:00:00' else scope.inputTime tmpDateAndTime = parseDateString("#{scope.inputDate} #{tmpTime}") if !tmpDateAndTime throw 'Invalid Time' tmpDate = tmpDateAndTime unless datesAreEqualToMinute(ngModelCtrl.$viewValue, tmpDate) if !scope.selectDate(tmpDate, false) throw 'Invalid Date' if closeCalendar scope.toggleCalendar(false) scope.inputDateErr = false scope.inputTimeErr = false catch err if err == 'Invalid Date' scope.inputDateErr = true else if err == 'Invalid Time' scope.inputTimeErr = true # When tab is pressed from the date input and the timepicker # is disabled, close the popup scope.onDateInputTab = -> if scope.disableTimepicker scope.toggleCalendar(false) true # When tab is pressed from the time input, close the popup scope.onTimeInputTab = -> scope.toggleCalendar(false) true # View the next and previous months in the calendar popup scope.nextMonth = -> setCalendarDate(new Date(new Date(scope.calendarDate).setMonth(scope.calendarDate.getMonth() + 1))) refreshView() scope.prevMonth = -> setCalendarDate(new Date(new Date(scope.calendarDate).setMonth(scope.calendarDate.getMonth() - 1))) refreshView() # Set the date model to null scope.clear = -> scope.selectDate(null, true) scope.today = -> scope.selectDate(new Date(), true) initialize() # TEMPLATE # ================================================================ template: """ <div class='quickdate'> <a href='' ng-focus='toggleCalendar(true)' ng-click='toggleCalendar(true)' class='quickdate-button' title='{{hoverText}}'><div ng-hide='iconClass' ng-bind-html='buttonIconHtml'></div>{{mainButtonStr}}</a> <div class='quickdate-popup' ng-class='{open: calendarShown}'> <a href='' tabindex='-1' class='quickdate-close' ng-click='toggleCalendar()'><div ng-bind-html='closeButtonHtml'></div></a> <div class='quickdate-text-inputs'> <div class='quickdate-input-wrapper'> <label>{{dateText}}</label> <input class='quickdate-date-input' ng-class="{'ng-invalid': inputDateErr, 'form-control': true}" name='inputDate' type='text' ng-model='inputDate' placeholder='1/1/2013' ng-enter="selectDateFromInput(true)" ng-blur="selectDateFromInput(false)" on-tab='onDateInputTab()' /> </div> <div class='quickdate-input-wrapper' ng-hide='disableTimepicker'> <label>{{timeText}}</label> <input class='quickdate-time-input' ng-class="{'ng-invalid': inputTimeErr, 'form-control': true}" name='inputTime' type='text' ng-model='inputTime' placeholder='12:00 PM' ng-enter="selectDateFromInput(true)" ng-blur="selectDateFromInput(false)" on-tab='onTimeInputTab()'> </div> </div> <div class='quickdate-calendar-header'> <a href='' class='quickdate-prev-month quickdate-action-link' tabindex='-1' ng-click='prevMonth()'><div ng-bind-html='prevLinkHtml'></div></a> <span class='quickdate-month'>{{calendarDate | date:'MMMM yyyy'}}</span> <a href='' class='quickdate-next-month quickdate-action-link' ng-click='nextMonth()' tabindex='-1' ><div ng-bind-html='nextLinkHtml'></div></a> </div> <table class='quickdate-calendar'> <thead> <tr> <th ng-repeat='day in dayAbbreviations'>{{day}}</th> </tr> </thead> <tbody> <tr ng-repeat='week in weeks'> <td ng-mousedown='selectDate(day.date, false, true)' ng-click='$event.preventDefault()' ng-class='{"other-month": day.other, "disabled-date": day.disabled, "selected": day.selected, "is-today": day.today}' ng-repeat='day in week'>{{day.date | date:'d'}}</td> </tr> </tbody> </table> <div class='quickdate-popup-footer'> <a href='' class='btn btn-sm btn-danger' tabindex='-1' ng-hide='disableClearButton' ng-click='clear()'>{{clearText}}</a> <a href='' class='btn btn-sm btn-primary' tabindex='-1' ng-hide='disableTodayButton' ng-click='today()'>{{todayText}}</a> <a href='' class='btn btn-sm btn-primary' tabindex='-1' ng-click='toggleCalendar(false)'>{{okText}}</a> </div> </div> </div> """ ] app.directive 'ngEnter', -> (scope, element, attr) -> element.bind 'keydown keypress', (e) -> if (e.which == 13) scope.$apply(attr.ngEnter) e.preventDefault() app.directive 'onTab', -> restrict: 'A', link: (scope, element, attr) -> element.bind 'keydown keypress', (e) -> if (e.which == 9) && !e.shiftKey scope.$apply(attr.onTab)
[ { "context": "# https://amussey.github.io/2015/08/11/testing-hubot-scripts.html\n\n", "end": 17, "score": 0.9173654913902283, "start": 10, "tag": "USERNAME", "value": "amussey" }, { "context": ".getReviewers()\n expect( reviewers ).to.eql 'Emma, Hank'\n\n describe '#pullRequest...
test/bitbucket-pr_test.coffee
hubot-scripts/hubot-bitbucket-pr
20
# https://amussey.github.io/2015/08/11/testing-hubot-scripts.html Coffee = require('coffee-script') fs = require('fs') Helper = require('hubot-test-helper') expect = require('chai').expect # Compile without the function wrapper so we can test the PullRequestEvent class contents = Coffee.compile( fs.readFileSync('./src/bitbucket-pr.coffee', 'utf8')+'', bare: true ) eval( contents ) # helper loads a specific script if it's a file helper = new Helper('../src/bitbucket-pr.coffee') ROBOT = helper.createRoom().robot # https://confluence.atlassian.com/bitbucket/event-payloads-740262817.html CREATED_RESP = require('./support/created.json') COMMENT_RESP = require('./support/comment.json') MERGED_RESP = require('./support/merged.json') UPDATED_RESP = require('./support/updated.json') APPROVED_RESP = require('./support/approved.json') DECLINED_RESP = require('./support/declined.json') UNAPPROVED_RESP = require('./support/unapproved.json') ISSUE_CREATED_RESP = require('./support/issue-created.json') ISSUE_COMMENTED_RESP = require('./support/issue-commented.json') ISSUE_UPDATED_RESP = require('./support/issue-updated.json') # Mock robot for the logger.debug functions in getMessage MOCK_ROBOT = logger: debug: (str) -> str describe 'getEnvAnnounceOptions()', -> beforeEach -> @original_process_var = process.env.HUBOT_BITBUCKET_PULLREQUEST_ANNOUNCE afterEach -> process.env.HUBOT_BITBUCKET_PULLREQUEST_ANNOUNCE = @original_process_var context 'process.env.HUBOT_BITBUCKET_PULLREQUEST_ANNOUNCE is not set', -> it 'should fallback to the default variables', -> delete process.env.HUBOT_BITBUCKET_PULLREQUEST_ANNOUNCE generated_announce_options = getEnvAnnounceOptions() expect( generated_announce_options ).to.eql ['created', 'updated', 'declined', 'merged', 'comment_created', 'approve', 'unapprove', 'issue_created', 'issue_comment_created', 'issue_updated'] context 'process.env.HUBOT_BITBUCKET_PULLREQUEST_ANNOUNCE is "created,merged"', -> it 'should generate an array from the provided variable', -> process.env.HUBOT_BITBUCKET_PULLREQUEST_ANNOUNCE = 'created,merged' generated_announce_options = getEnvAnnounceOptions() expect( generated_announce_options ).to.eql ['created', 'merged'] describe 'encourageMe()', -> it 'should contain an encouragement and be a string', -> generated_encouragement = encourageMe() expect( generated_encouragement ).to.be.a 'string' describe 'PullRequestEvent', -> pre = null beforeEach -> pre = new PullRequestEvent(MOCK_ROBOT, CREATED_RESP, 'pullrequest:created') # Clear variable afterEach -> pre = null describe '#constructor', -> it 'should have all instance attributes for a pull request', -> expect( pre.actor ).to.eql 'Emma' expect( pre.title ).to.eql 'Title of pull request' expect( pre.source_branch ).to.eql 'branch2' expect( pre.destination_branch ).to.eql 'master' expect( pre.repo_name ).to.eql 'repo_name' expect( pre.link ).to.eql 'https://api.bitbucket.org/pullrequest_id' expect( pre.reason ).to.eql ':\n"reason for declining the PR (if applicable)"' it 'should have all instance attributes for an issue ', -> pre = new PullRequestEvent(MOCK_ROBOT, ISSUE_CREATED_RESP, 'issue:created') expect( pre.actor ).to.eql 'Emma' expect( pre.title ).to.eql 'Issue title' expect( pre.repo_name ).to.eql 'repo_name' expect( pre.link ).to.eql 'https://api.bitbucket.org/issue_id' expect( pre.priority ).to.eql 'trivial' expect( pre.state ).to.eql 'new' expect( pre.kind ).to.eql 'bug' describe '#getReviewers()', -> it 'should have reviewers', -> reviewers = pre.getReviewers() expect( reviewers ).to.eql 'Emma, Hank' describe '#pullRequestGenericAction()', -> it 'should have a custom message', -> action = pre.pullRequestGenericAction('created', 'thwarting the attempted merge of') expect( action ).to.eql 'Emma *created* pull request "Title of pull request," thwarting the attempted merge of `branch2` and `master` into a `repo_name` super branch:\n"reason for declining the PR (if applicable)"' describe '#getMessage()', -> it 'should provide the message for pullrequest:created', -> message = pre.getMessage() expect( message ).to.eql 'Yo Emma, Hank, Emma just *created* the pull request "Title of pull request" for `branch2` on `repo_name`. \nhttps://api.bitbucket.org/pullrequest_id' describe 'SlackPullRequestEvent', -> pre = null beforeEach -> pre = new SlackPullRequestEvent(MOCK_ROBOT, CREATED_RESP, 'pullrequest:created') # Clear variable afterEach -> pre = null describe '#pullRequestGenericAction()', -> it 'should have a successful reply on create', -> action = pre.pullRequestGenericAction('created', COLORS.created) expect( action.text ).to.eql 'Pull Request created by Emma' expect( action.color ).to.eql COLORS.created expect( action.fields[0].title ).to.eql pre.title expect( action.fields[1].value ).to.eql '<https://api.bitbucket.org/pullrequest_id|View on Bitbucket>' describe '#pullRequestCreated()', -> it 'should have a custom message', -> action = pre.pullRequestCreated() expect( action.text ).to.eql 'New Request from Emma' expect( action.color ).to.eql COLORS.created expect( action.fields[0].title ).to.eql pre.title expect( action.fields[1].value ).to.eql 'Merge branch2 to master\n<https://api.bitbucket.org/pullrequest_id|View on Bitbucket>' describe '#pullRequestDeclined()', -> it 'should use pullRequestGenericAction\'s response' , -> pre = new SlackPullRequestEvent(MOCK_ROBOT, DECLINED_RESP, 'pullrequest:declined') action = pre.pullRequestDeclined() expect( action.text ).to.eql 'Pull Request Declined by Emma' expect( action.color ).to.eql COLORS.declined expect( action.fields[0].title ).to.eql pre.title expect( action.fields[1].value ).to.eql '<https://api.bitbucket.org/pullrequest_id|View on Bitbucket>' describe '#issueCreated()', -> it 'should respond with issue formatting', -> pre = new SlackPullRequestEvent(MOCK_ROBOT, ISSUE_CREATED_RESP, 'issue:created') action = pre.issueCreated() expect( action.text ).to.eql 'New Issue from Emma' expect( action.color ).to.eql COLORS.created expect( action.fields[0].title ).to.eql "#{pre.title} (bug)" expect( action.fields[1].value ).to.eql '<https://api.bitbucket.org/issue_id|View on Bitbucket>' describe '#issueUpdated()', -> it 'should respond with issue formatting', -> pre = new SlackPullRequestEvent(MOCK_ROBOT, ISSUE_UPDATED_RESP, 'issue:updated') action = pre.issueUpdated() expect( action.color ).to.eql COLORS.updated expect( action.fields[0].title ).to.eql 'Emma changed' expect( action.fields[0].value ).to.eql "*status*: open -> on hold"
5778
# https://amussey.github.io/2015/08/11/testing-hubot-scripts.html Coffee = require('coffee-script') fs = require('fs') Helper = require('hubot-test-helper') expect = require('chai').expect # Compile without the function wrapper so we can test the PullRequestEvent class contents = Coffee.compile( fs.readFileSync('./src/bitbucket-pr.coffee', 'utf8')+'', bare: true ) eval( contents ) # helper loads a specific script if it's a file helper = new Helper('../src/bitbucket-pr.coffee') ROBOT = helper.createRoom().robot # https://confluence.atlassian.com/bitbucket/event-payloads-740262817.html CREATED_RESP = require('./support/created.json') COMMENT_RESP = require('./support/comment.json') MERGED_RESP = require('./support/merged.json') UPDATED_RESP = require('./support/updated.json') APPROVED_RESP = require('./support/approved.json') DECLINED_RESP = require('./support/declined.json') UNAPPROVED_RESP = require('./support/unapproved.json') ISSUE_CREATED_RESP = require('./support/issue-created.json') ISSUE_COMMENTED_RESP = require('./support/issue-commented.json') ISSUE_UPDATED_RESP = require('./support/issue-updated.json') # Mock robot for the logger.debug functions in getMessage MOCK_ROBOT = logger: debug: (str) -> str describe 'getEnvAnnounceOptions()', -> beforeEach -> @original_process_var = process.env.HUBOT_BITBUCKET_PULLREQUEST_ANNOUNCE afterEach -> process.env.HUBOT_BITBUCKET_PULLREQUEST_ANNOUNCE = @original_process_var context 'process.env.HUBOT_BITBUCKET_PULLREQUEST_ANNOUNCE is not set', -> it 'should fallback to the default variables', -> delete process.env.HUBOT_BITBUCKET_PULLREQUEST_ANNOUNCE generated_announce_options = getEnvAnnounceOptions() expect( generated_announce_options ).to.eql ['created', 'updated', 'declined', 'merged', 'comment_created', 'approve', 'unapprove', 'issue_created', 'issue_comment_created', 'issue_updated'] context 'process.env.HUBOT_BITBUCKET_PULLREQUEST_ANNOUNCE is "created,merged"', -> it 'should generate an array from the provided variable', -> process.env.HUBOT_BITBUCKET_PULLREQUEST_ANNOUNCE = 'created,merged' generated_announce_options = getEnvAnnounceOptions() expect( generated_announce_options ).to.eql ['created', 'merged'] describe 'encourageMe()', -> it 'should contain an encouragement and be a string', -> generated_encouragement = encourageMe() expect( generated_encouragement ).to.be.a 'string' describe 'PullRequestEvent', -> pre = null beforeEach -> pre = new PullRequestEvent(MOCK_ROBOT, CREATED_RESP, 'pullrequest:created') # Clear variable afterEach -> pre = null describe '#constructor', -> it 'should have all instance attributes for a pull request', -> expect( pre.actor ).to.eql 'Emma' expect( pre.title ).to.eql 'Title of pull request' expect( pre.source_branch ).to.eql 'branch2' expect( pre.destination_branch ).to.eql 'master' expect( pre.repo_name ).to.eql 'repo_name' expect( pre.link ).to.eql 'https://api.bitbucket.org/pullrequest_id' expect( pre.reason ).to.eql ':\n"reason for declining the PR (if applicable)"' it 'should have all instance attributes for an issue ', -> pre = new PullRequestEvent(MOCK_ROBOT, ISSUE_CREATED_RESP, 'issue:created') expect( pre.actor ).to.eql 'Emma' expect( pre.title ).to.eql 'Issue title' expect( pre.repo_name ).to.eql 'repo_name' expect( pre.link ).to.eql 'https://api.bitbucket.org/issue_id' expect( pre.priority ).to.eql 'trivial' expect( pre.state ).to.eql 'new' expect( pre.kind ).to.eql 'bug' describe '#getReviewers()', -> it 'should have reviewers', -> reviewers = pre.getReviewers() expect( reviewers ).to.eql '<NAME>' describe '#pullRequestGenericAction()', -> it 'should have a custom message', -> action = pre.pullRequestGenericAction('created', 'thwarting the attempted merge of') expect( action ).to.eql '<NAME> *created* pull request "Title of pull request," thwarting the attempted merge of `branch2` and `master` into a `repo_name` super branch:\n"reason for declining the PR (if applicable)"' describe '#getMessage()', -> it 'should provide the message for pullrequest:created', -> message = pre.getMessage() expect( message ).to.eql 'Yo <NAME>, <NAME> just *created* the pull request "Title of pull request" for `branch2` on `repo_name`. \nhttps://api.bitbucket.org/pullrequest_id' describe 'SlackPullRequestEvent', -> pre = null beforeEach -> pre = new SlackPullRequestEvent(MOCK_ROBOT, CREATED_RESP, 'pullrequest:created') # Clear variable afterEach -> pre = null describe '#pullRequestGenericAction()', -> it 'should have a successful reply on create', -> action = pre.pullRequestGenericAction('created', COLORS.created) expect( action.text ).to.eql 'Pull Request created by <NAME>' expect( action.color ).to.eql COLORS.created expect( action.fields[0].title ).to.eql pre.title expect( action.fields[1].value ).to.eql '<https://api.bitbucket.org/pullrequest_id|View on Bitbucket>' describe '#pullRequestCreated()', -> it 'should have a custom message', -> action = pre.pullRequestCreated() expect( action.text ).to.eql 'New Request from <NAME>' expect( action.color ).to.eql COLORS.created expect( action.fields[0].title ).to.eql pre.title expect( action.fields[1].value ).to.eql 'Merge branch2 to master\n<https://api.bitbucket.org/pullrequest_id|View on Bitbucket>' describe '#pullRequestDeclined()', -> it 'should use pullRequestGenericAction\'s response' , -> pre = new SlackPullRequestEvent(MOCK_ROBOT, DECLINED_RESP, 'pullrequest:declined') action = pre.pullRequestDeclined() expect( action.text ).to.eql 'Pull Request Declined by <NAME>' expect( action.color ).to.eql COLORS.declined expect( action.fields[0].title ).to.eql pre.title expect( action.fields[1].value ).to.eql '<https://api.bitbucket.org/pullrequest_id|View on Bitbucket>' describe '#issueCreated()', -> it 'should respond with issue formatting', -> pre = new SlackPullRequestEvent(MOCK_ROBOT, ISSUE_CREATED_RESP, 'issue:created') action = pre.issueCreated() expect( action.text ).to.eql 'New Issue from <NAME>' expect( action.color ).to.eql COLORS.created expect( action.fields[0].title ).to.eql "#{pre.title} (bug)" expect( action.fields[1].value ).to.eql '<https://api.bitbucket.org/issue_id|View on Bitbucket>' describe '#issueUpdated()', -> it 'should respond with issue formatting', -> pre = new SlackPullRequestEvent(MOCK_ROBOT, ISSUE_UPDATED_RESP, 'issue:updated') action = pre.issueUpdated() expect( action.color ).to.eql COLORS.updated expect( action.fields[0].title ).to.eql '<NAME> changed' expect( action.fields[0].value ).to.eql "*status*: open -> on hold"
true
# https://amussey.github.io/2015/08/11/testing-hubot-scripts.html Coffee = require('coffee-script') fs = require('fs') Helper = require('hubot-test-helper') expect = require('chai').expect # Compile without the function wrapper so we can test the PullRequestEvent class contents = Coffee.compile( fs.readFileSync('./src/bitbucket-pr.coffee', 'utf8')+'', bare: true ) eval( contents ) # helper loads a specific script if it's a file helper = new Helper('../src/bitbucket-pr.coffee') ROBOT = helper.createRoom().robot # https://confluence.atlassian.com/bitbucket/event-payloads-740262817.html CREATED_RESP = require('./support/created.json') COMMENT_RESP = require('./support/comment.json') MERGED_RESP = require('./support/merged.json') UPDATED_RESP = require('./support/updated.json') APPROVED_RESP = require('./support/approved.json') DECLINED_RESP = require('./support/declined.json') UNAPPROVED_RESP = require('./support/unapproved.json') ISSUE_CREATED_RESP = require('./support/issue-created.json') ISSUE_COMMENTED_RESP = require('./support/issue-commented.json') ISSUE_UPDATED_RESP = require('./support/issue-updated.json') # Mock robot for the logger.debug functions in getMessage MOCK_ROBOT = logger: debug: (str) -> str describe 'getEnvAnnounceOptions()', -> beforeEach -> @original_process_var = process.env.HUBOT_BITBUCKET_PULLREQUEST_ANNOUNCE afterEach -> process.env.HUBOT_BITBUCKET_PULLREQUEST_ANNOUNCE = @original_process_var context 'process.env.HUBOT_BITBUCKET_PULLREQUEST_ANNOUNCE is not set', -> it 'should fallback to the default variables', -> delete process.env.HUBOT_BITBUCKET_PULLREQUEST_ANNOUNCE generated_announce_options = getEnvAnnounceOptions() expect( generated_announce_options ).to.eql ['created', 'updated', 'declined', 'merged', 'comment_created', 'approve', 'unapprove', 'issue_created', 'issue_comment_created', 'issue_updated'] context 'process.env.HUBOT_BITBUCKET_PULLREQUEST_ANNOUNCE is "created,merged"', -> it 'should generate an array from the provided variable', -> process.env.HUBOT_BITBUCKET_PULLREQUEST_ANNOUNCE = 'created,merged' generated_announce_options = getEnvAnnounceOptions() expect( generated_announce_options ).to.eql ['created', 'merged'] describe 'encourageMe()', -> it 'should contain an encouragement and be a string', -> generated_encouragement = encourageMe() expect( generated_encouragement ).to.be.a 'string' describe 'PullRequestEvent', -> pre = null beforeEach -> pre = new PullRequestEvent(MOCK_ROBOT, CREATED_RESP, 'pullrequest:created') # Clear variable afterEach -> pre = null describe '#constructor', -> it 'should have all instance attributes for a pull request', -> expect( pre.actor ).to.eql 'Emma' expect( pre.title ).to.eql 'Title of pull request' expect( pre.source_branch ).to.eql 'branch2' expect( pre.destination_branch ).to.eql 'master' expect( pre.repo_name ).to.eql 'repo_name' expect( pre.link ).to.eql 'https://api.bitbucket.org/pullrequest_id' expect( pre.reason ).to.eql ':\n"reason for declining the PR (if applicable)"' it 'should have all instance attributes for an issue ', -> pre = new PullRequestEvent(MOCK_ROBOT, ISSUE_CREATED_RESP, 'issue:created') expect( pre.actor ).to.eql 'Emma' expect( pre.title ).to.eql 'Issue title' expect( pre.repo_name ).to.eql 'repo_name' expect( pre.link ).to.eql 'https://api.bitbucket.org/issue_id' expect( pre.priority ).to.eql 'trivial' expect( pre.state ).to.eql 'new' expect( pre.kind ).to.eql 'bug' describe '#getReviewers()', -> it 'should have reviewers', -> reviewers = pre.getReviewers() expect( reviewers ).to.eql 'PI:NAME:<NAME>END_PI' describe '#pullRequestGenericAction()', -> it 'should have a custom message', -> action = pre.pullRequestGenericAction('created', 'thwarting the attempted merge of') expect( action ).to.eql 'PI:NAME:<NAME>END_PI *created* pull request "Title of pull request," thwarting the attempted merge of `branch2` and `master` into a `repo_name` super branch:\n"reason for declining the PR (if applicable)"' describe '#getMessage()', -> it 'should provide the message for pullrequest:created', -> message = pre.getMessage() expect( message ).to.eql 'Yo PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI just *created* the pull request "Title of pull request" for `branch2` on `repo_name`. \nhttps://api.bitbucket.org/pullrequest_id' describe 'SlackPullRequestEvent', -> pre = null beforeEach -> pre = new SlackPullRequestEvent(MOCK_ROBOT, CREATED_RESP, 'pullrequest:created') # Clear variable afterEach -> pre = null describe '#pullRequestGenericAction()', -> it 'should have a successful reply on create', -> action = pre.pullRequestGenericAction('created', COLORS.created) expect( action.text ).to.eql 'Pull Request created by PI:NAME:<NAME>END_PI' expect( action.color ).to.eql COLORS.created expect( action.fields[0].title ).to.eql pre.title expect( action.fields[1].value ).to.eql '<https://api.bitbucket.org/pullrequest_id|View on Bitbucket>' describe '#pullRequestCreated()', -> it 'should have a custom message', -> action = pre.pullRequestCreated() expect( action.text ).to.eql 'New Request from PI:NAME:<NAME>END_PI' expect( action.color ).to.eql COLORS.created expect( action.fields[0].title ).to.eql pre.title expect( action.fields[1].value ).to.eql 'Merge branch2 to master\n<https://api.bitbucket.org/pullrequest_id|View on Bitbucket>' describe '#pullRequestDeclined()', -> it 'should use pullRequestGenericAction\'s response' , -> pre = new SlackPullRequestEvent(MOCK_ROBOT, DECLINED_RESP, 'pullrequest:declined') action = pre.pullRequestDeclined() expect( action.text ).to.eql 'Pull Request Declined by PI:NAME:<NAME>END_PI' expect( action.color ).to.eql COLORS.declined expect( action.fields[0].title ).to.eql pre.title expect( action.fields[1].value ).to.eql '<https://api.bitbucket.org/pullrequest_id|View on Bitbucket>' describe '#issueCreated()', -> it 'should respond with issue formatting', -> pre = new SlackPullRequestEvent(MOCK_ROBOT, ISSUE_CREATED_RESP, 'issue:created') action = pre.issueCreated() expect( action.text ).to.eql 'New Issue from PI:NAME:<NAME>END_PI' expect( action.color ).to.eql COLORS.created expect( action.fields[0].title ).to.eql "#{pre.title} (bug)" expect( action.fields[1].value ).to.eql '<https://api.bitbucket.org/issue_id|View on Bitbucket>' describe '#issueUpdated()', -> it 'should respond with issue formatting', -> pre = new SlackPullRequestEvent(MOCK_ROBOT, ISSUE_UPDATED_RESP, 'issue:updated') action = pre.issueUpdated() expect( action.color ).to.eql COLORS.updated expect( action.fields[0].title ).to.eql 'PI:NAME:<NAME>END_PI changed' expect( action.fields[0].value ).to.eql "*status*: open -> on hold"
[ { "context": "ds\"\nphase: \"beta\"\nphase_modifier: \"Private\"\nsro: \"Kenny Robertson\"\nservice_man: \"Liz Whitefield\"\nfacing: \"internal\"", "end": 239, "score": 0.9998924136161804, "start": 224, "tag": "NAME", "value": "Kenny Robertson" }, { "context": "r: \"Private\"\nsro: \...
app/data/projects/secure-communications.cson
tsmorgan/dwp-ux-work
0
id: 18 name: "Secure communications" description: "Authenticates third party medical professionals and lets them send information securely." theme: "Platforms" location: "Leeds" phase: "beta" phase_modifier: "Private" sro: "Kenny Robertson" service_man: "Liz Whitefield" facing: "internal" phase_history: discovery: [ { label: "Completed" date: "December 2014" } ] alpha: [ { label: "Completed" date: "July 2015" } ] beta: [ { label: "Started" date: "August 2015" } { label: "Private beta started" date: "April 2016" } { label: "Public beta predicted" date: "January 2017" } ] priority: "High" prototype: "http://ds1500.herokuapp.com/"
161183
id: 18 name: "Secure communications" description: "Authenticates third party medical professionals and lets them send information securely." theme: "Platforms" location: "Leeds" phase: "beta" phase_modifier: "Private" sro: "<NAME>" service_man: "<NAME>" facing: "internal" phase_history: discovery: [ { label: "Completed" date: "December 2014" } ] alpha: [ { label: "Completed" date: "July 2015" } ] beta: [ { label: "Started" date: "August 2015" } { label: "Private beta started" date: "April 2016" } { label: "Public beta predicted" date: "January 2017" } ] priority: "High" prototype: "http://ds1500.herokuapp.com/"
true
id: 18 name: "Secure communications" description: "Authenticates third party medical professionals and lets them send information securely." theme: "Platforms" location: "Leeds" phase: "beta" phase_modifier: "Private" sro: "PI:NAME:<NAME>END_PI" service_man: "PI:NAME:<NAME>END_PI" facing: "internal" phase_history: discovery: [ { label: "Completed" date: "December 2014" } ] alpha: [ { label: "Completed" date: "July 2015" } ] beta: [ { label: "Started" date: "August 2015" } { label: "Private beta started" date: "April 2016" } { label: "Public beta predicted" date: "January 2017" } ] priority: "High" prototype: "http://ds1500.herokuapp.com/"
[ { "context": ".insert { 'import': @importRecord._id, 'importer': @name, 'type': 'users', 'users': tempUsers }\n\t\t@use", "end": 2485, "score": 0.5288708209991455, "start": 2485, "tag": "USERNAME", "value": "" }, { "context": "antUser._id\n\t\t\t\t\t\t\t@userTags.push\n\t\t\t\t\t\t\t...
packages/rocketchat-importer-hipchat/server.coffee
kumarpradeephk/mychatapp
1
import moment from 'moment' import 'moment-timezone' Importer.HipChat = class Importer.HipChat extends Importer.Base @RoomPrefix = 'hipchat_export/rooms/' @UsersPrefix = 'hipchat_export/users/' constructor: (name, descriptionI18N, mimeType) -> super(name, descriptionI18N, mimeType) @logger.debug('Constructed a new Slack Importer.') @userTags = [] prepare: (dataURI, sentContentType, fileName) => super(dataURI, sentContentType, fileName) {image, contentType} = RocketChatFile.dataURIParse dataURI zip = new @AdmZip(new Buffer(image, 'base64')) zipEntries = zip.getEntries() tempRooms = [] tempUsers = [] tempMessages = {} for entry in zipEntries do (entry) => if entry.entryName.indexOf('__MACOSX') > -1 #ignore all of the files inside of __MACOSX @logger.debug("Ignoring the file: #{entry.entryName}") if not entry.isDirectory if entry.entryName.indexOf(Importer.HipChat.RoomPrefix) > -1 roomName = entry.entryName.split(Importer.HipChat.RoomPrefix)[1] if roomName is 'list.json' @updateProgress Importer.ProgressStep.PREPARING_CHANNELS tempRooms = JSON.parse(entry.getData().toString()).rooms for room in tempRooms room.name = _.slugify room.name else if roomName.indexOf('/') > -1 item = roomName.split('/') roomName = _.slugify item[0] #random msgGroupData = item[1].split('.')[0] #2015-10-04 if not tempMessages[roomName] tempMessages[roomName] = {} # For some reason some of the json files in the HipChat export aren't valid JSON # files, so we need to catch those and just ignore them (sadly). try tempMessages[roomName][msgGroupData] = JSON.parse entry.getData().toString() catch @logger.warn "#{entry.entryName} is not a valid JSON file! Unable to import it." else if entry.entryName.indexOf(Importer.HipChat.UsersPrefix) > -1 usersName = entry.entryName.split(Importer.HipChat.UsersPrefix)[1] if usersName is 'list.json' @updateProgress Importer.ProgressStep.PREPARING_USERS tempUsers = JSON.parse(entry.getData().toString()).users else @logger.warn "Unexpected file in the #{@name} import: #{entry.entryName}" # Insert the users record, eventually this might have to be split into several ones as well # if someone tries to import a several thousands users instance usersId = @collection.insert { 'import': @importRecord._id, 'importer': @name, 'type': 'users', 'users': tempUsers } @users = @collection.findOne usersId @updateRecord { 'count.users': tempUsers.length } @addCountToTotal tempUsers.length # Insert the rooms records. channelsId = @collection.insert { 'import': @importRecord._id, 'importer': @name, 'type': 'channels', 'channels': tempRooms } @channels = @collection.findOne channelsId @updateRecord { 'count.channels': tempRooms.length } @addCountToTotal tempRooms.length # Insert the messages records @updateProgress Importer.ProgressStep.PREPARING_MESSAGES messagesCount = 0 for channel, messagesObj of tempMessages do (channel, messagesObj) => if not @messages[channel] @messages[channel] = {} for date, msgs of messagesObj messagesCount += msgs.length @updateRecord { 'messagesstatus': "#{channel}/#{date}" } if Importer.Base.getBSONSize(msgs) > Importer.Base.MaxBSONSize for splitMsg, i in Importer.Base.getBSONSafeArraysFromAnArray(msgs) messagesId = @collection.insert { 'import': @importRecord._id, 'importer': @name, 'type': 'messages', 'name': "#{channel}/#{date}.#{i}", 'messages': splitMsg } @messages[channel]["#{date}.#{i}"] = @collection.findOne messagesId else messagesId = @collection.insert { 'import': @importRecord._id, 'importer': @name, 'type': 'messages', 'name': "#{channel}/#{date}", 'messages': msgs } @messages[channel][date] = @collection.findOne messagesId @updateRecord { 'count.messages': messagesCount, 'messagesstatus': null } @addCountToTotal messagesCount if tempUsers.length is 0 or tempRooms.length is 0 or messagesCount is 0 @logger.warn "The loaded users count #{tempUsers.length}, the loaded channels #{tempRooms.length}, and the loaded messages #{messagesCount}" @updateProgress Importer.ProgressStep.ERROR return @getProgress() selectionUsers = tempUsers.map (user) -> #HipChat's export doesn't contain bot users, from the data I've seen return new Importer.SelectionUser user.user_id, user.name, user.email, user.is_deleted, false, !user.is_bot selectionChannels = tempRooms.map (room) -> return new Importer.SelectionChannel room.room_id, room.name, room.is_archived, true, false @updateProgress Importer.ProgressStep.USER_SELECTION return new Importer.Selection @name, selectionUsers, selectionChannels startImport: (importSelection) => super(importSelection) start = Date.now() for user in importSelection.users for u in @users.users when u.user_id is user.user_id u.do_import = user.do_import @collection.update { _id: @users._id }, { $set: { 'users': @users.users }} for channel in importSelection.channels for c in @channels.channels when c.room_id is channel.channel_id c.do_import = channel.do_import @collection.update { _id: @channels._id }, { $set: { 'channels': @channels.channels }} startedByUserId = Meteor.userId() Meteor.defer => @updateProgress Importer.ProgressStep.IMPORTING_USERS for user in @users.users when user.do_import do (user) => Meteor.runAsUser startedByUserId, () => existantUser = RocketChat.models.Users.findOneByEmailAddress user.email if existantUser user.rocketId = existantUser._id @userTags.push hipchat: "@#{user.mention_name}" rocket: "@#{existantUser.username}" else userId = Accounts.createUser { email: user.email, password: Date.now() + user.name + user.email.toUpperCase() } user.rocketId = userId @userTags.push hipchat: "@#{user.mention_name}" rocket: "@#{user.mention_name}" Meteor.runAsUser userId, () => Meteor.call 'setUsername', user.mention_name, {joinDefaultChannelsSilenced: true} Meteor.call 'setAvatarFromService', user.photo_url, undefined, 'url' Meteor.call 'userSetUtcOffset', parseInt moment().tz(user.timezone).format('Z').toString().split(':')[0] if user.name? RocketChat.models.Users.setName userId, user.name #Deleted users are 'inactive' users in Rocket.Chat if user.is_deleted Meteor.call 'setUserActiveStatus', userId, false @addCountCompleted 1 @collection.update { _id: @users._id }, { $set: { 'users': @users.users }} @updateProgress Importer.ProgressStep.IMPORTING_CHANNELS for channel in @channels.channels when channel.do_import do (channel) => Meteor.runAsUser startedByUserId, () => channel.name = channel.name.replace(/ /g, '') existantRoom = RocketChat.models.Rooms.findOneByName channel.name if existantRoom channel.rocketId = existantRoom._id else userId = '' for user in @users.users when user.user_id is channel.owner_user_id userId = user.rocketId if userId is '' @logger.warn "Failed to find the channel creator for #{channel.name}, setting it to the current running user." userId = startedByUserId Meteor.runAsUser userId, () => returned = Meteor.call 'createChannel', channel.name, [] channel.rocketId = returned.rid RocketChat.models.Rooms.update { _id: channel.rocketId }, { $set: { 'ts': new Date(channel.created * 1000) }} @addCountCompleted 1 @collection.update { _id: @channels._id }, { $set: { 'channels': @channels.channels }} @updateProgress Importer.ProgressStep.IMPORTING_MESSAGES nousers = {}; for channel, messagesObj of @messages do (channel, messagesObj) => Meteor.runAsUser startedByUserId, () => hipchatChannel = @getHipChatChannelFromName channel if hipchatChannel?.do_import room = RocketChat.models.Rooms.findOneById hipchatChannel.rocketId, { fields: { usernames: 1, t: 1, name: 1 } } for date, msgs of messagesObj @updateRecord { 'messagesstatus': "#{channel}/#{date}.#{msgs.messages.length}" } for message in msgs.messages if message.from? user = @getRocketUser(message.from.user_id) if user? msgObj = msg: @convertHipChatMessageToRocketChat(message.message) ts: new Date(message.date) u: _id: user._id username: user.username RocketChat.sendMessage user, msgObj, room, true else if not nousers[message.from.user_id] nousers[message.from.user_id] = message.from else if not _.isArray message console.warn 'Please report the following:', message @addCountCompleted 1 @logger.warn 'The following did not have users:', nousers @updateProgress Importer.ProgressStep.FINISHING for channel in @channels.channels when channel.do_import and channel.is_archived do (channel) => Meteor.runAsUser startedByUserId, () => Meteor.call 'archiveRoom', channel.rocketId @updateProgress Importer.ProgressStep.DONE timeTook = Date.now() - start @logger.log "Import took #{timeTook} milliseconds." return @getProgress() getHipChatChannelFromName: (channelName) => for channel in @channels.channels when channel.name is channelName return channel getRocketUser: (hipchatId) => for user in @users.users when user.user_id is hipchatId return RocketChat.models.Users.findOneById user.rocketId, { fields: { username: 1 }} convertHipChatMessageToRocketChat: (message) => if message? for userReplace in @userTags message = message.replace userReplace.hipchat, userReplace.rocket else message = '' return message getSelection: () => selectionUsers = @users.users.map (user) -> #HipChat's export doesn't contain bot users, from the data I've seen return new Importer.SelectionUser user.user_id, user.name, user.email, user.is_deleted, false, !user.is_bot selectionChannels = @channels.channels.map (room) -> return new Importer.SelectionChannel room.room_id, room.name, room.is_archived, true, false return new Importer.Selection @name, selectionUsers, selectionChannels
85960
import moment from 'moment' import 'moment-timezone' Importer.HipChat = class Importer.HipChat extends Importer.Base @RoomPrefix = 'hipchat_export/rooms/' @UsersPrefix = 'hipchat_export/users/' constructor: (name, descriptionI18N, mimeType) -> super(name, descriptionI18N, mimeType) @logger.debug('Constructed a new Slack Importer.') @userTags = [] prepare: (dataURI, sentContentType, fileName) => super(dataURI, sentContentType, fileName) {image, contentType} = RocketChatFile.dataURIParse dataURI zip = new @AdmZip(new Buffer(image, 'base64')) zipEntries = zip.getEntries() tempRooms = [] tempUsers = [] tempMessages = {} for entry in zipEntries do (entry) => if entry.entryName.indexOf('__MACOSX') > -1 #ignore all of the files inside of __MACOSX @logger.debug("Ignoring the file: #{entry.entryName}") if not entry.isDirectory if entry.entryName.indexOf(Importer.HipChat.RoomPrefix) > -1 roomName = entry.entryName.split(Importer.HipChat.RoomPrefix)[1] if roomName is 'list.json' @updateProgress Importer.ProgressStep.PREPARING_CHANNELS tempRooms = JSON.parse(entry.getData().toString()).rooms for room in tempRooms room.name = _.slugify room.name else if roomName.indexOf('/') > -1 item = roomName.split('/') roomName = _.slugify item[0] #random msgGroupData = item[1].split('.')[0] #2015-10-04 if not tempMessages[roomName] tempMessages[roomName] = {} # For some reason some of the json files in the HipChat export aren't valid JSON # files, so we need to catch those and just ignore them (sadly). try tempMessages[roomName][msgGroupData] = JSON.parse entry.getData().toString() catch @logger.warn "#{entry.entryName} is not a valid JSON file! Unable to import it." else if entry.entryName.indexOf(Importer.HipChat.UsersPrefix) > -1 usersName = entry.entryName.split(Importer.HipChat.UsersPrefix)[1] if usersName is 'list.json' @updateProgress Importer.ProgressStep.PREPARING_USERS tempUsers = JSON.parse(entry.getData().toString()).users else @logger.warn "Unexpected file in the #{@name} import: #{entry.entryName}" # Insert the users record, eventually this might have to be split into several ones as well # if someone tries to import a several thousands users instance usersId = @collection.insert { 'import': @importRecord._id, 'importer': @name, 'type': 'users', 'users': tempUsers } @users = @collection.findOne usersId @updateRecord { 'count.users': tempUsers.length } @addCountToTotal tempUsers.length # Insert the rooms records. channelsId = @collection.insert { 'import': @importRecord._id, 'importer': @name, 'type': 'channels', 'channels': tempRooms } @channels = @collection.findOne channelsId @updateRecord { 'count.channels': tempRooms.length } @addCountToTotal tempRooms.length # Insert the messages records @updateProgress Importer.ProgressStep.PREPARING_MESSAGES messagesCount = 0 for channel, messagesObj of tempMessages do (channel, messagesObj) => if not @messages[channel] @messages[channel] = {} for date, msgs of messagesObj messagesCount += msgs.length @updateRecord { 'messagesstatus': "#{channel}/#{date}" } if Importer.Base.getBSONSize(msgs) > Importer.Base.MaxBSONSize for splitMsg, i in Importer.Base.getBSONSafeArraysFromAnArray(msgs) messagesId = @collection.insert { 'import': @importRecord._id, 'importer': @name, 'type': 'messages', 'name': "#{channel}/#{date}.#{i}", 'messages': splitMsg } @messages[channel]["#{date}.#{i}"] = @collection.findOne messagesId else messagesId = @collection.insert { 'import': @importRecord._id, 'importer': @name, 'type': 'messages', 'name': "#{channel}/#{date}", 'messages': msgs } @messages[channel][date] = @collection.findOne messagesId @updateRecord { 'count.messages': messagesCount, 'messagesstatus': null } @addCountToTotal messagesCount if tempUsers.length is 0 or tempRooms.length is 0 or messagesCount is 0 @logger.warn "The loaded users count #{tempUsers.length}, the loaded channels #{tempRooms.length}, and the loaded messages #{messagesCount}" @updateProgress Importer.ProgressStep.ERROR return @getProgress() selectionUsers = tempUsers.map (user) -> #HipChat's export doesn't contain bot users, from the data I've seen return new Importer.SelectionUser user.user_id, user.name, user.email, user.is_deleted, false, !user.is_bot selectionChannels = tempRooms.map (room) -> return new Importer.SelectionChannel room.room_id, room.name, room.is_archived, true, false @updateProgress Importer.ProgressStep.USER_SELECTION return new Importer.Selection @name, selectionUsers, selectionChannels startImport: (importSelection) => super(importSelection) start = Date.now() for user in importSelection.users for u in @users.users when u.user_id is user.user_id u.do_import = user.do_import @collection.update { _id: @users._id }, { $set: { 'users': @users.users }} for channel in importSelection.channels for c in @channels.channels when c.room_id is channel.channel_id c.do_import = channel.do_import @collection.update { _id: @channels._id }, { $set: { 'channels': @channels.channels }} startedByUserId = Meteor.userId() Meteor.defer => @updateProgress Importer.ProgressStep.IMPORTING_USERS for user in @users.users when user.do_import do (user) => Meteor.runAsUser startedByUserId, () => existantUser = RocketChat.models.Users.findOneByEmailAddress user.email if existantUser user.rocketId = existantUser._id @userTags.push hipchat: "@#{user.mention_name}" rocket: "@#{existantUser.username}" else userId = Accounts.createUser { email: user.email, password: <PASSWORD>() + <PASSWORD> + user.email.<PASSWORD>() } user.rocketId = userId @userTags.push hipchat: "@#{user.mention_name}" rocket: "@#{user.mention_name}" Meteor.runAsUser userId, () => Meteor.call 'setUsername', user.mention_name, {joinDefaultChannelsSilenced: true} Meteor.call 'setAvatarFromService', user.photo_url, undefined, 'url' Meteor.call 'userSetUtcOffset', parseInt moment().tz(user.timezone).format('Z').toString().split(':')[0] if user.name? RocketChat.models.Users.setName userId, user.name #Deleted users are 'inactive' users in Rocket.Chat if user.is_deleted Meteor.call 'setUserActiveStatus', userId, false @addCountCompleted 1 @collection.update { _id: @users._id }, { $set: { 'users': @users.users }} @updateProgress Importer.ProgressStep.IMPORTING_CHANNELS for channel in @channels.channels when channel.do_import do (channel) => Meteor.runAsUser startedByUserId, () => channel.name = channel.name.replace(/ /g, '') existantRoom = RocketChat.models.Rooms.findOneByName channel.name if existantRoom channel.rocketId = existantRoom._id else userId = '' for user in @users.users when user.user_id is channel.owner_user_id userId = user.rocketId if userId is '' @logger.warn "Failed to find the channel creator for #{channel.name}, setting it to the current running user." userId = startedByUserId Meteor.runAsUser userId, () => returned = Meteor.call 'createChannel', channel.name, [] channel.rocketId = returned.rid RocketChat.models.Rooms.update { _id: channel.rocketId }, { $set: { 'ts': new Date(channel.created * 1000) }} @addCountCompleted 1 @collection.update { _id: @channels._id }, { $set: { 'channels': @channels.channels }} @updateProgress Importer.ProgressStep.IMPORTING_MESSAGES nousers = {}; for channel, messagesObj of @messages do (channel, messagesObj) => Meteor.runAsUser startedByUserId, () => hipchatChannel = @getHipChatChannelFromName channel if hipchatChannel?.do_import room = RocketChat.models.Rooms.findOneById hipchatChannel.rocketId, { fields: { usernames: 1, t: 1, name: 1 } } for date, msgs of messagesObj @updateRecord { 'messagesstatus': "#{channel}/#{date}.#{msgs.messages.length}" } for message in msgs.messages if message.from? user = @getRocketUser(message.from.user_id) if user? msgObj = msg: @convertHipChatMessageToRocketChat(message.message) ts: new Date(message.date) u: _id: user._id username: user.username RocketChat.sendMessage user, msgObj, room, true else if not nousers[message.from.user_id] nousers[message.from.user_id] = message.from else if not _.isArray message console.warn 'Please report the following:', message @addCountCompleted 1 @logger.warn 'The following did not have users:', nousers @updateProgress Importer.ProgressStep.FINISHING for channel in @channels.channels when channel.do_import and channel.is_archived do (channel) => Meteor.runAsUser startedByUserId, () => Meteor.call 'archiveRoom', channel.rocketId @updateProgress Importer.ProgressStep.DONE timeTook = Date.now() - start @logger.log "Import took #{timeTook} milliseconds." return @getProgress() getHipChatChannelFromName: (channelName) => for channel in @channels.channels when channel.name is channelName return channel getRocketUser: (hipchatId) => for user in @users.users when user.user_id is hipchatId return RocketChat.models.Users.findOneById user.rocketId, { fields: { username: 1 }} convertHipChatMessageToRocketChat: (message) => if message? for userReplace in @userTags message = message.replace userReplace.hipchat, userReplace.rocket else message = '' return message getSelection: () => selectionUsers = @users.users.map (user) -> #HipChat's export doesn't contain bot users, from the data I've seen return new Importer.SelectionUser user.user_id, user.name, user.email, user.is_deleted, false, !user.is_bot selectionChannels = @channels.channels.map (room) -> return new Importer.SelectionChannel room.room_id, room.name, room.is_archived, true, false return new Importer.Selection @name, selectionUsers, selectionChannels
true
import moment from 'moment' import 'moment-timezone' Importer.HipChat = class Importer.HipChat extends Importer.Base @RoomPrefix = 'hipchat_export/rooms/' @UsersPrefix = 'hipchat_export/users/' constructor: (name, descriptionI18N, mimeType) -> super(name, descriptionI18N, mimeType) @logger.debug('Constructed a new Slack Importer.') @userTags = [] prepare: (dataURI, sentContentType, fileName) => super(dataURI, sentContentType, fileName) {image, contentType} = RocketChatFile.dataURIParse dataURI zip = new @AdmZip(new Buffer(image, 'base64')) zipEntries = zip.getEntries() tempRooms = [] tempUsers = [] tempMessages = {} for entry in zipEntries do (entry) => if entry.entryName.indexOf('__MACOSX') > -1 #ignore all of the files inside of __MACOSX @logger.debug("Ignoring the file: #{entry.entryName}") if not entry.isDirectory if entry.entryName.indexOf(Importer.HipChat.RoomPrefix) > -1 roomName = entry.entryName.split(Importer.HipChat.RoomPrefix)[1] if roomName is 'list.json' @updateProgress Importer.ProgressStep.PREPARING_CHANNELS tempRooms = JSON.parse(entry.getData().toString()).rooms for room in tempRooms room.name = _.slugify room.name else if roomName.indexOf('/') > -1 item = roomName.split('/') roomName = _.slugify item[0] #random msgGroupData = item[1].split('.')[0] #2015-10-04 if not tempMessages[roomName] tempMessages[roomName] = {} # For some reason some of the json files in the HipChat export aren't valid JSON # files, so we need to catch those and just ignore them (sadly). try tempMessages[roomName][msgGroupData] = JSON.parse entry.getData().toString() catch @logger.warn "#{entry.entryName} is not a valid JSON file! Unable to import it." else if entry.entryName.indexOf(Importer.HipChat.UsersPrefix) > -1 usersName = entry.entryName.split(Importer.HipChat.UsersPrefix)[1] if usersName is 'list.json' @updateProgress Importer.ProgressStep.PREPARING_USERS tempUsers = JSON.parse(entry.getData().toString()).users else @logger.warn "Unexpected file in the #{@name} import: #{entry.entryName}" # Insert the users record, eventually this might have to be split into several ones as well # if someone tries to import a several thousands users instance usersId = @collection.insert { 'import': @importRecord._id, 'importer': @name, 'type': 'users', 'users': tempUsers } @users = @collection.findOne usersId @updateRecord { 'count.users': tempUsers.length } @addCountToTotal tempUsers.length # Insert the rooms records. channelsId = @collection.insert { 'import': @importRecord._id, 'importer': @name, 'type': 'channels', 'channels': tempRooms } @channels = @collection.findOne channelsId @updateRecord { 'count.channels': tempRooms.length } @addCountToTotal tempRooms.length # Insert the messages records @updateProgress Importer.ProgressStep.PREPARING_MESSAGES messagesCount = 0 for channel, messagesObj of tempMessages do (channel, messagesObj) => if not @messages[channel] @messages[channel] = {} for date, msgs of messagesObj messagesCount += msgs.length @updateRecord { 'messagesstatus': "#{channel}/#{date}" } if Importer.Base.getBSONSize(msgs) > Importer.Base.MaxBSONSize for splitMsg, i in Importer.Base.getBSONSafeArraysFromAnArray(msgs) messagesId = @collection.insert { 'import': @importRecord._id, 'importer': @name, 'type': 'messages', 'name': "#{channel}/#{date}.#{i}", 'messages': splitMsg } @messages[channel]["#{date}.#{i}"] = @collection.findOne messagesId else messagesId = @collection.insert { 'import': @importRecord._id, 'importer': @name, 'type': 'messages', 'name': "#{channel}/#{date}", 'messages': msgs } @messages[channel][date] = @collection.findOne messagesId @updateRecord { 'count.messages': messagesCount, 'messagesstatus': null } @addCountToTotal messagesCount if tempUsers.length is 0 or tempRooms.length is 0 or messagesCount is 0 @logger.warn "The loaded users count #{tempUsers.length}, the loaded channels #{tempRooms.length}, and the loaded messages #{messagesCount}" @updateProgress Importer.ProgressStep.ERROR return @getProgress() selectionUsers = tempUsers.map (user) -> #HipChat's export doesn't contain bot users, from the data I've seen return new Importer.SelectionUser user.user_id, user.name, user.email, user.is_deleted, false, !user.is_bot selectionChannels = tempRooms.map (room) -> return new Importer.SelectionChannel room.room_id, room.name, room.is_archived, true, false @updateProgress Importer.ProgressStep.USER_SELECTION return new Importer.Selection @name, selectionUsers, selectionChannels startImport: (importSelection) => super(importSelection) start = Date.now() for user in importSelection.users for u in @users.users when u.user_id is user.user_id u.do_import = user.do_import @collection.update { _id: @users._id }, { $set: { 'users': @users.users }} for channel in importSelection.channels for c in @channels.channels when c.room_id is channel.channel_id c.do_import = channel.do_import @collection.update { _id: @channels._id }, { $set: { 'channels': @channels.channels }} startedByUserId = Meteor.userId() Meteor.defer => @updateProgress Importer.ProgressStep.IMPORTING_USERS for user in @users.users when user.do_import do (user) => Meteor.runAsUser startedByUserId, () => existantUser = RocketChat.models.Users.findOneByEmailAddress user.email if existantUser user.rocketId = existantUser._id @userTags.push hipchat: "@#{user.mention_name}" rocket: "@#{existantUser.username}" else userId = Accounts.createUser { email: user.email, password: PI:PASSWORD:<PASSWORD>END_PI() + PI:PASSWORD:<PASSWORD>END_PI + user.email.PI:PASSWORD:<PASSWORD>END_PI() } user.rocketId = userId @userTags.push hipchat: "@#{user.mention_name}" rocket: "@#{user.mention_name}" Meteor.runAsUser userId, () => Meteor.call 'setUsername', user.mention_name, {joinDefaultChannelsSilenced: true} Meteor.call 'setAvatarFromService', user.photo_url, undefined, 'url' Meteor.call 'userSetUtcOffset', parseInt moment().tz(user.timezone).format('Z').toString().split(':')[0] if user.name? RocketChat.models.Users.setName userId, user.name #Deleted users are 'inactive' users in Rocket.Chat if user.is_deleted Meteor.call 'setUserActiveStatus', userId, false @addCountCompleted 1 @collection.update { _id: @users._id }, { $set: { 'users': @users.users }} @updateProgress Importer.ProgressStep.IMPORTING_CHANNELS for channel in @channels.channels when channel.do_import do (channel) => Meteor.runAsUser startedByUserId, () => channel.name = channel.name.replace(/ /g, '') existantRoom = RocketChat.models.Rooms.findOneByName channel.name if existantRoom channel.rocketId = existantRoom._id else userId = '' for user in @users.users when user.user_id is channel.owner_user_id userId = user.rocketId if userId is '' @logger.warn "Failed to find the channel creator for #{channel.name}, setting it to the current running user." userId = startedByUserId Meteor.runAsUser userId, () => returned = Meteor.call 'createChannel', channel.name, [] channel.rocketId = returned.rid RocketChat.models.Rooms.update { _id: channel.rocketId }, { $set: { 'ts': new Date(channel.created * 1000) }} @addCountCompleted 1 @collection.update { _id: @channels._id }, { $set: { 'channels': @channels.channels }} @updateProgress Importer.ProgressStep.IMPORTING_MESSAGES nousers = {}; for channel, messagesObj of @messages do (channel, messagesObj) => Meteor.runAsUser startedByUserId, () => hipchatChannel = @getHipChatChannelFromName channel if hipchatChannel?.do_import room = RocketChat.models.Rooms.findOneById hipchatChannel.rocketId, { fields: { usernames: 1, t: 1, name: 1 } } for date, msgs of messagesObj @updateRecord { 'messagesstatus': "#{channel}/#{date}.#{msgs.messages.length}" } for message in msgs.messages if message.from? user = @getRocketUser(message.from.user_id) if user? msgObj = msg: @convertHipChatMessageToRocketChat(message.message) ts: new Date(message.date) u: _id: user._id username: user.username RocketChat.sendMessage user, msgObj, room, true else if not nousers[message.from.user_id] nousers[message.from.user_id] = message.from else if not _.isArray message console.warn 'Please report the following:', message @addCountCompleted 1 @logger.warn 'The following did not have users:', nousers @updateProgress Importer.ProgressStep.FINISHING for channel in @channels.channels when channel.do_import and channel.is_archived do (channel) => Meteor.runAsUser startedByUserId, () => Meteor.call 'archiveRoom', channel.rocketId @updateProgress Importer.ProgressStep.DONE timeTook = Date.now() - start @logger.log "Import took #{timeTook} milliseconds." return @getProgress() getHipChatChannelFromName: (channelName) => for channel in @channels.channels when channel.name is channelName return channel getRocketUser: (hipchatId) => for user in @users.users when user.user_id is hipchatId return RocketChat.models.Users.findOneById user.rocketId, { fields: { username: 1 }} convertHipChatMessageToRocketChat: (message) => if message? for userReplace in @userTags message = message.replace userReplace.hipchat, userReplace.rocket else message = '' return message getSelection: () => selectionUsers = @users.users.map (user) -> #HipChat's export doesn't contain bot users, from the data I've seen return new Importer.SelectionUser user.user_id, user.name, user.email, user.is_deleted, false, !user.is_bot selectionChannels = @channels.channels.map (room) -> return new Importer.SelectionChannel room.room_id, room.name, room.is_archived, true, false return new Importer.Selection @name, selectionUsers, selectionChannels
[ { "context": "eryauth id\n\tappSecret = process.env.appSecret || '85f7e0a0cc804886180b887c1f04a3c1' #defaults to everyauth secret\n\n\t@passport.serial", "end": 225, "score": 0.9890223145484924, "start": 193, "tag": "KEY", "value": "85f7e0a0cc804886180b887c1f04a3c1" } ]
business-layer/common/authentication.coffee
dfraser74/whoislikingyou
0
exports.boot = () -> UserClass = require "../../data-layer/collections/user" appId = process.env.appId || '111565172259433' #defaults to everyauth id appSecret = process.env.appSecret || '85f7e0a0cc804886180b887c1f04a3c1' #defaults to everyauth secret @passport.serializeUser (user, callback) -> callback(null, user.id) @passport.deserializeUser (id, callback) -> UserClass.User.findOne { _id: id }, (err, user) -> callback(err, user) # use facebook strategy fS = @facebookStrategy.Strategy @passport.use new fS({ clientID: appId, clientSecret: appSecret, callbackURL: "/auth/facebook/callback"}, (accessToken, refreshToken, profile, callback) -> UserClass.upsert accessToken, profile, (err, user) -> callback err, user) exports.ensureAuthenticated = (req, res, next) -> return next() if req.isAuthenticated() res.redirect('/home')
221155
exports.boot = () -> UserClass = require "../../data-layer/collections/user" appId = process.env.appId || '111565172259433' #defaults to everyauth id appSecret = process.env.appSecret || '<KEY>' #defaults to everyauth secret @passport.serializeUser (user, callback) -> callback(null, user.id) @passport.deserializeUser (id, callback) -> UserClass.User.findOne { _id: id }, (err, user) -> callback(err, user) # use facebook strategy fS = @facebookStrategy.Strategy @passport.use new fS({ clientID: appId, clientSecret: appSecret, callbackURL: "/auth/facebook/callback"}, (accessToken, refreshToken, profile, callback) -> UserClass.upsert accessToken, profile, (err, user) -> callback err, user) exports.ensureAuthenticated = (req, res, next) -> return next() if req.isAuthenticated() res.redirect('/home')
true
exports.boot = () -> UserClass = require "../../data-layer/collections/user" appId = process.env.appId || '111565172259433' #defaults to everyauth id appSecret = process.env.appSecret || 'PI:KEY:<KEY>END_PI' #defaults to everyauth secret @passport.serializeUser (user, callback) -> callback(null, user.id) @passport.deserializeUser (id, callback) -> UserClass.User.findOne { _id: id }, (err, user) -> callback(err, user) # use facebook strategy fS = @facebookStrategy.Strategy @passport.use new fS({ clientID: appId, clientSecret: appSecret, callbackURL: "/auth/facebook/callback"}, (accessToken, refreshToken, profile, callback) -> UserClass.upsert accessToken, profile, (err, user) -> callback err, user) exports.ensureAuthenticated = (req, res, next) -> return next() if req.isAuthenticated() res.redirect('/home')
[ { "context": "o the best\n# fitting type.\n#\n# _Copyright (c) 2011 Olaf Delgado-Friedrichs_\n\n# ----\n\n# First, we import some necessary funct", "end": 259, "score": 0.9998722076416016, "start": 236, "tag": "NAME", "value": "Olaf Delgado-Friedrichs" } ]
lib/number.coffee
odf/pazy.js
0
# A generic number type, currently supporting integral Javascript numbers, # arbitrary precision integers and fractions. # # Arguments and results of arithmetic operations are coerced to the best # fitting type. # # _Copyright (c) 2011 Olaf Delgado-Friedrichs_ # ---- # First, we import some necessary functions and data structures. if typeof(require) != 'undefined' { bounce } = require 'functional' { seq } = require 'sequence' else { bounce, seq } = this.pazy # ---- # If this source file is being executed directly, run in test mode. quicktest = module? and not module.parent log = if quicktest then (str) -> console.log str else (str) -> # ---- # An integer is represented as either a plain signed Javascript number with # overflow (or strictly speaking: precision loss) checks or a lazy sequence of # unsigned numbers. The constant `BASE` determines the number base for the # latter representation. In addition, numbers with an absolute value smaller # than `BASE` are represented as plain numbers. # # In production mode, the number `BASE` is computed as the largest power of 100 # that fits into a Javascript number twice with full precision. The number # `HALFBASE` it its square root. According to the Javascript specification, we # should expect `BASE == 10e14` and `HALFBASE == 10e7`. BASE_LENGTH = if quicktest then 4 else seq.from(1) .map((n) -> 2 * n) .takeWhile((n) -> b = Math.pow 10, n 2 * b - 2 != 2 * b - 1 and -2 * b + 2 != -2 * b + 1 ) .last() BASE = Math.pow 10, BASE_LENGTH HALFBASE = Math.sqrt BASE # ---- # Internal helpers for constructing number representations. asNum = (n) -> if Math.abs(n) < BASE then new CheckedInt n else LongInt.fromNative n # ---- # The `num` function provides the public interface. num = (n = 0) -> switch typeof n when 'number' num.fromNative n when 'string' num.parse n else if n instanceof NumberBase n else throw new Error "expected a number, got #{n}" num.fromNative = (n) -> throw new Error "expected an integer, got #{n}" unless n == Math.floor n asNum n num.parse = (n) -> unless /^[+-]?\d+$/.test n throw new Error "expected an integer literal, got '#{n}'" [s, m] = switch n[0] when '-' then [-1, n[1..]] when '+' then [ 1, n[1..]] else [ 1, n] if m.length <= BASE_LENGTH new CheckedInt parseInt n else parsed = (to) -> if to > 0 from = Math.max 0, to - BASE_LENGTH seq.conj parseInt(m[from...to]), -> parsed from else null new LongInt s, parsed m.length # ---- # The `NumberBase` class implements dispatching on binary arithmetic # operators. class NumberBase makeNum = (n) -> if n instanceof NumberBase n else if typeof n == 'number' if Math.floor(n) == n if Math.abs(n) < BASE new CheckedInt n else LongInt.fromNative n else throw new Error "expected an integer, got #{n}" else throw new Error "expected a number, got #{n}" upcast = (a, b) -> [op1, op2] = [makeNum(a), makeNum(b)] out = switch op1.constructor when CheckedInt switch op2.constructor when CheckedInt [op1, op2] when LongInt [LongInt.fromNative(op1.val), op2] when Fraction [new Fraction(op1, num 1), op2] when LongInt switch op2.constructor when CheckedInt [op1, LongInt.fromNative(op2.val)] when LongInt [op1, op2] when Fraction [new Fraction(op1, num 1), op2] when Fraction switch op2.constructor when CheckedInt, LongInt [op1, new Fraction op2, num 1] when Fraction [op1, op2] if out out else [tp1, tp2] = [op1.constructor, op2.constructor] throw new Error "operands of types #{tp1} and #{tp2} not supported" downcast = (x) -> if x instanceof LongInt and x.lt BASE if x.digits? new CheckedInt x.digits.first() * x.sign else new CheckedInt 0 else if x instanceof Fraction and x.denom.eq(1) x.numer else x operator = (name, f) -> num[name] = (args...) -> f.call num, args... NumberBase::[name] = (args...) -> num[name] this, args... for name in ['cmp', 'plus', 'minus', 'times', 'div', 'idiv', 'mod', 'gcd'] do (name) -> namex = "#{name}__" operator name, (a, b) -> [x, y] = upcast a, b downcast x[namex] y div__: (other) -> Fraction.normalized this, other gcd__: (other) -> step = (a, b) -> if b.isPos() then -> step b, a.mod(b) else a [x, y] = [@abs(), other.abs()] if x.gt(y) then bounce step x, y else bounce step x, y operator 'lt', (a, b) -> num.cmp(a, b) < 0 operator 'gt', (a, b) -> num.cmp(a, b) > 0 operator 'eq', (a, b) -> num.cmp(a, b) == 0 operator 'equals', (a, b) -> num.cmp(a, b) == 0 for name in [ 'neg', 'abs', 'sgn', 'isPos', 'isNeg', 'isZero', 'isEven', 'isOdd' ] do (name) -> namex = "#{name}__" operator name, (a) -> makeNum(a)[namex]() operator 'isqrt', (a) -> downcast makeNum(a)['isqrt__']() operator 'pow', (a, b) -> step = (p, r, s) -> if s.isPos() if s.isOdd() > 0 -> step p.times(r), r, s.minus 1 else -> step p, r.times(r), s.idiv 2 else p downcast bounce step makeNum(1), makeNum(a), makeNum(b) # ---- # The `CheckInt` class provides integer operations with 'overflow checks'. In # other words, if the result cannot be represented with full precision as a # Javascript number, a `LongInt` is produced instead. class CheckedInt extends NumberBase constructor: (@val = 0) -> neg__: -> new CheckedInt -@val abs__: -> new CheckedInt Math.abs @val sgn__: -> if @val < 0 then -1 else if @val > 0 then 1 else 0 isPos__: -> @val > 0 isNeg__: -> @val < 0 isZero__: -> @val == 0 isEven__: -> @val % 2 == 0 isOdd__: -> @val % 2 != 0 isqrt__: -> new CheckedInt Math.floor Math.sqrt @val cmp__: (other) -> if @val < other.val then -1 else if @val > other.val then 1 else 0 plus__: (other) -> asNum @val + other.val minus__: (other) -> asNum @val - other.val times__: (other) -> x = @val * other.val if Math.abs(x) < BASE new CheckedInt x else LongInt.fromNative(@val).times other idiv__: (x) -> new CheckedInt Math.floor @val / x.val mod__: (x) -> new CheckedInt @val % x.val toString: -> "" + @val toNative: -> @val # ---- # Here are the beginnings of the `LongInt` class. class LongInt extends NumberBase constructor: (sign, @digits) -> @sign = if @digits? then sign else 0 @first = @digits?.first() or 0 neg__: -> new LongInt -@sign, @digits abs__: -> new LongInt 1, @digits sgn__: -> @sign isPos__: -> @sign > 0 isNeg__: -> @sign < 0 isZero__: -> @sign == 0 isEven__: -> @first % 2 == 0 isOdd__: -> @first % 2 != 0 zeroes = BASE.toString()[1..] rdump = (s) -> if s s.map((t) -> "#{zeroes[t.toString().length..]}#{t}").into([]).join('|') else '[]' dump = (s) -> rdump s?.reverse() ZERO = seq [0] cleanup = (s) -> s?.reverse()?.dropWhile((x) -> x == 0)?.reverse() or null isqrt = (s) -> n = s.size() step = (r) -> rn = seq idiv(add(r, idiv(s, r)), seq([2])) if cmp(r, rn) then -> step(rn) else rn bounce step s.take n >> 1 isqrt__: -> if @isZero() asNum 0 else if @isPos() new LongInt 1, isqrt @digits else throw new Error "expected a non-negative number, got #{this}" cmp = (r, s) -> seq.sub(r, s)?.reverse()?.dropWhile((x) -> x == 0)?.first() or 0 cmp__: (x) -> if @isZero() -x.sign else if x.isZero() @sign else if @sign != x.sign @sign else @sign * cmp @digits, x.digits add = (r, s, c = 0) -> if c or (r and s) [r_, s_] = [r or ZERO, s or ZERO] x = r_.first() + s_.first() + c [digit, carry] = if x >= BASE then [x - BASE, 1] else [x, 0] seq.conj(digit, -> add(r_.rest(), s_.rest(), carry)) else s or r plus__: (x) -> if @sign != x.sign @minus x.neg() else new LongInt @sign, add @digits, x.digits sub = (r, s) -> step = (r, s, b = 0) -> if b or (r and s) [r_, s_] = [r or ZERO, s or ZERO] x = r_.first() - s_.first() - b [digit, borrow] = if x < 0 then [x + BASE, 1] else [x, 0] seq.conj(digit, -> step(r_.rest(), s_.rest(), borrow)) else s or r cleanup step r, s minus__: (x) -> if @sign != x.sign @plus x.neg() else if cmp(@digits, x.digits) < 0 new LongInt -@sign, sub x.digits, @digits else new LongInt @sign, sub @digits, x.digits split = (n) -> [n % HALFBASE, Math.floor n / HALFBASE] digitTimesDigit = (a, b) -> if b < BASE / a [a * b, 0] else [a0, a1] = split a [b0, b1] = split b [m0, m1] = split a0 * b1 + b0 * a1 tmp = a0 * b0 + m0 * HALFBASE [lo, carry] = if tmp < BASE then [tmp, 0] else [tmp - BASE, 1] [lo, a1 * b1 + m1 + carry] seqTimesDigit = (s, d, c = 0) -> if c or s s_ = s or ZERO [lo, hi] = digitTimesDigit(d, s_.first()) seq.conj(lo + c, -> seqTimesDigit(s_.rest(), d, hi)) mul = (a, b) -> step = (r, a, b) -> if a t = add(r, seqTimesDigit(b, a.first())) or ZERO seq.conj(t.first(), -> step(t.rest(), a.rest(), b)) else r step null, a, b times__: (x) -> new LongInt @sign * x.sign, mul @digits, x.digits idivmod = (r, s) -> return [ZERO, ZERO] unless cleanup r scale = Math.floor BASE / (s.last() + 1) [r_, s_] = (seq seqTimesDigit(x, scale) for x in [r, s]) [m, d] = [s_.size(), s_.last() + 1] step = (q, h, t) -> f = if h?.size() < m 0 else n = (h?.last() * if h?.size() > m then BASE else 1) or 0 (Math.floor n / d) or (if cmp(h, s_) >= 0 then 1 else 0) if f -> step(add(q, seq.conj(f)), sub(h, seqTimesDigit(s_, f)), t) else if t -> step(seq.conj(0, -> q), seq.conj(t.first(), -> h), t.rest()) else [cleanup(q), h && idiv(h, seq [scale])] bounce step null, null, r_?.reverse() idiv = (r, s) -> idivmod(r, s)[0] mod = (r, s) -> idivmod(r, s)[1] idiv__: (x) -> d = cmp @digits, x.digits if d < 0 asNum 0 else if d == 0 asNum @sign * x.sign else new LongInt @sign * x.sign, idiv @digits, x.digits mod__: (x) -> d = cmp @digits, x.digits if d < 0 this else if d == 0 asNum 0 else new LongInt @sign * x.sign, mod @digits, x.digits toString: -> parts = @digits?.reverse()?.dropWhile((d) -> d == 0)?.map (d) -> d.toString() if parts sign = if @isNeg() then '-' else '' rest = parts.rest()?.map (t) -> "#{zeroes[t.length..]}#{t}" sign + parts.first() + if rest? then rest.join '' else '' else '0' toNative: -> step = (n, s) -> if s then -> step n * BASE + s.first(), s.rest() else n rev = @digits?.reverse()?.dropWhile (d) -> d == 0 @sign * bounce step 0, rev makeDigits = (m) -> if m then seq.conj m % BASE, -> makeDigits Math.floor(m / BASE) else null @fromNative: (n) -> if n < 0 new LongInt -1, makeDigits -n else if n > 0 new LongInt 1, makeDigits n else new LongInt 0, null # ---- # The 'Fraction' class implements rational numbers. class Fraction extends NumberBase constructor: (@numer, @denom) -> @normalized = (n, d) -> if d.eq 0 throw new Error "expected a non-zero denominator, got #{d}" else if d.lt 0 Fraction.normalized n.neg(), d.neg() else a = num.gcd n, d new Fraction n.idiv(a), d.idiv(a) neg__: -> new Fraction @numer.neg(), @denom abs__: -> new Fraction @numer.abs(), @denom sgn__: -> @numer.sgn() inv__: -> Fraction.normalized @denom, @numer isPos__: -> @numer.isPos() isNeg__: -> @numer.isNeg() isZero__: -> @numer.isZero() isEven__: -> @denom.eq(1) and @numer.isEven() isOdd__: -> @denom.eq(1) and @numer.isOdd() isqrt__: -> num.idiv(@numer, @denom).isqrt() cmp__: (x) -> @minus__(x).numer.cmp 0 plus__: (x) -> a = num.gcd @denom, x.denom s = num.idiv x.denom, a t = num.idiv @denom, a Fraction.normalized s.times(@numer).plus(t.times(x.numer)), s.times @denom minus__: (x) -> @plus__ x.neg__() times__: (x) -> a = num.gcd @numer, x.denom b = num.gcd @denom, x.numer n = @numer.idiv(a).times(x.numer.idiv(b)) d = @denom.idiv(b).times(x.denom.idiv(a)) Fraction.normalized n, d div__: (x) -> @times__ x.inv__() toString: -> if @denom.eq 1 then "#{@numer}" else "#{@numer}/#{@denom}" toNative: -> @numer.toNative() / @denom.toNative() # ---- # Exporting. exports = module?.exports or this.pazy ?= {} exports.num = num # ---- # Some quick tests. if quicktest { show } = require 'testing' a = b = c = 0 log '' show -> null show -> undefined log '' show -> num(98).gcd 21 show -> num(77777).gcd 21 log '' show -> a = num Math.pow 2, 13 show -> LongInt.fromNative a.val show -> a.plus 2 show -> a.times 1 show -> a.times 2 show -> a.plus 2000 log '' show -> num -123456789000000 show -> num '-1234' show -> num '-123456789000000' log '' show -> num(123456789).plus 876543211 show -> num(123456789).minus 123450000 show -> num(123456789).minus 123456790 show -> num(123456789).minus 123456789 show -> num(123456789).plus -123450000 log '' show -> num(12345).times 100001 show -> num(11111).times 9 show -> num(111).idiv 37 show -> num(111111).idiv 37 show -> num(111111111).idiv 37 show -> num(111111111).idiv 12345679 show -> num(99980001).idiv 49990001 show -> num(20001).idiv 10001 log '' show -> num(111).mod 37 show -> num(111112).mod 37 show -> num(111111111).mod 12345679 log '' show -> num(9801).isqrt() show -> num(998001).isqrt() show -> num(99980001).isqrt() log '' show -> num(10).pow 6 show -> num(2).pow 16 log '' show -> num.plus 123456789, 876543211 show -> num.isqrt 99980001 show -> num.pow 2, 16 show -> num.abs -12345 show -> num.isZero 1 show -> num.isZero 123456 show -> num.isZero 0 show -> num.isNeg 0 show -> num.isNeg -45 show -> num.isNeg -12345 show -> num.isOdd -12345 log '' show -> num.eq 8, num(111119).mod 37 show -> num.lt 65535, num.pow 2, 16 show -> num.gt 65535, num.pow 2, 16 show -> num.gt 65536, num.pow 2, 16 show -> num.gt 65537, num.pow 2, 16 log '' show -> num.div 2, 3 show -> num.div(9,10).times(num.div(5,21)) show -> num.div(3,5).minus(num.div(7,11)) show -> num.div 111111111, 12345679 * 2 show -> num.div(28,3).isqrt() show -> num.div(1,2).plus num.div(1,2) show -> num.div(2,3).plus num.div(4,3) show -> num.div(2,3).plus 1 show -> num.div(2,3).div 2
157795
# A generic number type, currently supporting integral Javascript numbers, # arbitrary precision integers and fractions. # # Arguments and results of arithmetic operations are coerced to the best # fitting type. # # _Copyright (c) 2011 <NAME>_ # ---- # First, we import some necessary functions and data structures. if typeof(require) != 'undefined' { bounce } = require 'functional' { seq } = require 'sequence' else { bounce, seq } = this.pazy # ---- # If this source file is being executed directly, run in test mode. quicktest = module? and not module.parent log = if quicktest then (str) -> console.log str else (str) -> # ---- # An integer is represented as either a plain signed Javascript number with # overflow (or strictly speaking: precision loss) checks or a lazy sequence of # unsigned numbers. The constant `BASE` determines the number base for the # latter representation. In addition, numbers with an absolute value smaller # than `BASE` are represented as plain numbers. # # In production mode, the number `BASE` is computed as the largest power of 100 # that fits into a Javascript number twice with full precision. The number # `HALFBASE` it its square root. According to the Javascript specification, we # should expect `BASE == 10e14` and `HALFBASE == 10e7`. BASE_LENGTH = if quicktest then 4 else seq.from(1) .map((n) -> 2 * n) .takeWhile((n) -> b = Math.pow 10, n 2 * b - 2 != 2 * b - 1 and -2 * b + 2 != -2 * b + 1 ) .last() BASE = Math.pow 10, BASE_LENGTH HALFBASE = Math.sqrt BASE # ---- # Internal helpers for constructing number representations. asNum = (n) -> if Math.abs(n) < BASE then new CheckedInt n else LongInt.fromNative n # ---- # The `num` function provides the public interface. num = (n = 0) -> switch typeof n when 'number' num.fromNative n when 'string' num.parse n else if n instanceof NumberBase n else throw new Error "expected a number, got #{n}" num.fromNative = (n) -> throw new Error "expected an integer, got #{n}" unless n == Math.floor n asNum n num.parse = (n) -> unless /^[+-]?\d+$/.test n throw new Error "expected an integer literal, got '#{n}'" [s, m] = switch n[0] when '-' then [-1, n[1..]] when '+' then [ 1, n[1..]] else [ 1, n] if m.length <= BASE_LENGTH new CheckedInt parseInt n else parsed = (to) -> if to > 0 from = Math.max 0, to - BASE_LENGTH seq.conj parseInt(m[from...to]), -> parsed from else null new LongInt s, parsed m.length # ---- # The `NumberBase` class implements dispatching on binary arithmetic # operators. class NumberBase makeNum = (n) -> if n instanceof NumberBase n else if typeof n == 'number' if Math.floor(n) == n if Math.abs(n) < BASE new CheckedInt n else LongInt.fromNative n else throw new Error "expected an integer, got #{n}" else throw new Error "expected a number, got #{n}" upcast = (a, b) -> [op1, op2] = [makeNum(a), makeNum(b)] out = switch op1.constructor when CheckedInt switch op2.constructor when CheckedInt [op1, op2] when LongInt [LongInt.fromNative(op1.val), op2] when Fraction [new Fraction(op1, num 1), op2] when LongInt switch op2.constructor when CheckedInt [op1, LongInt.fromNative(op2.val)] when LongInt [op1, op2] when Fraction [new Fraction(op1, num 1), op2] when Fraction switch op2.constructor when CheckedInt, LongInt [op1, new Fraction op2, num 1] when Fraction [op1, op2] if out out else [tp1, tp2] = [op1.constructor, op2.constructor] throw new Error "operands of types #{tp1} and #{tp2} not supported" downcast = (x) -> if x instanceof LongInt and x.lt BASE if x.digits? new CheckedInt x.digits.first() * x.sign else new CheckedInt 0 else if x instanceof Fraction and x.denom.eq(1) x.numer else x operator = (name, f) -> num[name] = (args...) -> f.call num, args... NumberBase::[name] = (args...) -> num[name] this, args... for name in ['cmp', 'plus', 'minus', 'times', 'div', 'idiv', 'mod', 'gcd'] do (name) -> namex = "#{name}__" operator name, (a, b) -> [x, y] = upcast a, b downcast x[namex] y div__: (other) -> Fraction.normalized this, other gcd__: (other) -> step = (a, b) -> if b.isPos() then -> step b, a.mod(b) else a [x, y] = [@abs(), other.abs()] if x.gt(y) then bounce step x, y else bounce step x, y operator 'lt', (a, b) -> num.cmp(a, b) < 0 operator 'gt', (a, b) -> num.cmp(a, b) > 0 operator 'eq', (a, b) -> num.cmp(a, b) == 0 operator 'equals', (a, b) -> num.cmp(a, b) == 0 for name in [ 'neg', 'abs', 'sgn', 'isPos', 'isNeg', 'isZero', 'isEven', 'isOdd' ] do (name) -> namex = "#{name}__" operator name, (a) -> makeNum(a)[namex]() operator 'isqrt', (a) -> downcast makeNum(a)['isqrt__']() operator 'pow', (a, b) -> step = (p, r, s) -> if s.isPos() if s.isOdd() > 0 -> step p.times(r), r, s.minus 1 else -> step p, r.times(r), s.idiv 2 else p downcast bounce step makeNum(1), makeNum(a), makeNum(b) # ---- # The `CheckInt` class provides integer operations with 'overflow checks'. In # other words, if the result cannot be represented with full precision as a # Javascript number, a `LongInt` is produced instead. class CheckedInt extends NumberBase constructor: (@val = 0) -> neg__: -> new CheckedInt -@val abs__: -> new CheckedInt Math.abs @val sgn__: -> if @val < 0 then -1 else if @val > 0 then 1 else 0 isPos__: -> @val > 0 isNeg__: -> @val < 0 isZero__: -> @val == 0 isEven__: -> @val % 2 == 0 isOdd__: -> @val % 2 != 0 isqrt__: -> new CheckedInt Math.floor Math.sqrt @val cmp__: (other) -> if @val < other.val then -1 else if @val > other.val then 1 else 0 plus__: (other) -> asNum @val + other.val minus__: (other) -> asNum @val - other.val times__: (other) -> x = @val * other.val if Math.abs(x) < BASE new CheckedInt x else LongInt.fromNative(@val).times other idiv__: (x) -> new CheckedInt Math.floor @val / x.val mod__: (x) -> new CheckedInt @val % x.val toString: -> "" + @val toNative: -> @val # ---- # Here are the beginnings of the `LongInt` class. class LongInt extends NumberBase constructor: (sign, @digits) -> @sign = if @digits? then sign else 0 @first = @digits?.first() or 0 neg__: -> new LongInt -@sign, @digits abs__: -> new LongInt 1, @digits sgn__: -> @sign isPos__: -> @sign > 0 isNeg__: -> @sign < 0 isZero__: -> @sign == 0 isEven__: -> @first % 2 == 0 isOdd__: -> @first % 2 != 0 zeroes = BASE.toString()[1..] rdump = (s) -> if s s.map((t) -> "#{zeroes[t.toString().length..]}#{t}").into([]).join('|') else '[]' dump = (s) -> rdump s?.reverse() ZERO = seq [0] cleanup = (s) -> s?.reverse()?.dropWhile((x) -> x == 0)?.reverse() or null isqrt = (s) -> n = s.size() step = (r) -> rn = seq idiv(add(r, idiv(s, r)), seq([2])) if cmp(r, rn) then -> step(rn) else rn bounce step s.take n >> 1 isqrt__: -> if @isZero() asNum 0 else if @isPos() new LongInt 1, isqrt @digits else throw new Error "expected a non-negative number, got #{this}" cmp = (r, s) -> seq.sub(r, s)?.reverse()?.dropWhile((x) -> x == 0)?.first() or 0 cmp__: (x) -> if @isZero() -x.sign else if x.isZero() @sign else if @sign != x.sign @sign else @sign * cmp @digits, x.digits add = (r, s, c = 0) -> if c or (r and s) [r_, s_] = [r or ZERO, s or ZERO] x = r_.first() + s_.first() + c [digit, carry] = if x >= BASE then [x - BASE, 1] else [x, 0] seq.conj(digit, -> add(r_.rest(), s_.rest(), carry)) else s or r plus__: (x) -> if @sign != x.sign @minus x.neg() else new LongInt @sign, add @digits, x.digits sub = (r, s) -> step = (r, s, b = 0) -> if b or (r and s) [r_, s_] = [r or ZERO, s or ZERO] x = r_.first() - s_.first() - b [digit, borrow] = if x < 0 then [x + BASE, 1] else [x, 0] seq.conj(digit, -> step(r_.rest(), s_.rest(), borrow)) else s or r cleanup step r, s minus__: (x) -> if @sign != x.sign @plus x.neg() else if cmp(@digits, x.digits) < 0 new LongInt -@sign, sub x.digits, @digits else new LongInt @sign, sub @digits, x.digits split = (n) -> [n % HALFBASE, Math.floor n / HALFBASE] digitTimesDigit = (a, b) -> if b < BASE / a [a * b, 0] else [a0, a1] = split a [b0, b1] = split b [m0, m1] = split a0 * b1 + b0 * a1 tmp = a0 * b0 + m0 * HALFBASE [lo, carry] = if tmp < BASE then [tmp, 0] else [tmp - BASE, 1] [lo, a1 * b1 + m1 + carry] seqTimesDigit = (s, d, c = 0) -> if c or s s_ = s or ZERO [lo, hi] = digitTimesDigit(d, s_.first()) seq.conj(lo + c, -> seqTimesDigit(s_.rest(), d, hi)) mul = (a, b) -> step = (r, a, b) -> if a t = add(r, seqTimesDigit(b, a.first())) or ZERO seq.conj(t.first(), -> step(t.rest(), a.rest(), b)) else r step null, a, b times__: (x) -> new LongInt @sign * x.sign, mul @digits, x.digits idivmod = (r, s) -> return [ZERO, ZERO] unless cleanup r scale = Math.floor BASE / (s.last() + 1) [r_, s_] = (seq seqTimesDigit(x, scale) for x in [r, s]) [m, d] = [s_.size(), s_.last() + 1] step = (q, h, t) -> f = if h?.size() < m 0 else n = (h?.last() * if h?.size() > m then BASE else 1) or 0 (Math.floor n / d) or (if cmp(h, s_) >= 0 then 1 else 0) if f -> step(add(q, seq.conj(f)), sub(h, seqTimesDigit(s_, f)), t) else if t -> step(seq.conj(0, -> q), seq.conj(t.first(), -> h), t.rest()) else [cleanup(q), h && idiv(h, seq [scale])] bounce step null, null, r_?.reverse() idiv = (r, s) -> idivmod(r, s)[0] mod = (r, s) -> idivmod(r, s)[1] idiv__: (x) -> d = cmp @digits, x.digits if d < 0 asNum 0 else if d == 0 asNum @sign * x.sign else new LongInt @sign * x.sign, idiv @digits, x.digits mod__: (x) -> d = cmp @digits, x.digits if d < 0 this else if d == 0 asNum 0 else new LongInt @sign * x.sign, mod @digits, x.digits toString: -> parts = @digits?.reverse()?.dropWhile((d) -> d == 0)?.map (d) -> d.toString() if parts sign = if @isNeg() then '-' else '' rest = parts.rest()?.map (t) -> "#{zeroes[t.length..]}#{t}" sign + parts.first() + if rest? then rest.join '' else '' else '0' toNative: -> step = (n, s) -> if s then -> step n * BASE + s.first(), s.rest() else n rev = @digits?.reverse()?.dropWhile (d) -> d == 0 @sign * bounce step 0, rev makeDigits = (m) -> if m then seq.conj m % BASE, -> makeDigits Math.floor(m / BASE) else null @fromNative: (n) -> if n < 0 new LongInt -1, makeDigits -n else if n > 0 new LongInt 1, makeDigits n else new LongInt 0, null # ---- # The 'Fraction' class implements rational numbers. class Fraction extends NumberBase constructor: (@numer, @denom) -> @normalized = (n, d) -> if d.eq 0 throw new Error "expected a non-zero denominator, got #{d}" else if d.lt 0 Fraction.normalized n.neg(), d.neg() else a = num.gcd n, d new Fraction n.idiv(a), d.idiv(a) neg__: -> new Fraction @numer.neg(), @denom abs__: -> new Fraction @numer.abs(), @denom sgn__: -> @numer.sgn() inv__: -> Fraction.normalized @denom, @numer isPos__: -> @numer.isPos() isNeg__: -> @numer.isNeg() isZero__: -> @numer.isZero() isEven__: -> @denom.eq(1) and @numer.isEven() isOdd__: -> @denom.eq(1) and @numer.isOdd() isqrt__: -> num.idiv(@numer, @denom).isqrt() cmp__: (x) -> @minus__(x).numer.cmp 0 plus__: (x) -> a = num.gcd @denom, x.denom s = num.idiv x.denom, a t = num.idiv @denom, a Fraction.normalized s.times(@numer).plus(t.times(x.numer)), s.times @denom minus__: (x) -> @plus__ x.neg__() times__: (x) -> a = num.gcd @numer, x.denom b = num.gcd @denom, x.numer n = @numer.idiv(a).times(x.numer.idiv(b)) d = @denom.idiv(b).times(x.denom.idiv(a)) Fraction.normalized n, d div__: (x) -> @times__ x.inv__() toString: -> if @denom.eq 1 then "#{@numer}" else "#{@numer}/#{@denom}" toNative: -> @numer.toNative() / @denom.toNative() # ---- # Exporting. exports = module?.exports or this.pazy ?= {} exports.num = num # ---- # Some quick tests. if quicktest { show } = require 'testing' a = b = c = 0 log '' show -> null show -> undefined log '' show -> num(98).gcd 21 show -> num(77777).gcd 21 log '' show -> a = num Math.pow 2, 13 show -> LongInt.fromNative a.val show -> a.plus 2 show -> a.times 1 show -> a.times 2 show -> a.plus 2000 log '' show -> num -123456789000000 show -> num '-1234' show -> num '-123456789000000' log '' show -> num(123456789).plus 876543211 show -> num(123456789).minus 123450000 show -> num(123456789).minus 123456790 show -> num(123456789).minus 123456789 show -> num(123456789).plus -123450000 log '' show -> num(12345).times 100001 show -> num(11111).times 9 show -> num(111).idiv 37 show -> num(111111).idiv 37 show -> num(111111111).idiv 37 show -> num(111111111).idiv 12345679 show -> num(99980001).idiv 49990001 show -> num(20001).idiv 10001 log '' show -> num(111).mod 37 show -> num(111112).mod 37 show -> num(111111111).mod 12345679 log '' show -> num(9801).isqrt() show -> num(998001).isqrt() show -> num(99980001).isqrt() log '' show -> num(10).pow 6 show -> num(2).pow 16 log '' show -> num.plus 123456789, 876543211 show -> num.isqrt 99980001 show -> num.pow 2, 16 show -> num.abs -12345 show -> num.isZero 1 show -> num.isZero 123456 show -> num.isZero 0 show -> num.isNeg 0 show -> num.isNeg -45 show -> num.isNeg -12345 show -> num.isOdd -12345 log '' show -> num.eq 8, num(111119).mod 37 show -> num.lt 65535, num.pow 2, 16 show -> num.gt 65535, num.pow 2, 16 show -> num.gt 65536, num.pow 2, 16 show -> num.gt 65537, num.pow 2, 16 log '' show -> num.div 2, 3 show -> num.div(9,10).times(num.div(5,21)) show -> num.div(3,5).minus(num.div(7,11)) show -> num.div 111111111, 12345679 * 2 show -> num.div(28,3).isqrt() show -> num.div(1,2).plus num.div(1,2) show -> num.div(2,3).plus num.div(4,3) show -> num.div(2,3).plus 1 show -> num.div(2,3).div 2
true
# A generic number type, currently supporting integral Javascript numbers, # arbitrary precision integers and fractions. # # Arguments and results of arithmetic operations are coerced to the best # fitting type. # # _Copyright (c) 2011 PI:NAME:<NAME>END_PI_ # ---- # First, we import some necessary functions and data structures. if typeof(require) != 'undefined' { bounce } = require 'functional' { seq } = require 'sequence' else { bounce, seq } = this.pazy # ---- # If this source file is being executed directly, run in test mode. quicktest = module? and not module.parent log = if quicktest then (str) -> console.log str else (str) -> # ---- # An integer is represented as either a plain signed Javascript number with # overflow (or strictly speaking: precision loss) checks or a lazy sequence of # unsigned numbers. The constant `BASE` determines the number base for the # latter representation. In addition, numbers with an absolute value smaller # than `BASE` are represented as plain numbers. # # In production mode, the number `BASE` is computed as the largest power of 100 # that fits into a Javascript number twice with full precision. The number # `HALFBASE` it its square root. According to the Javascript specification, we # should expect `BASE == 10e14` and `HALFBASE == 10e7`. BASE_LENGTH = if quicktest then 4 else seq.from(1) .map((n) -> 2 * n) .takeWhile((n) -> b = Math.pow 10, n 2 * b - 2 != 2 * b - 1 and -2 * b + 2 != -2 * b + 1 ) .last() BASE = Math.pow 10, BASE_LENGTH HALFBASE = Math.sqrt BASE # ---- # Internal helpers for constructing number representations. asNum = (n) -> if Math.abs(n) < BASE then new CheckedInt n else LongInt.fromNative n # ---- # The `num` function provides the public interface. num = (n = 0) -> switch typeof n when 'number' num.fromNative n when 'string' num.parse n else if n instanceof NumberBase n else throw new Error "expected a number, got #{n}" num.fromNative = (n) -> throw new Error "expected an integer, got #{n}" unless n == Math.floor n asNum n num.parse = (n) -> unless /^[+-]?\d+$/.test n throw new Error "expected an integer literal, got '#{n}'" [s, m] = switch n[0] when '-' then [-1, n[1..]] when '+' then [ 1, n[1..]] else [ 1, n] if m.length <= BASE_LENGTH new CheckedInt parseInt n else parsed = (to) -> if to > 0 from = Math.max 0, to - BASE_LENGTH seq.conj parseInt(m[from...to]), -> parsed from else null new LongInt s, parsed m.length # ---- # The `NumberBase` class implements dispatching on binary arithmetic # operators. class NumberBase makeNum = (n) -> if n instanceof NumberBase n else if typeof n == 'number' if Math.floor(n) == n if Math.abs(n) < BASE new CheckedInt n else LongInt.fromNative n else throw new Error "expected an integer, got #{n}" else throw new Error "expected a number, got #{n}" upcast = (a, b) -> [op1, op2] = [makeNum(a), makeNum(b)] out = switch op1.constructor when CheckedInt switch op2.constructor when CheckedInt [op1, op2] when LongInt [LongInt.fromNative(op1.val), op2] when Fraction [new Fraction(op1, num 1), op2] when LongInt switch op2.constructor when CheckedInt [op1, LongInt.fromNative(op2.val)] when LongInt [op1, op2] when Fraction [new Fraction(op1, num 1), op2] when Fraction switch op2.constructor when CheckedInt, LongInt [op1, new Fraction op2, num 1] when Fraction [op1, op2] if out out else [tp1, tp2] = [op1.constructor, op2.constructor] throw new Error "operands of types #{tp1} and #{tp2} not supported" downcast = (x) -> if x instanceof LongInt and x.lt BASE if x.digits? new CheckedInt x.digits.first() * x.sign else new CheckedInt 0 else if x instanceof Fraction and x.denom.eq(1) x.numer else x operator = (name, f) -> num[name] = (args...) -> f.call num, args... NumberBase::[name] = (args...) -> num[name] this, args... for name in ['cmp', 'plus', 'minus', 'times', 'div', 'idiv', 'mod', 'gcd'] do (name) -> namex = "#{name}__" operator name, (a, b) -> [x, y] = upcast a, b downcast x[namex] y div__: (other) -> Fraction.normalized this, other gcd__: (other) -> step = (a, b) -> if b.isPos() then -> step b, a.mod(b) else a [x, y] = [@abs(), other.abs()] if x.gt(y) then bounce step x, y else bounce step x, y operator 'lt', (a, b) -> num.cmp(a, b) < 0 operator 'gt', (a, b) -> num.cmp(a, b) > 0 operator 'eq', (a, b) -> num.cmp(a, b) == 0 operator 'equals', (a, b) -> num.cmp(a, b) == 0 for name in [ 'neg', 'abs', 'sgn', 'isPos', 'isNeg', 'isZero', 'isEven', 'isOdd' ] do (name) -> namex = "#{name}__" operator name, (a) -> makeNum(a)[namex]() operator 'isqrt', (a) -> downcast makeNum(a)['isqrt__']() operator 'pow', (a, b) -> step = (p, r, s) -> if s.isPos() if s.isOdd() > 0 -> step p.times(r), r, s.minus 1 else -> step p, r.times(r), s.idiv 2 else p downcast bounce step makeNum(1), makeNum(a), makeNum(b) # ---- # The `CheckInt` class provides integer operations with 'overflow checks'. In # other words, if the result cannot be represented with full precision as a # Javascript number, a `LongInt` is produced instead. class CheckedInt extends NumberBase constructor: (@val = 0) -> neg__: -> new CheckedInt -@val abs__: -> new CheckedInt Math.abs @val sgn__: -> if @val < 0 then -1 else if @val > 0 then 1 else 0 isPos__: -> @val > 0 isNeg__: -> @val < 0 isZero__: -> @val == 0 isEven__: -> @val % 2 == 0 isOdd__: -> @val % 2 != 0 isqrt__: -> new CheckedInt Math.floor Math.sqrt @val cmp__: (other) -> if @val < other.val then -1 else if @val > other.val then 1 else 0 plus__: (other) -> asNum @val + other.val minus__: (other) -> asNum @val - other.val times__: (other) -> x = @val * other.val if Math.abs(x) < BASE new CheckedInt x else LongInt.fromNative(@val).times other idiv__: (x) -> new CheckedInt Math.floor @val / x.val mod__: (x) -> new CheckedInt @val % x.val toString: -> "" + @val toNative: -> @val # ---- # Here are the beginnings of the `LongInt` class. class LongInt extends NumberBase constructor: (sign, @digits) -> @sign = if @digits? then sign else 0 @first = @digits?.first() or 0 neg__: -> new LongInt -@sign, @digits abs__: -> new LongInt 1, @digits sgn__: -> @sign isPos__: -> @sign > 0 isNeg__: -> @sign < 0 isZero__: -> @sign == 0 isEven__: -> @first % 2 == 0 isOdd__: -> @first % 2 != 0 zeroes = BASE.toString()[1..] rdump = (s) -> if s s.map((t) -> "#{zeroes[t.toString().length..]}#{t}").into([]).join('|') else '[]' dump = (s) -> rdump s?.reverse() ZERO = seq [0] cleanup = (s) -> s?.reverse()?.dropWhile((x) -> x == 0)?.reverse() or null isqrt = (s) -> n = s.size() step = (r) -> rn = seq idiv(add(r, idiv(s, r)), seq([2])) if cmp(r, rn) then -> step(rn) else rn bounce step s.take n >> 1 isqrt__: -> if @isZero() asNum 0 else if @isPos() new LongInt 1, isqrt @digits else throw new Error "expected a non-negative number, got #{this}" cmp = (r, s) -> seq.sub(r, s)?.reverse()?.dropWhile((x) -> x == 0)?.first() or 0 cmp__: (x) -> if @isZero() -x.sign else if x.isZero() @sign else if @sign != x.sign @sign else @sign * cmp @digits, x.digits add = (r, s, c = 0) -> if c or (r and s) [r_, s_] = [r or ZERO, s or ZERO] x = r_.first() + s_.first() + c [digit, carry] = if x >= BASE then [x - BASE, 1] else [x, 0] seq.conj(digit, -> add(r_.rest(), s_.rest(), carry)) else s or r plus__: (x) -> if @sign != x.sign @minus x.neg() else new LongInt @sign, add @digits, x.digits sub = (r, s) -> step = (r, s, b = 0) -> if b or (r and s) [r_, s_] = [r or ZERO, s or ZERO] x = r_.first() - s_.first() - b [digit, borrow] = if x < 0 then [x + BASE, 1] else [x, 0] seq.conj(digit, -> step(r_.rest(), s_.rest(), borrow)) else s or r cleanup step r, s minus__: (x) -> if @sign != x.sign @plus x.neg() else if cmp(@digits, x.digits) < 0 new LongInt -@sign, sub x.digits, @digits else new LongInt @sign, sub @digits, x.digits split = (n) -> [n % HALFBASE, Math.floor n / HALFBASE] digitTimesDigit = (a, b) -> if b < BASE / a [a * b, 0] else [a0, a1] = split a [b0, b1] = split b [m0, m1] = split a0 * b1 + b0 * a1 tmp = a0 * b0 + m0 * HALFBASE [lo, carry] = if tmp < BASE then [tmp, 0] else [tmp - BASE, 1] [lo, a1 * b1 + m1 + carry] seqTimesDigit = (s, d, c = 0) -> if c or s s_ = s or ZERO [lo, hi] = digitTimesDigit(d, s_.first()) seq.conj(lo + c, -> seqTimesDigit(s_.rest(), d, hi)) mul = (a, b) -> step = (r, a, b) -> if a t = add(r, seqTimesDigit(b, a.first())) or ZERO seq.conj(t.first(), -> step(t.rest(), a.rest(), b)) else r step null, a, b times__: (x) -> new LongInt @sign * x.sign, mul @digits, x.digits idivmod = (r, s) -> return [ZERO, ZERO] unless cleanup r scale = Math.floor BASE / (s.last() + 1) [r_, s_] = (seq seqTimesDigit(x, scale) for x in [r, s]) [m, d] = [s_.size(), s_.last() + 1] step = (q, h, t) -> f = if h?.size() < m 0 else n = (h?.last() * if h?.size() > m then BASE else 1) or 0 (Math.floor n / d) or (if cmp(h, s_) >= 0 then 1 else 0) if f -> step(add(q, seq.conj(f)), sub(h, seqTimesDigit(s_, f)), t) else if t -> step(seq.conj(0, -> q), seq.conj(t.first(), -> h), t.rest()) else [cleanup(q), h && idiv(h, seq [scale])] bounce step null, null, r_?.reverse() idiv = (r, s) -> idivmod(r, s)[0] mod = (r, s) -> idivmod(r, s)[1] idiv__: (x) -> d = cmp @digits, x.digits if d < 0 asNum 0 else if d == 0 asNum @sign * x.sign else new LongInt @sign * x.sign, idiv @digits, x.digits mod__: (x) -> d = cmp @digits, x.digits if d < 0 this else if d == 0 asNum 0 else new LongInt @sign * x.sign, mod @digits, x.digits toString: -> parts = @digits?.reverse()?.dropWhile((d) -> d == 0)?.map (d) -> d.toString() if parts sign = if @isNeg() then '-' else '' rest = parts.rest()?.map (t) -> "#{zeroes[t.length..]}#{t}" sign + parts.first() + if rest? then rest.join '' else '' else '0' toNative: -> step = (n, s) -> if s then -> step n * BASE + s.first(), s.rest() else n rev = @digits?.reverse()?.dropWhile (d) -> d == 0 @sign * bounce step 0, rev makeDigits = (m) -> if m then seq.conj m % BASE, -> makeDigits Math.floor(m / BASE) else null @fromNative: (n) -> if n < 0 new LongInt -1, makeDigits -n else if n > 0 new LongInt 1, makeDigits n else new LongInt 0, null # ---- # The 'Fraction' class implements rational numbers. class Fraction extends NumberBase constructor: (@numer, @denom) -> @normalized = (n, d) -> if d.eq 0 throw new Error "expected a non-zero denominator, got #{d}" else if d.lt 0 Fraction.normalized n.neg(), d.neg() else a = num.gcd n, d new Fraction n.idiv(a), d.idiv(a) neg__: -> new Fraction @numer.neg(), @denom abs__: -> new Fraction @numer.abs(), @denom sgn__: -> @numer.sgn() inv__: -> Fraction.normalized @denom, @numer isPos__: -> @numer.isPos() isNeg__: -> @numer.isNeg() isZero__: -> @numer.isZero() isEven__: -> @denom.eq(1) and @numer.isEven() isOdd__: -> @denom.eq(1) and @numer.isOdd() isqrt__: -> num.idiv(@numer, @denom).isqrt() cmp__: (x) -> @minus__(x).numer.cmp 0 plus__: (x) -> a = num.gcd @denom, x.denom s = num.idiv x.denom, a t = num.idiv @denom, a Fraction.normalized s.times(@numer).plus(t.times(x.numer)), s.times @denom minus__: (x) -> @plus__ x.neg__() times__: (x) -> a = num.gcd @numer, x.denom b = num.gcd @denom, x.numer n = @numer.idiv(a).times(x.numer.idiv(b)) d = @denom.idiv(b).times(x.denom.idiv(a)) Fraction.normalized n, d div__: (x) -> @times__ x.inv__() toString: -> if @denom.eq 1 then "#{@numer}" else "#{@numer}/#{@denom}" toNative: -> @numer.toNative() / @denom.toNative() # ---- # Exporting. exports = module?.exports or this.pazy ?= {} exports.num = num # ---- # Some quick tests. if quicktest { show } = require 'testing' a = b = c = 0 log '' show -> null show -> undefined log '' show -> num(98).gcd 21 show -> num(77777).gcd 21 log '' show -> a = num Math.pow 2, 13 show -> LongInt.fromNative a.val show -> a.plus 2 show -> a.times 1 show -> a.times 2 show -> a.plus 2000 log '' show -> num -123456789000000 show -> num '-1234' show -> num '-123456789000000' log '' show -> num(123456789).plus 876543211 show -> num(123456789).minus 123450000 show -> num(123456789).minus 123456790 show -> num(123456789).minus 123456789 show -> num(123456789).plus -123450000 log '' show -> num(12345).times 100001 show -> num(11111).times 9 show -> num(111).idiv 37 show -> num(111111).idiv 37 show -> num(111111111).idiv 37 show -> num(111111111).idiv 12345679 show -> num(99980001).idiv 49990001 show -> num(20001).idiv 10001 log '' show -> num(111).mod 37 show -> num(111112).mod 37 show -> num(111111111).mod 12345679 log '' show -> num(9801).isqrt() show -> num(998001).isqrt() show -> num(99980001).isqrt() log '' show -> num(10).pow 6 show -> num(2).pow 16 log '' show -> num.plus 123456789, 876543211 show -> num.isqrt 99980001 show -> num.pow 2, 16 show -> num.abs -12345 show -> num.isZero 1 show -> num.isZero 123456 show -> num.isZero 0 show -> num.isNeg 0 show -> num.isNeg -45 show -> num.isNeg -12345 show -> num.isOdd -12345 log '' show -> num.eq 8, num(111119).mod 37 show -> num.lt 65535, num.pow 2, 16 show -> num.gt 65535, num.pow 2, 16 show -> num.gt 65536, num.pow 2, 16 show -> num.gt 65537, num.pow 2, 16 log '' show -> num.div 2, 3 show -> num.div(9,10).times(num.div(5,21)) show -> num.div(3,5).minus(num.div(7,11)) show -> num.div 111111111, 12345679 * 2 show -> num.div(28,3).isqrt() show -> num.div(1,2).plus num.div(1,2) show -> num.div(2,3).plus num.div(4,3) show -> num.div(2,3).plus 1 show -> num.div(2,3).div 2
[ { "context": "# https://github.com/cowboy/grunt/blob/master/docs/task_init.md\n# https://git", "end": 27, "score": 0.9996605515480042, "start": 21, "tag": "USERNAME", "value": "cowboy" }, { "context": "lob/master/docs/task_init.md\n# https://github.com/kmiyashiro/grunt-mocha\n# https...
node_modules/tower/grunt.coffee
MagicPower2/Power
1
# https://github.com/cowboy/grunt/blob/master/docs/task_init.md # https://github.com/kmiyashiro/grunt-mocha # https://github.com/shama/grunt-hub/blob/master/tasks/watch.js module.exports = (grunt) -> require('./packages/tower-tasks/tasks')(grunt) try require('./wiki/grunt')(grunt) hasWiki = true catch error hasWiki = false require('./coffee-inheritance') require('./index.js') # require towerRoot/index.js _ = Tower._ file = grunt.file _path = require('path') githubDownloadStore = null # CoffeeScript files coffeeSrcPaths = _.select file.expand([ 'packages/**/*.coffee' ]), (i) -> !i.match('templates') jsSrcPaths = _.select file.expand([ 'packages/**/*.js' ]), (i) -> !i.match('templates') clientTestPaths = file.expand([ 'test/cases/*/shared/**/*.coffee' 'test/cases/*/client/**/*.coffee' ]) clientTestDestinationPath = 'test/example/public/javascripts' clientTestMap = {} testCasesPath = _path.relative(process.cwd(), 'test/cases') clientTestPaths.forEach (path) -> key = path.replace(testCasesPath, '').split(_path.sep)[1] array = clientTestMap[key] ||= [] array.push(path) towerFiles = ['lib/tower/client.js'] config = pkg: '<json:package.json>' meta: banner: """ /*! * Tower.js v<%= pkg.version %> * <%= pkg.homepage %> * * Copyright <%= grunt.template.today('yyyy') %>, Lance Pollard * <%= _.pluck(pkg.licenses, 'type').join(', ') %> License. * http://towerjs.org/license * * Date: <%= grunt.template.today('isoDate') %> */ """ concat: tower: src: ['<banner>', towerFiles] dest: 'dist/tower.js' core: src: ['<banner>', towerFiles] dest: 'dist/tower.core.js' # If you only want the model on the client model: src: ['<banner>', towerFiles] dest: 'dist/tower.model.js' # If you want the controller/route functionality as well controller: src: ['<banner>', towerFiles] dest: 'dist/tower.controller.js' min: dist: src: ['dist/tower.js'] dest: 'dist/tower.min.js' coffee: all: src: coffeeSrcPaths dest: 'lib' strip: 'packages/' options: bare: true tests: src: clientTestPaths dest: clientTestDestinationPath options: bare: false copy: packageJSON: src: ['packages/**/package.json', 'packages/tower-generator/server/generators/**/templates/**/*'] strip: 'packages/' dest: 'lib' clientForTests: src: ['dist/tower.js'] strip: 'dist/' dest: _path.join('test/example', 'vendor/javascripts') js: src: jsSrcPaths strip: 'packages/' dest: 'lib' watch: packageJSON: files: ['packages/**/package.json', 'packages/tower-generator/server/generators/**/templates/**/*'] tasks: ['copy:packageJSON'] #mainPackageJSON: # files: ['package.json'] # tasks: ['injectTestDependencies:packageJSON'] build: client: {} uploadToGithub: tower: {} dependencies: client: {} bundleDependencies: client: {} bundleTests: client: {} injectTestDependencies: packageJSON: src: ['package.json'] #jshint: # options: # curly: true # eqeqeq: true # immed: true # latedef: true # newcap: true # noarg: true # sub: true # undef: true # eqnull: true # browser: true coffeeSrcPaths.forEach (name) -> config.coffee[name] = src: name dest: 'lib' strip: 'packages/' options: bare: true config.watch[name] = files: [name] tasks: ["coffee:#{name}"] jsSrcPaths.forEach (name) -> config.copy[name] = src: name dest: 'lib' strip: 'packages/' config.watch[name] = files: [name] tasks: ["copy:#{name}"] # clientTestPaths.forEach (name) -> concatTestsCommand = [] for key, value of clientTestMap dest = _path.join(clientTestDestinationPath, 'test/cases', key + 'Test.js') concatTestCommand = "concat:#{key}Tests" concatTestsCommand.push(concatTestCommand) for name in value config.coffee[name] = src: name dest: clientTestDestinationPath options: bare: false config.watch[name] = files: [name] tasks: ["coffee:#{name}"]#, concatTestCommand] src = _.map value, (i) -> _path.join(clientTestDestinationPath, i).replace(/\.coffee$/, '.js') config.concat["#{key}Tests"] = src: src dest: dest # @todo need to copy file to test/x when it changes #for name in src # config.concat[name] if hasWiki config.wiki = toc: true config.watch['wiki:toc'] = files: ['wiki/_sidebar.md'] tasks: ['wiki:toc'] wikiFiles = file.expand([ 'wiki/en/**/*.md' ]) config.wikiLinks = all: src: wikiFiles #wikiFiles.forEach (wikiFile) -> # slug = _.parameterize(wikiFile) # # #config.watch[slug] = # # files: [wikiFile] # # tasks: ["wikiLinks:#{slug}"] # config.wikiLinks[slug] = # src: wikiFile # dest: wikiFile # # config grunt.initConfig(config) #grunt.loadNpmTasks 'grunt-coffee' grunt.registerTask 'concat:tests', concatTestsCommand.join(' ') grunt.registerTask 'default', 'coffee:all copy:js copy:packageJSON build:client copy:clientForTests coffee:tests' grunt.registerTask 'start', 'default watch' grunt.registerTask 'dist', 'build uploadToGithub' grunt.registerTask '' grunt.registerTask 'uploadToGithub', -> taskComplete = @async() grunt.helper 'uploadToGitHub', 'dist/tower.js', "tower-#{grunt.config('pkg.version')}.js", taskComplete
141611
# https://github.com/cowboy/grunt/blob/master/docs/task_init.md # https://github.com/kmiyashiro/grunt-mocha # https://github.com/shama/grunt-hub/blob/master/tasks/watch.js module.exports = (grunt) -> require('./packages/tower-tasks/tasks')(grunt) try require('./wiki/grunt')(grunt) hasWiki = true catch error hasWiki = false require('./coffee-inheritance') require('./index.js') # require towerRoot/index.js _ = Tower._ file = grunt.file _path = require('path') githubDownloadStore = null # CoffeeScript files coffeeSrcPaths = _.select file.expand([ 'packages/**/*.coffee' ]), (i) -> !i.match('templates') jsSrcPaths = _.select file.expand([ 'packages/**/*.js' ]), (i) -> !i.match('templates') clientTestPaths = file.expand([ 'test/cases/*/shared/**/*.coffee' 'test/cases/*/client/**/*.coffee' ]) clientTestDestinationPath = 'test/example/public/javascripts' clientTestMap = {} testCasesPath = _path.relative(process.cwd(), 'test/cases') clientTestPaths.forEach (path) -> key = path.replace(testCasesPath, '').split(_path.sep)[1] array = clientTestMap[key] ||= [] array.push(path) towerFiles = ['lib/tower/client.js'] config = pkg: '<json:package.json>' meta: banner: """ /*! * Tower.js v<%= pkg.version %> * <%= pkg.homepage %> * * Copyright <%= grunt.template.today('yyyy') %>, <NAME> * <%= _.pluck(pkg.licenses, 'type').join(', ') %> License. * http://towerjs.org/license * * Date: <%= grunt.template.today('isoDate') %> */ """ concat: tower: src: ['<banner>', towerFiles] dest: 'dist/tower.js' core: src: ['<banner>', towerFiles] dest: 'dist/tower.core.js' # If you only want the model on the client model: src: ['<banner>', towerFiles] dest: 'dist/tower.model.js' # If you want the controller/route functionality as well controller: src: ['<banner>', towerFiles] dest: 'dist/tower.controller.js' min: dist: src: ['dist/tower.js'] dest: 'dist/tower.min.js' coffee: all: src: coffeeSrcPaths dest: 'lib' strip: 'packages/' options: bare: true tests: src: clientTestPaths dest: clientTestDestinationPath options: bare: false copy: packageJSON: src: ['packages/**/package.json', 'packages/tower-generator/server/generators/**/templates/**/*'] strip: 'packages/' dest: 'lib' clientForTests: src: ['dist/tower.js'] strip: 'dist/' dest: _path.join('test/example', 'vendor/javascripts') js: src: jsSrcPaths strip: 'packages/' dest: 'lib' watch: packageJSON: files: ['packages/**/package.json', 'packages/tower-generator/server/generators/**/templates/**/*'] tasks: ['copy:packageJSON'] #mainPackageJSON: # files: ['package.json'] # tasks: ['injectTestDependencies:packageJSON'] build: client: {} uploadToGithub: tower: {} dependencies: client: {} bundleDependencies: client: {} bundleTests: client: {} injectTestDependencies: packageJSON: src: ['package.json'] #jshint: # options: # curly: true # eqeqeq: true # immed: true # latedef: true # newcap: true # noarg: true # sub: true # undef: true # eqnull: true # browser: true coffeeSrcPaths.forEach (name) -> config.coffee[name] = src: name dest: 'lib' strip: 'packages/' options: bare: true config.watch[name] = files: [name] tasks: ["coffee:#{name}"] jsSrcPaths.forEach (name) -> config.copy[name] = src: name dest: 'lib' strip: 'packages/' config.watch[name] = files: [name] tasks: ["copy:#{name}"] # clientTestPaths.forEach (name) -> concatTestsCommand = [] for key, value of clientTestMap dest = _path.join(clientTestDestinationPath, 'test/cases', key + 'Test.js') concatTestCommand = "concat:#{key}Tests" concatTestsCommand.push(concatTestCommand) for name in value config.coffee[name] = src: name dest: clientTestDestinationPath options: bare: false config.watch[name] = files: [name] tasks: ["coffee:#{name}"]#, concatTestCommand] src = _.map value, (i) -> _path.join(clientTestDestinationPath, i).replace(/\.coffee$/, '.js') config.concat["#{key}Tests"] = src: src dest: dest # @todo need to copy file to test/x when it changes #for name in src # config.concat[name] if hasWiki config.wiki = toc: true config.watch['wiki:toc'] = files: ['wiki/_sidebar.md'] tasks: ['wiki:toc'] wikiFiles = file.expand([ 'wiki/en/**/*.md' ]) config.wikiLinks = all: src: wikiFiles #wikiFiles.forEach (wikiFile) -> # slug = _.parameterize(wikiFile) # # #config.watch[slug] = # # files: [wikiFile] # # tasks: ["wikiLinks:#{slug}"] # config.wikiLinks[slug] = # src: wikiFile # dest: wikiFile # # config grunt.initConfig(config) #grunt.loadNpmTasks 'grunt-coffee' grunt.registerTask 'concat:tests', concatTestsCommand.join(' ') grunt.registerTask 'default', 'coffee:all copy:js copy:packageJSON build:client copy:clientForTests coffee:tests' grunt.registerTask 'start', 'default watch' grunt.registerTask 'dist', 'build uploadToGithub' grunt.registerTask '' grunt.registerTask 'uploadToGithub', -> taskComplete = @async() grunt.helper 'uploadToGitHub', 'dist/tower.js', "tower-#{grunt.config('pkg.version')}.js", taskComplete
true
# https://github.com/cowboy/grunt/blob/master/docs/task_init.md # https://github.com/kmiyashiro/grunt-mocha # https://github.com/shama/grunt-hub/blob/master/tasks/watch.js module.exports = (grunt) -> require('./packages/tower-tasks/tasks')(grunt) try require('./wiki/grunt')(grunt) hasWiki = true catch error hasWiki = false require('./coffee-inheritance') require('./index.js') # require towerRoot/index.js _ = Tower._ file = grunt.file _path = require('path') githubDownloadStore = null # CoffeeScript files coffeeSrcPaths = _.select file.expand([ 'packages/**/*.coffee' ]), (i) -> !i.match('templates') jsSrcPaths = _.select file.expand([ 'packages/**/*.js' ]), (i) -> !i.match('templates') clientTestPaths = file.expand([ 'test/cases/*/shared/**/*.coffee' 'test/cases/*/client/**/*.coffee' ]) clientTestDestinationPath = 'test/example/public/javascripts' clientTestMap = {} testCasesPath = _path.relative(process.cwd(), 'test/cases') clientTestPaths.forEach (path) -> key = path.replace(testCasesPath, '').split(_path.sep)[1] array = clientTestMap[key] ||= [] array.push(path) towerFiles = ['lib/tower/client.js'] config = pkg: '<json:package.json>' meta: banner: """ /*! * Tower.js v<%= pkg.version %> * <%= pkg.homepage %> * * Copyright <%= grunt.template.today('yyyy') %>, PI:NAME:<NAME>END_PI * <%= _.pluck(pkg.licenses, 'type').join(', ') %> License. * http://towerjs.org/license * * Date: <%= grunt.template.today('isoDate') %> */ """ concat: tower: src: ['<banner>', towerFiles] dest: 'dist/tower.js' core: src: ['<banner>', towerFiles] dest: 'dist/tower.core.js' # If you only want the model on the client model: src: ['<banner>', towerFiles] dest: 'dist/tower.model.js' # If you want the controller/route functionality as well controller: src: ['<banner>', towerFiles] dest: 'dist/tower.controller.js' min: dist: src: ['dist/tower.js'] dest: 'dist/tower.min.js' coffee: all: src: coffeeSrcPaths dest: 'lib' strip: 'packages/' options: bare: true tests: src: clientTestPaths dest: clientTestDestinationPath options: bare: false copy: packageJSON: src: ['packages/**/package.json', 'packages/tower-generator/server/generators/**/templates/**/*'] strip: 'packages/' dest: 'lib' clientForTests: src: ['dist/tower.js'] strip: 'dist/' dest: _path.join('test/example', 'vendor/javascripts') js: src: jsSrcPaths strip: 'packages/' dest: 'lib' watch: packageJSON: files: ['packages/**/package.json', 'packages/tower-generator/server/generators/**/templates/**/*'] tasks: ['copy:packageJSON'] #mainPackageJSON: # files: ['package.json'] # tasks: ['injectTestDependencies:packageJSON'] build: client: {} uploadToGithub: tower: {} dependencies: client: {} bundleDependencies: client: {} bundleTests: client: {} injectTestDependencies: packageJSON: src: ['package.json'] #jshint: # options: # curly: true # eqeqeq: true # immed: true # latedef: true # newcap: true # noarg: true # sub: true # undef: true # eqnull: true # browser: true coffeeSrcPaths.forEach (name) -> config.coffee[name] = src: name dest: 'lib' strip: 'packages/' options: bare: true config.watch[name] = files: [name] tasks: ["coffee:#{name}"] jsSrcPaths.forEach (name) -> config.copy[name] = src: name dest: 'lib' strip: 'packages/' config.watch[name] = files: [name] tasks: ["copy:#{name}"] # clientTestPaths.forEach (name) -> concatTestsCommand = [] for key, value of clientTestMap dest = _path.join(clientTestDestinationPath, 'test/cases', key + 'Test.js') concatTestCommand = "concat:#{key}Tests" concatTestsCommand.push(concatTestCommand) for name in value config.coffee[name] = src: name dest: clientTestDestinationPath options: bare: false config.watch[name] = files: [name] tasks: ["coffee:#{name}"]#, concatTestCommand] src = _.map value, (i) -> _path.join(clientTestDestinationPath, i).replace(/\.coffee$/, '.js') config.concat["#{key}Tests"] = src: src dest: dest # @todo need to copy file to test/x when it changes #for name in src # config.concat[name] if hasWiki config.wiki = toc: true config.watch['wiki:toc'] = files: ['wiki/_sidebar.md'] tasks: ['wiki:toc'] wikiFiles = file.expand([ 'wiki/en/**/*.md' ]) config.wikiLinks = all: src: wikiFiles #wikiFiles.forEach (wikiFile) -> # slug = _.parameterize(wikiFile) # # #config.watch[slug] = # # files: [wikiFile] # # tasks: ["wikiLinks:#{slug}"] # config.wikiLinks[slug] = # src: wikiFile # dest: wikiFile # # config grunt.initConfig(config) #grunt.loadNpmTasks 'grunt-coffee' grunt.registerTask 'concat:tests', concatTestsCommand.join(' ') grunt.registerTask 'default', 'coffee:all copy:js copy:packageJSON build:client copy:clientForTests coffee:tests' grunt.registerTask 'start', 'default watch' grunt.registerTask 'dist', 'build uploadToGithub' grunt.registerTask '' grunt.registerTask 'uploadToGithub', -> taskComplete = @async() grunt.helper 'uploadToGitHub', 'dist/tower.js', "tower-#{grunt.config('pkg.version')}.js", taskComplete
[ { "context": "subject = TT.Utils.reconcileArrayOrder\n key = 'foo'\n oldArray = [{ foo: 2 }, { foo: 1 }]\n newA", "end": 1208, "score": 0.9683363437652588, "start": 1205, "tag": "KEY", "value": "foo" } ]
test/spec/tt.utils.spec.coffee
mence/TrackerTracker
3
describe "TT.Utils", -> describe "#exists", -> subject = TT.Utils.exists it "should return true when object is not null and not undefined", -> expect(subject('')).toBe true expect(subject(0)).toBe true expect(subject(1)).toBe true expect(subject('abc')).toBe true expect(subject({})).toBe true it "should return false if object is null or undefined", -> expect(subject()).toBe false expect(subject(undefined)).toBe false expect(subject(null)).toBe false describe "#arrayMove", -> subject = TT.Utils.arrayMove arr = null beforeEach -> arr = [1, 2, 3, 4, 5, 6] it "should move a key from one index to another", -> expect(subject(arr, 2, 5)).toEqual [1, 2, 4, 5, 6, 3] expect(subject(arr, 5, 2)).toEqual [1, 2, 3, 4, 5, 6] expect(subject(arr, 0, 5)).toEqual [2, 3, 4, 5, 6, 1] say "the new index is beyond the end of the array", -> it "should pad the array with undefined values until it gets to the requested index", -> expect(subject(arr, 2, 6)).toEqual [1, 2, 4, 5, 6, undefined, 3] describe "#reconcileArrayOrder", -> subject = TT.Utils.reconcileArrayOrder key = 'foo' oldArray = [{ foo: 2 }, { foo: 1 }] newArray = [{ foo: 0 }, { foo: 1 }, { foo: 2 }, { foo: 3 }] expectedArray = [{ foo: 2 }, { foo: 1 }, { foo: 0 }, { foo: 3 }] it "should rearrange the newArray to use the order of the oldArray", -> expect(subject(key, oldArray, newArray)).toEqual expectedArray describe "#getIndexByKey", -> subject = TT.Utils.getIndexByKey arr = [{ foo: 1 }, { foo: 2 }, { foo: 3 }, { foo: 4 }] it "should return the index of the row with the matching property", -> expect(subject(arr, 'foo', 3)).toEqual 2 describe "#localStorage", -> subject = TT.Utils.localStorage key = 'myKey' val = null afterEach -> subject(key, null) say "an object is passed in", -> beforeEach -> val = { a: 1, b: 2, c: 3 } it "should store the stringified version of that object in localStorage", -> expect(subject(key)).toBe undefined expect(subject(key, val)).toBe '{"a":1,"b":2,"c":3}' say "null is passed in", -> beforeEach -> val = null it "should delete the key", -> expect(subject(key)).toBe undefined expect(subject(key, 'abc')).toBe 'abc' expect(subject(key, null)).toBe undefined expect(subject(key)).toBe undefined describe "#strToFunction", -> subject = TT.Utils.strToFunction beforeEach -> window.MyLib = { myLibFunc: -> MyModule: { myModuleFunc: -> } } afterEach -> delete window.MyLib say "a valid function is passed in", -> it "should return the function", -> expect(subject('MyLib.MyModule.myModuleFunc')).toBe MyLib.MyModule.myModuleFunc say "a valid function and context is passed in", -> it "should return the function", -> expect(subject('MyModule.myModuleFunc', MyLib)).toBe MyLib.MyModule.myModuleFunc say "an invalid function is passed in", -> it "should return undefined", -> expect(subject('Foo.Bar.myFunc')).toBe false describe "#generateInitials", -> subject = TT.Utils.generateInitials it "should return an initialized version of the input string", -> expect(subject('User Interface')).toBe 'UI' describe "#removeFromArray", -> subject = TT.Utils.removeFromArray say "an input value strictly matches a value found in the array", -> it "should return the array without the value", -> expect(subject([1, 2, 3, 4, 5], 4)).toEqual [1, 2, 3, 5] say "an input value does not match any value in the array", -> it "should return the array without any change", -> expect(subject([123, 'abc'], '123')).toEqual [123, 'abc']
145344
describe "TT.Utils", -> describe "#exists", -> subject = TT.Utils.exists it "should return true when object is not null and not undefined", -> expect(subject('')).toBe true expect(subject(0)).toBe true expect(subject(1)).toBe true expect(subject('abc')).toBe true expect(subject({})).toBe true it "should return false if object is null or undefined", -> expect(subject()).toBe false expect(subject(undefined)).toBe false expect(subject(null)).toBe false describe "#arrayMove", -> subject = TT.Utils.arrayMove arr = null beforeEach -> arr = [1, 2, 3, 4, 5, 6] it "should move a key from one index to another", -> expect(subject(arr, 2, 5)).toEqual [1, 2, 4, 5, 6, 3] expect(subject(arr, 5, 2)).toEqual [1, 2, 3, 4, 5, 6] expect(subject(arr, 0, 5)).toEqual [2, 3, 4, 5, 6, 1] say "the new index is beyond the end of the array", -> it "should pad the array with undefined values until it gets to the requested index", -> expect(subject(arr, 2, 6)).toEqual [1, 2, 4, 5, 6, undefined, 3] describe "#reconcileArrayOrder", -> subject = TT.Utils.reconcileArrayOrder key = '<KEY>' oldArray = [{ foo: 2 }, { foo: 1 }] newArray = [{ foo: 0 }, { foo: 1 }, { foo: 2 }, { foo: 3 }] expectedArray = [{ foo: 2 }, { foo: 1 }, { foo: 0 }, { foo: 3 }] it "should rearrange the newArray to use the order of the oldArray", -> expect(subject(key, oldArray, newArray)).toEqual expectedArray describe "#getIndexByKey", -> subject = TT.Utils.getIndexByKey arr = [{ foo: 1 }, { foo: 2 }, { foo: 3 }, { foo: 4 }] it "should return the index of the row with the matching property", -> expect(subject(arr, 'foo', 3)).toEqual 2 describe "#localStorage", -> subject = TT.Utils.localStorage key = 'myKey' val = null afterEach -> subject(key, null) say "an object is passed in", -> beforeEach -> val = { a: 1, b: 2, c: 3 } it "should store the stringified version of that object in localStorage", -> expect(subject(key)).toBe undefined expect(subject(key, val)).toBe '{"a":1,"b":2,"c":3}' say "null is passed in", -> beforeEach -> val = null it "should delete the key", -> expect(subject(key)).toBe undefined expect(subject(key, 'abc')).toBe 'abc' expect(subject(key, null)).toBe undefined expect(subject(key)).toBe undefined describe "#strToFunction", -> subject = TT.Utils.strToFunction beforeEach -> window.MyLib = { myLibFunc: -> MyModule: { myModuleFunc: -> } } afterEach -> delete window.MyLib say "a valid function is passed in", -> it "should return the function", -> expect(subject('MyLib.MyModule.myModuleFunc')).toBe MyLib.MyModule.myModuleFunc say "a valid function and context is passed in", -> it "should return the function", -> expect(subject('MyModule.myModuleFunc', MyLib)).toBe MyLib.MyModule.myModuleFunc say "an invalid function is passed in", -> it "should return undefined", -> expect(subject('Foo.Bar.myFunc')).toBe false describe "#generateInitials", -> subject = TT.Utils.generateInitials it "should return an initialized version of the input string", -> expect(subject('User Interface')).toBe 'UI' describe "#removeFromArray", -> subject = TT.Utils.removeFromArray say "an input value strictly matches a value found in the array", -> it "should return the array without the value", -> expect(subject([1, 2, 3, 4, 5], 4)).toEqual [1, 2, 3, 5] say "an input value does not match any value in the array", -> it "should return the array without any change", -> expect(subject([123, 'abc'], '123')).toEqual [123, 'abc']
true
describe "TT.Utils", -> describe "#exists", -> subject = TT.Utils.exists it "should return true when object is not null and not undefined", -> expect(subject('')).toBe true expect(subject(0)).toBe true expect(subject(1)).toBe true expect(subject('abc')).toBe true expect(subject({})).toBe true it "should return false if object is null or undefined", -> expect(subject()).toBe false expect(subject(undefined)).toBe false expect(subject(null)).toBe false describe "#arrayMove", -> subject = TT.Utils.arrayMove arr = null beforeEach -> arr = [1, 2, 3, 4, 5, 6] it "should move a key from one index to another", -> expect(subject(arr, 2, 5)).toEqual [1, 2, 4, 5, 6, 3] expect(subject(arr, 5, 2)).toEqual [1, 2, 3, 4, 5, 6] expect(subject(arr, 0, 5)).toEqual [2, 3, 4, 5, 6, 1] say "the new index is beyond the end of the array", -> it "should pad the array with undefined values until it gets to the requested index", -> expect(subject(arr, 2, 6)).toEqual [1, 2, 4, 5, 6, undefined, 3] describe "#reconcileArrayOrder", -> subject = TT.Utils.reconcileArrayOrder key = 'PI:KEY:<KEY>END_PI' oldArray = [{ foo: 2 }, { foo: 1 }] newArray = [{ foo: 0 }, { foo: 1 }, { foo: 2 }, { foo: 3 }] expectedArray = [{ foo: 2 }, { foo: 1 }, { foo: 0 }, { foo: 3 }] it "should rearrange the newArray to use the order of the oldArray", -> expect(subject(key, oldArray, newArray)).toEqual expectedArray describe "#getIndexByKey", -> subject = TT.Utils.getIndexByKey arr = [{ foo: 1 }, { foo: 2 }, { foo: 3 }, { foo: 4 }] it "should return the index of the row with the matching property", -> expect(subject(arr, 'foo', 3)).toEqual 2 describe "#localStorage", -> subject = TT.Utils.localStorage key = 'myKey' val = null afterEach -> subject(key, null) say "an object is passed in", -> beforeEach -> val = { a: 1, b: 2, c: 3 } it "should store the stringified version of that object in localStorage", -> expect(subject(key)).toBe undefined expect(subject(key, val)).toBe '{"a":1,"b":2,"c":3}' say "null is passed in", -> beforeEach -> val = null it "should delete the key", -> expect(subject(key)).toBe undefined expect(subject(key, 'abc')).toBe 'abc' expect(subject(key, null)).toBe undefined expect(subject(key)).toBe undefined describe "#strToFunction", -> subject = TT.Utils.strToFunction beforeEach -> window.MyLib = { myLibFunc: -> MyModule: { myModuleFunc: -> } } afterEach -> delete window.MyLib say "a valid function is passed in", -> it "should return the function", -> expect(subject('MyLib.MyModule.myModuleFunc')).toBe MyLib.MyModule.myModuleFunc say "a valid function and context is passed in", -> it "should return the function", -> expect(subject('MyModule.myModuleFunc', MyLib)).toBe MyLib.MyModule.myModuleFunc say "an invalid function is passed in", -> it "should return undefined", -> expect(subject('Foo.Bar.myFunc')).toBe false describe "#generateInitials", -> subject = TT.Utils.generateInitials it "should return an initialized version of the input string", -> expect(subject('User Interface')).toBe 'UI' describe "#removeFromArray", -> subject = TT.Utils.removeFromArray say "an input value strictly matches a value found in the array", -> it "should return the array without the value", -> expect(subject([1, 2, 3, 4, 5], 4)).toEqual [1, 2, 3, 5] say "an input value does not match any value in the array", -> it "should return the array without any change", -> expect(subject([123, 'abc'], '123')).toEqual [123, 'abc']
[ { "context": ">\n wongo.save 'MockHookUserDefined', {name: 'Fetter'}, (err, result) ->\n assert.ifError(err)\n ", "end": 2029, "score": 0.9996914863586426, "start": 2023, "tag": "NAME", "value": "Fetter" }, { "context": ">\n wongo.save 'MockHookUserDefined', {name: '...
test/hooks.test.coffee
wookets/wongo
0
assert = require 'assert' wongo = require '../lib/wongo' describe 'Wongo Schema Hook Override', -> describe 'Prune', -> wongo.schema 'MockHookDisablePrune', fields: name: String hooks: prune: false it 'should be able to disable prune', (done) -> wongo.save 'MockHookDisablePrune', {name: 'Cherry', field2: 'ImSafe'}, (err, result) -> assert.ifError(err) assert.equal(result.field2, 'ImSafe') done() it.skip 'should be able to override prune', (done) -> done() describe 'Defaults', -> wongo.schema 'MockHookDisableDefaults', fields: name: String animal: {type: String, default: 'MooCow'} hooks: applyDefaults: false it 'should be able to disable defaults', (done) -> wongo.save 'MockHookDisableDefaults', {name: 'Snufy'}, (err, result) -> assert.ifError(err) assert.notEqual(result.animal, 'MooCow') done() it.skip 'should be able to override defaults', (done) -> done() describe 'Validate', -> wongo.schema 'MockHookDisableValidate', fields: name: {type: String, max: 3} hooks: validate: false it 'should be able to disable validate', (done) -> wongo.save 'MockHookDisableValidate', {name: 'Fetry'}, (err, result) -> assert.ifError(err) assert.equal(result.name, 'Fetry') done() it.skip 'should be able to override validate', (done) -> done() describe 'BeforeSave', -> wongo.schema 'MockHookUserDefined', fields: name: String beforeSave: String afterSave: String hooks: beforeSave: (document, schema, done) -> document.beforeSave = 'meowpants' done() afterSave: (document, schema, done) -> document.afterSave = 'meower' done() it 'should be able to handle a user defined beforeSave function', (done) -> wongo.save 'MockHookUserDefined', {name: 'Fetter'}, (err, result) -> assert.ifError(err) assert.equal(result.beforeSave, 'meowpants') done() it 'should be able to handle a user defined afterSave function', (done) -> wongo.save 'MockHookUserDefined', {name: 'Fetter'}, (err, result) -> assert.ifError(err) assert.equal(result.afterSave, 'meower') done()
50661
assert = require 'assert' wongo = require '../lib/wongo' describe 'Wongo Schema Hook Override', -> describe 'Prune', -> wongo.schema 'MockHookDisablePrune', fields: name: String hooks: prune: false it 'should be able to disable prune', (done) -> wongo.save 'MockHookDisablePrune', {name: 'Cherry', field2: 'ImSafe'}, (err, result) -> assert.ifError(err) assert.equal(result.field2, 'ImSafe') done() it.skip 'should be able to override prune', (done) -> done() describe 'Defaults', -> wongo.schema 'MockHookDisableDefaults', fields: name: String animal: {type: String, default: 'MooCow'} hooks: applyDefaults: false it 'should be able to disable defaults', (done) -> wongo.save 'MockHookDisableDefaults', {name: 'Snufy'}, (err, result) -> assert.ifError(err) assert.notEqual(result.animal, 'MooCow') done() it.skip 'should be able to override defaults', (done) -> done() describe 'Validate', -> wongo.schema 'MockHookDisableValidate', fields: name: {type: String, max: 3} hooks: validate: false it 'should be able to disable validate', (done) -> wongo.save 'MockHookDisableValidate', {name: 'Fetry'}, (err, result) -> assert.ifError(err) assert.equal(result.name, 'Fetry') done() it.skip 'should be able to override validate', (done) -> done() describe 'BeforeSave', -> wongo.schema 'MockHookUserDefined', fields: name: String beforeSave: String afterSave: String hooks: beforeSave: (document, schema, done) -> document.beforeSave = 'meowpants' done() afterSave: (document, schema, done) -> document.afterSave = 'meower' done() it 'should be able to handle a user defined beforeSave function', (done) -> wongo.save 'MockHookUserDefined', {name: '<NAME>'}, (err, result) -> assert.ifError(err) assert.equal(result.beforeSave, 'meowpants') done() it 'should be able to handle a user defined afterSave function', (done) -> wongo.save 'MockHookUserDefined', {name: '<NAME>'}, (err, result) -> assert.ifError(err) assert.equal(result.afterSave, 'meower') done()
true
assert = require 'assert' wongo = require '../lib/wongo' describe 'Wongo Schema Hook Override', -> describe 'Prune', -> wongo.schema 'MockHookDisablePrune', fields: name: String hooks: prune: false it 'should be able to disable prune', (done) -> wongo.save 'MockHookDisablePrune', {name: 'Cherry', field2: 'ImSafe'}, (err, result) -> assert.ifError(err) assert.equal(result.field2, 'ImSafe') done() it.skip 'should be able to override prune', (done) -> done() describe 'Defaults', -> wongo.schema 'MockHookDisableDefaults', fields: name: String animal: {type: String, default: 'MooCow'} hooks: applyDefaults: false it 'should be able to disable defaults', (done) -> wongo.save 'MockHookDisableDefaults', {name: 'Snufy'}, (err, result) -> assert.ifError(err) assert.notEqual(result.animal, 'MooCow') done() it.skip 'should be able to override defaults', (done) -> done() describe 'Validate', -> wongo.schema 'MockHookDisableValidate', fields: name: {type: String, max: 3} hooks: validate: false it 'should be able to disable validate', (done) -> wongo.save 'MockHookDisableValidate', {name: 'Fetry'}, (err, result) -> assert.ifError(err) assert.equal(result.name, 'Fetry') done() it.skip 'should be able to override validate', (done) -> done() describe 'BeforeSave', -> wongo.schema 'MockHookUserDefined', fields: name: String beforeSave: String afterSave: String hooks: beforeSave: (document, schema, done) -> document.beforeSave = 'meowpants' done() afterSave: (document, schema, done) -> document.afterSave = 'meower' done() it 'should be able to handle a user defined beforeSave function', (done) -> wongo.save 'MockHookUserDefined', {name: 'PI:NAME:<NAME>END_PI'}, (err, result) -> assert.ifError(err) assert.equal(result.beforeSave, 'meowpants') done() it 'should be able to handle a user defined afterSave function', (done) -> wongo.save 'MockHookUserDefined', {name: 'PI:NAME:<NAME>END_PI'}, (err, result) -> assert.ifError(err) assert.equal(result.afterSave, 'meower') done()
[ { "context": "rmedMatches, (value, key) ->\n key = \"#{startTag}#{key}#{endTag}\"\n if key == stacheString\n ", "end": 1010, "score": 0.5537708401679993, "start": 1010, "tag": "KEY", "value": "" }, { "context": "tches, (value, key) ->\n key = \"#{startTag}#{key}#{endTag...
src/christacheio.coffee
octoblu/christacheio
0
_ = require 'lodash' debug = require('debug')('christacheio') escape = require 'escape-string-regexp' stacheMatch = (stacheExp, stacheString) -> regex = new RegExp stacheExp, 'g' matches = [] while match = regex.exec stacheString matches.push match[1] return matches stachest = (stacheString, obj, options={}, depth=1) -> return stacheString if ! _.isString stacheString {tags,transformation,negationCharacters} = options tags ?= ['{{', '}}'] negationCharacters ?= _.uniq(tags.join '').join '' transformation ?= (data) -> data [startTag, endTag] = tags stacheExp = "#{escape startTag}([^#{escape negationCharacters}]*?)#{escape endTag}" transformedMatches = {} newStache = _.clone stacheString _.each stacheMatch(stacheExp, stacheString), (key) -> value = _.get obj, key transformedMatches[key] = transformation(value) if value? transformedMatches[key] ?= null # you need this return _.each transformedMatches, (value, key) -> key = "#{startTag}#{key}#{endTag}" if key == stacheString newStache = value return escapedKey = escape key value = JSON.stringify(value) unless _.isString value regex = new RegExp(escapedKey, 'g') newStache = newStache.replace regex, value return stachemore = depth < options.recurseDepth and newStache != stacheString return stachest newStache, obj, options, depth+1 if stachemore return newStache stacheception = (stache, obj, options, limbo=[]) -> limbo.push stache _.forOwn stache, (value, key) -> return if _.includes limbo, value delete stache[key] key = stachest key, obj, options if _.isObject value stache[key] = stacheception value, obj, options, limbo return stache[key] = stachest value, obj, options return christacheio = (stache, obj, options) -> return stachest stache, obj, options unless _.isObject stache stache = _.cloneDeep stache return stacheception stache, obj, options module.exports = christacheio
152163
_ = require 'lodash' debug = require('debug')('christacheio') escape = require 'escape-string-regexp' stacheMatch = (stacheExp, stacheString) -> regex = new RegExp stacheExp, 'g' matches = [] while match = regex.exec stacheString matches.push match[1] return matches stachest = (stacheString, obj, options={}, depth=1) -> return stacheString if ! _.isString stacheString {tags,transformation,negationCharacters} = options tags ?= ['{{', '}}'] negationCharacters ?= _.uniq(tags.join '').join '' transformation ?= (data) -> data [startTag, endTag] = tags stacheExp = "#{escape startTag}([^#{escape negationCharacters}]*?)#{escape endTag}" transformedMatches = {} newStache = _.clone stacheString _.each stacheMatch(stacheExp, stacheString), (key) -> value = _.get obj, key transformedMatches[key] = transformation(value) if value? transformedMatches[key] ?= null # you need this return _.each transformedMatches, (value, key) -> key = "#{startTag<KEY>}#{key<KEY>}#{endTag}" if key == stacheString newStache = value return escapedKey = escape key value = JSON.stringify(value) unless _.isString value regex = new RegExp(escapedKey, 'g') newStache = newStache.replace regex, value return stachemore = depth < options.recurseDepth and newStache != stacheString return stachest newStache, obj, options, depth+1 if stachemore return newStache stacheception = (stache, obj, options, limbo=[]) -> limbo.push stache _.forOwn stache, (value, key) -> return if _.includes limbo, value delete stache[key] key = stachest key, obj, options if _.isObject value stache[key] = stacheception value, obj, options, limbo return stache[key] = stachest value, obj, options return christacheio = (stache, obj, options) -> return stachest stache, obj, options unless _.isObject stache stache = _.cloneDeep stache return stacheception stache, obj, options module.exports = christacheio
true
_ = require 'lodash' debug = require('debug')('christacheio') escape = require 'escape-string-regexp' stacheMatch = (stacheExp, stacheString) -> regex = new RegExp stacheExp, 'g' matches = [] while match = regex.exec stacheString matches.push match[1] return matches stachest = (stacheString, obj, options={}, depth=1) -> return stacheString if ! _.isString stacheString {tags,transformation,negationCharacters} = options tags ?= ['{{', '}}'] negationCharacters ?= _.uniq(tags.join '').join '' transformation ?= (data) -> data [startTag, endTag] = tags stacheExp = "#{escape startTag}([^#{escape negationCharacters}]*?)#{escape endTag}" transformedMatches = {} newStache = _.clone stacheString _.each stacheMatch(stacheExp, stacheString), (key) -> value = _.get obj, key transformedMatches[key] = transformation(value) if value? transformedMatches[key] ?= null # you need this return _.each transformedMatches, (value, key) -> key = "#{startTagPI:KEY:<KEY>END_PI}#{keyPI:KEY:<KEY>END_PI}#{endTag}" if key == stacheString newStache = value return escapedKey = escape key value = JSON.stringify(value) unless _.isString value regex = new RegExp(escapedKey, 'g') newStache = newStache.replace regex, value return stachemore = depth < options.recurseDepth and newStache != stacheString return stachest newStache, obj, options, depth+1 if stachemore return newStache stacheception = (stache, obj, options, limbo=[]) -> limbo.push stache _.forOwn stache, (value, key) -> return if _.includes limbo, value delete stache[key] key = stachest key, obj, options if _.isObject value stache[key] = stacheception value, obj, options, limbo return stache[key] = stachest value, obj, options return christacheio = (stache, obj, options) -> return stachest stache, obj, options unless _.isObject stache stache = _.cloneDeep stache return stacheception stache, obj, options module.exports = christacheio
[ { "context": "\")\r\n\r\ngenid = (len = 16, prefix = \"\", keyspace = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\") ->\r\n prefix += keyspace.charAt(Math.floor(Math", "end": 411, "score": 0.9996888041496277, "start": 349, "tag": "KEY", "value": "ABCDEFGHIJKLMNOPQRSTUVW...
servers/run/index.coffee
sitedata/plunker
340
express = require("express") nconf = require("nconf") _ = require("underscore")._ validator = require("json-schema") mime = require("mime") url = require("url") request = require("request") path = require("path") module.exports = app = express.createServer() runUrl = nconf.get("url:run") genid = (len = 16, prefix = "", keyspace = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789") -> prefix += keyspace.charAt(Math.floor(Math.random() * keyspace.length)) while len-- > 0 prefix app.configure -> app.use require("./middleware/cors").middleware() app.use require("./middleware/json").middleware() app.set "views", "#{__dirname}/views" app.set "view engine", "jade" app.set "view options", layout: false LRU = require("lru-cache") previews = LRU(512) apiUrl = nconf.get("url:api") coffee = require("coffee-script") livescript = require("LiveScript") iced = require("iced-coffee-script") less = require("less") sass = require("sass") jade = require("jade") markdown = require("marked") stylus = require("stylus") nib = require("nib") compilers = sass: match: /\.css$/ ext: ['sass'] compile: (str, fn) -> try fn(null, sass.render(str)) catch err fn(err) less: match: /\.css$/ ext: ['less'] compile: (str, fn) -> try less.render(str, fn) catch err fn(err) stylus: match: /\.css/ ext: ['styl'] compile: (str, fn) -> try stylus(str) .use(nib()) .import("nib") .render(fn) catch err fn(err) coffeescript: match: /\.js$/ ext: ['coffee'] compile: (str, fn) -> try fn(null, coffee.compile(str, bare: true)) catch err fn(err) livescript: match: /\.js$/ ext: ['ls'] compile: (str, fn) -> try fn(null, livescript.compile(str)) catch err fn(err) icedcoffee: match: /\.js$/ ext: ['iced'] compile: (str, fn) -> try fn(null, iced.compile(str, runtime: "inline")) catch err fn(err) jade: match: /\.html$/ ext: ['jade'] compile: (str, fn) -> render = jade.compile(str, pretty: true) try fn(null, render({})) catch err fn(err) markdown: match: /\.html$/ ext: ['md',"markdown"] compile: (str, fn) -> try fn(null, markdown(str)) catch err fn(err) renderPlunkFile = (req, res, next) -> # TODO: Determine if a special plunk 'landing' page should be served and serve it plunk = req.plunk filename = req.params[0] or "index.html" file = plunk.files[filename] res.header "Cache-Control", "no-cache" res.header "Expires", 0 if file then res.send(file.content, {"Content-Type": if req.accepts(file.mime) then file.mime else "text/plain"}) else if filename base = path.basename(filename, path.extname(filename)) type = mime.lookup(filename) or "text/plain" for name, compiler of compilers when filename.match(compiler.match) for ext in compiler.ext if found = plunk.files["#{base}.#{ext}"] compiler.compile found.content, (err, compiled) -> if err then next(err) else res.send(compiled, {"Content-Type": if req.accepts(type) then type else "text/plain"}) break res.send(404) unless found else res.local "plunk", plunk res.render "directory" app.get "/plunks/:id/*", (req, res, next) -> req_url = url.parse(req.url) unless req.params[0] or /\/$/.test(req_url.pathname) req_url.pathname += "/" return res.redirect(url.format(req_url), 301) request.get "#{apiUrl}/plunks/#{req.params.id}", (err, response, body) -> return res.send(500) if err return res.send(response.statusCode) if response.statusCode >= 400 try req.plunk = JSON.parse(body) catch e return res.send(500) unless req.plunk then res.send(404) # TODO: Better error page else renderPlunkFile(req, res, next) app.get "/plunks/:id", (req, res) -> res.redirect("/#{req.params.id}/", 301) app.post "/:id?", (req, res, next) -> json = req.body schema = require("./schema/previews/create") {valid, errors} = validator.validate(json, schema) # Despite its awesomeness, validator does not support disallow or additionalProperties; we need to check plunk.files size if json.files and _.isEmpty(json.files) valid = false errors.push attribute: "minProperties" property: "files" message: "A minimum of one file is required" unless valid then next(new Error("Invalid json: #{errors}")) else id = req.params.id or genid() # Don't care about id clashes. They are disposable anyway json.id = id json.run_url = "#{runUrl}/#{id}/" _.each json.files, (file, filename) -> json.files[filename] = filename: filename content: file.content mime: mime.lookup(filename, "text/plain") run_url: json.run_url + filename previews.set(id, json) status = if req.params.id then 200 else 201 res.json(json, status) app.get "/:id/*", (req, res, next) -> unless req.plunk = previews.get(req.params.id) then res.send(404) # TODO: Better error page else req_url = url.parse(req.url) unless req.params[0] or /\/$/.test(req_url.pathname) req_url.pathname += "/" return res.redirect(url.format(req_url), 301) renderPlunkFile(req, res, next) app.get "*", (req, res) -> res.send("Preview does not exist or has expired.", 404)
57874
express = require("express") nconf = require("nconf") _ = require("underscore")._ validator = require("json-schema") mime = require("mime") url = require("url") request = require("request") path = require("path") module.exports = app = express.createServer() runUrl = nconf.get("url:run") genid = (len = 16, prefix = "", keyspace = "<KEY>") -> prefix += keyspace.charAt(Math.floor(Math.random() * keyspace.length)) while len-- > 0 prefix app.configure -> app.use require("./middleware/cors").middleware() app.use require("./middleware/json").middleware() app.set "views", "#{__dirname}/views" app.set "view engine", "jade" app.set "view options", layout: false LRU = require("lru-cache") previews = LRU(512) apiUrl = nconf.get("url:api") coffee = require("coffee-script") livescript = require("LiveScript") iced = require("iced-coffee-script") less = require("less") sass = require("sass") jade = require("jade") markdown = require("marked") stylus = require("stylus") nib = require("nib") compilers = sass: match: /\.css$/ ext: ['sass'] compile: (str, fn) -> try fn(null, sass.render(str)) catch err fn(err) less: match: /\.css$/ ext: ['less'] compile: (str, fn) -> try less.render(str, fn) catch err fn(err) stylus: match: /\.css/ ext: ['styl'] compile: (str, fn) -> try stylus(str) .use(nib()) .import("nib") .render(fn) catch err fn(err) coffeescript: match: /\.js$/ ext: ['coffee'] compile: (str, fn) -> try fn(null, coffee.compile(str, bare: true)) catch err fn(err) livescript: match: /\.js$/ ext: ['ls'] compile: (str, fn) -> try fn(null, livescript.compile(str)) catch err fn(err) icedcoffee: match: /\.js$/ ext: ['iced'] compile: (str, fn) -> try fn(null, iced.compile(str, runtime: "inline")) catch err fn(err) jade: match: /\.html$/ ext: ['jade'] compile: (str, fn) -> render = jade.compile(str, pretty: true) try fn(null, render({})) catch err fn(err) markdown: match: /\.html$/ ext: ['md',"markdown"] compile: (str, fn) -> try fn(null, markdown(str)) catch err fn(err) renderPlunkFile = (req, res, next) -> # TODO: Determine if a special plunk 'landing' page should be served and serve it plunk = req.plunk filename = req.params[0] or "index.html" file = plunk.files[filename] res.header "Cache-Control", "no-cache" res.header "Expires", 0 if file then res.send(file.content, {"Content-Type": if req.accepts(file.mime) then file.mime else "text/plain"}) else if filename base = path.basename(filename, path.extname(filename)) type = mime.lookup(filename) or "text/plain" for name, compiler of compilers when filename.match(compiler.match) for ext in compiler.ext if found = plunk.files["#{base}.#{ext}"] compiler.compile found.content, (err, compiled) -> if err then next(err) else res.send(compiled, {"Content-Type": if req.accepts(type) then type else "text/plain"}) break res.send(404) unless found else res.local "plunk", plunk res.render "directory" app.get "/plunks/:id/*", (req, res, next) -> req_url = url.parse(req.url) unless req.params[0] or /\/$/.test(req_url.pathname) req_url.pathname += "/" return res.redirect(url.format(req_url), 301) request.get "#{apiUrl}/plunks/#{req.params.id}", (err, response, body) -> return res.send(500) if err return res.send(response.statusCode) if response.statusCode >= 400 try req.plunk = JSON.parse(body) catch e return res.send(500) unless req.plunk then res.send(404) # TODO: Better error page else renderPlunkFile(req, res, next) app.get "/plunks/:id", (req, res) -> res.redirect("/#{req.params.id}/", 301) app.post "/:id?", (req, res, next) -> json = req.body schema = require("./schema/previews/create") {valid, errors} = validator.validate(json, schema) # Despite its awesomeness, validator does not support disallow or additionalProperties; we need to check plunk.files size if json.files and _.isEmpty(json.files) valid = false errors.push attribute: "minProperties" property: "files" message: "A minimum of one file is required" unless valid then next(new Error("Invalid json: #{errors}")) else id = req.params.id or genid() # Don't care about id clashes. They are disposable anyway json.id = id json.run_url = "#{runUrl}/#{id}/" _.each json.files, (file, filename) -> json.files[filename] = filename: filename content: file.content mime: mime.lookup(filename, "text/plain") run_url: json.run_url + filename previews.set(id, json) status = if req.params.id then 200 else 201 res.json(json, status) app.get "/:id/*", (req, res, next) -> unless req.plunk = previews.get(req.params.id) then res.send(404) # TODO: Better error page else req_url = url.parse(req.url) unless req.params[0] or /\/$/.test(req_url.pathname) req_url.pathname += "/" return res.redirect(url.format(req_url), 301) renderPlunkFile(req, res, next) app.get "*", (req, res) -> res.send("Preview does not exist or has expired.", 404)
true
express = require("express") nconf = require("nconf") _ = require("underscore")._ validator = require("json-schema") mime = require("mime") url = require("url") request = require("request") path = require("path") module.exports = app = express.createServer() runUrl = nconf.get("url:run") genid = (len = 16, prefix = "", keyspace = "PI:KEY:<KEY>END_PI") -> prefix += keyspace.charAt(Math.floor(Math.random() * keyspace.length)) while len-- > 0 prefix app.configure -> app.use require("./middleware/cors").middleware() app.use require("./middleware/json").middleware() app.set "views", "#{__dirname}/views" app.set "view engine", "jade" app.set "view options", layout: false LRU = require("lru-cache") previews = LRU(512) apiUrl = nconf.get("url:api") coffee = require("coffee-script") livescript = require("LiveScript") iced = require("iced-coffee-script") less = require("less") sass = require("sass") jade = require("jade") markdown = require("marked") stylus = require("stylus") nib = require("nib") compilers = sass: match: /\.css$/ ext: ['sass'] compile: (str, fn) -> try fn(null, sass.render(str)) catch err fn(err) less: match: /\.css$/ ext: ['less'] compile: (str, fn) -> try less.render(str, fn) catch err fn(err) stylus: match: /\.css/ ext: ['styl'] compile: (str, fn) -> try stylus(str) .use(nib()) .import("nib") .render(fn) catch err fn(err) coffeescript: match: /\.js$/ ext: ['coffee'] compile: (str, fn) -> try fn(null, coffee.compile(str, bare: true)) catch err fn(err) livescript: match: /\.js$/ ext: ['ls'] compile: (str, fn) -> try fn(null, livescript.compile(str)) catch err fn(err) icedcoffee: match: /\.js$/ ext: ['iced'] compile: (str, fn) -> try fn(null, iced.compile(str, runtime: "inline")) catch err fn(err) jade: match: /\.html$/ ext: ['jade'] compile: (str, fn) -> render = jade.compile(str, pretty: true) try fn(null, render({})) catch err fn(err) markdown: match: /\.html$/ ext: ['md',"markdown"] compile: (str, fn) -> try fn(null, markdown(str)) catch err fn(err) renderPlunkFile = (req, res, next) -> # TODO: Determine if a special plunk 'landing' page should be served and serve it plunk = req.plunk filename = req.params[0] or "index.html" file = plunk.files[filename] res.header "Cache-Control", "no-cache" res.header "Expires", 0 if file then res.send(file.content, {"Content-Type": if req.accepts(file.mime) then file.mime else "text/plain"}) else if filename base = path.basename(filename, path.extname(filename)) type = mime.lookup(filename) or "text/plain" for name, compiler of compilers when filename.match(compiler.match) for ext in compiler.ext if found = plunk.files["#{base}.#{ext}"] compiler.compile found.content, (err, compiled) -> if err then next(err) else res.send(compiled, {"Content-Type": if req.accepts(type) then type else "text/plain"}) break res.send(404) unless found else res.local "plunk", plunk res.render "directory" app.get "/plunks/:id/*", (req, res, next) -> req_url = url.parse(req.url) unless req.params[0] or /\/$/.test(req_url.pathname) req_url.pathname += "/" return res.redirect(url.format(req_url), 301) request.get "#{apiUrl}/plunks/#{req.params.id}", (err, response, body) -> return res.send(500) if err return res.send(response.statusCode) if response.statusCode >= 400 try req.plunk = JSON.parse(body) catch e return res.send(500) unless req.plunk then res.send(404) # TODO: Better error page else renderPlunkFile(req, res, next) app.get "/plunks/:id", (req, res) -> res.redirect("/#{req.params.id}/", 301) app.post "/:id?", (req, res, next) -> json = req.body schema = require("./schema/previews/create") {valid, errors} = validator.validate(json, schema) # Despite its awesomeness, validator does not support disallow or additionalProperties; we need to check plunk.files size if json.files and _.isEmpty(json.files) valid = false errors.push attribute: "minProperties" property: "files" message: "A minimum of one file is required" unless valid then next(new Error("Invalid json: #{errors}")) else id = req.params.id or genid() # Don't care about id clashes. They are disposable anyway json.id = id json.run_url = "#{runUrl}/#{id}/" _.each json.files, (file, filename) -> json.files[filename] = filename: filename content: file.content mime: mime.lookup(filename, "text/plain") run_url: json.run_url + filename previews.set(id, json) status = if req.params.id then 200 else 201 res.json(json, status) app.get "/:id/*", (req, res, next) -> unless req.plunk = previews.get(req.params.id) then res.send(404) # TODO: Better error page else req_url = url.parse(req.url) unless req.params[0] or /\/$/.test(req_url.pathname) req_url.pathname += "/" return res.redirect(url.format(req_url), 301) renderPlunkFile(req, res, next) app.get "*", (req, res) -> res.send("Preview does not exist or has expired.", 404)
[ { "context": "@getAvatarUrlFromUsername = (username) ->\n\tkey = \"avatar_random_#{username}\"\n\trandom = Session?.keys[key] or 0\n\n\tif not userna", "end": 76, "score": 0.9980445504188538, "start": 50, "tag": "KEY", "value": "avatar_random_#{username}\"" } ]
packages/rocketchat-ui/lib/getAvatarUrlFromUsername.coffee
kumarpradeephk/mychatapp
1
@getAvatarUrlFromUsername = (username) -> key = "avatar_random_#{username}" random = Session?.keys[key] or 0 if not username? return cdnPrefix = (RocketChat.settings.get('CDN_PREFIX') or '').trim().replace(/\/$/, '') pathPrefix = (__meteor_runtime_config__.ROOT_URL_PATH_PREFIX or '').trim().replace(/\/$/, '') if cdnPrefix path = cdnPrefix + pathPrefix else if Meteor.isCordova # Meteor.absoluteUrl alread has path prefix path = Meteor.absoluteUrl().replace(/\/$/, '') else path = pathPrefix return "#{path}/avatar/#{encodeURIComponent(username)}?_dc=#{random}"
65056
@getAvatarUrlFromUsername = (username) -> key = "<KEY> random = Session?.keys[key] or 0 if not username? return cdnPrefix = (RocketChat.settings.get('CDN_PREFIX') or '').trim().replace(/\/$/, '') pathPrefix = (__meteor_runtime_config__.ROOT_URL_PATH_PREFIX or '').trim().replace(/\/$/, '') if cdnPrefix path = cdnPrefix + pathPrefix else if Meteor.isCordova # Meteor.absoluteUrl alread has path prefix path = Meteor.absoluteUrl().replace(/\/$/, '') else path = pathPrefix return "#{path}/avatar/#{encodeURIComponent(username)}?_dc=#{random}"
true
@getAvatarUrlFromUsername = (username) -> key = "PI:KEY:<KEY>END_PI random = Session?.keys[key] or 0 if not username? return cdnPrefix = (RocketChat.settings.get('CDN_PREFIX') or '').trim().replace(/\/$/, '') pathPrefix = (__meteor_runtime_config__.ROOT_URL_PATH_PREFIX or '').trim().replace(/\/$/, '') if cdnPrefix path = cdnPrefix + pathPrefix else if Meteor.isCordova # Meteor.absoluteUrl alread has path prefix path = Meteor.absoluteUrl().replace(/\/$/, '') else path = pathPrefix return "#{path}/avatar/#{encodeURIComponent(username)}?_dc=#{random}"
[ { "context": "ypto'\n\nmodule.exports = class Actor\n constructor: (@name, @email) ->\n if @email\n @hash = crypto.cr", "end": 77, "score": 0.9740625023841858, "start": 71, "tag": "USERNAME", "value": "(@name" }, { "context": "epresentation of the Actor.\n toString: ->\n ...
src/actor.coffee
roelofjan-elsinga/gift
85
crypto = require 'crypto' module.exports = class Actor constructor: (@name, @email) -> if @email @hash = crypto.createHash("md5").update(@email, "ascii").digest("hex") # Public: Get a string representation of the Actor. toString: -> "#{@name} <#{@email}>" # Public: Parse an Actor from a "bla <bla@example.com>" string. # # Returns Actor. @from_string: (str) -> if /<.+>/.test str [m, name, email] = /(.*) <(.+?)>/.exec str return new Actor(name, email) else return new Actor(str, null)
223198
crypto = require 'crypto' module.exports = class Actor constructor: (@name, @email) -> if @email @hash = crypto.createHash("md5").update(@email, "ascii").digest("hex") # Public: Get a string representation of the Actor. toString: -> "#{@name} <#{@email}>" # Public: Parse an Actor from a "bla <<EMAIL>>" string. # # Returns Actor. @from_string: (str) -> if /<.+>/.test str [m, name, email] = /(.*) <(.+?)>/.exec str return new Actor(name, email) else return new Actor(str, null)
true
crypto = require 'crypto' module.exports = class Actor constructor: (@name, @email) -> if @email @hash = crypto.createHash("md5").update(@email, "ascii").digest("hex") # Public: Get a string representation of the Actor. toString: -> "#{@name} <#{@email}>" # Public: Parse an Actor from a "bla <PI:EMAIL:<EMAIL>END_PI>" string. # # Returns Actor. @from_string: (str) -> if /<.+>/.test str [m, name, email] = /(.*) <(.+?)>/.exec str return new Actor(name, email) else return new Actor(str, null)
[ { "context": "\n\n# pipe handling, stolen with permission from 'epipebomb'\n# by michael.hart.au@gmail.com\nepipeFilter = (er", "end": 124, "score": 0.7790737748146057, "start": 117, "tag": "USERNAME", "value": "ipebomb" }, { "context": "ling, stolen with permission from 'epipebomb'\...
src/command.coffee
davidchambers/tutor
45
formatters = require './formatters' tutor = require './tutor' # pipe handling, stolen with permission from 'epipebomb' # by michael.hart.au@gmail.com epipeFilter = (err) -> process.exit() if err.code is 'EPIPE' # If there's more than one error handler (ie, us), # then the error won't be bubbled up anyway if process.stdout.listeners('error').length <= 1 process.stdout.removeAllListeners() # Pretend we were never here process.stdout.emit 'error', err # Then emit as if we were never here process.stdout.on 'error', epipeFilter # Then reattach, ready for the next error! process.stdout.on 'error', epipeFilter program = require 'commander' program.version require('../package').version ['formats', 'sets', 'types'].forEach (resource) -> program .command resource .option '-f, --format [formatter]', '"json" or "summary"', 'summary' .action (options) -> tutor[resource] formatters[resource][options.format] program .command 'card <name|id>' .description "output the given card's details" .option '-f, --format [formatter]', '"json" or "summary"', 'summary' .action (value, options) -> tutor.card (if +value is +value then +value else value), formatters.card[options.format] program .command 'set <name>' .description 'output one page of cards from the named set' .option '-f, --format [formatter]', '"json" or "summary"', 'summary' .action (name, options) -> tutor.set name, formatters.set[options.format] module.exports = program
190206
formatters = require './formatters' tutor = require './tutor' # pipe handling, stolen with permission from 'epipebomb' # by <EMAIL> epipeFilter = (err) -> process.exit() if err.code is 'EPIPE' # If there's more than one error handler (ie, us), # then the error won't be bubbled up anyway if process.stdout.listeners('error').length <= 1 process.stdout.removeAllListeners() # Pretend we were never here process.stdout.emit 'error', err # Then emit as if we were never here process.stdout.on 'error', epipeFilter # Then reattach, ready for the next error! process.stdout.on 'error', epipeFilter program = require 'commander' program.version require('../package').version ['formats', 'sets', 'types'].forEach (resource) -> program .command resource .option '-f, --format [formatter]', '"json" or "summary"', 'summary' .action (options) -> tutor[resource] formatters[resource][options.format] program .command 'card <name|id>' .description "output the given card's details" .option '-f, --format [formatter]', '"json" or "summary"', 'summary' .action (value, options) -> tutor.card (if +value is +value then +value else value), formatters.card[options.format] program .command 'set <name>' .description 'output one page of cards from the named set' .option '-f, --format [formatter]', '"json" or "summary"', 'summary' .action (name, options) -> tutor.set name, formatters.set[options.format] module.exports = program
true
formatters = require './formatters' tutor = require './tutor' # pipe handling, stolen with permission from 'epipebomb' # by PI:EMAIL:<EMAIL>END_PI epipeFilter = (err) -> process.exit() if err.code is 'EPIPE' # If there's more than one error handler (ie, us), # then the error won't be bubbled up anyway if process.stdout.listeners('error').length <= 1 process.stdout.removeAllListeners() # Pretend we were never here process.stdout.emit 'error', err # Then emit as if we were never here process.stdout.on 'error', epipeFilter # Then reattach, ready for the next error! process.stdout.on 'error', epipeFilter program = require 'commander' program.version require('../package').version ['formats', 'sets', 'types'].forEach (resource) -> program .command resource .option '-f, --format [formatter]', '"json" or "summary"', 'summary' .action (options) -> tutor[resource] formatters[resource][options.format] program .command 'card <name|id>' .description "output the given card's details" .option '-f, --format [formatter]', '"json" or "summary"', 'summary' .action (value, options) -> tutor.card (if +value is +value then +value else value), formatters.card[options.format] program .command 'set <name>' .description 'output one page of cards from the named set' .option '-f, --format [formatter]', '"json" or "summary"', 'summary' .action (name, options) -> tutor.set name, formatters.set[options.format] module.exports = program
[ { "context": "Copyright 2013 Canopy Canopy Canopy, Inc.\n# Author Adam Florin\n\nclass Alongslide::Parser\n\n # Store names of flo", "end": 146, "score": 0.9960240125656128, "start": 135, "tag": "NAME", "value": "Adam Florin" } ]
app/assets/javascripts/alongslide/parser.coffee
triplecanopy/alongslide
33
# # parser.coffee: parse raw HTML into Alongslide types: sections, panels, etc. # # Copyright 2013 Canopy Canopy Canopy, Inc. # Author Adam Florin class Alongslide::Parser # Store names of flows here as we create them. # # sections: [] backgrounds: [] flowNames : [] panelNames : [] constructor: (options) -> {@source} = options @preprocessSource() # # preprocessSource: -> # Put dummy content inside empty directives as CSSRegions trims any empty # elements found near the boundaries of a region. (@source.find ".alongslide:empty").text("[ALS]") # Parser entrypoint. # # Build sections and store them directly as CSSRegions named flows. # # Retun panels and footnotes, which will be needed by other components. # # Note! Parse order matters! Sections should go last, once all non-section # material has been scraped out of @source. # parse: -> @sourceLength = 0 panels = @collectPanels() footnotes = @collectFootnotes() @collectSections() flowNames : @flowNames panelNames : @panelNames backgrounds : @backgrounds panels : panels footnotes : footnotes sourceLength: @sourceLength collectPanels: -> rawPanels = @source.find('.alongslide.show.panel') _.object _.map rawPanels, (el) => $el = $(el) panelId = $el.data('alongslide-id') panelEl = $el.clone().removeClass('show') # Cleanup $el.empty().removeClass('panel') @panelNames.push(panelId) return [ panelId, panelEl ] # Sift through passed-in sections, delineating them based on `enter` and `exit` # directives, then assigning each to a flow. # collectSections: -> @source.find('.alongslide.enter.section').each (index, directiveElement) => directive = $(directiveElement) id = directive.data('alongslide-id') exitSelector = '.alongslide.exit.section[data-alongslide-id='+id+']' # build section for content BEFORE section enter lastSectionContents = directive.prevAll().detach().get().reverse() @buildSection(lastSectionContents, directive) if lastSectionContents.length # build section for content AFTER section enter sectionContents = directive.nextUntil(exitSelector).detach() @buildSection(sectionContents, directive, id) # cleanup section build process directive.remove() (@source.find exitSelector).remove() @buildSection @source.children() unless @source.is(':empty') # Build section, given content. # # Create new NamedFlow for it, and log the name. # # Create section background. # # @param content - jQuery object of section contents # @param directive (optional) - directive which specified the section # @param id (optional) - Alongslide section ID # buildSection: (content, directive, id) -> flowName = id || "sectionFlow#{@flowNames.length}" idElement = directive?.removeClass('alongslide').empty().removeClass('enter') || $("<div/>") idElement.attr('data-alongslide-id', flowName) # create section section = idElement.clone().append(content) # tally up length @sourceLength += section.text().length # create NamedFlow document.namedFlows.get(flowName).addContent(section.get(0)) @flowNames.push flowName # create background if ID is specified if id? background = idElement.clone().addClass('background frame').html("&nbsp;") @backgrounds.push(background) # Search for footntes as formatted by Redcarpet's footnotes callback # # Each has an ID of the form `fn1`, which corresponds to the links in the # footnote references. # # Returns a DOM node whose child elements are footnote definitions and removes the generated footnotes from DOM collectFootnotes: -> @source.find('.als-footnotes:last') .remove()
116934
# # parser.coffee: parse raw HTML into Alongslide types: sections, panels, etc. # # Copyright 2013 Canopy Canopy Canopy, Inc. # Author <NAME> class Alongslide::Parser # Store names of flows here as we create them. # # sections: [] backgrounds: [] flowNames : [] panelNames : [] constructor: (options) -> {@source} = options @preprocessSource() # # preprocessSource: -> # Put dummy content inside empty directives as CSSRegions trims any empty # elements found near the boundaries of a region. (@source.find ".alongslide:empty").text("[ALS]") # Parser entrypoint. # # Build sections and store them directly as CSSRegions named flows. # # Retun panels and footnotes, which will be needed by other components. # # Note! Parse order matters! Sections should go last, once all non-section # material has been scraped out of @source. # parse: -> @sourceLength = 0 panels = @collectPanels() footnotes = @collectFootnotes() @collectSections() flowNames : @flowNames panelNames : @panelNames backgrounds : @backgrounds panels : panels footnotes : footnotes sourceLength: @sourceLength collectPanels: -> rawPanels = @source.find('.alongslide.show.panel') _.object _.map rawPanels, (el) => $el = $(el) panelId = $el.data('alongslide-id') panelEl = $el.clone().removeClass('show') # Cleanup $el.empty().removeClass('panel') @panelNames.push(panelId) return [ panelId, panelEl ] # Sift through passed-in sections, delineating them based on `enter` and `exit` # directives, then assigning each to a flow. # collectSections: -> @source.find('.alongslide.enter.section').each (index, directiveElement) => directive = $(directiveElement) id = directive.data('alongslide-id') exitSelector = '.alongslide.exit.section[data-alongslide-id='+id+']' # build section for content BEFORE section enter lastSectionContents = directive.prevAll().detach().get().reverse() @buildSection(lastSectionContents, directive) if lastSectionContents.length # build section for content AFTER section enter sectionContents = directive.nextUntil(exitSelector).detach() @buildSection(sectionContents, directive, id) # cleanup section build process directive.remove() (@source.find exitSelector).remove() @buildSection @source.children() unless @source.is(':empty') # Build section, given content. # # Create new NamedFlow for it, and log the name. # # Create section background. # # @param content - jQuery object of section contents # @param directive (optional) - directive which specified the section # @param id (optional) - Alongslide section ID # buildSection: (content, directive, id) -> flowName = id || "sectionFlow#{@flowNames.length}" idElement = directive?.removeClass('alongslide').empty().removeClass('enter') || $("<div/>") idElement.attr('data-alongslide-id', flowName) # create section section = idElement.clone().append(content) # tally up length @sourceLength += section.text().length # create NamedFlow document.namedFlows.get(flowName).addContent(section.get(0)) @flowNames.push flowName # create background if ID is specified if id? background = idElement.clone().addClass('background frame').html("&nbsp;") @backgrounds.push(background) # Search for footntes as formatted by Redcarpet's footnotes callback # # Each has an ID of the form `fn1`, which corresponds to the links in the # footnote references. # # Returns a DOM node whose child elements are footnote definitions and removes the generated footnotes from DOM collectFootnotes: -> @source.find('.als-footnotes:last') .remove()
true
# # parser.coffee: parse raw HTML into Alongslide types: sections, panels, etc. # # Copyright 2013 Canopy Canopy Canopy, Inc. # Author PI:NAME:<NAME>END_PI class Alongslide::Parser # Store names of flows here as we create them. # # sections: [] backgrounds: [] flowNames : [] panelNames : [] constructor: (options) -> {@source} = options @preprocessSource() # # preprocessSource: -> # Put dummy content inside empty directives as CSSRegions trims any empty # elements found near the boundaries of a region. (@source.find ".alongslide:empty").text("[ALS]") # Parser entrypoint. # # Build sections and store them directly as CSSRegions named flows. # # Retun panels and footnotes, which will be needed by other components. # # Note! Parse order matters! Sections should go last, once all non-section # material has been scraped out of @source. # parse: -> @sourceLength = 0 panels = @collectPanels() footnotes = @collectFootnotes() @collectSections() flowNames : @flowNames panelNames : @panelNames backgrounds : @backgrounds panels : panels footnotes : footnotes sourceLength: @sourceLength collectPanels: -> rawPanels = @source.find('.alongslide.show.panel') _.object _.map rawPanels, (el) => $el = $(el) panelId = $el.data('alongslide-id') panelEl = $el.clone().removeClass('show') # Cleanup $el.empty().removeClass('panel') @panelNames.push(panelId) return [ panelId, panelEl ] # Sift through passed-in sections, delineating them based on `enter` and `exit` # directives, then assigning each to a flow. # collectSections: -> @source.find('.alongslide.enter.section').each (index, directiveElement) => directive = $(directiveElement) id = directive.data('alongslide-id') exitSelector = '.alongslide.exit.section[data-alongslide-id='+id+']' # build section for content BEFORE section enter lastSectionContents = directive.prevAll().detach().get().reverse() @buildSection(lastSectionContents, directive) if lastSectionContents.length # build section for content AFTER section enter sectionContents = directive.nextUntil(exitSelector).detach() @buildSection(sectionContents, directive, id) # cleanup section build process directive.remove() (@source.find exitSelector).remove() @buildSection @source.children() unless @source.is(':empty') # Build section, given content. # # Create new NamedFlow for it, and log the name. # # Create section background. # # @param content - jQuery object of section contents # @param directive (optional) - directive which specified the section # @param id (optional) - Alongslide section ID # buildSection: (content, directive, id) -> flowName = id || "sectionFlow#{@flowNames.length}" idElement = directive?.removeClass('alongslide').empty().removeClass('enter') || $("<div/>") idElement.attr('data-alongslide-id', flowName) # create section section = idElement.clone().append(content) # tally up length @sourceLength += section.text().length # create NamedFlow document.namedFlows.get(flowName).addContent(section.get(0)) @flowNames.push flowName # create background if ID is specified if id? background = idElement.clone().addClass('background frame').html("&nbsp;") @backgrounds.push(background) # Search for footntes as formatted by Redcarpet's footnotes callback # # Each has an ID of the form `fn1`, which corresponds to the links in the # footnote references. # # Returns a DOM node whose child elements are footnote definitions and removes the generated footnotes from DOM collectFootnotes: -> @source.find('.als-footnotes:last') .remove()
[ { "context": " project = new Project\n id: 23\n name: \"Project Test\"\n description: \"Project description\"\n i", "end": 200, "score": 0.991493821144104, "start": 188, "tag": "NAME", "value": "Project Test" } ]
public/coffeescripts/tests/models/project.coffee
googleheim/ablass
0
define ["project", "project_view", "../../fixtures/projects"], (Project, ProjectItemView, projects)-> describe "Model Project", ()-> project = new Project id: 23 name: "Project Test" description: "Project description" icon: "httpishthing" project_view = new ProjectItemView( {model: project} ) it "should have attributes", ()-> expect(project.get("name")).toBe("Project Test") it "should parse a template with given attributes", ()-> project_view.render() expect(project_view.$el).toBeTruthy() expect(project_view.$el.find("div.name").html()).toBe("Project Test") expect(project_view.$el.find("div.icon").html()).toMatch("src=\"httpishthing") expect(project_view.$el.find("div.description").html()).toBe("Project description")
91307
define ["project", "project_view", "../../fixtures/projects"], (Project, ProjectItemView, projects)-> describe "Model Project", ()-> project = new Project id: 23 name: "<NAME>" description: "Project description" icon: "httpishthing" project_view = new ProjectItemView( {model: project} ) it "should have attributes", ()-> expect(project.get("name")).toBe("Project Test") it "should parse a template with given attributes", ()-> project_view.render() expect(project_view.$el).toBeTruthy() expect(project_view.$el.find("div.name").html()).toBe("Project Test") expect(project_view.$el.find("div.icon").html()).toMatch("src=\"httpishthing") expect(project_view.$el.find("div.description").html()).toBe("Project description")
true
define ["project", "project_view", "../../fixtures/projects"], (Project, ProjectItemView, projects)-> describe "Model Project", ()-> project = new Project id: 23 name: "PI:NAME:<NAME>END_PI" description: "Project description" icon: "httpishthing" project_view = new ProjectItemView( {model: project} ) it "should have attributes", ()-> expect(project.get("name")).toBe("Project Test") it "should parse a template with given attributes", ()-> project_view.render() expect(project_view.$el).toBeTruthy() expect(project_view.$el.find("div.name").html()).toBe("Project Test") expect(project_view.$el.find("div.icon").html()).toMatch("src=\"httpishthing") expect(project_view.$el.find("div.description").html()).toBe("Project description")
[ { "context": "io.com\n\nCopyright 2016 Chai Biotechnologies Inc. <info@chaibio.com>\n\nLicensed under the Apache License, Version 2.0 ", "end": 194, "score": 0.9999234080314636, "start": 178, "tag": "EMAIL", "value": "info@chaibio.com" } ]
frontend/javascripts/app/services/melt_curve_service.coffee
MakerButt/chaipcr
1
### Chai PCR - Software platform for Open qPCR and Chai's Real-Time PCR instruments. For more information visit http://www.chaibio.com Copyright 2016 Chai Biotechnologies Inc. <info@chaibio.com> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ### App.service 'MeltCurveService', [ 'AmplificationChartHelper' 'Webworker' (AmplificationChartHelper, Webworker) -> self = @ @COLORS = [ '#04A0D9' '#1578BE' '#2455A8' '#3D3191' '#75278E' '#B01D8B' '#FA1485' '#FF0050' '#EA244E' '#FA3C00' '#F0662D' '#F6B014' '#FCDF2B' '#B7D436' '#68BD43' '#14A451' ] @SAMPLE_TARGET_COLORS = [ '#04A0D9' '#2455A8' '#75278E' '#FA1485' '#EA244E' '#F0662D' '#FCDF2B' '#68BD43' '#1578BE' '#3D3191' '#B01D8B' '#FF0050' '#FA3C00' '#F6B014' '#B7D436' '#14A451' ] self.defaultData = (is_dual_channel) -> datasets = {} if is_dual_channel for ch in [1..2] by 1 for i in [0..15] by 1 datasets["well_#{i}_#{ch}"] = [] else for i in [0..15] by 1 datasets["well_#{i}_1"] = [] return datasets @blankWellData = (is_dual_channel, well_targets) -> well_targets = angular.copy well_targets well_data = [] for i in [0.. 15] by 1 item = {} item['well_num'] = i+1 item['tm'] = [] item['channel'] = 1 item['active'] = false if is_dual_channel item['target_name'] = well_targets[2*i].name if well_targets[2*i] item['target_id'] = well_targets[2*i].id if well_targets[2*i] item['color'] = well_targets[2*i].color if well_targets[2*i] item['well_type'] = well_targets[2*i].well_type if well_targets[2*i] else item['target_name'] = well_targets[i].name if well_targets[i] item['target_id'] = well_targets[i].id if well_targets[i] item['color'] = well_targets[i].color if well_targets[i] item['well_type'] = well_targets[i].well_type if well_targets[i] well_data.push item if is_dual_channel dual_item = angular.copy item dual_item['target_name'] = well_targets[2*i+1].name if well_targets[2*i+1] dual_item['target_id'] = well_targets[2*i+1].id if well_targets[2*i+1] dual_item['color'] = well_targets[2*i+1].color if well_targets[2*i+1] dual_item['well_type'] = well_targets[2*i+1].well_type if well_targets[2*i+1] dual_item['channel'] = 2 well_data.push dual_item return well_data @initialSummaryData = (summary_data, target_data) -> summary_data = angular.copy summary_data target_data = angular.copy target_data summary_data[0].push "channel" for i in [1.. summary_data.length - 1] by 1 target = _.filter target_data, (elem) -> elem[0] is summary_data[i][0] summary_data[i].push target[0][2] return _.sortBy summary_data, (elem) -> elem[elem.length - 1] @normalizeSummaryData = (summary_data, target_data, well_targets) -> summary_data = angular.copy summary_data target_data = angular.copy target_data well_targets = angular.copy well_targets well_data = [] for i in [0.. summary_data.length - 1] by 1 item = summary_data[i] target = _.filter well_targets, (target) -> target and target.id is item.target_id and target.well_num is item.well_num if target.length item['target_name'] = target[0].name if target[0] item['channel'] = target[0].channel if target[0] item['color'] = target[0].color if target[0] item['well_type'] = target[0].well_type if target[0] else target = _.filter target_data, (target) -> target.target_id is item.target_id item['target_name'] = target[0].target_name if target[0] item['channel'] = target[0].channel if target[0] item['color'] = @SAMPLE_TARGET_COLORS[target[0].channel - 1] if target[0] item['well_type'] = '' item['active'] = false well_data.push item return well_data @normalizeChartData = (chart_data, target_data, well_targets) -> chart_data = angular.copy chart_data target_data = angular.copy target_data well_targets = angular.copy well_targets for i in [0.. chart_data.length - 1] by 1 item = chart_data[i] target = _.filter well_targets, (target) -> target && target.id is item.target_id if target.length chart_data[i]['channel'] = target[0].channel if target[0] else target = _.filter target_data, (target) -> target.target_id is item.target_id chart_data[i]['channel'] = if target[0]['target_name'] == 'Ch 1' then 1 else 2 return chart_data @normalizeWellTargetData = (well_data, is_dual_channel) -> well_data = angular.copy well_data channel_count = if is_dual_channel then 2 else 1 targets = [] for i in [0.. 16 * channel_count - 1] by 1 targets[i] = id: null name: null channel: null color: null for i in [0.. well_data.length - 1] by 1 targets[(well_data[i].well_num - 1) * channel_count + well_data[i].channel - 1] = id: well_data[i].target_id name: well_data[i].target_name channel: well_data[i].channel color: well_data[i].color return targets self.chartConfig = -> series = [] # for i in [0..1] by 1 for i in [0..15] by 1 series.push dataset: "well_#{i}" color: AmplificationChartHelper.COLORS[i] series: series axes: x: key: 'temperature' label: 'Temperature (°C)' ticks: 8 tickFormat: (x) -> x = x || 0 x = Math.round(x * 10) / 10 return x y: scale: 'linear' unit: 'k' ticks: 10 tickFormat: (y) -># Math.round( y * 10 ) / 10 Math.round(( y / 1000) * 10) / 10 box: label: x: 'Temp' y: 'RFU' # end chartConfig self.parseData = (data, is_dual_channel, cb) -> parseData = (data, is_dual_channel) -> datasets = {} if is_dual_channel for ch in [1..2] by 1 for i in [0..15] by 1 datasets["well_#{i}_#{ch}"] = [] else for i in [0..15] by 1 datasets["well_#{i}_1"] = [] for well, i in data by 1 datasets["well_#{data[i].well_num - 1}_#{data[i].channel}"] = [] for temp, ii in data[i].temperature by 1 total_temp = 0 for t in [0...data.length] by 1 total_temp += if data[t] then data[t].temperature[ii] else 0 datasets["well_#{data[i].well_num - 1}_#{data[i].channel}"].push temperature: Math.round((total_temp / data.length) * 100) / 100 derivative: Math.round(data[i].derivative_data[ii] * 100) / 100 normalized: Math.round(data[i].normalized_data[ii] * 100) / 100 complete(datasets) return Webworker.create(parseData, async:true).run(data, is_dual_channel) # end parseData self.optimizeForEachResolution = (mc_data, resolutions) -> data = [] for res in resolutions by 1 data.push(self.optimizeForResolution(angular.copy(mc_data), res)) return data self.optimizeForResolution = (mc_data, resolution) -> return if !mc_data calibration_dp = 200 chunkSize = Math.round( resolution / calibration_dp ) chunkSize = if chunkSize > 0 then chunkSize else 1 new_data = {} for well_i in [0..15] by 1 new_data["well_#{well_i}"] = [] well_data = mc_data["well_#{well_i}"] chunked = _.chunk well_data, chunkSize new_data["well_#{well_i}"] = _.map chunked, (chunk) -> averaged_data = [] total_temperature = 0 total_derivative = 0 total_normalized = 0 for c in chunk by 1 total_temperature += c.temperature total_derivative += c.derivative total_normalized += c.normalized return { temperature: total_temperature/chunk.length derivative: total_derivative/chunk.length normalized: total_normalized/chunk.length } new_data["well_#{well_i}"].unshift well_data[0] new_data["well_#{well_i}"].push well_data[well_data.length-1] return new_data self.moveData = (data, data_length, resolution, scrollbar) -> scrollbar = scrollbar || 0 scrollbar = if scrollbar < 0 then 0 else scrollbar scrollbar = if scrollbar > 1 then 1 else scrollbar mc_data = angular.copy(data) new_data = {} data_span = Math.round((resolution/data_length) * mc_data['well_0'].length) start = (mc_data['well_0'].length - data_span) * scrollbar end = start + data_span start = Math.floor(start) end = Math.ceil(end) for i in [0..15] by 1 new_data["well_#{i}"] = mc_data["well_#{i}"].slice(start, end) return new_data self.averagedTm = (tms) -> return null if !tms return null if !tms[0] return tms[0] self.getYExtrems = (data, chart_type) -> data_length = data['well_0'].length min = 0 max = 0 for i in [0...data_length] by 1 for ii in [0..15] by 1 val = data["well_#{ii}"][i][chart_type] min = if val < min then val else min max = if val > max then val else max return { min: min max: max } return self ]
123661
### Chai PCR - Software platform for Open qPCR and Chai's Real-Time PCR instruments. For more information visit http://www.chaibio.com Copyright 2016 Chai Biotechnologies Inc. <<EMAIL>> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ### App.service 'MeltCurveService', [ 'AmplificationChartHelper' 'Webworker' (AmplificationChartHelper, Webworker) -> self = @ @COLORS = [ '#04A0D9' '#1578BE' '#2455A8' '#3D3191' '#75278E' '#B01D8B' '#FA1485' '#FF0050' '#EA244E' '#FA3C00' '#F0662D' '#F6B014' '#FCDF2B' '#B7D436' '#68BD43' '#14A451' ] @SAMPLE_TARGET_COLORS = [ '#04A0D9' '#2455A8' '#75278E' '#FA1485' '#EA244E' '#F0662D' '#FCDF2B' '#68BD43' '#1578BE' '#3D3191' '#B01D8B' '#FF0050' '#FA3C00' '#F6B014' '#B7D436' '#14A451' ] self.defaultData = (is_dual_channel) -> datasets = {} if is_dual_channel for ch in [1..2] by 1 for i in [0..15] by 1 datasets["well_#{i}_#{ch}"] = [] else for i in [0..15] by 1 datasets["well_#{i}_1"] = [] return datasets @blankWellData = (is_dual_channel, well_targets) -> well_targets = angular.copy well_targets well_data = [] for i in [0.. 15] by 1 item = {} item['well_num'] = i+1 item['tm'] = [] item['channel'] = 1 item['active'] = false if is_dual_channel item['target_name'] = well_targets[2*i].name if well_targets[2*i] item['target_id'] = well_targets[2*i].id if well_targets[2*i] item['color'] = well_targets[2*i].color if well_targets[2*i] item['well_type'] = well_targets[2*i].well_type if well_targets[2*i] else item['target_name'] = well_targets[i].name if well_targets[i] item['target_id'] = well_targets[i].id if well_targets[i] item['color'] = well_targets[i].color if well_targets[i] item['well_type'] = well_targets[i].well_type if well_targets[i] well_data.push item if is_dual_channel dual_item = angular.copy item dual_item['target_name'] = well_targets[2*i+1].name if well_targets[2*i+1] dual_item['target_id'] = well_targets[2*i+1].id if well_targets[2*i+1] dual_item['color'] = well_targets[2*i+1].color if well_targets[2*i+1] dual_item['well_type'] = well_targets[2*i+1].well_type if well_targets[2*i+1] dual_item['channel'] = 2 well_data.push dual_item return well_data @initialSummaryData = (summary_data, target_data) -> summary_data = angular.copy summary_data target_data = angular.copy target_data summary_data[0].push "channel" for i in [1.. summary_data.length - 1] by 1 target = _.filter target_data, (elem) -> elem[0] is summary_data[i][0] summary_data[i].push target[0][2] return _.sortBy summary_data, (elem) -> elem[elem.length - 1] @normalizeSummaryData = (summary_data, target_data, well_targets) -> summary_data = angular.copy summary_data target_data = angular.copy target_data well_targets = angular.copy well_targets well_data = [] for i in [0.. summary_data.length - 1] by 1 item = summary_data[i] target = _.filter well_targets, (target) -> target and target.id is item.target_id and target.well_num is item.well_num if target.length item['target_name'] = target[0].name if target[0] item['channel'] = target[0].channel if target[0] item['color'] = target[0].color if target[0] item['well_type'] = target[0].well_type if target[0] else target = _.filter target_data, (target) -> target.target_id is item.target_id item['target_name'] = target[0].target_name if target[0] item['channel'] = target[0].channel if target[0] item['color'] = @SAMPLE_TARGET_COLORS[target[0].channel - 1] if target[0] item['well_type'] = '' item['active'] = false well_data.push item return well_data @normalizeChartData = (chart_data, target_data, well_targets) -> chart_data = angular.copy chart_data target_data = angular.copy target_data well_targets = angular.copy well_targets for i in [0.. chart_data.length - 1] by 1 item = chart_data[i] target = _.filter well_targets, (target) -> target && target.id is item.target_id if target.length chart_data[i]['channel'] = target[0].channel if target[0] else target = _.filter target_data, (target) -> target.target_id is item.target_id chart_data[i]['channel'] = if target[0]['target_name'] == 'Ch 1' then 1 else 2 return chart_data @normalizeWellTargetData = (well_data, is_dual_channel) -> well_data = angular.copy well_data channel_count = if is_dual_channel then 2 else 1 targets = [] for i in [0.. 16 * channel_count - 1] by 1 targets[i] = id: null name: null channel: null color: null for i in [0.. well_data.length - 1] by 1 targets[(well_data[i].well_num - 1) * channel_count + well_data[i].channel - 1] = id: well_data[i].target_id name: well_data[i].target_name channel: well_data[i].channel color: well_data[i].color return targets self.chartConfig = -> series = [] # for i in [0..1] by 1 for i in [0..15] by 1 series.push dataset: "well_#{i}" color: AmplificationChartHelper.COLORS[i] series: series axes: x: key: 'temperature' label: 'Temperature (°C)' ticks: 8 tickFormat: (x) -> x = x || 0 x = Math.round(x * 10) / 10 return x y: scale: 'linear' unit: 'k' ticks: 10 tickFormat: (y) -># Math.round( y * 10 ) / 10 Math.round(( y / 1000) * 10) / 10 box: label: x: 'Temp' y: 'RFU' # end chartConfig self.parseData = (data, is_dual_channel, cb) -> parseData = (data, is_dual_channel) -> datasets = {} if is_dual_channel for ch in [1..2] by 1 for i in [0..15] by 1 datasets["well_#{i}_#{ch}"] = [] else for i in [0..15] by 1 datasets["well_#{i}_1"] = [] for well, i in data by 1 datasets["well_#{data[i].well_num - 1}_#{data[i].channel}"] = [] for temp, ii in data[i].temperature by 1 total_temp = 0 for t in [0...data.length] by 1 total_temp += if data[t] then data[t].temperature[ii] else 0 datasets["well_#{data[i].well_num - 1}_#{data[i].channel}"].push temperature: Math.round((total_temp / data.length) * 100) / 100 derivative: Math.round(data[i].derivative_data[ii] * 100) / 100 normalized: Math.round(data[i].normalized_data[ii] * 100) / 100 complete(datasets) return Webworker.create(parseData, async:true).run(data, is_dual_channel) # end parseData self.optimizeForEachResolution = (mc_data, resolutions) -> data = [] for res in resolutions by 1 data.push(self.optimizeForResolution(angular.copy(mc_data), res)) return data self.optimizeForResolution = (mc_data, resolution) -> return if !mc_data calibration_dp = 200 chunkSize = Math.round( resolution / calibration_dp ) chunkSize = if chunkSize > 0 then chunkSize else 1 new_data = {} for well_i in [0..15] by 1 new_data["well_#{well_i}"] = [] well_data = mc_data["well_#{well_i}"] chunked = _.chunk well_data, chunkSize new_data["well_#{well_i}"] = _.map chunked, (chunk) -> averaged_data = [] total_temperature = 0 total_derivative = 0 total_normalized = 0 for c in chunk by 1 total_temperature += c.temperature total_derivative += c.derivative total_normalized += c.normalized return { temperature: total_temperature/chunk.length derivative: total_derivative/chunk.length normalized: total_normalized/chunk.length } new_data["well_#{well_i}"].unshift well_data[0] new_data["well_#{well_i}"].push well_data[well_data.length-1] return new_data self.moveData = (data, data_length, resolution, scrollbar) -> scrollbar = scrollbar || 0 scrollbar = if scrollbar < 0 then 0 else scrollbar scrollbar = if scrollbar > 1 then 1 else scrollbar mc_data = angular.copy(data) new_data = {} data_span = Math.round((resolution/data_length) * mc_data['well_0'].length) start = (mc_data['well_0'].length - data_span) * scrollbar end = start + data_span start = Math.floor(start) end = Math.ceil(end) for i in [0..15] by 1 new_data["well_#{i}"] = mc_data["well_#{i}"].slice(start, end) return new_data self.averagedTm = (tms) -> return null if !tms return null if !tms[0] return tms[0] self.getYExtrems = (data, chart_type) -> data_length = data['well_0'].length min = 0 max = 0 for i in [0...data_length] by 1 for ii in [0..15] by 1 val = data["well_#{ii}"][i][chart_type] min = if val < min then val else min max = if val > max then val else max return { min: min max: max } return self ]
true
### Chai PCR - Software platform for Open qPCR and Chai's Real-Time PCR instruments. For more information visit http://www.chaibio.com Copyright 2016 Chai Biotechnologies Inc. <PI:EMAIL:<EMAIL>END_PI> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ### App.service 'MeltCurveService', [ 'AmplificationChartHelper' 'Webworker' (AmplificationChartHelper, Webworker) -> self = @ @COLORS = [ '#04A0D9' '#1578BE' '#2455A8' '#3D3191' '#75278E' '#B01D8B' '#FA1485' '#FF0050' '#EA244E' '#FA3C00' '#F0662D' '#F6B014' '#FCDF2B' '#B7D436' '#68BD43' '#14A451' ] @SAMPLE_TARGET_COLORS = [ '#04A0D9' '#2455A8' '#75278E' '#FA1485' '#EA244E' '#F0662D' '#FCDF2B' '#68BD43' '#1578BE' '#3D3191' '#B01D8B' '#FF0050' '#FA3C00' '#F6B014' '#B7D436' '#14A451' ] self.defaultData = (is_dual_channel) -> datasets = {} if is_dual_channel for ch in [1..2] by 1 for i in [0..15] by 1 datasets["well_#{i}_#{ch}"] = [] else for i in [0..15] by 1 datasets["well_#{i}_1"] = [] return datasets @blankWellData = (is_dual_channel, well_targets) -> well_targets = angular.copy well_targets well_data = [] for i in [0.. 15] by 1 item = {} item['well_num'] = i+1 item['tm'] = [] item['channel'] = 1 item['active'] = false if is_dual_channel item['target_name'] = well_targets[2*i].name if well_targets[2*i] item['target_id'] = well_targets[2*i].id if well_targets[2*i] item['color'] = well_targets[2*i].color if well_targets[2*i] item['well_type'] = well_targets[2*i].well_type if well_targets[2*i] else item['target_name'] = well_targets[i].name if well_targets[i] item['target_id'] = well_targets[i].id if well_targets[i] item['color'] = well_targets[i].color if well_targets[i] item['well_type'] = well_targets[i].well_type if well_targets[i] well_data.push item if is_dual_channel dual_item = angular.copy item dual_item['target_name'] = well_targets[2*i+1].name if well_targets[2*i+1] dual_item['target_id'] = well_targets[2*i+1].id if well_targets[2*i+1] dual_item['color'] = well_targets[2*i+1].color if well_targets[2*i+1] dual_item['well_type'] = well_targets[2*i+1].well_type if well_targets[2*i+1] dual_item['channel'] = 2 well_data.push dual_item return well_data @initialSummaryData = (summary_data, target_data) -> summary_data = angular.copy summary_data target_data = angular.copy target_data summary_data[0].push "channel" for i in [1.. summary_data.length - 1] by 1 target = _.filter target_data, (elem) -> elem[0] is summary_data[i][0] summary_data[i].push target[0][2] return _.sortBy summary_data, (elem) -> elem[elem.length - 1] @normalizeSummaryData = (summary_data, target_data, well_targets) -> summary_data = angular.copy summary_data target_data = angular.copy target_data well_targets = angular.copy well_targets well_data = [] for i in [0.. summary_data.length - 1] by 1 item = summary_data[i] target = _.filter well_targets, (target) -> target and target.id is item.target_id and target.well_num is item.well_num if target.length item['target_name'] = target[0].name if target[0] item['channel'] = target[0].channel if target[0] item['color'] = target[0].color if target[0] item['well_type'] = target[0].well_type if target[0] else target = _.filter target_data, (target) -> target.target_id is item.target_id item['target_name'] = target[0].target_name if target[0] item['channel'] = target[0].channel if target[0] item['color'] = @SAMPLE_TARGET_COLORS[target[0].channel - 1] if target[0] item['well_type'] = '' item['active'] = false well_data.push item return well_data @normalizeChartData = (chart_data, target_data, well_targets) -> chart_data = angular.copy chart_data target_data = angular.copy target_data well_targets = angular.copy well_targets for i in [0.. chart_data.length - 1] by 1 item = chart_data[i] target = _.filter well_targets, (target) -> target && target.id is item.target_id if target.length chart_data[i]['channel'] = target[0].channel if target[0] else target = _.filter target_data, (target) -> target.target_id is item.target_id chart_data[i]['channel'] = if target[0]['target_name'] == 'Ch 1' then 1 else 2 return chart_data @normalizeWellTargetData = (well_data, is_dual_channel) -> well_data = angular.copy well_data channel_count = if is_dual_channel then 2 else 1 targets = [] for i in [0.. 16 * channel_count - 1] by 1 targets[i] = id: null name: null channel: null color: null for i in [0.. well_data.length - 1] by 1 targets[(well_data[i].well_num - 1) * channel_count + well_data[i].channel - 1] = id: well_data[i].target_id name: well_data[i].target_name channel: well_data[i].channel color: well_data[i].color return targets self.chartConfig = -> series = [] # for i in [0..1] by 1 for i in [0..15] by 1 series.push dataset: "well_#{i}" color: AmplificationChartHelper.COLORS[i] series: series axes: x: key: 'temperature' label: 'Temperature (°C)' ticks: 8 tickFormat: (x) -> x = x || 0 x = Math.round(x * 10) / 10 return x y: scale: 'linear' unit: 'k' ticks: 10 tickFormat: (y) -># Math.round( y * 10 ) / 10 Math.round(( y / 1000) * 10) / 10 box: label: x: 'Temp' y: 'RFU' # end chartConfig self.parseData = (data, is_dual_channel, cb) -> parseData = (data, is_dual_channel) -> datasets = {} if is_dual_channel for ch in [1..2] by 1 for i in [0..15] by 1 datasets["well_#{i}_#{ch}"] = [] else for i in [0..15] by 1 datasets["well_#{i}_1"] = [] for well, i in data by 1 datasets["well_#{data[i].well_num - 1}_#{data[i].channel}"] = [] for temp, ii in data[i].temperature by 1 total_temp = 0 for t in [0...data.length] by 1 total_temp += if data[t] then data[t].temperature[ii] else 0 datasets["well_#{data[i].well_num - 1}_#{data[i].channel}"].push temperature: Math.round((total_temp / data.length) * 100) / 100 derivative: Math.round(data[i].derivative_data[ii] * 100) / 100 normalized: Math.round(data[i].normalized_data[ii] * 100) / 100 complete(datasets) return Webworker.create(parseData, async:true).run(data, is_dual_channel) # end parseData self.optimizeForEachResolution = (mc_data, resolutions) -> data = [] for res in resolutions by 1 data.push(self.optimizeForResolution(angular.copy(mc_data), res)) return data self.optimizeForResolution = (mc_data, resolution) -> return if !mc_data calibration_dp = 200 chunkSize = Math.round( resolution / calibration_dp ) chunkSize = if chunkSize > 0 then chunkSize else 1 new_data = {} for well_i in [0..15] by 1 new_data["well_#{well_i}"] = [] well_data = mc_data["well_#{well_i}"] chunked = _.chunk well_data, chunkSize new_data["well_#{well_i}"] = _.map chunked, (chunk) -> averaged_data = [] total_temperature = 0 total_derivative = 0 total_normalized = 0 for c in chunk by 1 total_temperature += c.temperature total_derivative += c.derivative total_normalized += c.normalized return { temperature: total_temperature/chunk.length derivative: total_derivative/chunk.length normalized: total_normalized/chunk.length } new_data["well_#{well_i}"].unshift well_data[0] new_data["well_#{well_i}"].push well_data[well_data.length-1] return new_data self.moveData = (data, data_length, resolution, scrollbar) -> scrollbar = scrollbar || 0 scrollbar = if scrollbar < 0 then 0 else scrollbar scrollbar = if scrollbar > 1 then 1 else scrollbar mc_data = angular.copy(data) new_data = {} data_span = Math.round((resolution/data_length) * mc_data['well_0'].length) start = (mc_data['well_0'].length - data_span) * scrollbar end = start + data_span start = Math.floor(start) end = Math.ceil(end) for i in [0..15] by 1 new_data["well_#{i}"] = mc_data["well_#{i}"].slice(start, end) return new_data self.averagedTm = (tms) -> return null if !tms return null if !tms[0] return tms[0] self.getYExtrems = (data, chart_type) -> data_length = data['well_0'].length min = 0 max = 0 for i in [0...data_length] by 1 for ii in [0..15] by 1 val = data["well_#{ii}"][i][chart_type] min = if val < min then val else min max = if val > max then val else max return { min: min max: max } return self ]
[ { "context": "oximity of an element to the viewport.\n# Thanks to Pamela Fox for this!\ninView = (el, nearThreshold) ->\n viewp", "end": 5997, "score": 0.9998211860656738, "start": 5987, "tag": "NAME", "value": "Pamela Fox" } ]
app/assets/javascripts/backbone/routers/items_router.js.coffee
masondesu/haberdash-fox
1
class HaberdashFox.Routers.ItemsRouter extends Backbone.Router initialize: (options) -> @items = new HaberdashFox.Collections.ItemsCollection() @collections = new HaberdashFox.Collections.CollectionsCollection() @bind 'all', @_trackPageview $(document).on "click", "a:not([data-bypass])", (evt) -> href = $(@).attr("href") protocol = @protocol + "//" if href.slice(protocol.length) isnt protocol evt.preventDefault() window.router.navigate href, true # An array for caching images pre-loaded via $.load() # See the loadVisibleImages function below. HaberdashFox.CachedImages = [] # Throttle the loadVisibleImage call that's bound # to the window's scroll event throttledScroll = _.throttle((-> loadVisibleImages('.slide, .item')), 500) $(window).on 'scroll', throttledScroll # Easier just to call this on both $ -> loadVisibleImages('.slide, .item') routes: "" : "index" "items/:slug" : "item" "collection/:slug" : "collection" "shops" : "shops" index: -> # Pass the featured collection slug into the collection method # below, via the HaberdashFox.FeaturedCollectionSlug, # which is set by Rails in application.html.slim. # # This is done because the featured collection slug # changes from week to week. @collection(HaberdashFox.FeaturedCollectionSlug) item: (slug) -> # If we already have it in the collection, just render it if item = @items.get(slug) @renderItem(item) # otherwise fetch it else item = new HaberdashFox.Models.Item slug: slug item.fetch success: (model, response, options) => # Add it to the items collection (for fast lookup # next time) and render it @items.add(model) @renderItem(model) renderItem: (item) -> @view = new HaberdashFox.Views.Items.ShowView(model: item) $("#js-content").html(@view.render().el) window.scrollTo(0,0) # lazy load all slides when the slider is fully loaded # loadVisibleImages('.slide') is passed into the iOS constructor # in the initSlider method @initSlider() collection: (slug) -> # If we already have it in the collection, just render it if collection = @collections.get(slug) @renderCollection(collection) # otherwise fetch it else collection = new HaberdashFox.Models.Collection slug: slug collection.fetch success: (model, response, options) => # Add it to the collections collection (for fast lookup # next time) and render it @collections.add(model) @renderCollection(model) renderCollection: (collection) -> @view = new HaberdashFox.Views.Collections.ShowView(model: collection) $("#js-content").html(@view.render().el) window.scrollTo(0,0) # lazy load all item images loadVisibleImages('.item') shops: -> if @shopsCollection? @renderShops() else @shopsCollection = new HaberdashFox.Models.Collection @shopsCollection.url = '/shops' @shopsCollection.fetch success: (model) => @renderShops() renderShops: -> @view = new HaberdashFox.Views.Collections.ShowView model: @shopsCollection template: JST["backbone/templates/collections/shops"] $("#js-content").html(@view.render().el) window.scrollTo(0,0) # lazy load all item images loadVisibleImages('.item') _trackPageview: -> url = Backbone.history.getFragment() _gaq.push(['_trackPageview', "/#{url}"]) # slider for the single item view initSlider: -> slider = $(".iosSlider") slider.iosSlider desktopClickDrag: true snapToChildren: true infiniteSlider: true navSlideSelector: ".slide-selectors .item" onSlideChange: @slideChange onSliderLoaded: (-> loadVisibleImages('.slide', true)) autoSlide: false scrollbar: true scrollbarContainer: ".scrollbar" scrollbarMargin: "0" scrollbarBorderRadius: "0" keyboardControls: true navPrevSelector: $('#js-scrollleft') navNextSelector: $('#js-scrollright') # Animate the navigation in $('#js-mobile-navigation-button').click -> $('#js-mobile-navigation td').each (index) -> setTimeout( (=> $(@).addClass 'active') , (index * 50)) # Animate the navigation out $('td a').click -> $('#js-mobile-navigation td').each (index) -> setTimeout( (=> $(@).removeClass 'active') , (index * 50)) slideChange: (args) -> $(".slide-selectors .item").removeClass "selected" $(".slide-selectors .item:eq(" + (args.currentSlideNumber - 1) + ")").addClass "selected" # A lazy-loader for images loadVisibleImages = (selector, ignoreProximity) -> $(selector).not('loadeded').each -> # store the element, its data-src, and its current style attribute el = $(@) imageUrl = el.attr('data-src') currentStyle = el.attr('style') || '' # if it's within 300px above or below the viewport if ignoreProximity || inView($(this), 500) # add the loading gif to the parent <a> el.parent('a').addClass('loading') # this allows us to call $.load() conditionally if HaberdashFox.CachedImages[imageUrl] el.attr('style', "background-image: url(#{imageUrl});" ) else # we didn't find the url in the CachedImages array, so preload it # with $.load() and set the background-image on the el in # the $.load() callback $('<img/>').attr('src', imageUrl).load => el.addClass('loadeded').attr('style', "background-image: url(#{imageUrl}); " + currentStyle ) # add this url to this array to prevent calling $.load() # again for the same image. HaberdashFox.CachedImages.push imageUrl # Checks the proximity of an element to the viewport. # Thanks to Pamela Fox for this! inView = (el, nearThreshold) -> viewportHeight = $(window).height() scrollTop = $(document).scrollTop() elTop = el.offset().top elHeight = el.height() nearThreshold = nearThreshold or 0 return true if (scrollTop + viewportHeight + nearThreshold) > (elTop + elHeight) false
123084
class HaberdashFox.Routers.ItemsRouter extends Backbone.Router initialize: (options) -> @items = new HaberdashFox.Collections.ItemsCollection() @collections = new HaberdashFox.Collections.CollectionsCollection() @bind 'all', @_trackPageview $(document).on "click", "a:not([data-bypass])", (evt) -> href = $(@).attr("href") protocol = @protocol + "//" if href.slice(protocol.length) isnt protocol evt.preventDefault() window.router.navigate href, true # An array for caching images pre-loaded via $.load() # See the loadVisibleImages function below. HaberdashFox.CachedImages = [] # Throttle the loadVisibleImage call that's bound # to the window's scroll event throttledScroll = _.throttle((-> loadVisibleImages('.slide, .item')), 500) $(window).on 'scroll', throttledScroll # Easier just to call this on both $ -> loadVisibleImages('.slide, .item') routes: "" : "index" "items/:slug" : "item" "collection/:slug" : "collection" "shops" : "shops" index: -> # Pass the featured collection slug into the collection method # below, via the HaberdashFox.FeaturedCollectionSlug, # which is set by Rails in application.html.slim. # # This is done because the featured collection slug # changes from week to week. @collection(HaberdashFox.FeaturedCollectionSlug) item: (slug) -> # If we already have it in the collection, just render it if item = @items.get(slug) @renderItem(item) # otherwise fetch it else item = new HaberdashFox.Models.Item slug: slug item.fetch success: (model, response, options) => # Add it to the items collection (for fast lookup # next time) and render it @items.add(model) @renderItem(model) renderItem: (item) -> @view = new HaberdashFox.Views.Items.ShowView(model: item) $("#js-content").html(@view.render().el) window.scrollTo(0,0) # lazy load all slides when the slider is fully loaded # loadVisibleImages('.slide') is passed into the iOS constructor # in the initSlider method @initSlider() collection: (slug) -> # If we already have it in the collection, just render it if collection = @collections.get(slug) @renderCollection(collection) # otherwise fetch it else collection = new HaberdashFox.Models.Collection slug: slug collection.fetch success: (model, response, options) => # Add it to the collections collection (for fast lookup # next time) and render it @collections.add(model) @renderCollection(model) renderCollection: (collection) -> @view = new HaberdashFox.Views.Collections.ShowView(model: collection) $("#js-content").html(@view.render().el) window.scrollTo(0,0) # lazy load all item images loadVisibleImages('.item') shops: -> if @shopsCollection? @renderShops() else @shopsCollection = new HaberdashFox.Models.Collection @shopsCollection.url = '/shops' @shopsCollection.fetch success: (model) => @renderShops() renderShops: -> @view = new HaberdashFox.Views.Collections.ShowView model: @shopsCollection template: JST["backbone/templates/collections/shops"] $("#js-content").html(@view.render().el) window.scrollTo(0,0) # lazy load all item images loadVisibleImages('.item') _trackPageview: -> url = Backbone.history.getFragment() _gaq.push(['_trackPageview', "/#{url}"]) # slider for the single item view initSlider: -> slider = $(".iosSlider") slider.iosSlider desktopClickDrag: true snapToChildren: true infiniteSlider: true navSlideSelector: ".slide-selectors .item" onSlideChange: @slideChange onSliderLoaded: (-> loadVisibleImages('.slide', true)) autoSlide: false scrollbar: true scrollbarContainer: ".scrollbar" scrollbarMargin: "0" scrollbarBorderRadius: "0" keyboardControls: true navPrevSelector: $('#js-scrollleft') navNextSelector: $('#js-scrollright') # Animate the navigation in $('#js-mobile-navigation-button').click -> $('#js-mobile-navigation td').each (index) -> setTimeout( (=> $(@).addClass 'active') , (index * 50)) # Animate the navigation out $('td a').click -> $('#js-mobile-navigation td').each (index) -> setTimeout( (=> $(@).removeClass 'active') , (index * 50)) slideChange: (args) -> $(".slide-selectors .item").removeClass "selected" $(".slide-selectors .item:eq(" + (args.currentSlideNumber - 1) + ")").addClass "selected" # A lazy-loader for images loadVisibleImages = (selector, ignoreProximity) -> $(selector).not('loadeded').each -> # store the element, its data-src, and its current style attribute el = $(@) imageUrl = el.attr('data-src') currentStyle = el.attr('style') || '' # if it's within 300px above or below the viewport if ignoreProximity || inView($(this), 500) # add the loading gif to the parent <a> el.parent('a').addClass('loading') # this allows us to call $.load() conditionally if HaberdashFox.CachedImages[imageUrl] el.attr('style', "background-image: url(#{imageUrl});" ) else # we didn't find the url in the CachedImages array, so preload it # with $.load() and set the background-image on the el in # the $.load() callback $('<img/>').attr('src', imageUrl).load => el.addClass('loadeded').attr('style', "background-image: url(#{imageUrl}); " + currentStyle ) # add this url to this array to prevent calling $.load() # again for the same image. HaberdashFox.CachedImages.push imageUrl # Checks the proximity of an element to the viewport. # Thanks to <NAME> for this! inView = (el, nearThreshold) -> viewportHeight = $(window).height() scrollTop = $(document).scrollTop() elTop = el.offset().top elHeight = el.height() nearThreshold = nearThreshold or 0 return true if (scrollTop + viewportHeight + nearThreshold) > (elTop + elHeight) false
true
class HaberdashFox.Routers.ItemsRouter extends Backbone.Router initialize: (options) -> @items = new HaberdashFox.Collections.ItemsCollection() @collections = new HaberdashFox.Collections.CollectionsCollection() @bind 'all', @_trackPageview $(document).on "click", "a:not([data-bypass])", (evt) -> href = $(@).attr("href") protocol = @protocol + "//" if href.slice(protocol.length) isnt protocol evt.preventDefault() window.router.navigate href, true # An array for caching images pre-loaded via $.load() # See the loadVisibleImages function below. HaberdashFox.CachedImages = [] # Throttle the loadVisibleImage call that's bound # to the window's scroll event throttledScroll = _.throttle((-> loadVisibleImages('.slide, .item')), 500) $(window).on 'scroll', throttledScroll # Easier just to call this on both $ -> loadVisibleImages('.slide, .item') routes: "" : "index" "items/:slug" : "item" "collection/:slug" : "collection" "shops" : "shops" index: -> # Pass the featured collection slug into the collection method # below, via the HaberdashFox.FeaturedCollectionSlug, # which is set by Rails in application.html.slim. # # This is done because the featured collection slug # changes from week to week. @collection(HaberdashFox.FeaturedCollectionSlug) item: (slug) -> # If we already have it in the collection, just render it if item = @items.get(slug) @renderItem(item) # otherwise fetch it else item = new HaberdashFox.Models.Item slug: slug item.fetch success: (model, response, options) => # Add it to the items collection (for fast lookup # next time) and render it @items.add(model) @renderItem(model) renderItem: (item) -> @view = new HaberdashFox.Views.Items.ShowView(model: item) $("#js-content").html(@view.render().el) window.scrollTo(0,0) # lazy load all slides when the slider is fully loaded # loadVisibleImages('.slide') is passed into the iOS constructor # in the initSlider method @initSlider() collection: (slug) -> # If we already have it in the collection, just render it if collection = @collections.get(slug) @renderCollection(collection) # otherwise fetch it else collection = new HaberdashFox.Models.Collection slug: slug collection.fetch success: (model, response, options) => # Add it to the collections collection (for fast lookup # next time) and render it @collections.add(model) @renderCollection(model) renderCollection: (collection) -> @view = new HaberdashFox.Views.Collections.ShowView(model: collection) $("#js-content").html(@view.render().el) window.scrollTo(0,0) # lazy load all item images loadVisibleImages('.item') shops: -> if @shopsCollection? @renderShops() else @shopsCollection = new HaberdashFox.Models.Collection @shopsCollection.url = '/shops' @shopsCollection.fetch success: (model) => @renderShops() renderShops: -> @view = new HaberdashFox.Views.Collections.ShowView model: @shopsCollection template: JST["backbone/templates/collections/shops"] $("#js-content").html(@view.render().el) window.scrollTo(0,0) # lazy load all item images loadVisibleImages('.item') _trackPageview: -> url = Backbone.history.getFragment() _gaq.push(['_trackPageview', "/#{url}"]) # slider for the single item view initSlider: -> slider = $(".iosSlider") slider.iosSlider desktopClickDrag: true snapToChildren: true infiniteSlider: true navSlideSelector: ".slide-selectors .item" onSlideChange: @slideChange onSliderLoaded: (-> loadVisibleImages('.slide', true)) autoSlide: false scrollbar: true scrollbarContainer: ".scrollbar" scrollbarMargin: "0" scrollbarBorderRadius: "0" keyboardControls: true navPrevSelector: $('#js-scrollleft') navNextSelector: $('#js-scrollright') # Animate the navigation in $('#js-mobile-navigation-button').click -> $('#js-mobile-navigation td').each (index) -> setTimeout( (=> $(@).addClass 'active') , (index * 50)) # Animate the navigation out $('td a').click -> $('#js-mobile-navigation td').each (index) -> setTimeout( (=> $(@).removeClass 'active') , (index * 50)) slideChange: (args) -> $(".slide-selectors .item").removeClass "selected" $(".slide-selectors .item:eq(" + (args.currentSlideNumber - 1) + ")").addClass "selected" # A lazy-loader for images loadVisibleImages = (selector, ignoreProximity) -> $(selector).not('loadeded').each -> # store the element, its data-src, and its current style attribute el = $(@) imageUrl = el.attr('data-src') currentStyle = el.attr('style') || '' # if it's within 300px above or below the viewport if ignoreProximity || inView($(this), 500) # add the loading gif to the parent <a> el.parent('a').addClass('loading') # this allows us to call $.load() conditionally if HaberdashFox.CachedImages[imageUrl] el.attr('style', "background-image: url(#{imageUrl});" ) else # we didn't find the url in the CachedImages array, so preload it # with $.load() and set the background-image on the el in # the $.load() callback $('<img/>').attr('src', imageUrl).load => el.addClass('loadeded').attr('style', "background-image: url(#{imageUrl}); " + currentStyle ) # add this url to this array to prevent calling $.load() # again for the same image. HaberdashFox.CachedImages.push imageUrl # Checks the proximity of an element to the viewport. # Thanks to PI:NAME:<NAME>END_PI for this! inView = (el, nearThreshold) -> viewportHeight = $(window).height() scrollTop = $(document).scrollTop() elTop = el.offset().top elHeight = el.height() nearThreshold = nearThreshold or 0 return true if (scrollTop + viewportHeight + nearThreshold) > (elTop + elHeight) false
[ { "context": "ists the installed packages\n#\n# Copyright (C) 2011 Nikolay Nemshilov\n#\n\nexports.init = (args) ->\n repo = require('../", "end": 73, "score": 0.9998816251754761, "start": 56, "tag": "NAME", "value": "Nikolay Nemshilov" } ]
cli/commands/list.coffee
lovely-io/lovely.io-stl
2
# # Lists the installed packages # # Copyright (C) 2011 Nikolay Nemshilov # exports.init = (args) -> repo = require('../repository') for name, versions of repo.list() print " #{name.ljust(16)} #{versions.join(', ').grey}" exports.help = (args) -> """ Lists installed packages Usage: lovely list """
156602
# # Lists the installed packages # # Copyright (C) 2011 <NAME> # exports.init = (args) -> repo = require('../repository') for name, versions of repo.list() print " #{name.ljust(16)} #{versions.join(', ').grey}" exports.help = (args) -> """ Lists installed packages Usage: lovely list """
true
# # Lists the installed packages # # Copyright (C) 2011 PI:NAME:<NAME>END_PI # exports.init = (args) -> repo = require('../repository') for name, versions of repo.list() print " #{name.ljust(16)} #{versions.join(', ').grey}" exports.help = (args) -> """ Lists installed packages Usage: lovely list """
[ { "context": "# Copyright (c) Konode. All rights reserved.\n# This source code is subje", "end": 22, "score": 0.9965338110923767, "start": 16, "tag": "NAME", "value": "Konode" } ]
src/crashHandler.coffee
LogicalOutcomes/KoNote
1
# Copyright (c) Konode. All rights reserved. # This source code is subject to the terms of the Mozilla Public License, v. 2.0 # that can be found in the LICENSE file or at: http://mozilla.org/MPL/2.0 # This module handles unexpected errors caused by bugs in the application. # # Error info can be retrieved after the fact by running this in the console on # the user's computer: # JSON.parse(localStorage.crashLog) Fs = require 'fs' Moment = require 'moment' {generateId} = require './persist' load = (win) -> React = win.React ReactDOM = win.ReactDOM R = React.DOM nwWin = nw.Window.get(win) {FaIcon} = require('./utils').load(win) handle = (err) -> # Show NW window, in case it's still hidden # Exclude loginPage, since it's meant to be hidden if win.pageParameters and not win.pageParameters.page is 'login' and global.ActiveSession? nwWin.show() # Record where this function was actually called from. # Sometimes this additional info is useful, because async calls often # obscure what caused an error. handlerStackTrace = new Error('handler call stack tracer').stack # React freaks out if you call R.render inside a component's render # method. nextTick works around this. process.nextTick -> try # Log to console first console.error "CrashHandler received an error:" console.error err console.error err.stack # Create crash report object crash = { id: generateId() platform: process.platform arch: process.arch userAgent: win.navigator.userAgent appVersion: nw.App.manifest.version nwVersion: process.versions["node-webkit"] cwd: process.cwd() url: win.location.href timestamp: Moment().format() error: err.toString() errorStackTrace: err.stack errorHandlerStackTrace: handlerStackTrace } # Show crash screen to user containerDiv = win.document.createElement 'div' win.document.body.appendChild containerDiv ReactDOM.render CrashOverlay({crash}), containerDiv # Log to file # todo: truncate Fs.appendFileSync 'error.log', JSON.stringify(crash) catch err2 try console.error "CrashHandler has crashed." console.error err2 catch err3 # Nothing we can do... CrashOverlay = React.createFactory React.createClass displayName: 'CrashOverlay' mixins: [React.addons.PureRenderMixin] render: -> return R.div({className: 'crashOverlay'}, R.div({className: 'crashMessage'}, R.img({src: './assets/brand/kn.png'}) R.h1({}, "Oops, something went wrong.") R.div({}, """ KoNote encountered an unexpected error. If this happens repeatedly, please copy the error message below and send to KoNote support with details on how you encountered it. Thank you! """) R.textarea({ className: 'debugInfo' ref: 'debugInfo' disabled: false value: JSON.stringify @props.crash onClick: @_selectDebugInfo onChange: (->) # do nothing }) R.div({className: 'buttonContainer'}, R.button({ className: 'btn btn-danger' onClick: @_close }, "Close") R.button({ className: 'btn btn-default' onClick: @_copyCrashTrace }, "Copy " FaIcon('copy') ) ) ) ) _copyCrashTrace: -> clipboard = nw.Clipboard.get() clipboard.set JSON.stringify @props.crash _selectDebugInfo: -> @refs.debugInfo.select() _close: -> nwWin.close true return {handle} module.exports = {load}
123701
# Copyright (c) <NAME>. All rights reserved. # This source code is subject to the terms of the Mozilla Public License, v. 2.0 # that can be found in the LICENSE file or at: http://mozilla.org/MPL/2.0 # This module handles unexpected errors caused by bugs in the application. # # Error info can be retrieved after the fact by running this in the console on # the user's computer: # JSON.parse(localStorage.crashLog) Fs = require 'fs' Moment = require 'moment' {generateId} = require './persist' load = (win) -> React = win.React ReactDOM = win.ReactDOM R = React.DOM nwWin = nw.Window.get(win) {FaIcon} = require('./utils').load(win) handle = (err) -> # Show NW window, in case it's still hidden # Exclude loginPage, since it's meant to be hidden if win.pageParameters and not win.pageParameters.page is 'login' and global.ActiveSession? nwWin.show() # Record where this function was actually called from. # Sometimes this additional info is useful, because async calls often # obscure what caused an error. handlerStackTrace = new Error('handler call stack tracer').stack # React freaks out if you call R.render inside a component's render # method. nextTick works around this. process.nextTick -> try # Log to console first console.error "CrashHandler received an error:" console.error err console.error err.stack # Create crash report object crash = { id: generateId() platform: process.platform arch: process.arch userAgent: win.navigator.userAgent appVersion: nw.App.manifest.version nwVersion: process.versions["node-webkit"] cwd: process.cwd() url: win.location.href timestamp: Moment().format() error: err.toString() errorStackTrace: err.stack errorHandlerStackTrace: handlerStackTrace } # Show crash screen to user containerDiv = win.document.createElement 'div' win.document.body.appendChild containerDiv ReactDOM.render CrashOverlay({crash}), containerDiv # Log to file # todo: truncate Fs.appendFileSync 'error.log', JSON.stringify(crash) catch err2 try console.error "CrashHandler has crashed." console.error err2 catch err3 # Nothing we can do... CrashOverlay = React.createFactory React.createClass displayName: 'CrashOverlay' mixins: [React.addons.PureRenderMixin] render: -> return R.div({className: 'crashOverlay'}, R.div({className: 'crashMessage'}, R.img({src: './assets/brand/kn.png'}) R.h1({}, "Oops, something went wrong.") R.div({}, """ KoNote encountered an unexpected error. If this happens repeatedly, please copy the error message below and send to KoNote support with details on how you encountered it. Thank you! """) R.textarea({ className: 'debugInfo' ref: 'debugInfo' disabled: false value: JSON.stringify @props.crash onClick: @_selectDebugInfo onChange: (->) # do nothing }) R.div({className: 'buttonContainer'}, R.button({ className: 'btn btn-danger' onClick: @_close }, "Close") R.button({ className: 'btn btn-default' onClick: @_copyCrashTrace }, "Copy " FaIcon('copy') ) ) ) ) _copyCrashTrace: -> clipboard = nw.Clipboard.get() clipboard.set JSON.stringify @props.crash _selectDebugInfo: -> @refs.debugInfo.select() _close: -> nwWin.close true return {handle} module.exports = {load}
true
# Copyright (c) PI:NAME:<NAME>END_PI. All rights reserved. # This source code is subject to the terms of the Mozilla Public License, v. 2.0 # that can be found in the LICENSE file or at: http://mozilla.org/MPL/2.0 # This module handles unexpected errors caused by bugs in the application. # # Error info can be retrieved after the fact by running this in the console on # the user's computer: # JSON.parse(localStorage.crashLog) Fs = require 'fs' Moment = require 'moment' {generateId} = require './persist' load = (win) -> React = win.React ReactDOM = win.ReactDOM R = React.DOM nwWin = nw.Window.get(win) {FaIcon} = require('./utils').load(win) handle = (err) -> # Show NW window, in case it's still hidden # Exclude loginPage, since it's meant to be hidden if win.pageParameters and not win.pageParameters.page is 'login' and global.ActiveSession? nwWin.show() # Record where this function was actually called from. # Sometimes this additional info is useful, because async calls often # obscure what caused an error. handlerStackTrace = new Error('handler call stack tracer').stack # React freaks out if you call R.render inside a component's render # method. nextTick works around this. process.nextTick -> try # Log to console first console.error "CrashHandler received an error:" console.error err console.error err.stack # Create crash report object crash = { id: generateId() platform: process.platform arch: process.arch userAgent: win.navigator.userAgent appVersion: nw.App.manifest.version nwVersion: process.versions["node-webkit"] cwd: process.cwd() url: win.location.href timestamp: Moment().format() error: err.toString() errorStackTrace: err.stack errorHandlerStackTrace: handlerStackTrace } # Show crash screen to user containerDiv = win.document.createElement 'div' win.document.body.appendChild containerDiv ReactDOM.render CrashOverlay({crash}), containerDiv # Log to file # todo: truncate Fs.appendFileSync 'error.log', JSON.stringify(crash) catch err2 try console.error "CrashHandler has crashed." console.error err2 catch err3 # Nothing we can do... CrashOverlay = React.createFactory React.createClass displayName: 'CrashOverlay' mixins: [React.addons.PureRenderMixin] render: -> return R.div({className: 'crashOverlay'}, R.div({className: 'crashMessage'}, R.img({src: './assets/brand/kn.png'}) R.h1({}, "Oops, something went wrong.") R.div({}, """ KoNote encountered an unexpected error. If this happens repeatedly, please copy the error message below and send to KoNote support with details on how you encountered it. Thank you! """) R.textarea({ className: 'debugInfo' ref: 'debugInfo' disabled: false value: JSON.stringify @props.crash onClick: @_selectDebugInfo onChange: (->) # do nothing }) R.div({className: 'buttonContainer'}, R.button({ className: 'btn btn-danger' onClick: @_close }, "Close") R.button({ className: 'btn btn-default' onClick: @_copyCrashTrace }, "Copy " FaIcon('copy') ) ) ) ) _copyCrashTrace: -> clipboard = nw.Clipboard.get() clipboard.set JSON.stringify @props.crash _selectDebugInfo: -> @refs.debugInfo.select() _close: -> nwWin.close true return {handle} module.exports = {load}
[ { "context": "uire) ->\n THREE = require 'three'\n ###\n @author Eberhard Graether / http://egraether.com/\n ###\n THREE.TrackballCo", "end": 79, "score": 0.9998879432678223, "start": 62, "tag": "NAME", "value": "Eberhard Graether" }, { "context": "ance = 0\n @maxDistance = I...
src/app/editors/visualEditor/trackballControls.coffee
tstone/CoffeeSCad
1
define (require) -> THREE = require 'three' ### @author Eberhard Graether / http://egraether.com/ ### THREE.TrackballControls = (object, domElement) -> # API #A #S #D # internals # for reset # events # methods # listeners keydown = (event) -> return if _this.enabled is false window.removeEventListener "keydown", keydown _prevState = _state if _state isnt STATE.NONE return else if event.keyCode is _this.keys[STATE.ROTATE] and not _this.noRotate _state = STATE.ROTATE else if event.keyCode is _this.keys[STATE.ZOOM] and not _this.noZoom _state = STATE.ZOOM else _state = STATE.PAN if event.keyCode is _this.keys[STATE.PAN] and not _this.noPan keyup = (event) -> return if _this.enabled is false _state = _prevState window.addEventListener "keydown", keydown, false mousedown = (event) -> return if _this.enabled is false event.preventDefault() event.stopPropagation() _state = event.button if _state is STATE.NONE if _state is STATE.ROTATE and not _this.noRotate _rotateStart = _rotateEnd = _this.getMouseProjectionOnBall(event.clientX, event.clientY) else if _state is STATE.ZOOM and not _this.noZoom _zoomStart = _zoomEnd = _this.getMouseOnScreen(event.clientX, event.clientY) else _panStart = _panEnd = _this.getMouseOnScreen(event.clientX, event.clientY) if _state is STATE.PAN and not _this.noPan document.addEventListener "mousemove", mousemove, false document.addEventListener "mouseup", mouseup, false mousemove = (event) -> return if _this.enabled is false event.preventDefault() event.stopPropagation() if _state is STATE.ROTATE and not _this.noRotate _rotateEnd = _this.getMouseProjectionOnBall(event.clientX, event.clientY) else if _state is STATE.ZOOM and not _this.noZoom _zoomEnd = _this.getMouseOnScreen(event.clientX, event.clientY) else _panEnd = _this.getMouseOnScreen(event.clientX, event.clientY) if _state is STATE.PAN and not _this.noPan mouseup = (event) -> return if _this.enabled is false event.preventDefault() event.stopPropagation() _state = STATE.NONE document.removeEventListener "mousemove", mousemove document.removeEventListener "mouseup", mouseup mousewheel = (event) -> return if _this.enabled is false event.preventDefault() event.stopPropagation() delta = 0 if event.wheelDelta # WebKit / Opera / Explorer 9 delta = event.wheelDelta / 40 # Firefox else delta = -event.detail / 3 if event.detail _zoomStart.y += (1 / delta) * 0.05 touchstart = (event) -> return if _this.enabled is false switch event.touches.length when 1 _state = STATE.TOUCH_ROTATE _rotateStart = _rotateEnd = _this.getMouseProjectionOnBall(event.touches[0].pageX, event.touches[0].pageY) when 2 _state = STATE.TOUCH_ZOOM dx = event.touches[0].pageX - event.touches[1].pageX dy = event.touches[0].pageY - event.touches[1].pageY _touchZoomDistanceEnd = _touchZoomDistanceStart = Math.sqrt(dx * dx + dy * dy) when 3 _state = STATE.TOUCH_PAN _panStart = _panEnd = _this.getMouseOnScreen(event.touches[0].pageX, event.touches[0].pageY) else _state = STATE.NONE touchmove = (event) -> return if _this.enabled is false event.preventDefault() event.stopPropagation() switch event.touches.length when 1 _rotateEnd = _this.getMouseProjectionOnBall(event.touches[0].pageX, event.touches[0].pageY) when 2 dx = event.touches[0].pageX - event.touches[1].pageX dy = event.touches[0].pageY - event.touches[1].pageY _touchZoomDistanceEnd = Math.sqrt(dx * dx + dy * dy) when 3 _panEnd = _this.getMouseOnScreen(event.touches[0].pageX, event.touches[0].pageY) else _state = STATE.NONE touchend = (event) -> return if _this.enabled is false switch event.touches.length when 1 _rotateStart = _rotateEnd = _this.getMouseProjectionOnBall(event.touches[0].pageX, event.touches[0].pageY) when 2 _touchZoomDistanceStart = _touchZoomDistanceEnd = 0 when 3 _panStart = _panEnd = _this.getMouseOnScreen(event.touches[0].pageX, event.touches[0].pageY) _state = STATE.NONE THREE.EventDispatcher.call this _this = this STATE = NONE: -1 ROTATE: 0 ZOOM: 1 PAN: 2 TOUCH_ROTATE: 3 TOUCH_ZOOM: 4 TOUCH_PAN: 5 @object = object @domElement = (if (domElement isnt `undefined`) then domElement else document) @enabled = true @screen = width: 0 height: 0 offsetLeft: 0 offsetTop: 0 @radius = (@screen.width + @screen.height) / 4 @rotateSpeed = 1.0 @zoomSpeed = 1.2 @panSpeed = 0.3 @noRotate = false @noZoom = false @noPan = false @staticMoving = false @dynamicDampingFactor = 0.2 @minDistance = 0 @maxDistance = Infinity @keys = [65, 83, 68] @target = new THREE.Vector3() lastPosition = new THREE.Vector3() _state = STATE.NONE _prevState = STATE.NONE _eye = new THREE.Vector3() _rotateStart = new THREE.Vector3() _rotateEnd = new THREE.Vector3() _zoomStart = new THREE.Vector2() _zoomEnd = new THREE.Vector2() _touchZoomDistanceStart = 0 _touchZoomDistanceEnd = 0 _panStart = new THREE.Vector2() _panEnd = new THREE.Vector2() @target0 = @target.clone() @position0 = @object.position.clone() @up0 = @object.up.clone() changeEvent = type: "change" @handleResize = -> @screen.width = window.innerWidth @screen.height = window.innerHeight @screen.offsetLeft = 0 @screen.offsetTop = 0 @radius = (@screen.width + @screen.height) / 4 @handleEvent = (event) -> this[event.type] event if typeof this[event.type] is "function" @getMouseOnScreen = (clientX, clientY) -> new THREE.Vector2((clientX - _this.screen.offsetLeft) / _this.radius * 0.5, (clientY - _this.screen.offsetTop) / _this.radius * 0.5) @getMouseProjectionOnBall = (clientX, clientY) -> mouseOnBall = new THREE.Vector3((clientX - _this.screen.width * 0.5 - _this.screen.offsetLeft) / _this.radius, (_this.screen.height * 0.5 + _this.screen.offsetTop - clientY) / _this.radius, 0.0) length = mouseOnBall.length() if length > 1.0 mouseOnBall.normalize() else mouseOnBall.z = Math.sqrt(1.0 - length * length) _eye.copy(_this.object.position).sub _this.target projection = _this.object.up.clone().setLength(mouseOnBall.y) projection.add _this.object.up.clone().cross(_eye).setLength(mouseOnBall.x) projection.add _eye.setLength(mouseOnBall.z) projection @rotateCamera = -> angle = Math.acos(_rotateStart.dot(_rotateEnd) / _rotateStart.length() / _rotateEnd.length()) if angle axis = (new THREE.Vector3()).crossVectors(_rotateStart, _rotateEnd).normalize() quaternion = new THREE.Quaternion() angle *= _this.rotateSpeed quaternion.setFromAxisAngle axis, -angle _eye.applyQuaternion quaternion _this.object.up.applyQuaternion quaternion _rotateEnd.applyQuaternion quaternion if _this.staticMoving _rotateStart.copy _rotateEnd else quaternion.setFromAxisAngle axis, angle * (_this.dynamicDampingFactor - 1.0) _rotateStart.applyQuaternion quaternion @zoomCamera = -> if _state is STATE.TOUCH_ZOOM factor = _touchZoomDistanceStart / _touchZoomDistanceEnd _touchZoomDistanceStart = _touchZoomDistanceEnd _eye.multiplyScalar factor else factor = 1.0 + (_zoomEnd.y - _zoomStart.y) * _this.zoomSpeed if factor isnt 1.0 and factor > 0.0 _eye.multiplyScalar factor if _this.staticMoving _zoomStart.copy _zoomEnd else _zoomStart.y += (_zoomEnd.y - _zoomStart.y) * @dynamicDampingFactor @panCamera = -> mouseChange = _panEnd.clone().sub(_panStart) if mouseChange.lengthSq() mouseChange.multiplyScalar _eye.length() * _this.panSpeed pan = _eye.clone().cross(_this.object.up).setLength(mouseChange.x) pan.add _this.object.up.clone().setLength(mouseChange.y) _this.object.position.add pan _this.target.add pan if _this.staticMoving _panStart = _panEnd else _panStart.add mouseChange.subVectors(_panEnd, _panStart).multiplyScalar(_this.dynamicDampingFactor) @checkDistances = -> if not _this.noZoom or not _this.noPan _this.object.position.setLength _this.maxDistance if _this.object.position.lengthSq() > _this.maxDistance * _this.maxDistance _this.object.position.addVectors _this.target, _eye.setLength(_this.minDistance) if _eye.lengthSq() < _this.minDistance * _this.minDistance @update = -> _eye.subVectors _this.object.position, _this.target _this.rotateCamera() unless _this.noRotate _this.zoomCamera() unless _this.noZoom _this.panCamera() unless _this.noPan _this.object.position.addVectors _this.target, _eye _this.checkDistances() _this.object.lookAt _this.target if lastPosition.distanceToSquared(_this.object.position) > 0 _this.dispatchEvent changeEvent lastPosition.copy _this.object.position @reset = -> _state = STATE.NONE _prevState = STATE.NONE _this.target.copy _this.target0 _this.object.position.copy _this.position0 _this.object.up.copy _this.up0 _eye.subVectors _this.object.position, _this.target _this.object.lookAt _this.target _this.dispatchEvent changeEvent lastPosition.copy _this.object.position @domElement.addEventListener "contextmenu", ((event) -> event.preventDefault() ), false @domElement.addEventListener "mousedown", mousedown, false @domElement.addEventListener "mousewheel", mousewheel, false @domElement.addEventListener "DOMMouseScroll", mousewheel, false # firefox @domElement.addEventListener "touchstart", touchstart, false @domElement.addEventListener "touchend", touchend, false @domElement.addEventListener "touchmove", touchmove, false window.addEventListener "keydown", keydown, false window.addEventListener "keyup", keyup, false @handleResize() return THREE.TrackballControls
112073
define (require) -> THREE = require 'three' ### @author <NAME> / http://egraether.com/ ### THREE.TrackballControls = (object, domElement) -> # API #A #S #D # internals # for reset # events # methods # listeners keydown = (event) -> return if _this.enabled is false window.removeEventListener "keydown", keydown _prevState = _state if _state isnt STATE.NONE return else if event.keyCode is _this.keys[STATE.ROTATE] and not _this.noRotate _state = STATE.ROTATE else if event.keyCode is _this.keys[STATE.ZOOM] and not _this.noZoom _state = STATE.ZOOM else _state = STATE.PAN if event.keyCode is _this.keys[STATE.PAN] and not _this.noPan keyup = (event) -> return if _this.enabled is false _state = _prevState window.addEventListener "keydown", keydown, false mousedown = (event) -> return if _this.enabled is false event.preventDefault() event.stopPropagation() _state = event.button if _state is STATE.NONE if _state is STATE.ROTATE and not _this.noRotate _rotateStart = _rotateEnd = _this.getMouseProjectionOnBall(event.clientX, event.clientY) else if _state is STATE.ZOOM and not _this.noZoom _zoomStart = _zoomEnd = _this.getMouseOnScreen(event.clientX, event.clientY) else _panStart = _panEnd = _this.getMouseOnScreen(event.clientX, event.clientY) if _state is STATE.PAN and not _this.noPan document.addEventListener "mousemove", mousemove, false document.addEventListener "mouseup", mouseup, false mousemove = (event) -> return if _this.enabled is false event.preventDefault() event.stopPropagation() if _state is STATE.ROTATE and not _this.noRotate _rotateEnd = _this.getMouseProjectionOnBall(event.clientX, event.clientY) else if _state is STATE.ZOOM and not _this.noZoom _zoomEnd = _this.getMouseOnScreen(event.clientX, event.clientY) else _panEnd = _this.getMouseOnScreen(event.clientX, event.clientY) if _state is STATE.PAN and not _this.noPan mouseup = (event) -> return if _this.enabled is false event.preventDefault() event.stopPropagation() _state = STATE.NONE document.removeEventListener "mousemove", mousemove document.removeEventListener "mouseup", mouseup mousewheel = (event) -> return if _this.enabled is false event.preventDefault() event.stopPropagation() delta = 0 if event.wheelDelta # WebKit / Opera / Explorer 9 delta = event.wheelDelta / 40 # Firefox else delta = -event.detail / 3 if event.detail _zoomStart.y += (1 / delta) * 0.05 touchstart = (event) -> return if _this.enabled is false switch event.touches.length when 1 _state = STATE.TOUCH_ROTATE _rotateStart = _rotateEnd = _this.getMouseProjectionOnBall(event.touches[0].pageX, event.touches[0].pageY) when 2 _state = STATE.TOUCH_ZOOM dx = event.touches[0].pageX - event.touches[1].pageX dy = event.touches[0].pageY - event.touches[1].pageY _touchZoomDistanceEnd = _touchZoomDistanceStart = Math.sqrt(dx * dx + dy * dy) when 3 _state = STATE.TOUCH_PAN _panStart = _panEnd = _this.getMouseOnScreen(event.touches[0].pageX, event.touches[0].pageY) else _state = STATE.NONE touchmove = (event) -> return if _this.enabled is false event.preventDefault() event.stopPropagation() switch event.touches.length when 1 _rotateEnd = _this.getMouseProjectionOnBall(event.touches[0].pageX, event.touches[0].pageY) when 2 dx = event.touches[0].pageX - event.touches[1].pageX dy = event.touches[0].pageY - event.touches[1].pageY _touchZoomDistanceEnd = Math.sqrt(dx * dx + dy * dy) when 3 _panEnd = _this.getMouseOnScreen(event.touches[0].pageX, event.touches[0].pageY) else _state = STATE.NONE touchend = (event) -> return if _this.enabled is false switch event.touches.length when 1 _rotateStart = _rotateEnd = _this.getMouseProjectionOnBall(event.touches[0].pageX, event.touches[0].pageY) when 2 _touchZoomDistanceStart = _touchZoomDistanceEnd = 0 when 3 _panStart = _panEnd = _this.getMouseOnScreen(event.touches[0].pageX, event.touches[0].pageY) _state = STATE.NONE THREE.EventDispatcher.call this _this = this STATE = NONE: -1 ROTATE: 0 ZOOM: 1 PAN: 2 TOUCH_ROTATE: 3 TOUCH_ZOOM: 4 TOUCH_PAN: 5 @object = object @domElement = (if (domElement isnt `undefined`) then domElement else document) @enabled = true @screen = width: 0 height: 0 offsetLeft: 0 offsetTop: 0 @radius = (@screen.width + @screen.height) / 4 @rotateSpeed = 1.0 @zoomSpeed = 1.2 @panSpeed = 0.3 @noRotate = false @noZoom = false @noPan = false @staticMoving = false @dynamicDampingFactor = 0.2 @minDistance = 0 @maxDistance = Infinity @keys = [<KEY>] @target = new THREE.Vector3() lastPosition = new THREE.Vector3() _state = STATE.NONE _prevState = STATE.NONE _eye = new THREE.Vector3() _rotateStart = new THREE.Vector3() _rotateEnd = new THREE.Vector3() _zoomStart = new THREE.Vector2() _zoomEnd = new THREE.Vector2() _touchZoomDistanceStart = 0 _touchZoomDistanceEnd = 0 _panStart = new THREE.Vector2() _panEnd = new THREE.Vector2() @target0 = @target.clone() @position0 = @object.position.clone() @up0 = @object.up.clone() changeEvent = type: "change" @handleResize = -> @screen.width = window.innerWidth @screen.height = window.innerHeight @screen.offsetLeft = 0 @screen.offsetTop = 0 @radius = (@screen.width + @screen.height) / 4 @handleEvent = (event) -> this[event.type] event if typeof this[event.type] is "function" @getMouseOnScreen = (clientX, clientY) -> new THREE.Vector2((clientX - _this.screen.offsetLeft) / _this.radius * 0.5, (clientY - _this.screen.offsetTop) / _this.radius * 0.5) @getMouseProjectionOnBall = (clientX, clientY) -> mouseOnBall = new THREE.Vector3((clientX - _this.screen.width * 0.5 - _this.screen.offsetLeft) / _this.radius, (_this.screen.height * 0.5 + _this.screen.offsetTop - clientY) / _this.radius, 0.0) length = mouseOnBall.length() if length > 1.0 mouseOnBall.normalize() else mouseOnBall.z = Math.sqrt(1.0 - length * length) _eye.copy(_this.object.position).sub _this.target projection = _this.object.up.clone().setLength(mouseOnBall.y) projection.add _this.object.up.clone().cross(_eye).setLength(mouseOnBall.x) projection.add _eye.setLength(mouseOnBall.z) projection @rotateCamera = -> angle = Math.acos(_rotateStart.dot(_rotateEnd) / _rotateStart.length() / _rotateEnd.length()) if angle axis = (new THREE.Vector3()).crossVectors(_rotateStart, _rotateEnd).normalize() quaternion = new THREE.Quaternion() angle *= _this.rotateSpeed quaternion.setFromAxisAngle axis, -angle _eye.applyQuaternion quaternion _this.object.up.applyQuaternion quaternion _rotateEnd.applyQuaternion quaternion if _this.staticMoving _rotateStart.copy _rotateEnd else quaternion.setFromAxisAngle axis, angle * (_this.dynamicDampingFactor - 1.0) _rotateStart.applyQuaternion quaternion @zoomCamera = -> if _state is STATE.TOUCH_ZOOM factor = _touchZoomDistanceStart / _touchZoomDistanceEnd _touchZoomDistanceStart = _touchZoomDistanceEnd _eye.multiplyScalar factor else factor = 1.0 + (_zoomEnd.y - _zoomStart.y) * _this.zoomSpeed if factor isnt 1.0 and factor > 0.0 _eye.multiplyScalar factor if _this.staticMoving _zoomStart.copy _zoomEnd else _zoomStart.y += (_zoomEnd.y - _zoomStart.y) * @dynamicDampingFactor @panCamera = -> mouseChange = _panEnd.clone().sub(_panStart) if mouseChange.lengthSq() mouseChange.multiplyScalar _eye.length() * _this.panSpeed pan = _eye.clone().cross(_this.object.up).setLength(mouseChange.x) pan.add _this.object.up.clone().setLength(mouseChange.y) _this.object.position.add pan _this.target.add pan if _this.staticMoving _panStart = _panEnd else _panStart.add mouseChange.subVectors(_panEnd, _panStart).multiplyScalar(_this.dynamicDampingFactor) @checkDistances = -> if not _this.noZoom or not _this.noPan _this.object.position.setLength _this.maxDistance if _this.object.position.lengthSq() > _this.maxDistance * _this.maxDistance _this.object.position.addVectors _this.target, _eye.setLength(_this.minDistance) if _eye.lengthSq() < _this.minDistance * _this.minDistance @update = -> _eye.subVectors _this.object.position, _this.target _this.rotateCamera() unless _this.noRotate _this.zoomCamera() unless _this.noZoom _this.panCamera() unless _this.noPan _this.object.position.addVectors _this.target, _eye _this.checkDistances() _this.object.lookAt _this.target if lastPosition.distanceToSquared(_this.object.position) > 0 _this.dispatchEvent changeEvent lastPosition.copy _this.object.position @reset = -> _state = STATE.NONE _prevState = STATE.NONE _this.target.copy _this.target0 _this.object.position.copy _this.position0 _this.object.up.copy _this.up0 _eye.subVectors _this.object.position, _this.target _this.object.lookAt _this.target _this.dispatchEvent changeEvent lastPosition.copy _this.object.position @domElement.addEventListener "contextmenu", ((event) -> event.preventDefault() ), false @domElement.addEventListener "mousedown", mousedown, false @domElement.addEventListener "mousewheel", mousewheel, false @domElement.addEventListener "DOMMouseScroll", mousewheel, false # firefox @domElement.addEventListener "touchstart", touchstart, false @domElement.addEventListener "touchend", touchend, false @domElement.addEventListener "touchmove", touchmove, false window.addEventListener "keydown", keydown, false window.addEventListener "keyup", keyup, false @handleResize() return THREE.TrackballControls
true
define (require) -> THREE = require 'three' ### @author PI:NAME:<NAME>END_PI / http://egraether.com/ ### THREE.TrackballControls = (object, domElement) -> # API #A #S #D # internals # for reset # events # methods # listeners keydown = (event) -> return if _this.enabled is false window.removeEventListener "keydown", keydown _prevState = _state if _state isnt STATE.NONE return else if event.keyCode is _this.keys[STATE.ROTATE] and not _this.noRotate _state = STATE.ROTATE else if event.keyCode is _this.keys[STATE.ZOOM] and not _this.noZoom _state = STATE.ZOOM else _state = STATE.PAN if event.keyCode is _this.keys[STATE.PAN] and not _this.noPan keyup = (event) -> return if _this.enabled is false _state = _prevState window.addEventListener "keydown", keydown, false mousedown = (event) -> return if _this.enabled is false event.preventDefault() event.stopPropagation() _state = event.button if _state is STATE.NONE if _state is STATE.ROTATE and not _this.noRotate _rotateStart = _rotateEnd = _this.getMouseProjectionOnBall(event.clientX, event.clientY) else if _state is STATE.ZOOM and not _this.noZoom _zoomStart = _zoomEnd = _this.getMouseOnScreen(event.clientX, event.clientY) else _panStart = _panEnd = _this.getMouseOnScreen(event.clientX, event.clientY) if _state is STATE.PAN and not _this.noPan document.addEventListener "mousemove", mousemove, false document.addEventListener "mouseup", mouseup, false mousemove = (event) -> return if _this.enabled is false event.preventDefault() event.stopPropagation() if _state is STATE.ROTATE and not _this.noRotate _rotateEnd = _this.getMouseProjectionOnBall(event.clientX, event.clientY) else if _state is STATE.ZOOM and not _this.noZoom _zoomEnd = _this.getMouseOnScreen(event.clientX, event.clientY) else _panEnd = _this.getMouseOnScreen(event.clientX, event.clientY) if _state is STATE.PAN and not _this.noPan mouseup = (event) -> return if _this.enabled is false event.preventDefault() event.stopPropagation() _state = STATE.NONE document.removeEventListener "mousemove", mousemove document.removeEventListener "mouseup", mouseup mousewheel = (event) -> return if _this.enabled is false event.preventDefault() event.stopPropagation() delta = 0 if event.wheelDelta # WebKit / Opera / Explorer 9 delta = event.wheelDelta / 40 # Firefox else delta = -event.detail / 3 if event.detail _zoomStart.y += (1 / delta) * 0.05 touchstart = (event) -> return if _this.enabled is false switch event.touches.length when 1 _state = STATE.TOUCH_ROTATE _rotateStart = _rotateEnd = _this.getMouseProjectionOnBall(event.touches[0].pageX, event.touches[0].pageY) when 2 _state = STATE.TOUCH_ZOOM dx = event.touches[0].pageX - event.touches[1].pageX dy = event.touches[0].pageY - event.touches[1].pageY _touchZoomDistanceEnd = _touchZoomDistanceStart = Math.sqrt(dx * dx + dy * dy) when 3 _state = STATE.TOUCH_PAN _panStart = _panEnd = _this.getMouseOnScreen(event.touches[0].pageX, event.touches[0].pageY) else _state = STATE.NONE touchmove = (event) -> return if _this.enabled is false event.preventDefault() event.stopPropagation() switch event.touches.length when 1 _rotateEnd = _this.getMouseProjectionOnBall(event.touches[0].pageX, event.touches[0].pageY) when 2 dx = event.touches[0].pageX - event.touches[1].pageX dy = event.touches[0].pageY - event.touches[1].pageY _touchZoomDistanceEnd = Math.sqrt(dx * dx + dy * dy) when 3 _panEnd = _this.getMouseOnScreen(event.touches[0].pageX, event.touches[0].pageY) else _state = STATE.NONE touchend = (event) -> return if _this.enabled is false switch event.touches.length when 1 _rotateStart = _rotateEnd = _this.getMouseProjectionOnBall(event.touches[0].pageX, event.touches[0].pageY) when 2 _touchZoomDistanceStart = _touchZoomDistanceEnd = 0 when 3 _panStart = _panEnd = _this.getMouseOnScreen(event.touches[0].pageX, event.touches[0].pageY) _state = STATE.NONE THREE.EventDispatcher.call this _this = this STATE = NONE: -1 ROTATE: 0 ZOOM: 1 PAN: 2 TOUCH_ROTATE: 3 TOUCH_ZOOM: 4 TOUCH_PAN: 5 @object = object @domElement = (if (domElement isnt `undefined`) then domElement else document) @enabled = true @screen = width: 0 height: 0 offsetLeft: 0 offsetTop: 0 @radius = (@screen.width + @screen.height) / 4 @rotateSpeed = 1.0 @zoomSpeed = 1.2 @panSpeed = 0.3 @noRotate = false @noZoom = false @noPan = false @staticMoving = false @dynamicDampingFactor = 0.2 @minDistance = 0 @maxDistance = Infinity @keys = [PI:KEY:<KEY>END_PI] @target = new THREE.Vector3() lastPosition = new THREE.Vector3() _state = STATE.NONE _prevState = STATE.NONE _eye = new THREE.Vector3() _rotateStart = new THREE.Vector3() _rotateEnd = new THREE.Vector3() _zoomStart = new THREE.Vector2() _zoomEnd = new THREE.Vector2() _touchZoomDistanceStart = 0 _touchZoomDistanceEnd = 0 _panStart = new THREE.Vector2() _panEnd = new THREE.Vector2() @target0 = @target.clone() @position0 = @object.position.clone() @up0 = @object.up.clone() changeEvent = type: "change" @handleResize = -> @screen.width = window.innerWidth @screen.height = window.innerHeight @screen.offsetLeft = 0 @screen.offsetTop = 0 @radius = (@screen.width + @screen.height) / 4 @handleEvent = (event) -> this[event.type] event if typeof this[event.type] is "function" @getMouseOnScreen = (clientX, clientY) -> new THREE.Vector2((clientX - _this.screen.offsetLeft) / _this.radius * 0.5, (clientY - _this.screen.offsetTop) / _this.radius * 0.5) @getMouseProjectionOnBall = (clientX, clientY) -> mouseOnBall = new THREE.Vector3((clientX - _this.screen.width * 0.5 - _this.screen.offsetLeft) / _this.radius, (_this.screen.height * 0.5 + _this.screen.offsetTop - clientY) / _this.radius, 0.0) length = mouseOnBall.length() if length > 1.0 mouseOnBall.normalize() else mouseOnBall.z = Math.sqrt(1.0 - length * length) _eye.copy(_this.object.position).sub _this.target projection = _this.object.up.clone().setLength(mouseOnBall.y) projection.add _this.object.up.clone().cross(_eye).setLength(mouseOnBall.x) projection.add _eye.setLength(mouseOnBall.z) projection @rotateCamera = -> angle = Math.acos(_rotateStart.dot(_rotateEnd) / _rotateStart.length() / _rotateEnd.length()) if angle axis = (new THREE.Vector3()).crossVectors(_rotateStart, _rotateEnd).normalize() quaternion = new THREE.Quaternion() angle *= _this.rotateSpeed quaternion.setFromAxisAngle axis, -angle _eye.applyQuaternion quaternion _this.object.up.applyQuaternion quaternion _rotateEnd.applyQuaternion quaternion if _this.staticMoving _rotateStart.copy _rotateEnd else quaternion.setFromAxisAngle axis, angle * (_this.dynamicDampingFactor - 1.0) _rotateStart.applyQuaternion quaternion @zoomCamera = -> if _state is STATE.TOUCH_ZOOM factor = _touchZoomDistanceStart / _touchZoomDistanceEnd _touchZoomDistanceStart = _touchZoomDistanceEnd _eye.multiplyScalar factor else factor = 1.0 + (_zoomEnd.y - _zoomStart.y) * _this.zoomSpeed if factor isnt 1.0 and factor > 0.0 _eye.multiplyScalar factor if _this.staticMoving _zoomStart.copy _zoomEnd else _zoomStart.y += (_zoomEnd.y - _zoomStart.y) * @dynamicDampingFactor @panCamera = -> mouseChange = _panEnd.clone().sub(_panStart) if mouseChange.lengthSq() mouseChange.multiplyScalar _eye.length() * _this.panSpeed pan = _eye.clone().cross(_this.object.up).setLength(mouseChange.x) pan.add _this.object.up.clone().setLength(mouseChange.y) _this.object.position.add pan _this.target.add pan if _this.staticMoving _panStart = _panEnd else _panStart.add mouseChange.subVectors(_panEnd, _panStart).multiplyScalar(_this.dynamicDampingFactor) @checkDistances = -> if not _this.noZoom or not _this.noPan _this.object.position.setLength _this.maxDistance if _this.object.position.lengthSq() > _this.maxDistance * _this.maxDistance _this.object.position.addVectors _this.target, _eye.setLength(_this.minDistance) if _eye.lengthSq() < _this.minDistance * _this.minDistance @update = -> _eye.subVectors _this.object.position, _this.target _this.rotateCamera() unless _this.noRotate _this.zoomCamera() unless _this.noZoom _this.panCamera() unless _this.noPan _this.object.position.addVectors _this.target, _eye _this.checkDistances() _this.object.lookAt _this.target if lastPosition.distanceToSquared(_this.object.position) > 0 _this.dispatchEvent changeEvent lastPosition.copy _this.object.position @reset = -> _state = STATE.NONE _prevState = STATE.NONE _this.target.copy _this.target0 _this.object.position.copy _this.position0 _this.object.up.copy _this.up0 _eye.subVectors _this.object.position, _this.target _this.object.lookAt _this.target _this.dispatchEvent changeEvent lastPosition.copy _this.object.position @domElement.addEventListener "contextmenu", ((event) -> event.preventDefault() ), false @domElement.addEventListener "mousedown", mousedown, false @domElement.addEventListener "mousewheel", mousewheel, false @domElement.addEventListener "DOMMouseScroll", mousewheel, false # firefox @domElement.addEventListener "touchstart", touchstart, false @domElement.addEventListener "touchend", touchend, false @domElement.addEventListener "touchmove", touchmove, false window.addEventListener "keydown", keydown, false window.addEventListener "keyup", keyup, false @handleResize() return THREE.TrackballControls
[ { "context": "is will either be a name or a description. E.g. \"Aunt Susan\", \"my cousin with the red hair\".\n @returns {Arra", "end": 4266, "score": 0.9898759126663208, "start": 4256, "tag": "NAME", "value": "Aunt Susan" } ]
src/fhir/familyhistory.coffee
luis1van/cql-execution-1
2
# Copyright (c) 2014 The MITRE Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # * Neither the name of HL7 nor the names of its contributors may be used to # endorse or promote products derived from this software without specific # prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. # IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, # INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT # NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. DT = require '../cql-datatypes' CORE = require('./core') Element = CORE.Element Resource = CORE.Resource Timing = CORE.Timing Period = CORE.Period Parameters = CORE.Parameters Coding = CORE.Coding Resource = CORE.Resource Range = CORE.Range Quantity = CORE.Quantity Attachment = CORE.Attachment BackboneElement = CORE.BackboneElement DomainResource = CORE.DomainResource ContactPoint = CORE.ContactPoint ElementDefinition = CORE.ElementDefinition Extension = CORE.Extension HumanName = CORE.HumanName Address = CORE.Address Ratio = CORE.Ratio SampledData = CORE.SampledData Reference = CORE.Reference CodeableConcept = CORE.CodeableConcept Identifier = CORE.Identifier Narrative = CORE.Narrative Element = CORE.Element ###* Embedded class @class FamilyHistoryRelationConditionComponent @exports FamilyHistoryRelationConditionComponent as FamilyHistoryRelationConditionComponent ### class FamilyHistoryRelationConditionComponent extends BackboneElement constructor: (@json) -> super(@json) ###* The actual condition specified. Could be a coded condition (like MI or Diabetes) or a less specific string like 'cancer' depending on how much is known about the condition and the capabilities of the creating system. @returns {CodeableConcept} ### type: -> if @json['type'] then new CodeableConcept(@json['type']) ###* Indicates what happened as a result of this condition. If the condition resulted in death, deceased date is captured on the relation. @returns {CodeableConcept} ### outcome: -> if @json['outcome'] then new CodeableConcept(@json['outcome']) onsetAge:-> new Quantity(@json['onsetAge']) ###* Either the age of onset, range of approximate age or descriptive string can be recorded. For conditions with multiple occurrences, this describes the first known occurrence. @returns {Range} ### onsetRange: -> if @json['onsetRange'] then new Range(@json['onsetRange']) ###* Either the age of onset, range of approximate age or descriptive string can be recorded. For conditions with multiple occurrences, this describes the first known occurrence. @returns {Array} an array of {@link String} objects ### onsetString:-> @json['onsetString'] ###* An area where general notes can be placed about this specific condition. @returns {Array} an array of {@link String} objects ### note:-> @json['note'] ###* Embedded class @class FamilyHistoryRelationComponent @exports FamilyHistoryRelationComponent as FamilyHistoryRelationComponent ### class FamilyHistoryRelationComponent extends BackboneElement constructor: (@json) -> super(@json) ###* This will either be a name or a description. E.g. "Aunt Susan", "my cousin with the red hair". @returns {Array} an array of {@link String} objects ### name:-> @json['name'] ###* The type of relationship this person has to the patient (father, mother, brother etc.). @returns {CodeableConcept} ### relationship: -> if @json['relationship'] then new CodeableConcept(@json['relationship']) ###* The actual or approximate date of birth of the relative. @returns {Period} ### bornPeriod: -> if @json['bornPeriod'] then new Period(@json['bornPeriod']) ###* The actual or approximate date of birth of the relative. @returns {Array} an array of {@link Date} objects ### bornDate:-> if @json['bornDate'] then DT.DateTime.parse(@json['bornDate']) ###* The actual or approximate date of birth of the relative. @returns {Array} an array of {@link String} objects ### bornString:-> @json['bornString'] ageAge:-> new Quantity(@json['ageAge']) ###* The actual or approximate age of the relative at the time the family history is recorded. @returns {Range} ### ageRange: -> if @json['ageRange'] then new Range(@json['ageRange']) ###* The actual or approximate age of the relative at the time the family history is recorded. @returns {Array} an array of {@link String} objects ### ageString:-> @json['ageString'] ###* If this resource is indicating that the related person is deceased, then an indicator of whether the person is deceased (yes) or not (no) or the age or age range or description of age at death - can be indicated here. If the reason for death is known, then it can be indicated in the outcome code of the condition - in this case the deceased property should still be set. @returns {Array} an array of {@link boolean} objects ### deceasedBoolean:-> @json['deceasedBoolean'] deceasedAge:-> new Quantity(@json['deceasedAge']) ###* If this resource is indicating that the related person is deceased, then an indicator of whether the person is deceased (yes) or not (no) or the age or age range or description of age at death - can be indicated here. If the reason for death is known, then it can be indicated in the outcome code of the condition - in this case the deceased property should still be set. @returns {Range} ### deceasedRange: -> if @json['deceasedRange'] then new Range(@json['deceasedRange']) ###* If this resource is indicating that the related person is deceased, then an indicator of whether the person is deceased (yes) or not (no) or the age or age range or description of age at death - can be indicated here. If the reason for death is known, then it can be indicated in the outcome code of the condition - in this case the deceased property should still be set. @returns {Array} an array of {@link Date} objects ### deceasedDate:-> if @json['deceasedDate'] then DT.DateTime.parse(@json['deceasedDate']) ###* If this resource is indicating that the related person is deceased, then an indicator of whether the person is deceased (yes) or not (no) or the age or age range or description of age at death - can be indicated here. If the reason for death is known, then it can be indicated in the outcome code of the condition - in this case the deceased property should still be set. @returns {Array} an array of {@link String} objects ### deceasedString:-> @json['deceasedString'] ###* This property allows a non condition-specific note to the made about the related person. Ideally, the note would be in the condition property, but this is not always possible. @returns {Array} an array of {@link String} objects ### note:-> @json['note'] ###* The significant Conditions (or condition) that the family member had. This is a repeating section to allow a system to represent more than one condition per resource, though there is nothing stopping multiple resources - one per condition. @returns {Array} an array of {@link FamilyHistoryRelationConditionComponent} objects ### condition: -> if @json['condition'] for item in @json['condition'] new FamilyHistoryRelationConditionComponent(item) ###* Significant health events and conditions for people related to the subject relevant in the context of care for the subject. @class FamilyHistory @exports FamilyHistory as FamilyHistory ### class FamilyHistory extends DomainResource constructor: (@json) -> super(@json) ###* This records identifiers associated with this family history record that are defined by business processes and/ or used to refer to it when a direct URL reference to the resource itself is not appropriate (e.g. in CDA documents, or in written / printed documentation). @returns {Array} an array of {@link Identifier} objects ### identifier: -> if @json['identifier'] for item in @json['identifier'] new Identifier(item) ###* The person who this history concerns. @returns {Reference} ### patient: -> if @json['patient'] then new Reference(@json['patient']) ###* The date (and possibly time) when the family history was taken. @returns {Array} an array of {@link Date} objects ### date:-> if @json['date'] then DT.DateTime.parse(@json['date']) ###* Conveys information about family history not specific to individual relations. @returns {Array} an array of {@link String} objects ### note:-> @json['note'] ###* The related person. Each FamilyHistory resource contains the entire family history for a single person. @returns {Array} an array of {@link FamilyHistoryRelationComponent} objects ### relation: -> if @json['relation'] for item in @json['relation'] new FamilyHistoryRelationComponent(item) module.exports.FamilyHistory = FamilyHistory
129160
# Copyright (c) 2014 The MITRE Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # * Neither the name of HL7 nor the names of its contributors may be used to # endorse or promote products derived from this software without specific # prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. # IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, # INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT # NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. DT = require '../cql-datatypes' CORE = require('./core') Element = CORE.Element Resource = CORE.Resource Timing = CORE.Timing Period = CORE.Period Parameters = CORE.Parameters Coding = CORE.Coding Resource = CORE.Resource Range = CORE.Range Quantity = CORE.Quantity Attachment = CORE.Attachment BackboneElement = CORE.BackboneElement DomainResource = CORE.DomainResource ContactPoint = CORE.ContactPoint ElementDefinition = CORE.ElementDefinition Extension = CORE.Extension HumanName = CORE.HumanName Address = CORE.Address Ratio = CORE.Ratio SampledData = CORE.SampledData Reference = CORE.Reference CodeableConcept = CORE.CodeableConcept Identifier = CORE.Identifier Narrative = CORE.Narrative Element = CORE.Element ###* Embedded class @class FamilyHistoryRelationConditionComponent @exports FamilyHistoryRelationConditionComponent as FamilyHistoryRelationConditionComponent ### class FamilyHistoryRelationConditionComponent extends BackboneElement constructor: (@json) -> super(@json) ###* The actual condition specified. Could be a coded condition (like MI or Diabetes) or a less specific string like 'cancer' depending on how much is known about the condition and the capabilities of the creating system. @returns {CodeableConcept} ### type: -> if @json['type'] then new CodeableConcept(@json['type']) ###* Indicates what happened as a result of this condition. If the condition resulted in death, deceased date is captured on the relation. @returns {CodeableConcept} ### outcome: -> if @json['outcome'] then new CodeableConcept(@json['outcome']) onsetAge:-> new Quantity(@json['onsetAge']) ###* Either the age of onset, range of approximate age or descriptive string can be recorded. For conditions with multiple occurrences, this describes the first known occurrence. @returns {Range} ### onsetRange: -> if @json['onsetRange'] then new Range(@json['onsetRange']) ###* Either the age of onset, range of approximate age or descriptive string can be recorded. For conditions with multiple occurrences, this describes the first known occurrence. @returns {Array} an array of {@link String} objects ### onsetString:-> @json['onsetString'] ###* An area where general notes can be placed about this specific condition. @returns {Array} an array of {@link String} objects ### note:-> @json['note'] ###* Embedded class @class FamilyHistoryRelationComponent @exports FamilyHistoryRelationComponent as FamilyHistoryRelationComponent ### class FamilyHistoryRelationComponent extends BackboneElement constructor: (@json) -> super(@json) ###* This will either be a name or a description. E.g. "<NAME>", "my cousin with the red hair". @returns {Array} an array of {@link String} objects ### name:-> @json['name'] ###* The type of relationship this person has to the patient (father, mother, brother etc.). @returns {CodeableConcept} ### relationship: -> if @json['relationship'] then new CodeableConcept(@json['relationship']) ###* The actual or approximate date of birth of the relative. @returns {Period} ### bornPeriod: -> if @json['bornPeriod'] then new Period(@json['bornPeriod']) ###* The actual or approximate date of birth of the relative. @returns {Array} an array of {@link Date} objects ### bornDate:-> if @json['bornDate'] then DT.DateTime.parse(@json['bornDate']) ###* The actual or approximate date of birth of the relative. @returns {Array} an array of {@link String} objects ### bornString:-> @json['bornString'] ageAge:-> new Quantity(@json['ageAge']) ###* The actual or approximate age of the relative at the time the family history is recorded. @returns {Range} ### ageRange: -> if @json['ageRange'] then new Range(@json['ageRange']) ###* The actual or approximate age of the relative at the time the family history is recorded. @returns {Array} an array of {@link String} objects ### ageString:-> @json['ageString'] ###* If this resource is indicating that the related person is deceased, then an indicator of whether the person is deceased (yes) or not (no) or the age or age range or description of age at death - can be indicated here. If the reason for death is known, then it can be indicated in the outcome code of the condition - in this case the deceased property should still be set. @returns {Array} an array of {@link boolean} objects ### deceasedBoolean:-> @json['deceasedBoolean'] deceasedAge:-> new Quantity(@json['deceasedAge']) ###* If this resource is indicating that the related person is deceased, then an indicator of whether the person is deceased (yes) or not (no) or the age or age range or description of age at death - can be indicated here. If the reason for death is known, then it can be indicated in the outcome code of the condition - in this case the deceased property should still be set. @returns {Range} ### deceasedRange: -> if @json['deceasedRange'] then new Range(@json['deceasedRange']) ###* If this resource is indicating that the related person is deceased, then an indicator of whether the person is deceased (yes) or not (no) or the age or age range or description of age at death - can be indicated here. If the reason for death is known, then it can be indicated in the outcome code of the condition - in this case the deceased property should still be set. @returns {Array} an array of {@link Date} objects ### deceasedDate:-> if @json['deceasedDate'] then DT.DateTime.parse(@json['deceasedDate']) ###* If this resource is indicating that the related person is deceased, then an indicator of whether the person is deceased (yes) or not (no) or the age or age range or description of age at death - can be indicated here. If the reason for death is known, then it can be indicated in the outcome code of the condition - in this case the deceased property should still be set. @returns {Array} an array of {@link String} objects ### deceasedString:-> @json['deceasedString'] ###* This property allows a non condition-specific note to the made about the related person. Ideally, the note would be in the condition property, but this is not always possible. @returns {Array} an array of {@link String} objects ### note:-> @json['note'] ###* The significant Conditions (or condition) that the family member had. This is a repeating section to allow a system to represent more than one condition per resource, though there is nothing stopping multiple resources - one per condition. @returns {Array} an array of {@link FamilyHistoryRelationConditionComponent} objects ### condition: -> if @json['condition'] for item in @json['condition'] new FamilyHistoryRelationConditionComponent(item) ###* Significant health events and conditions for people related to the subject relevant in the context of care for the subject. @class FamilyHistory @exports FamilyHistory as FamilyHistory ### class FamilyHistory extends DomainResource constructor: (@json) -> super(@json) ###* This records identifiers associated with this family history record that are defined by business processes and/ or used to refer to it when a direct URL reference to the resource itself is not appropriate (e.g. in CDA documents, or in written / printed documentation). @returns {Array} an array of {@link Identifier} objects ### identifier: -> if @json['identifier'] for item in @json['identifier'] new Identifier(item) ###* The person who this history concerns. @returns {Reference} ### patient: -> if @json['patient'] then new Reference(@json['patient']) ###* The date (and possibly time) when the family history was taken. @returns {Array} an array of {@link Date} objects ### date:-> if @json['date'] then DT.DateTime.parse(@json['date']) ###* Conveys information about family history not specific to individual relations. @returns {Array} an array of {@link String} objects ### note:-> @json['note'] ###* The related person. Each FamilyHistory resource contains the entire family history for a single person. @returns {Array} an array of {@link FamilyHistoryRelationComponent} objects ### relation: -> if @json['relation'] for item in @json['relation'] new FamilyHistoryRelationComponent(item) module.exports.FamilyHistory = FamilyHistory
true
# Copyright (c) 2014 The MITRE Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # * Neither the name of HL7 nor the names of its contributors may be used to # endorse or promote products derived from this software without specific # prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. # IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, # INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT # NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. DT = require '../cql-datatypes' CORE = require('./core') Element = CORE.Element Resource = CORE.Resource Timing = CORE.Timing Period = CORE.Period Parameters = CORE.Parameters Coding = CORE.Coding Resource = CORE.Resource Range = CORE.Range Quantity = CORE.Quantity Attachment = CORE.Attachment BackboneElement = CORE.BackboneElement DomainResource = CORE.DomainResource ContactPoint = CORE.ContactPoint ElementDefinition = CORE.ElementDefinition Extension = CORE.Extension HumanName = CORE.HumanName Address = CORE.Address Ratio = CORE.Ratio SampledData = CORE.SampledData Reference = CORE.Reference CodeableConcept = CORE.CodeableConcept Identifier = CORE.Identifier Narrative = CORE.Narrative Element = CORE.Element ###* Embedded class @class FamilyHistoryRelationConditionComponent @exports FamilyHistoryRelationConditionComponent as FamilyHistoryRelationConditionComponent ### class FamilyHistoryRelationConditionComponent extends BackboneElement constructor: (@json) -> super(@json) ###* The actual condition specified. Could be a coded condition (like MI or Diabetes) or a less specific string like 'cancer' depending on how much is known about the condition and the capabilities of the creating system. @returns {CodeableConcept} ### type: -> if @json['type'] then new CodeableConcept(@json['type']) ###* Indicates what happened as a result of this condition. If the condition resulted in death, deceased date is captured on the relation. @returns {CodeableConcept} ### outcome: -> if @json['outcome'] then new CodeableConcept(@json['outcome']) onsetAge:-> new Quantity(@json['onsetAge']) ###* Either the age of onset, range of approximate age or descriptive string can be recorded. For conditions with multiple occurrences, this describes the first known occurrence. @returns {Range} ### onsetRange: -> if @json['onsetRange'] then new Range(@json['onsetRange']) ###* Either the age of onset, range of approximate age or descriptive string can be recorded. For conditions with multiple occurrences, this describes the first known occurrence. @returns {Array} an array of {@link String} objects ### onsetString:-> @json['onsetString'] ###* An area where general notes can be placed about this specific condition. @returns {Array} an array of {@link String} objects ### note:-> @json['note'] ###* Embedded class @class FamilyHistoryRelationComponent @exports FamilyHistoryRelationComponent as FamilyHistoryRelationComponent ### class FamilyHistoryRelationComponent extends BackboneElement constructor: (@json) -> super(@json) ###* This will either be a name or a description. E.g. "PI:NAME:<NAME>END_PI", "my cousin with the red hair". @returns {Array} an array of {@link String} objects ### name:-> @json['name'] ###* The type of relationship this person has to the patient (father, mother, brother etc.). @returns {CodeableConcept} ### relationship: -> if @json['relationship'] then new CodeableConcept(@json['relationship']) ###* The actual or approximate date of birth of the relative. @returns {Period} ### bornPeriod: -> if @json['bornPeriod'] then new Period(@json['bornPeriod']) ###* The actual or approximate date of birth of the relative. @returns {Array} an array of {@link Date} objects ### bornDate:-> if @json['bornDate'] then DT.DateTime.parse(@json['bornDate']) ###* The actual or approximate date of birth of the relative. @returns {Array} an array of {@link String} objects ### bornString:-> @json['bornString'] ageAge:-> new Quantity(@json['ageAge']) ###* The actual or approximate age of the relative at the time the family history is recorded. @returns {Range} ### ageRange: -> if @json['ageRange'] then new Range(@json['ageRange']) ###* The actual or approximate age of the relative at the time the family history is recorded. @returns {Array} an array of {@link String} objects ### ageString:-> @json['ageString'] ###* If this resource is indicating that the related person is deceased, then an indicator of whether the person is deceased (yes) or not (no) or the age or age range or description of age at death - can be indicated here. If the reason for death is known, then it can be indicated in the outcome code of the condition - in this case the deceased property should still be set. @returns {Array} an array of {@link boolean} objects ### deceasedBoolean:-> @json['deceasedBoolean'] deceasedAge:-> new Quantity(@json['deceasedAge']) ###* If this resource is indicating that the related person is deceased, then an indicator of whether the person is deceased (yes) or not (no) or the age or age range or description of age at death - can be indicated here. If the reason for death is known, then it can be indicated in the outcome code of the condition - in this case the deceased property should still be set. @returns {Range} ### deceasedRange: -> if @json['deceasedRange'] then new Range(@json['deceasedRange']) ###* If this resource is indicating that the related person is deceased, then an indicator of whether the person is deceased (yes) or not (no) or the age or age range or description of age at death - can be indicated here. If the reason for death is known, then it can be indicated in the outcome code of the condition - in this case the deceased property should still be set. @returns {Array} an array of {@link Date} objects ### deceasedDate:-> if @json['deceasedDate'] then DT.DateTime.parse(@json['deceasedDate']) ###* If this resource is indicating that the related person is deceased, then an indicator of whether the person is deceased (yes) or not (no) or the age or age range or description of age at death - can be indicated here. If the reason for death is known, then it can be indicated in the outcome code of the condition - in this case the deceased property should still be set. @returns {Array} an array of {@link String} objects ### deceasedString:-> @json['deceasedString'] ###* This property allows a non condition-specific note to the made about the related person. Ideally, the note would be in the condition property, but this is not always possible. @returns {Array} an array of {@link String} objects ### note:-> @json['note'] ###* The significant Conditions (or condition) that the family member had. This is a repeating section to allow a system to represent more than one condition per resource, though there is nothing stopping multiple resources - one per condition. @returns {Array} an array of {@link FamilyHistoryRelationConditionComponent} objects ### condition: -> if @json['condition'] for item in @json['condition'] new FamilyHistoryRelationConditionComponent(item) ###* Significant health events and conditions for people related to the subject relevant in the context of care for the subject. @class FamilyHistory @exports FamilyHistory as FamilyHistory ### class FamilyHistory extends DomainResource constructor: (@json) -> super(@json) ###* This records identifiers associated with this family history record that are defined by business processes and/ or used to refer to it when a direct URL reference to the resource itself is not appropriate (e.g. in CDA documents, or in written / printed documentation). @returns {Array} an array of {@link Identifier} objects ### identifier: -> if @json['identifier'] for item in @json['identifier'] new Identifier(item) ###* The person who this history concerns. @returns {Reference} ### patient: -> if @json['patient'] then new Reference(@json['patient']) ###* The date (and possibly time) when the family history was taken. @returns {Array} an array of {@link Date} objects ### date:-> if @json['date'] then DT.DateTime.parse(@json['date']) ###* Conveys information about family history not specific to individual relations. @returns {Array} an array of {@link String} objects ### note:-> @json['note'] ###* The related person. Each FamilyHistory resource contains the entire family history for a single person. @returns {Array} an array of {@link FamilyHistoryRelationComponent} objects ### relation: -> if @json['relation'] for item in @json['relation'] new FamilyHistoryRelationComponent(item) module.exports.FamilyHistory = FamilyHistory
[ { "context": "gramming for microcontrollers\n# Copyright (c) 2013 Jon Nordby <jononor@gmail.com>\n# MicroFlo may be freely dist", "end": 90, "score": 0.9998406767845154, "start": 80, "tag": "NAME", "value": "Jon Nordby" }, { "context": "microcontrollers\n# Copyright (c) 2013 Jon Nord...
test/generate.coffee
microflo/microflo
136
### MicroFlo - Flow-Based Programming for microcontrollers # Copyright (c) 2013 Jon Nordby <jononor@gmail.com> # MicroFlo may be freely distributed under the MIT license ### generate = null if typeof process != 'undefined' and process.execPath and process.execPath.indexOf('node') != -1 chai = require('chai') generate = require('../lib/generate') else generate = require('microflo/lib/generate') describe 'C++ header file generation', -> describe 'enumeration without values', -> out = generate.generateEnum 'MyEnum', 'My', Foo: {} Bar: {} it 'should become a C++ enum', -> chai.expect(out).to.equal 'enum MyEnum {\n MyFoo,\n MyBar\n};\n'
25041
### MicroFlo - Flow-Based Programming for microcontrollers # Copyright (c) 2013 <NAME> <<EMAIL>> # MicroFlo may be freely distributed under the MIT license ### generate = null if typeof process != 'undefined' and process.execPath and process.execPath.indexOf('node') != -1 chai = require('chai') generate = require('../lib/generate') else generate = require('microflo/lib/generate') describe 'C++ header file generation', -> describe 'enumeration without values', -> out = generate.generateEnum 'MyEnum', 'My', Foo: {} Bar: {} it 'should become a C++ enum', -> chai.expect(out).to.equal 'enum MyEnum {\n MyFoo,\n MyBar\n};\n'
true
### MicroFlo - Flow-Based Programming for microcontrollers # Copyright (c) 2013 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # MicroFlo may be freely distributed under the MIT license ### generate = null if typeof process != 'undefined' and process.execPath and process.execPath.indexOf('node') != -1 chai = require('chai') generate = require('../lib/generate') else generate = require('microflo/lib/generate') describe 'C++ header file generation', -> describe 'enumeration without values', -> out = generate.generateEnum 'MyEnum', 'My', Foo: {} Bar: {} it 'should become a C++ enum', -> chai.expect(out).to.equal 'enum MyEnum {\n MyFoo,\n MyBar\n};\n'
[ { "context": "\"_id\": \"538755f3cb18e70000712278\",\n \"name\": \"Jitters\",\n \"original\": \"530d8a70286ddc0000cc5d", "end": 826, "score": 0.5668671727180481, "start": 825, "tag": "NAME", "value": "J" }, { "context": "_id\": \"538755f3cb18e70000712278\",\n \"name\":...
test/demo/views/editor/component/AddThangComponentsModal.demo.coffee
JurianLock/codecombat
1
AddThangComponentsModal = require('views/editor/component/AddThangComponentsModal') response = [ { "_id": "53c46b06bd135abdb79a4f32", "name": "InventorySomething", "original": "53c46ae2bd135abdb79a4f2f", "official": false, "configSchema": { "additionalProperties": false, "type": "object" }, "propertyDocumentation": [], "dependencies": [], "code": "class AttacksSelf extends Component\n @className: 'AttacksSelf'\n chooseAction: ->\n @attack @", "description": "This Component makes the Thang attack itself.", "system": "inventory", "version": { "minor": 2, "major": 0, "isLatestMajor": true, "isLatestMinor": true } }, { "_id": "538755f3cb18e70000712278", "name": "Jitters", "original": "530d8a70286ddc0000cc5d9d", "official": false, "configSchema": { "additionalProperties": false, "type": "object" }, "propertyDocumentation": [], "dependencies": [], "code": "class AttacksSelf extends Component\n @className: 'AttacksSelf'\n chooseAction: ->\n @attack @", "description": "This Component makes the Thang jitter. Or, it would, if it did anything yet. (Test Component.)", "system": "movement", "version": { "minor": 3, "major": 0, "isLatestMajor": true, "isLatestMinor": true } }, { "_id": "538755f3cb18e70000712279", "name": "DelaysExistence", "original": "524cbbea3ea855e0ab00003d", "official": false, "configSchema": { "additionalProperties": false, "type": "object" }, "propertyDocumentation": [], "dependencies": [], "code": "class AttacksSelf extends Component\n @className: 'AttacksSelf'\n chooseAction: ->\n @attack @", "description": "This Thang doesn't show up right away.", "system": "existence", "version": { "minor": 25, "major": 0, "isLatestMajor": true, "isLatestMinor": true } }, { "_id": "538755f3cb18e7000071227a", "name": "RunsInCircles", "original": "52438245ef76c3dcf5000004", "official": false, "configSchema": { "additionalProperties": false, "type": "object" }, "propertyDocumentation": [], "dependencies": [], "code": "class AttacksSelf extends Component\n @className: 'AttacksSelf'\n chooseAction: ->\n @attack @", "description": "This Thang runs in circles.", "system": "ai", "version": { "minor": 39, "major": 0, "isLatestMajor": true, "isLatestMinor": true } }, { "_id": "538755f3cb18e7000071227b", "name": "AttacksSelf", "original": "52437b061d9e25b8dc000004", "official": false, "configSchema": { "additionalProperties": false, "type": "object" }, "propertyDocumentation": [], "dependencies": [], "code": "class AttacksSelf extends Component\n @className: 'AttacksSelf'\n chooseAction: ->\n @attack @", "description": "This Component makes the Thang attack itself.", "system": "ai", "version": { "minor": 41, "major": 0, "isLatestMajor": true, "isLatestMinor": true } }, { "_id": "538755f3cb18e7000071227d", "name": "FollowsNearestFriend", "original": "52437e31ef76c3dcf5000002", "official": false, "configSchema": { "additionalProperties": false, "type": "object" }, "propertyDocumentation": [], "dependencies": [], "code": "class AttacksSelf extends Component\n @className: 'AttacksSelf'\n chooseAction: ->\n @attack @", "description": "This Thang follows the nearest friend.", "system": "ai", "version": { "minor": 39, "major": 0, "isLatestMajor": true, "isLatestMinor": true } }, { "_id": "538755f4cb18e7000071227e", "name": "FollowsNearest", "original": "52437c851d9e25b8dc000008", "official": false, "configSchema": { "additionalProperties": false, "type": "object" }, "propertyDocumentation": [], "dependencies": [], "code": "class AttacksSelf extends Component\n @className: 'AttacksSelf'\n chooseAction: ->\n @attack @", "description": "This Thang follows the nearest other Thang.", "system": "ai", "version": { "minor": 39, "major": 0, "isLatestMajor": true, "isLatestMinor": true } } ] module.exports = -> view = new AddThangComponentsModal({skipOriginals:['52437c851d9e25b8dc000008']}) # FollowsNearest original console.log jasmine.Ajax.requests.all() jasmine.Ajax.requests.mostRecent().response({status: 200, responseText: JSON.stringify(response)}) view.render() return view
225227
AddThangComponentsModal = require('views/editor/component/AddThangComponentsModal') response = [ { "_id": "53c46b06bd135abdb79a4f32", "name": "InventorySomething", "original": "53c46ae2bd135abdb79a4f2f", "official": false, "configSchema": { "additionalProperties": false, "type": "object" }, "propertyDocumentation": [], "dependencies": [], "code": "class AttacksSelf extends Component\n @className: 'AttacksSelf'\n chooseAction: ->\n @attack @", "description": "This Component makes the Thang attack itself.", "system": "inventory", "version": { "minor": 2, "major": 0, "isLatestMajor": true, "isLatestMinor": true } }, { "_id": "538755f3cb18e70000712278", "name": "<NAME>itters", "original": "530d8a70286ddc0000cc5d9d", "official": false, "configSchema": { "additionalProperties": false, "type": "object" }, "propertyDocumentation": [], "dependencies": [], "code": "class AttacksSelf extends Component\n @className: 'AttacksSelf'\n chooseAction: ->\n @attack @", "description": "This Component makes the Thang jitter. Or, it would, if it did anything yet. (Test Component.)", "system": "movement", "version": { "minor": 3, "major": 0, "isLatestMajor": true, "isLatestMinor": true } }, { "_id": "538755f3cb18e70000712279", "name": "DelaysExistence", "original": "524cbbea3ea855e0ab00003d", "official": false, "configSchema": { "additionalProperties": false, "type": "object" }, "propertyDocumentation": [], "dependencies": [], "code": "class AttacksSelf extends Component\n @className: 'AttacksSelf'\n chooseAction: ->\n @attack @", "description": "This Thang doesn't show up right away.", "system": "existence", "version": { "minor": 25, "major": 0, "isLatestMajor": true, "isLatestMinor": true } }, { "_id": "538755f3cb18e7000071227a", "name": "RunsInCircles", "original": "52438245ef76c3dcf5000004", "official": false, "configSchema": { "additionalProperties": false, "type": "object" }, "propertyDocumentation": [], "dependencies": [], "code": "class AttacksSelf extends Component\n @className: 'AttacksSelf'\n chooseAction: ->\n @attack @", "description": "This Thang runs in circles.", "system": "ai", "version": { "minor": 39, "major": 0, "isLatestMajor": true, "isLatestMinor": true } }, { "_id": "538755f3cb18e7000071227b", "name": "AttacksSelf", "original": "52437b061d9e25b8dc000004", "official": false, "configSchema": { "additionalProperties": false, "type": "object" }, "propertyDocumentation": [], "dependencies": [], "code": "class AttacksSelf extends Component\n @className: 'AttacksSelf'\n chooseAction: ->\n @attack @", "description": "This Component makes the Thang attack itself.", "system": "ai", "version": { "minor": 41, "major": 0, "isLatestMajor": true, "isLatestMinor": true } }, { "_id": "538755f3cb18e7000071227d", "name": "FollowsNearestFriend", "original": "52437e31ef76c3dcf5000002", "official": false, "configSchema": { "additionalProperties": false, "type": "object" }, "propertyDocumentation": [], "dependencies": [], "code": "class AttacksSelf extends Component\n @className: 'AttacksSelf'\n chooseAction: ->\n @attack @", "description": "This Thang follows the nearest friend.", "system": "ai", "version": { "minor": 39, "major": 0, "isLatestMajor": true, "isLatestMinor": true } }, { "_id": "538755f4cb18e7000071227e", "name": "FollowsNearest", "original": "52437c851d9e25b8dc000008", "official": false, "configSchema": { "additionalProperties": false, "type": "object" }, "propertyDocumentation": [], "dependencies": [], "code": "class AttacksSelf extends Component\n @className: 'AttacksSelf'\n chooseAction: ->\n @attack @", "description": "This Thang follows the nearest other Thang.", "system": "ai", "version": { "minor": 39, "major": 0, "isLatestMajor": true, "isLatestMinor": true } } ] module.exports = -> view = new AddThangComponentsModal({skipOriginals:['52437c851d9e25b8dc000008']}) # FollowsNearest original console.log jasmine.Ajax.requests.all() jasmine.Ajax.requests.mostRecent().response({status: 200, responseText: JSON.stringify(response)}) view.render() return view
true
AddThangComponentsModal = require('views/editor/component/AddThangComponentsModal') response = [ { "_id": "53c46b06bd135abdb79a4f32", "name": "InventorySomething", "original": "53c46ae2bd135abdb79a4f2f", "official": false, "configSchema": { "additionalProperties": false, "type": "object" }, "propertyDocumentation": [], "dependencies": [], "code": "class AttacksSelf extends Component\n @className: 'AttacksSelf'\n chooseAction: ->\n @attack @", "description": "This Component makes the Thang attack itself.", "system": "inventory", "version": { "minor": 2, "major": 0, "isLatestMajor": true, "isLatestMinor": true } }, { "_id": "538755f3cb18e70000712278", "name": "PI:NAME:<NAME>END_PIitters", "original": "530d8a70286ddc0000cc5d9d", "official": false, "configSchema": { "additionalProperties": false, "type": "object" }, "propertyDocumentation": [], "dependencies": [], "code": "class AttacksSelf extends Component\n @className: 'AttacksSelf'\n chooseAction: ->\n @attack @", "description": "This Component makes the Thang jitter. Or, it would, if it did anything yet. (Test Component.)", "system": "movement", "version": { "minor": 3, "major": 0, "isLatestMajor": true, "isLatestMinor": true } }, { "_id": "538755f3cb18e70000712279", "name": "DelaysExistence", "original": "524cbbea3ea855e0ab00003d", "official": false, "configSchema": { "additionalProperties": false, "type": "object" }, "propertyDocumentation": [], "dependencies": [], "code": "class AttacksSelf extends Component\n @className: 'AttacksSelf'\n chooseAction: ->\n @attack @", "description": "This Thang doesn't show up right away.", "system": "existence", "version": { "minor": 25, "major": 0, "isLatestMajor": true, "isLatestMinor": true } }, { "_id": "538755f3cb18e7000071227a", "name": "RunsInCircles", "original": "52438245ef76c3dcf5000004", "official": false, "configSchema": { "additionalProperties": false, "type": "object" }, "propertyDocumentation": [], "dependencies": [], "code": "class AttacksSelf extends Component\n @className: 'AttacksSelf'\n chooseAction: ->\n @attack @", "description": "This Thang runs in circles.", "system": "ai", "version": { "minor": 39, "major": 0, "isLatestMajor": true, "isLatestMinor": true } }, { "_id": "538755f3cb18e7000071227b", "name": "AttacksSelf", "original": "52437b061d9e25b8dc000004", "official": false, "configSchema": { "additionalProperties": false, "type": "object" }, "propertyDocumentation": [], "dependencies": [], "code": "class AttacksSelf extends Component\n @className: 'AttacksSelf'\n chooseAction: ->\n @attack @", "description": "This Component makes the Thang attack itself.", "system": "ai", "version": { "minor": 41, "major": 0, "isLatestMajor": true, "isLatestMinor": true } }, { "_id": "538755f3cb18e7000071227d", "name": "FollowsNearestFriend", "original": "52437e31ef76c3dcf5000002", "official": false, "configSchema": { "additionalProperties": false, "type": "object" }, "propertyDocumentation": [], "dependencies": [], "code": "class AttacksSelf extends Component\n @className: 'AttacksSelf'\n chooseAction: ->\n @attack @", "description": "This Thang follows the nearest friend.", "system": "ai", "version": { "minor": 39, "major": 0, "isLatestMajor": true, "isLatestMinor": true } }, { "_id": "538755f4cb18e7000071227e", "name": "FollowsNearest", "original": "52437c851d9e25b8dc000008", "official": false, "configSchema": { "additionalProperties": false, "type": "object" }, "propertyDocumentation": [], "dependencies": [], "code": "class AttacksSelf extends Component\n @className: 'AttacksSelf'\n chooseAction: ->\n @attack @", "description": "This Thang follows the nearest other Thang.", "system": "ai", "version": { "minor": 39, "major": 0, "isLatestMajor": true, "isLatestMinor": true } } ] module.exports = -> view = new AddThangComponentsModal({skipOriginals:['52437c851d9e25b8dc000008']}) # FollowsNearest original console.log jasmine.Ajax.requests.all() jasmine.Ajax.requests.mostRecent().response({status: 200, responseText: JSON.stringify(response)}) view.render() return view
[ { "context": "count++\n new kd.InputView\n placeholder : 'email@domain.com'\n name : \"invitee#{count}\"\n\n\n constr", "end": 254, "score": 0.9999197721481323, "start": 238, "tag": "EMAIL", "value": "email@domain.com" } ]
client/landing/site.landing/coffee/team/forms/teaminvitetabform.coffee
ezgikaysi/koding
1
kd = require 'kd' JView = require './../../core/jview' module.exports = class TeamInviteTabForm extends kd.FormView JView.mixin @prototype count = 0 createInput = -> count++ new kd.InputView placeholder : 'email@domain.com' name : "invitee#{count}" constructor: (options = {}, data) -> options.cssClass = 'clearfix' super options, data @label = new kd.LabelView title : 'Allow sign up and team discovery with a company email address' for : 'allow' @checkbox = new kd.InputView defaultValue : on type : 'checkbox' name : 'allow' label : @label @input1 = createInput() @input2 = createInput() @input3 = createInput() @add = new kd.ButtonView title : 'ADD INVITATION' style : 'TeamsModal-button compact TeamsModal-button--gray add' callback : @bound 'addInvitee' @button = new kd.ButtonView title : 'NEXT' style : 'TeamsModal-button TeamsModal-button--green' attributes : { testpath : 'invite-button' } type : 'submit' addInvitee: -> input = createInput() wrapper = new kd.CustomHTMLView { cssClass : 'login-input-view' } wrapper.addSubView input @addSubView wrapper, '.additional' input.setFocus() pistachio: -> """ <div class='login-input-view'>{{> @input1}}</div> <div class='login-input-view'>{{> @input2}}</div> <div class='login-input-view'>{{> @input3}}</div> <div class='additional'></div> {{> @add}} <p class='dim'>if you’d like, you can send invitations after you finish setting up your team.</p> {{> @button}} """
61540
kd = require 'kd' JView = require './../../core/jview' module.exports = class TeamInviteTabForm extends kd.FormView JView.mixin @prototype count = 0 createInput = -> count++ new kd.InputView placeholder : '<EMAIL>' name : "invitee#{count}" constructor: (options = {}, data) -> options.cssClass = 'clearfix' super options, data @label = new kd.LabelView title : 'Allow sign up and team discovery with a company email address' for : 'allow' @checkbox = new kd.InputView defaultValue : on type : 'checkbox' name : 'allow' label : @label @input1 = createInput() @input2 = createInput() @input3 = createInput() @add = new kd.ButtonView title : 'ADD INVITATION' style : 'TeamsModal-button compact TeamsModal-button--gray add' callback : @bound 'addInvitee' @button = new kd.ButtonView title : 'NEXT' style : 'TeamsModal-button TeamsModal-button--green' attributes : { testpath : 'invite-button' } type : 'submit' addInvitee: -> input = createInput() wrapper = new kd.CustomHTMLView { cssClass : 'login-input-view' } wrapper.addSubView input @addSubView wrapper, '.additional' input.setFocus() pistachio: -> """ <div class='login-input-view'>{{> @input1}}</div> <div class='login-input-view'>{{> @input2}}</div> <div class='login-input-view'>{{> @input3}}</div> <div class='additional'></div> {{> @add}} <p class='dim'>if you’d like, you can send invitations after you finish setting up your team.</p> {{> @button}} """
true
kd = require 'kd' JView = require './../../core/jview' module.exports = class TeamInviteTabForm extends kd.FormView JView.mixin @prototype count = 0 createInput = -> count++ new kd.InputView placeholder : 'PI:EMAIL:<EMAIL>END_PI' name : "invitee#{count}" constructor: (options = {}, data) -> options.cssClass = 'clearfix' super options, data @label = new kd.LabelView title : 'Allow sign up and team discovery with a company email address' for : 'allow' @checkbox = new kd.InputView defaultValue : on type : 'checkbox' name : 'allow' label : @label @input1 = createInput() @input2 = createInput() @input3 = createInput() @add = new kd.ButtonView title : 'ADD INVITATION' style : 'TeamsModal-button compact TeamsModal-button--gray add' callback : @bound 'addInvitee' @button = new kd.ButtonView title : 'NEXT' style : 'TeamsModal-button TeamsModal-button--green' attributes : { testpath : 'invite-button' } type : 'submit' addInvitee: -> input = createInput() wrapper = new kd.CustomHTMLView { cssClass : 'login-input-view' } wrapper.addSubView input @addSubView wrapper, '.additional' input.setFocus() pistachio: -> """ <div class='login-input-view'>{{> @input1}}</div> <div class='login-input-view'>{{> @input2}}</div> <div class='login-input-view'>{{> @input3}}</div> <div class='additional'></div> {{> @add}} <p class='dim'>if you’d like, you can send invitations after you finish setting up your team.</p> {{> @button}} """
[ { "context": "ched = memjs.Client.create(p.servers, username: p.username, password: p.password)\n else\n memcached = mem", "end": 784, "score": 0.542460024356842, "start": 776, "tag": "USERNAME", "value": "username" }, { "context": ".create(p.servers, username: p.username, passwo...
application/game/server/boot/render.coffee
darkoverlordofdata/games
0
# # * Render Liquid Templates # * # fs = require('fs') path = require('path') liquid = require('liquid.coffee') memjs = require('memjs') # # * Send the html # * # * # send = (res, html) -> res.writeHead 200, 'Content-Length' : html.length 'Content-Type' : 'text/html; charset=utf-8' res.write(html) res.end() return ### * used for {% extends 'layout' %} ### liquid.Template.fileSystem = root: path.resolve(__dirname, '../views') readTemplateFile: (view) -> filename = path.join(__dirname, '../views', view)+'.tpl' return fs.readFileSync(filename, 'utf-8') module.exports = (app, mod) -> if process.env.memcachedcloud_aaaeb? p = JSON.parse(process.env.memcachedcloud_aaaeb) memcached = memjs.Client.create(p.servers, username: p.username, password: p.password) else memcached = memjs.Client.create('localhost:11211') memcached.flush (err) -> # # * Render the template # * first look in cache # * # mod.render = (res, view, data = {}) -> ### * Get the latest flash message from the middleware ### data.messages = res.req.flash() memcached.get view, (err, html) -> if html isnt null console.log "%s bytes retrieved from cache", String(html).length send(res, html) return else filename = path.join(__dirname, '../views', view)+'.tpl' fs.readFile filename, 'utf-8', (err, content) -> return res.req.next(err) if err template = liquid.Template.parse(content) html = template.render(data) send(res, html) memcached.set view, html, (err) -> console.log err if err return return
204423
# # * Render Liquid Templates # * # fs = require('fs') path = require('path') liquid = require('liquid.coffee') memjs = require('memjs') # # * Send the html # * # * # send = (res, html) -> res.writeHead 200, 'Content-Length' : html.length 'Content-Type' : 'text/html; charset=utf-8' res.write(html) res.end() return ### * used for {% extends 'layout' %} ### liquid.Template.fileSystem = root: path.resolve(__dirname, '../views') readTemplateFile: (view) -> filename = path.join(__dirname, '../views', view)+'.tpl' return fs.readFileSync(filename, 'utf-8') module.exports = (app, mod) -> if process.env.memcachedcloud_aaaeb? p = JSON.parse(process.env.memcachedcloud_aaaeb) memcached = memjs.Client.create(p.servers, username: p.username, password: <PASSWORD>) else memcached = memjs.Client.create('localhost:11211') memcached.flush (err) -> # # * Render the template # * first look in cache # * # mod.render = (res, view, data = {}) -> ### * Get the latest flash message from the middleware ### data.messages = res.req.flash() memcached.get view, (err, html) -> if html isnt null console.log "%s bytes retrieved from cache", String(html).length send(res, html) return else filename = path.join(__dirname, '../views', view)+'.tpl' fs.readFile filename, 'utf-8', (err, content) -> return res.req.next(err) if err template = liquid.Template.parse(content) html = template.render(data) send(res, html) memcached.set view, html, (err) -> console.log err if err return return
true
# # * Render Liquid Templates # * # fs = require('fs') path = require('path') liquid = require('liquid.coffee') memjs = require('memjs') # # * Send the html # * # * # send = (res, html) -> res.writeHead 200, 'Content-Length' : html.length 'Content-Type' : 'text/html; charset=utf-8' res.write(html) res.end() return ### * used for {% extends 'layout' %} ### liquid.Template.fileSystem = root: path.resolve(__dirname, '../views') readTemplateFile: (view) -> filename = path.join(__dirname, '../views', view)+'.tpl' return fs.readFileSync(filename, 'utf-8') module.exports = (app, mod) -> if process.env.memcachedcloud_aaaeb? p = JSON.parse(process.env.memcachedcloud_aaaeb) memcached = memjs.Client.create(p.servers, username: p.username, password: PI:PASSWORD:<PASSWORD>END_PI) else memcached = memjs.Client.create('localhost:11211') memcached.flush (err) -> # # * Render the template # * first look in cache # * # mod.render = (res, view, data = {}) -> ### * Get the latest flash message from the middleware ### data.messages = res.req.flash() memcached.get view, (err, html) -> if html isnt null console.log "%s bytes retrieved from cache", String(html).length send(res, html) return else filename = path.join(__dirname, '../views', view)+'.tpl' fs.readFile filename, 'utf-8', (err, content) -> return res.req.next(err) if err template = liquid.Template.parse(content) html = template.render(data) send(res, html) memcached.set view, html, (err) -> console.log err if err return return
[ { "context": "fileoverview Tests for CodePathAnalyzer.\n# @author Toru Nagashima\n###\n\n'use strict'\n\n#-----------------------------", "end": 73, "score": 0.9998707175254822, "start": 59, "tag": "NAME", "value": "Toru Nagashima" } ]
src/tests/code-path-analysis/code-path-analyzer.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview Tests for CodePathAnalyzer. # @author Toru Nagashima ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ assert = require 'assert' fs = require 'fs' path = require 'path' Linter = do -> linterModule = require 'eslint/lib/linter' linterModule.Linter ? linterModule EventGeneratorTester = require( '../../tools/internal-testers/event-generator-tester' ) createEmitter = try require 'eslint/lib/util/safe-emitter' catch require 'eslint/lib/linter/safe-emitter' debug = require '../../eslint-code-path-analysis-debug-helpers' CodePath = require '../../eslint-code-path-analysis-code-path' CodePathAnalyzer = require '../../eslint-code-path-analysis-code-path-analyzer' CodePathSegment = require '../../eslint-code-path-analysis-code-path-segment' NodeEventGenerator = try require 'eslint/lib/util/node-event-generator' catch require 'eslint/lib/linter/node-event-generator' #------------------------------------------------------------------------------ # Helpers #------------------------------------------------------------------------------ expectedPatternJS = /\/\*expected\s+((?:.|[\r\n])+?)\s*\*\//g expectedPattern = /###expected\s+((?:.|[\r\n])+?)\s*###/g lineEndingPattern = /\r?\n/g linter = new Linter() ###* # Extracts the content of `/*expected` comments from a given source code. # It's expected DOT arrows. # # @param {string} source - A source code text. # @returns {string[]} DOT arrows. ### getExpectedDotArrows = (source, {isJS}) -> regex = if isJS then expectedPatternJS else expectedPattern regex.lastIndex = 0 retv = [] while (m = regex.exec source) isnt null retv.push m[1].replace lineEndingPattern, '\n' retv #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ describe 'CodePathAnalyzer', -> EventGeneratorTester.testEventGeneratorInterface( new CodePathAnalyzer new NodeEventGenerator createEmitter() ) describe 'interface of code paths', -> actual = [] beforeEach -> actual ###:### = [] linter.defineRule 'test', -> onCodePathStart: (codePath) -> actual.push codePath linter.verify( 'function foo(a) { if (a) return 0; else throw new Error(); }' rules: test: 2 ) it 'should have `id` as unique string', -> assert typeof actual[0].id is 'string' assert typeof actual[1].id is 'string' assert actual[0].id isnt actual[1].id it 'should have `upper` as CodePath', -> assert actual[0].upper is null assert actual[1].upper is actual[0] it 'should have `childCodePaths` as CodePath[]', -> assert Array.isArray actual[0].childCodePaths assert Array.isArray actual[1].childCodePaths assert actual[0].childCodePaths.length is 1 assert actual[1].childCodePaths.length is 0 assert actual[0].childCodePaths[0] is actual[1] it 'should have `initialSegment` as CodePathSegment', -> assert actual[0].initialSegment instanceof CodePathSegment assert actual[1].initialSegment instanceof CodePathSegment assert actual[0].initialSegment.prevSegments.length is 0 assert actual[1].initialSegment.prevSegments.length is 0 it 'should have `finalSegments` as CodePathSegment[]', -> assert Array.isArray actual[0].finalSegments assert Array.isArray actual[1].finalSegments assert actual[0].finalSegments.length is 1 assert actual[1].finalSegments.length is 2 assert actual[0].finalSegments[0].nextSegments.length is 0 assert actual[1].finalSegments[0].nextSegments.length is 0 assert actual[1].finalSegments[1].nextSegments.length is 0 # finalSegments should include returnedSegments and thrownSegments. assert actual[0].finalSegments[0] is actual[0].returnedSegments[0] assert actual[1].finalSegments[0] is actual[1].returnedSegments[0] assert actual[1].finalSegments[1] is actual[1].thrownSegments[0] it 'should have `returnedSegments` as CodePathSegment[]', -> assert Array.isArray actual[0].returnedSegments assert Array.isArray actual[1].returnedSegments assert actual[0].returnedSegments.length is 1 assert actual[1].returnedSegments.length is 1 assert actual[0].returnedSegments[0] instanceof CodePathSegment assert actual[1].returnedSegments[0] instanceof CodePathSegment it 'should have `thrownSegments` as CodePathSegment[]', -> assert Array.isArray actual[0].thrownSegments assert Array.isArray actual[1].thrownSegments assert actual[0].thrownSegments.length is 0 assert actual[1].thrownSegments.length is 1 assert actual[1].thrownSegments[0] instanceof CodePathSegment it 'should have `currentSegments` as CodePathSegment[]', -> assert Array.isArray actual[0].currentSegments assert Array.isArray actual[1].currentSegments assert actual[0].currentSegments.length is 0 assert actual[1].currentSegments.length is 0 # there is the current segment in progress. linter.defineRule 'test', -> codePath = null onCodePathStart: (cp) -> codePath = cp ReturnStatement: -> assert codePath.currentSegments.length is 1 assert codePath.currentSegments[0] instanceof CodePathSegment ThrowStatement: -> assert codePath.currentSegments.length is 1 assert codePath.currentSegments[0] instanceof CodePathSegment linter.verify( 'function foo(a) { if (a) return 0; else throw new Error(); }' rules: test: 2 ) describe 'interface of code path segments', -> actual = [] beforeEach -> actual ###:### = [] linter.defineRule 'test', -> onCodePathSegmentStart: (segment) -> actual.push segment linter.verify( 'function foo(a) { if (a) return 0; else throw new Error(); }' rules: test: 2 ) it 'should have `id` as unique string', -> assert typeof actual[0].id is 'string' assert typeof actual[1].id is 'string' assert typeof actual[2].id is 'string' assert typeof actual[3].id is 'string' assert actual[0].id isnt actual[1].id assert actual[0].id isnt actual[2].id assert actual[0].id isnt actual[3].id assert actual[1].id isnt actual[2].id assert actual[1].id isnt actual[3].id assert actual[2].id isnt actual[3].id it 'should have `nextSegments` as CodePathSegment[]', -> assert Array.isArray actual[0].nextSegments assert Array.isArray actual[1].nextSegments assert Array.isArray actual[2].nextSegments assert Array.isArray actual[3].nextSegments assert actual[0].nextSegments.length is 0 assert actual[1].nextSegments.length is 2 assert actual[2].nextSegments.length is 0 assert actual[3].nextSegments.length is 0 assert actual[1].nextSegments[0] is actual[2] assert actual[1].nextSegments[1] is actual[3] it 'should have `allNextSegments` as CodePathSegment[]', -> assert Array.isArray actual[0].allNextSegments assert Array.isArray actual[1].allNextSegments assert Array.isArray actual[2].allNextSegments assert Array.isArray actual[3].allNextSegments assert actual[0].allNextSegments.length is 0 assert actual[1].allNextSegments.length is 2 assert actual[2].allNextSegments.length is 1 assert actual[3].allNextSegments.length is 1 assert actual[2].allNextSegments[0].reachable is no assert actual[3].allNextSegments[0].reachable is no it 'should have `prevSegments` as CodePathSegment[]', -> assert Array.isArray actual[0].prevSegments assert Array.isArray actual[1].prevSegments assert Array.isArray actual[2].prevSegments assert Array.isArray actual[3].prevSegments assert actual[0].prevSegments.length is 0 assert actual[1].prevSegments.length is 0 assert actual[2].prevSegments.length is 1 assert actual[3].prevSegments.length is 1 assert actual[2].prevSegments[0] is actual[1] assert actual[3].prevSegments[0] is actual[1] it 'should have `allPrevSegments` as CodePathSegment[]', -> assert Array.isArray actual[0].allPrevSegments assert Array.isArray actual[1].allPrevSegments assert Array.isArray actual[2].allPrevSegments assert Array.isArray actual[3].allPrevSegments assert actual[0].allPrevSegments.length is 0 assert actual[1].allPrevSegments.length is 0 assert actual[2].allPrevSegments.length is 1 assert actual[3].allPrevSegments.length is 1 it 'should have `reachable` as boolean', -> assert actual[0].reachable is yes assert actual[1].reachable is yes assert actual[2].reachable is yes assert actual[3].reachable is yes describe 'onCodePathStart', -> it 'should be fired at the head of programs/functions', -> count = 0 lastCodePathNodeType = null linter.defineRule 'test', -> onCodePathStart: (cp, node) -> count += 1 lastCodePathNodeType = node.type assert cp instanceof CodePath if count is 1 assert node.type is 'Program' else if count is 2 assert node.type is 'FunctionDeclaration' else if count is 3 assert node.type is 'FunctionExpression' else if count is 4 assert node.type is 'ArrowFunctionExpression' Program: -> assert lastCodePathNodeType is 'Program' FunctionDeclaration: -> assert lastCodePathNodeType is 'FunctionDeclaration' FunctionExpression: -> assert lastCodePathNodeType is 'FunctionExpression' ArrowFunctionExpression: -> assert lastCodePathNodeType is 'ArrowFunctionExpression' linter.verify( 'foo(); function foo() {} var foo = function() {}; var foo = () => {};' rules: {test: 2}, env: es6: yes ) assert count is 4 describe 'onCodePathEnd', -> it 'should be fired at the end of programs/functions', -> count = 0 lastNodeType = null linter.defineRule 'test', -> onCodePathEnd: (cp, node) -> count += 1 assert cp instanceof CodePath if count is 4 assert node.type is 'Program' else if count is 1 assert node.type is 'FunctionDeclaration' else if count is 2 assert node.type is 'FunctionExpression' else if count is 3 assert node.type is 'ArrowFunctionExpression' assert node.type is lastNodeType 'Program:exit': -> lastNodeType = 'Program' 'FunctionDeclaration:exit': -> lastNodeType ###:### = 'FunctionDeclaration' 'FunctionExpression:exit': -> lastNodeType ###:### = 'FunctionExpression' 'ArrowFunctionExpression:exit': -> lastNodeType ###:### = 'ArrowFunctionExpression' linter.verify( 'foo(); function foo() {} var foo = function() {}; var foo = () => {};' rules: {test: 2}, env: es6: yes ) assert count is 4 describe 'onCodePathSegmentStart', -> it 'should be fired at the head of programs/functions for the initial segment', -> count = 0 lastCodePathNodeType = null linter.defineRule 'test', -> onCodePathSegmentStart: (segment, node) -> count += 1 lastCodePathNodeType = node.type assert segment instanceof CodePathSegment if count is 1 assert node.type is 'Program' else if count is 2 assert node.type is 'FunctionDeclaration' else if count is 3 assert node.type is 'FunctionExpression' else if count is 4 assert node.type is 'ArrowFunctionExpression' Program: -> assert lastCodePathNodeType is 'Program' FunctionDeclaration: -> assert lastCodePathNodeType is 'FunctionDeclaration' FunctionExpression: -> assert lastCodePathNodeType is 'FunctionExpression' ArrowFunctionExpression: -> assert lastCodePathNodeType is 'ArrowFunctionExpression' linter.verify( 'foo(); function foo() {} var foo = function() {}; var foo = () => {};' rules: {test: 2}, env: es6: yes ) assert count is 4 describe 'onCodePathSegmentEnd', -> it 'should be fired at the end of programs/functions for the final segment', -> count = 0 lastNodeType = null linter.defineRule 'test', -> onCodePathSegmentEnd: (cp, node) -> count += 1 assert cp instanceof CodePathSegment if count is 4 assert node.type is 'Program' else if count is 1 assert node.type is 'FunctionDeclaration' else if count is 2 assert node.type is 'FunctionExpression' else if count is 3 assert node.type is 'ArrowFunctionExpression' assert node.type is lastNodeType 'Program:exit': -> lastNodeType = 'Program' 'FunctionDeclaration:exit': -> lastNodeType ###:### = 'FunctionDeclaration' 'FunctionExpression:exit': -> lastNodeType ###:### = 'FunctionExpression' 'ArrowFunctionExpression:exit': -> lastNodeType ###:### = 'ArrowFunctionExpression' linter.verify( 'foo(); function foo() {} var foo = function() {}; var foo = () => {};' rules: {test: 2}, env: es6: yes ) assert count is 4 describe 'onCodePathSegmentLoop', -> it 'should be fired in `while` loops', -> count = 0 linter.defineRule 'test', -> onCodePathSegmentLoop: (fromSegment, toSegment, node) -> count += 1 assert fromSegment instanceof CodePathSegment assert toSegment instanceof CodePathSegment assert node.type is 'WhileStatement' linter.verify 'while (a) { foo(); }', rules: test: 2 assert count is 1 it 'should be fired in `do-while` loops', -> count = 0 linter.defineRule 'test', -> onCodePathSegmentLoop: (fromSegment, toSegment, node) -> count += 1 assert fromSegment instanceof CodePathSegment assert toSegment instanceof CodePathSegment assert node.type is 'DoWhileStatement' linter.verify 'do { foo(); } while (a);', rules: test: 2 assert count is 1 it 'should be fired in `for` loops', -> count = 0 linter.defineRule 'test', -> onCodePathSegmentLoop: (fromSegment, toSegment, node) -> count += 1 assert fromSegment instanceof CodePathSegment assert toSegment instanceof CodePathSegment if count is 1 # connect path: "update" -> "test" assert node.parent.type is 'ForStatement' else if count is 2 assert node.type is 'ForStatement' linter.verify 'for (var i = 0; i < 10; ++i) { foo(); }', rules: test: 2 assert count is 2 it 'should be fired in `for-in` loops', -> count = 0 linter.defineRule 'test', -> onCodePathSegmentLoop: (fromSegment, toSegment, node) -> count += 1 assert fromSegment instanceof CodePathSegment assert toSegment instanceof CodePathSegment if count is 1 # connect path: "right" -> "left" assert node.parent.type is 'ForInStatement' else if count is 2 assert node.type is 'ForInStatement' linter.verify 'for (var k in obj) { foo(); }', rules: test: 2 assert count is 2 it 'should be fired in `for-of` loops', -> count = 0 linter.defineRule 'test', -> onCodePathSegmentLoop: (fromSegment, toSegment, node) -> count += 1 assert fromSegment instanceof CodePathSegment assert toSegment instanceof CodePathSegment if count is 1 # connect path: "right" -> "left" assert node.parent.type is 'ForOfStatement' else if count is 2 assert node.type is 'ForOfStatement' linter.verify 'for (var x of xs) { foo(); }', rules: {test: 2}, env: es6: yes assert count is 2 describe 'completed code paths are correct', -> testDataDir = path.join( __dirname '../../../src/tests/fixtures/code-path-analysis/' ) testDataFiles = fs.readdirSync testDataDir testDataFiles .filter (file) -> /\.(coffee|js)$/.test file .forEach (file) -> isJS = /\.js$/.test file it file, -> source = fs.readFileSync path.join(testDataDir, file), encoding: 'utf8' expected = getExpectedDotArrows source, {isJS} actual = [] assert expected.length > 0, '/*expected */ comments not found.' linter.defineRule 'test', -> onCodePathEnd: (codePath) -> actual.push debug.makeDotArrows codePath messages = linter.verify source, { rules: test: 2 ...( if isJS env: es6: yes # parser: path.join __dirname, '../../..' else parser: filePath: path.join __dirname, '../../..' definition: require path.join __dirname, '../../..' ) } assert.strictEqual messages.length, 0 assert.strictEqual( actual.length expected.length 'a count of code paths is wrong.' ) i = 0 while i < actual.length assert.strictEqual actual[i], expected[i] ++i
111527
###* # @fileoverview Tests for CodePathAnalyzer. # @author <NAME> ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ assert = require 'assert' fs = require 'fs' path = require 'path' Linter = do -> linterModule = require 'eslint/lib/linter' linterModule.Linter ? linterModule EventGeneratorTester = require( '../../tools/internal-testers/event-generator-tester' ) createEmitter = try require 'eslint/lib/util/safe-emitter' catch require 'eslint/lib/linter/safe-emitter' debug = require '../../eslint-code-path-analysis-debug-helpers' CodePath = require '../../eslint-code-path-analysis-code-path' CodePathAnalyzer = require '../../eslint-code-path-analysis-code-path-analyzer' CodePathSegment = require '../../eslint-code-path-analysis-code-path-segment' NodeEventGenerator = try require 'eslint/lib/util/node-event-generator' catch require 'eslint/lib/linter/node-event-generator' #------------------------------------------------------------------------------ # Helpers #------------------------------------------------------------------------------ expectedPatternJS = /\/\*expected\s+((?:.|[\r\n])+?)\s*\*\//g expectedPattern = /###expected\s+((?:.|[\r\n])+?)\s*###/g lineEndingPattern = /\r?\n/g linter = new Linter() ###* # Extracts the content of `/*expected` comments from a given source code. # It's expected DOT arrows. # # @param {string} source - A source code text. # @returns {string[]} DOT arrows. ### getExpectedDotArrows = (source, {isJS}) -> regex = if isJS then expectedPatternJS else expectedPattern regex.lastIndex = 0 retv = [] while (m = regex.exec source) isnt null retv.push m[1].replace lineEndingPattern, '\n' retv #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ describe 'CodePathAnalyzer', -> EventGeneratorTester.testEventGeneratorInterface( new CodePathAnalyzer new NodeEventGenerator createEmitter() ) describe 'interface of code paths', -> actual = [] beforeEach -> actual ###:### = [] linter.defineRule 'test', -> onCodePathStart: (codePath) -> actual.push codePath linter.verify( 'function foo(a) { if (a) return 0; else throw new Error(); }' rules: test: 2 ) it 'should have `id` as unique string', -> assert typeof actual[0].id is 'string' assert typeof actual[1].id is 'string' assert actual[0].id isnt actual[1].id it 'should have `upper` as CodePath', -> assert actual[0].upper is null assert actual[1].upper is actual[0] it 'should have `childCodePaths` as CodePath[]', -> assert Array.isArray actual[0].childCodePaths assert Array.isArray actual[1].childCodePaths assert actual[0].childCodePaths.length is 1 assert actual[1].childCodePaths.length is 0 assert actual[0].childCodePaths[0] is actual[1] it 'should have `initialSegment` as CodePathSegment', -> assert actual[0].initialSegment instanceof CodePathSegment assert actual[1].initialSegment instanceof CodePathSegment assert actual[0].initialSegment.prevSegments.length is 0 assert actual[1].initialSegment.prevSegments.length is 0 it 'should have `finalSegments` as CodePathSegment[]', -> assert Array.isArray actual[0].finalSegments assert Array.isArray actual[1].finalSegments assert actual[0].finalSegments.length is 1 assert actual[1].finalSegments.length is 2 assert actual[0].finalSegments[0].nextSegments.length is 0 assert actual[1].finalSegments[0].nextSegments.length is 0 assert actual[1].finalSegments[1].nextSegments.length is 0 # finalSegments should include returnedSegments and thrownSegments. assert actual[0].finalSegments[0] is actual[0].returnedSegments[0] assert actual[1].finalSegments[0] is actual[1].returnedSegments[0] assert actual[1].finalSegments[1] is actual[1].thrownSegments[0] it 'should have `returnedSegments` as CodePathSegment[]', -> assert Array.isArray actual[0].returnedSegments assert Array.isArray actual[1].returnedSegments assert actual[0].returnedSegments.length is 1 assert actual[1].returnedSegments.length is 1 assert actual[0].returnedSegments[0] instanceof CodePathSegment assert actual[1].returnedSegments[0] instanceof CodePathSegment it 'should have `thrownSegments` as CodePathSegment[]', -> assert Array.isArray actual[0].thrownSegments assert Array.isArray actual[1].thrownSegments assert actual[0].thrownSegments.length is 0 assert actual[1].thrownSegments.length is 1 assert actual[1].thrownSegments[0] instanceof CodePathSegment it 'should have `currentSegments` as CodePathSegment[]', -> assert Array.isArray actual[0].currentSegments assert Array.isArray actual[1].currentSegments assert actual[0].currentSegments.length is 0 assert actual[1].currentSegments.length is 0 # there is the current segment in progress. linter.defineRule 'test', -> codePath = null onCodePathStart: (cp) -> codePath = cp ReturnStatement: -> assert codePath.currentSegments.length is 1 assert codePath.currentSegments[0] instanceof CodePathSegment ThrowStatement: -> assert codePath.currentSegments.length is 1 assert codePath.currentSegments[0] instanceof CodePathSegment linter.verify( 'function foo(a) { if (a) return 0; else throw new Error(); }' rules: test: 2 ) describe 'interface of code path segments', -> actual = [] beforeEach -> actual ###:### = [] linter.defineRule 'test', -> onCodePathSegmentStart: (segment) -> actual.push segment linter.verify( 'function foo(a) { if (a) return 0; else throw new Error(); }' rules: test: 2 ) it 'should have `id` as unique string', -> assert typeof actual[0].id is 'string' assert typeof actual[1].id is 'string' assert typeof actual[2].id is 'string' assert typeof actual[3].id is 'string' assert actual[0].id isnt actual[1].id assert actual[0].id isnt actual[2].id assert actual[0].id isnt actual[3].id assert actual[1].id isnt actual[2].id assert actual[1].id isnt actual[3].id assert actual[2].id isnt actual[3].id it 'should have `nextSegments` as CodePathSegment[]', -> assert Array.isArray actual[0].nextSegments assert Array.isArray actual[1].nextSegments assert Array.isArray actual[2].nextSegments assert Array.isArray actual[3].nextSegments assert actual[0].nextSegments.length is 0 assert actual[1].nextSegments.length is 2 assert actual[2].nextSegments.length is 0 assert actual[3].nextSegments.length is 0 assert actual[1].nextSegments[0] is actual[2] assert actual[1].nextSegments[1] is actual[3] it 'should have `allNextSegments` as CodePathSegment[]', -> assert Array.isArray actual[0].allNextSegments assert Array.isArray actual[1].allNextSegments assert Array.isArray actual[2].allNextSegments assert Array.isArray actual[3].allNextSegments assert actual[0].allNextSegments.length is 0 assert actual[1].allNextSegments.length is 2 assert actual[2].allNextSegments.length is 1 assert actual[3].allNextSegments.length is 1 assert actual[2].allNextSegments[0].reachable is no assert actual[3].allNextSegments[0].reachable is no it 'should have `prevSegments` as CodePathSegment[]', -> assert Array.isArray actual[0].prevSegments assert Array.isArray actual[1].prevSegments assert Array.isArray actual[2].prevSegments assert Array.isArray actual[3].prevSegments assert actual[0].prevSegments.length is 0 assert actual[1].prevSegments.length is 0 assert actual[2].prevSegments.length is 1 assert actual[3].prevSegments.length is 1 assert actual[2].prevSegments[0] is actual[1] assert actual[3].prevSegments[0] is actual[1] it 'should have `allPrevSegments` as CodePathSegment[]', -> assert Array.isArray actual[0].allPrevSegments assert Array.isArray actual[1].allPrevSegments assert Array.isArray actual[2].allPrevSegments assert Array.isArray actual[3].allPrevSegments assert actual[0].allPrevSegments.length is 0 assert actual[1].allPrevSegments.length is 0 assert actual[2].allPrevSegments.length is 1 assert actual[3].allPrevSegments.length is 1 it 'should have `reachable` as boolean', -> assert actual[0].reachable is yes assert actual[1].reachable is yes assert actual[2].reachable is yes assert actual[3].reachable is yes describe 'onCodePathStart', -> it 'should be fired at the head of programs/functions', -> count = 0 lastCodePathNodeType = null linter.defineRule 'test', -> onCodePathStart: (cp, node) -> count += 1 lastCodePathNodeType = node.type assert cp instanceof CodePath if count is 1 assert node.type is 'Program' else if count is 2 assert node.type is 'FunctionDeclaration' else if count is 3 assert node.type is 'FunctionExpression' else if count is 4 assert node.type is 'ArrowFunctionExpression' Program: -> assert lastCodePathNodeType is 'Program' FunctionDeclaration: -> assert lastCodePathNodeType is 'FunctionDeclaration' FunctionExpression: -> assert lastCodePathNodeType is 'FunctionExpression' ArrowFunctionExpression: -> assert lastCodePathNodeType is 'ArrowFunctionExpression' linter.verify( 'foo(); function foo() {} var foo = function() {}; var foo = () => {};' rules: {test: 2}, env: es6: yes ) assert count is 4 describe 'onCodePathEnd', -> it 'should be fired at the end of programs/functions', -> count = 0 lastNodeType = null linter.defineRule 'test', -> onCodePathEnd: (cp, node) -> count += 1 assert cp instanceof CodePath if count is 4 assert node.type is 'Program' else if count is 1 assert node.type is 'FunctionDeclaration' else if count is 2 assert node.type is 'FunctionExpression' else if count is 3 assert node.type is 'ArrowFunctionExpression' assert node.type is lastNodeType 'Program:exit': -> lastNodeType = 'Program' 'FunctionDeclaration:exit': -> lastNodeType ###:### = 'FunctionDeclaration' 'FunctionExpression:exit': -> lastNodeType ###:### = 'FunctionExpression' 'ArrowFunctionExpression:exit': -> lastNodeType ###:### = 'ArrowFunctionExpression' linter.verify( 'foo(); function foo() {} var foo = function() {}; var foo = () => {};' rules: {test: 2}, env: es6: yes ) assert count is 4 describe 'onCodePathSegmentStart', -> it 'should be fired at the head of programs/functions for the initial segment', -> count = 0 lastCodePathNodeType = null linter.defineRule 'test', -> onCodePathSegmentStart: (segment, node) -> count += 1 lastCodePathNodeType = node.type assert segment instanceof CodePathSegment if count is 1 assert node.type is 'Program' else if count is 2 assert node.type is 'FunctionDeclaration' else if count is 3 assert node.type is 'FunctionExpression' else if count is 4 assert node.type is 'ArrowFunctionExpression' Program: -> assert lastCodePathNodeType is 'Program' FunctionDeclaration: -> assert lastCodePathNodeType is 'FunctionDeclaration' FunctionExpression: -> assert lastCodePathNodeType is 'FunctionExpression' ArrowFunctionExpression: -> assert lastCodePathNodeType is 'ArrowFunctionExpression' linter.verify( 'foo(); function foo() {} var foo = function() {}; var foo = () => {};' rules: {test: 2}, env: es6: yes ) assert count is 4 describe 'onCodePathSegmentEnd', -> it 'should be fired at the end of programs/functions for the final segment', -> count = 0 lastNodeType = null linter.defineRule 'test', -> onCodePathSegmentEnd: (cp, node) -> count += 1 assert cp instanceof CodePathSegment if count is 4 assert node.type is 'Program' else if count is 1 assert node.type is 'FunctionDeclaration' else if count is 2 assert node.type is 'FunctionExpression' else if count is 3 assert node.type is 'ArrowFunctionExpression' assert node.type is lastNodeType 'Program:exit': -> lastNodeType = 'Program' 'FunctionDeclaration:exit': -> lastNodeType ###:### = 'FunctionDeclaration' 'FunctionExpression:exit': -> lastNodeType ###:### = 'FunctionExpression' 'ArrowFunctionExpression:exit': -> lastNodeType ###:### = 'ArrowFunctionExpression' linter.verify( 'foo(); function foo() {} var foo = function() {}; var foo = () => {};' rules: {test: 2}, env: es6: yes ) assert count is 4 describe 'onCodePathSegmentLoop', -> it 'should be fired in `while` loops', -> count = 0 linter.defineRule 'test', -> onCodePathSegmentLoop: (fromSegment, toSegment, node) -> count += 1 assert fromSegment instanceof CodePathSegment assert toSegment instanceof CodePathSegment assert node.type is 'WhileStatement' linter.verify 'while (a) { foo(); }', rules: test: 2 assert count is 1 it 'should be fired in `do-while` loops', -> count = 0 linter.defineRule 'test', -> onCodePathSegmentLoop: (fromSegment, toSegment, node) -> count += 1 assert fromSegment instanceof CodePathSegment assert toSegment instanceof CodePathSegment assert node.type is 'DoWhileStatement' linter.verify 'do { foo(); } while (a);', rules: test: 2 assert count is 1 it 'should be fired in `for` loops', -> count = 0 linter.defineRule 'test', -> onCodePathSegmentLoop: (fromSegment, toSegment, node) -> count += 1 assert fromSegment instanceof CodePathSegment assert toSegment instanceof CodePathSegment if count is 1 # connect path: "update" -> "test" assert node.parent.type is 'ForStatement' else if count is 2 assert node.type is 'ForStatement' linter.verify 'for (var i = 0; i < 10; ++i) { foo(); }', rules: test: 2 assert count is 2 it 'should be fired in `for-in` loops', -> count = 0 linter.defineRule 'test', -> onCodePathSegmentLoop: (fromSegment, toSegment, node) -> count += 1 assert fromSegment instanceof CodePathSegment assert toSegment instanceof CodePathSegment if count is 1 # connect path: "right" -> "left" assert node.parent.type is 'ForInStatement' else if count is 2 assert node.type is 'ForInStatement' linter.verify 'for (var k in obj) { foo(); }', rules: test: 2 assert count is 2 it 'should be fired in `for-of` loops', -> count = 0 linter.defineRule 'test', -> onCodePathSegmentLoop: (fromSegment, toSegment, node) -> count += 1 assert fromSegment instanceof CodePathSegment assert toSegment instanceof CodePathSegment if count is 1 # connect path: "right" -> "left" assert node.parent.type is 'ForOfStatement' else if count is 2 assert node.type is 'ForOfStatement' linter.verify 'for (var x of xs) { foo(); }', rules: {test: 2}, env: es6: yes assert count is 2 describe 'completed code paths are correct', -> testDataDir = path.join( __dirname '../../../src/tests/fixtures/code-path-analysis/' ) testDataFiles = fs.readdirSync testDataDir testDataFiles .filter (file) -> /\.(coffee|js)$/.test file .forEach (file) -> isJS = /\.js$/.test file it file, -> source = fs.readFileSync path.join(testDataDir, file), encoding: 'utf8' expected = getExpectedDotArrows source, {isJS} actual = [] assert expected.length > 0, '/*expected */ comments not found.' linter.defineRule 'test', -> onCodePathEnd: (codePath) -> actual.push debug.makeDotArrows codePath messages = linter.verify source, { rules: test: 2 ...( if isJS env: es6: yes # parser: path.join __dirname, '../../..' else parser: filePath: path.join __dirname, '../../..' definition: require path.join __dirname, '../../..' ) } assert.strictEqual messages.length, 0 assert.strictEqual( actual.length expected.length 'a count of code paths is wrong.' ) i = 0 while i < actual.length assert.strictEqual actual[i], expected[i] ++i
true
###* # @fileoverview Tests for CodePathAnalyzer. # @author PI:NAME:<NAME>END_PI ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ assert = require 'assert' fs = require 'fs' path = require 'path' Linter = do -> linterModule = require 'eslint/lib/linter' linterModule.Linter ? linterModule EventGeneratorTester = require( '../../tools/internal-testers/event-generator-tester' ) createEmitter = try require 'eslint/lib/util/safe-emitter' catch require 'eslint/lib/linter/safe-emitter' debug = require '../../eslint-code-path-analysis-debug-helpers' CodePath = require '../../eslint-code-path-analysis-code-path' CodePathAnalyzer = require '../../eslint-code-path-analysis-code-path-analyzer' CodePathSegment = require '../../eslint-code-path-analysis-code-path-segment' NodeEventGenerator = try require 'eslint/lib/util/node-event-generator' catch require 'eslint/lib/linter/node-event-generator' #------------------------------------------------------------------------------ # Helpers #------------------------------------------------------------------------------ expectedPatternJS = /\/\*expected\s+((?:.|[\r\n])+?)\s*\*\//g expectedPattern = /###expected\s+((?:.|[\r\n])+?)\s*###/g lineEndingPattern = /\r?\n/g linter = new Linter() ###* # Extracts the content of `/*expected` comments from a given source code. # It's expected DOT arrows. # # @param {string} source - A source code text. # @returns {string[]} DOT arrows. ### getExpectedDotArrows = (source, {isJS}) -> regex = if isJS then expectedPatternJS else expectedPattern regex.lastIndex = 0 retv = [] while (m = regex.exec source) isnt null retv.push m[1].replace lineEndingPattern, '\n' retv #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ describe 'CodePathAnalyzer', -> EventGeneratorTester.testEventGeneratorInterface( new CodePathAnalyzer new NodeEventGenerator createEmitter() ) describe 'interface of code paths', -> actual = [] beforeEach -> actual ###:### = [] linter.defineRule 'test', -> onCodePathStart: (codePath) -> actual.push codePath linter.verify( 'function foo(a) { if (a) return 0; else throw new Error(); }' rules: test: 2 ) it 'should have `id` as unique string', -> assert typeof actual[0].id is 'string' assert typeof actual[1].id is 'string' assert actual[0].id isnt actual[1].id it 'should have `upper` as CodePath', -> assert actual[0].upper is null assert actual[1].upper is actual[0] it 'should have `childCodePaths` as CodePath[]', -> assert Array.isArray actual[0].childCodePaths assert Array.isArray actual[1].childCodePaths assert actual[0].childCodePaths.length is 1 assert actual[1].childCodePaths.length is 0 assert actual[0].childCodePaths[0] is actual[1] it 'should have `initialSegment` as CodePathSegment', -> assert actual[0].initialSegment instanceof CodePathSegment assert actual[1].initialSegment instanceof CodePathSegment assert actual[0].initialSegment.prevSegments.length is 0 assert actual[1].initialSegment.prevSegments.length is 0 it 'should have `finalSegments` as CodePathSegment[]', -> assert Array.isArray actual[0].finalSegments assert Array.isArray actual[1].finalSegments assert actual[0].finalSegments.length is 1 assert actual[1].finalSegments.length is 2 assert actual[0].finalSegments[0].nextSegments.length is 0 assert actual[1].finalSegments[0].nextSegments.length is 0 assert actual[1].finalSegments[1].nextSegments.length is 0 # finalSegments should include returnedSegments and thrownSegments. assert actual[0].finalSegments[0] is actual[0].returnedSegments[0] assert actual[1].finalSegments[0] is actual[1].returnedSegments[0] assert actual[1].finalSegments[1] is actual[1].thrownSegments[0] it 'should have `returnedSegments` as CodePathSegment[]', -> assert Array.isArray actual[0].returnedSegments assert Array.isArray actual[1].returnedSegments assert actual[0].returnedSegments.length is 1 assert actual[1].returnedSegments.length is 1 assert actual[0].returnedSegments[0] instanceof CodePathSegment assert actual[1].returnedSegments[0] instanceof CodePathSegment it 'should have `thrownSegments` as CodePathSegment[]', -> assert Array.isArray actual[0].thrownSegments assert Array.isArray actual[1].thrownSegments assert actual[0].thrownSegments.length is 0 assert actual[1].thrownSegments.length is 1 assert actual[1].thrownSegments[0] instanceof CodePathSegment it 'should have `currentSegments` as CodePathSegment[]', -> assert Array.isArray actual[0].currentSegments assert Array.isArray actual[1].currentSegments assert actual[0].currentSegments.length is 0 assert actual[1].currentSegments.length is 0 # there is the current segment in progress. linter.defineRule 'test', -> codePath = null onCodePathStart: (cp) -> codePath = cp ReturnStatement: -> assert codePath.currentSegments.length is 1 assert codePath.currentSegments[0] instanceof CodePathSegment ThrowStatement: -> assert codePath.currentSegments.length is 1 assert codePath.currentSegments[0] instanceof CodePathSegment linter.verify( 'function foo(a) { if (a) return 0; else throw new Error(); }' rules: test: 2 ) describe 'interface of code path segments', -> actual = [] beforeEach -> actual ###:### = [] linter.defineRule 'test', -> onCodePathSegmentStart: (segment) -> actual.push segment linter.verify( 'function foo(a) { if (a) return 0; else throw new Error(); }' rules: test: 2 ) it 'should have `id` as unique string', -> assert typeof actual[0].id is 'string' assert typeof actual[1].id is 'string' assert typeof actual[2].id is 'string' assert typeof actual[3].id is 'string' assert actual[0].id isnt actual[1].id assert actual[0].id isnt actual[2].id assert actual[0].id isnt actual[3].id assert actual[1].id isnt actual[2].id assert actual[1].id isnt actual[3].id assert actual[2].id isnt actual[3].id it 'should have `nextSegments` as CodePathSegment[]', -> assert Array.isArray actual[0].nextSegments assert Array.isArray actual[1].nextSegments assert Array.isArray actual[2].nextSegments assert Array.isArray actual[3].nextSegments assert actual[0].nextSegments.length is 0 assert actual[1].nextSegments.length is 2 assert actual[2].nextSegments.length is 0 assert actual[3].nextSegments.length is 0 assert actual[1].nextSegments[0] is actual[2] assert actual[1].nextSegments[1] is actual[3] it 'should have `allNextSegments` as CodePathSegment[]', -> assert Array.isArray actual[0].allNextSegments assert Array.isArray actual[1].allNextSegments assert Array.isArray actual[2].allNextSegments assert Array.isArray actual[3].allNextSegments assert actual[0].allNextSegments.length is 0 assert actual[1].allNextSegments.length is 2 assert actual[2].allNextSegments.length is 1 assert actual[3].allNextSegments.length is 1 assert actual[2].allNextSegments[0].reachable is no assert actual[3].allNextSegments[0].reachable is no it 'should have `prevSegments` as CodePathSegment[]', -> assert Array.isArray actual[0].prevSegments assert Array.isArray actual[1].prevSegments assert Array.isArray actual[2].prevSegments assert Array.isArray actual[3].prevSegments assert actual[0].prevSegments.length is 0 assert actual[1].prevSegments.length is 0 assert actual[2].prevSegments.length is 1 assert actual[3].prevSegments.length is 1 assert actual[2].prevSegments[0] is actual[1] assert actual[3].prevSegments[0] is actual[1] it 'should have `allPrevSegments` as CodePathSegment[]', -> assert Array.isArray actual[0].allPrevSegments assert Array.isArray actual[1].allPrevSegments assert Array.isArray actual[2].allPrevSegments assert Array.isArray actual[3].allPrevSegments assert actual[0].allPrevSegments.length is 0 assert actual[1].allPrevSegments.length is 0 assert actual[2].allPrevSegments.length is 1 assert actual[3].allPrevSegments.length is 1 it 'should have `reachable` as boolean', -> assert actual[0].reachable is yes assert actual[1].reachable is yes assert actual[2].reachable is yes assert actual[3].reachable is yes describe 'onCodePathStart', -> it 'should be fired at the head of programs/functions', -> count = 0 lastCodePathNodeType = null linter.defineRule 'test', -> onCodePathStart: (cp, node) -> count += 1 lastCodePathNodeType = node.type assert cp instanceof CodePath if count is 1 assert node.type is 'Program' else if count is 2 assert node.type is 'FunctionDeclaration' else if count is 3 assert node.type is 'FunctionExpression' else if count is 4 assert node.type is 'ArrowFunctionExpression' Program: -> assert lastCodePathNodeType is 'Program' FunctionDeclaration: -> assert lastCodePathNodeType is 'FunctionDeclaration' FunctionExpression: -> assert lastCodePathNodeType is 'FunctionExpression' ArrowFunctionExpression: -> assert lastCodePathNodeType is 'ArrowFunctionExpression' linter.verify( 'foo(); function foo() {} var foo = function() {}; var foo = () => {};' rules: {test: 2}, env: es6: yes ) assert count is 4 describe 'onCodePathEnd', -> it 'should be fired at the end of programs/functions', -> count = 0 lastNodeType = null linter.defineRule 'test', -> onCodePathEnd: (cp, node) -> count += 1 assert cp instanceof CodePath if count is 4 assert node.type is 'Program' else if count is 1 assert node.type is 'FunctionDeclaration' else if count is 2 assert node.type is 'FunctionExpression' else if count is 3 assert node.type is 'ArrowFunctionExpression' assert node.type is lastNodeType 'Program:exit': -> lastNodeType = 'Program' 'FunctionDeclaration:exit': -> lastNodeType ###:### = 'FunctionDeclaration' 'FunctionExpression:exit': -> lastNodeType ###:### = 'FunctionExpression' 'ArrowFunctionExpression:exit': -> lastNodeType ###:### = 'ArrowFunctionExpression' linter.verify( 'foo(); function foo() {} var foo = function() {}; var foo = () => {};' rules: {test: 2}, env: es6: yes ) assert count is 4 describe 'onCodePathSegmentStart', -> it 'should be fired at the head of programs/functions for the initial segment', -> count = 0 lastCodePathNodeType = null linter.defineRule 'test', -> onCodePathSegmentStart: (segment, node) -> count += 1 lastCodePathNodeType = node.type assert segment instanceof CodePathSegment if count is 1 assert node.type is 'Program' else if count is 2 assert node.type is 'FunctionDeclaration' else if count is 3 assert node.type is 'FunctionExpression' else if count is 4 assert node.type is 'ArrowFunctionExpression' Program: -> assert lastCodePathNodeType is 'Program' FunctionDeclaration: -> assert lastCodePathNodeType is 'FunctionDeclaration' FunctionExpression: -> assert lastCodePathNodeType is 'FunctionExpression' ArrowFunctionExpression: -> assert lastCodePathNodeType is 'ArrowFunctionExpression' linter.verify( 'foo(); function foo() {} var foo = function() {}; var foo = () => {};' rules: {test: 2}, env: es6: yes ) assert count is 4 describe 'onCodePathSegmentEnd', -> it 'should be fired at the end of programs/functions for the final segment', -> count = 0 lastNodeType = null linter.defineRule 'test', -> onCodePathSegmentEnd: (cp, node) -> count += 1 assert cp instanceof CodePathSegment if count is 4 assert node.type is 'Program' else if count is 1 assert node.type is 'FunctionDeclaration' else if count is 2 assert node.type is 'FunctionExpression' else if count is 3 assert node.type is 'ArrowFunctionExpression' assert node.type is lastNodeType 'Program:exit': -> lastNodeType = 'Program' 'FunctionDeclaration:exit': -> lastNodeType ###:### = 'FunctionDeclaration' 'FunctionExpression:exit': -> lastNodeType ###:### = 'FunctionExpression' 'ArrowFunctionExpression:exit': -> lastNodeType ###:### = 'ArrowFunctionExpression' linter.verify( 'foo(); function foo() {} var foo = function() {}; var foo = () => {};' rules: {test: 2}, env: es6: yes ) assert count is 4 describe 'onCodePathSegmentLoop', -> it 'should be fired in `while` loops', -> count = 0 linter.defineRule 'test', -> onCodePathSegmentLoop: (fromSegment, toSegment, node) -> count += 1 assert fromSegment instanceof CodePathSegment assert toSegment instanceof CodePathSegment assert node.type is 'WhileStatement' linter.verify 'while (a) { foo(); }', rules: test: 2 assert count is 1 it 'should be fired in `do-while` loops', -> count = 0 linter.defineRule 'test', -> onCodePathSegmentLoop: (fromSegment, toSegment, node) -> count += 1 assert fromSegment instanceof CodePathSegment assert toSegment instanceof CodePathSegment assert node.type is 'DoWhileStatement' linter.verify 'do { foo(); } while (a);', rules: test: 2 assert count is 1 it 'should be fired in `for` loops', -> count = 0 linter.defineRule 'test', -> onCodePathSegmentLoop: (fromSegment, toSegment, node) -> count += 1 assert fromSegment instanceof CodePathSegment assert toSegment instanceof CodePathSegment if count is 1 # connect path: "update" -> "test" assert node.parent.type is 'ForStatement' else if count is 2 assert node.type is 'ForStatement' linter.verify 'for (var i = 0; i < 10; ++i) { foo(); }', rules: test: 2 assert count is 2 it 'should be fired in `for-in` loops', -> count = 0 linter.defineRule 'test', -> onCodePathSegmentLoop: (fromSegment, toSegment, node) -> count += 1 assert fromSegment instanceof CodePathSegment assert toSegment instanceof CodePathSegment if count is 1 # connect path: "right" -> "left" assert node.parent.type is 'ForInStatement' else if count is 2 assert node.type is 'ForInStatement' linter.verify 'for (var k in obj) { foo(); }', rules: test: 2 assert count is 2 it 'should be fired in `for-of` loops', -> count = 0 linter.defineRule 'test', -> onCodePathSegmentLoop: (fromSegment, toSegment, node) -> count += 1 assert fromSegment instanceof CodePathSegment assert toSegment instanceof CodePathSegment if count is 1 # connect path: "right" -> "left" assert node.parent.type is 'ForOfStatement' else if count is 2 assert node.type is 'ForOfStatement' linter.verify 'for (var x of xs) { foo(); }', rules: {test: 2}, env: es6: yes assert count is 2 describe 'completed code paths are correct', -> testDataDir = path.join( __dirname '../../../src/tests/fixtures/code-path-analysis/' ) testDataFiles = fs.readdirSync testDataDir testDataFiles .filter (file) -> /\.(coffee|js)$/.test file .forEach (file) -> isJS = /\.js$/.test file it file, -> source = fs.readFileSync path.join(testDataDir, file), encoding: 'utf8' expected = getExpectedDotArrows source, {isJS} actual = [] assert expected.length > 0, '/*expected */ comments not found.' linter.defineRule 'test', -> onCodePathEnd: (codePath) -> actual.push debug.makeDotArrows codePath messages = linter.verify source, { rules: test: 2 ...( if isJS env: es6: yes # parser: path.join __dirname, '../../..' else parser: filePath: path.join __dirname, '../../..' definition: require path.join __dirname, '../../..' ) } assert.strictEqual messages.length, 0 assert.strictEqual( actual.length expected.length 'a count of code paths is wrong.' ) i = 0 while i < actual.length assert.strictEqual actual[i], expected[i] ++i
[ { "context": "=\n username: null\n email: null\n password: null\n code: null\n\n link: (scope, elem, attr, ctrl)", "end": 732, "score": 0.9992660880088806, "start": 728, "tag": "PASSWORD", "value": "null" } ]
h/js/directives.coffee
gergely-ujvari/h
0
annotation = ['$filter', 'annotator', ($filter, annotator) -> link: (scope, elem, attrs, controller) -> return unless controller? # Bind shift+enter to save elem.bind keydown: (e) -> if e.keyCode == 13 && e.shiftKey e.preventDefault() scope.save() # Watch for changes scope.$watch 'model.$modelValue.id', (id) -> scope.thread = annotator.threading.idTable[id] # Publish the controller scope.model = controller controller: 'AnnotationController' priority: 100 # Must run before ngModel require: '?ngModel' restrict: 'C' scope: {} templateUrl: 'annotation.html' ] authentication = -> base = username: null email: null password: null code: null link: (scope, elem, attr, ctrl) -> angular.extend scope, base controller: [ '$scope', 'authentication', ($scope, authentication) -> $scope.$on '$reset', => angular.extend $scope, base $scope.submit = (form) -> return unless form.$valid params = {} for name, control of form when control.$modelValue? params[name] = control.$modelValue method = "$#{form.$name}" authentication[method] params, -> $scope.$emit 'success', form.$name ] scope: model: '=authentication' markdown = ['$filter', '$timeout', ($filter, $timeout) -> link: (scope, elem, attr, ctrl) -> return unless ctrl? input = elem.find('textarea') output = elem.find('div') # Re-render the markdown when the view needs updating. ctrl.$render = -> input.attr('value', ctrl.$viewValue or '') scope.rendered = ($filter 'converter') (ctrl.$viewValue or '') # React to the changes to the text area input.bind 'blur change keyup', -> ctrl.$setViewValue input[0].value scope.$digest() # Auto-focus the input box when the widget becomes editable. # Re-render when it becomes uneditable. scope.$watch 'readonly', (readonly) -> ctrl.$render() unless readonly then $timeout -> input.focus() require: '?ngModel' restrict: 'E' scope: readonly: '@' required: '@' templateUrl: 'markdown.html' ] privacy = -> levels = ['Public', 'Private'] link: (scope, elem, attrs, controller) -> return unless controller? controller.$formatters.push (permissions) -> return unless permissions? if 'group:__world__' in (permissions.read or []) 'Public' else 'Private' controller.$parsers.push (privacy) -> return unless privacy? permissions = controller.$modelValue if privacy is 'Public' if permissions.read unless 'group:__world__' in permissions.read permissions.read.push 'group:__world__' else permissions.read = ['group:__world__'] else read = permissions.read or [] read = (role for role in read when role isnt 'group:__world__') permissions.read = read permissions scope.model = controller scope.levels = levels require: '?ngModel' restrict: 'E' scope: true templateUrl: 'privacy.html' recursive = ['$compile', '$timeout', ($compile, $timeout) -> compile: (tElement, tAttrs, transclude) -> placeholder = angular.element '<!-- recursive -->' attachQueue = [] tick = false template = tElement.contents().clone() tElement.html '' transclude = $compile template, (scope, cloneAttachFn) -> clone = placeholder.clone() cloneAttachFn clone $timeout -> transclude scope, (el, scope) -> attachQueue.push [clone, el] unless tick tick = true requestAnimationFrame -> tick = false for [clone, el] in attachQueue clone.after el clone.bind '$destroy', -> el.remove() attachQueue = [] clone post: (scope, iElement, iAttrs, controller) -> transclude scope, (contents) -> iElement.append contents restrict: 'A' terminal: true ] resettable = -> compile: (tElement, tAttrs, transclude) -> post: (scope, iElement, iAttrs) -> reset = -> transclude scope, (el) -> iElement.replaceWith el iElement = el reset() scope.$on '$reset', reset priority: 5000 restrict: 'A' transclude: 'element' ### # The slow validation directive ties an to a model controller and hides # it while the model is being edited. This behavior improves the user # experience of filling out forms by delaying validation messages until # after the user has made a mistake. ### slowValidate = ['$parse', '$timeout', ($parse, $timeout) -> link: (scope, elem, attr, ctrl) -> return unless ctrl? promise = null elem.addClass 'slow-validate' ctrl[attr.slowValidate]?.$viewChangeListeners?.push (value) -> elem.removeClass 'slow-validate-show' if promise $timeout.cancel promise promise = null promise = $timeout -> elem.addClass 'slow-validate-show' require: '^form' restrict: 'A' ] tabReveal = ['$parse', ($parse) -> compile: (tElement, tAttrs, transclude) -> panes = [] hiddenPanesGet = $parse tAttrs.tabReveal pre: (scope, iElement, iAttrs, [ngModel, tabbable] = controller) -> # Hijack the tabbable controller's addPane so that the visibility of the # secret ones can be managed. This avoids traversing the DOM to find # the tab panes. addPane = tabbable.addPane tabbable.addPane = (element, attr) => removePane = addPane.call tabbable, element, attr panes.push element: element attr: attr => for i in [0..panes.length] if panes[i].element is element panes.splice i, 1 break removePane() post: (scope, iElement, iAttrs, [ngModel, tabbable] = controller) -> tabs = angular.element(iElement.children()[0].childNodes) render = angular.bind ngModel, ngModel.$render ngModel.$render = -> render() hiddenPanes = hiddenPanesGet scope return unless angular.isArray hiddenPanes for i in [0..panes.length-1] pane = panes[i] value = pane.attr.value || pane.attr.title if value == ngModel.$viewValue pane.element.css 'display', '' angular.element(tabs[i]).css 'display', '' else if value in hiddenPanes pane.element.css 'display', 'none' angular.element(tabs[i]).css 'display', 'none' require: ['ngModel', 'tabbable'] ] thread = -> link: (scope, iElement, iAttrs, controller) -> scope.collapsed = false restrict: 'C' scope: true userPicker = -> restrict: 'ACE' scope: model: '=userPickerModel' options: '=userPickerOptions' templateUrl: 'userPicker.html' #Directive will be removed once the angularjs official version will have this directive ngBlur = ['$parse', ($parse) -> (scope, element, attr) -> fn = $parse attr['ngBlur'] element.bind 'blur', (event) -> scope.$apply -> fn scope, $event: event ] repeatAnim = -> restrict: 'A' scope: array: '=' template: '<div ng-init="runAnimOnLast()"><div ng-transclude></div></div>' transclude: true controller: ($scope, $element, $attrs) -> $scope.runAnimOnLast = -> #Run anim on the item's element #(which will be last child of directive element) item=$scope.array[0] itemElm = jQuery($element) .children() .first() .children() unless item._anim? return if item._anim is 'fade' itemElm .css({ opacity: 0 }) .animate({ opacity: 1 }, 1500) else if item._anim is 'slide' itemElm .css({ 'margin-left': itemElm.width() }) .animate({ 'margin-left': '0px' }, 1500) angular.module('h.directives', ['ngSanitize']) .directive('annotation', annotation) .directive('authentication', authentication) .directive('markdown', markdown) .directive('privacy', privacy) .directive('recursive', recursive) .directive('resettable', resettable) .directive('slowValidate', slowValidate) .directive('tabReveal', tabReveal) .directive('thread', thread) .directive('userPicker', userPicker) .directive('ngBlur', ngBlur) .directive('repeatAnim', repeatAnim)
98688
annotation = ['$filter', 'annotator', ($filter, annotator) -> link: (scope, elem, attrs, controller) -> return unless controller? # Bind shift+enter to save elem.bind keydown: (e) -> if e.keyCode == 13 && e.shiftKey e.preventDefault() scope.save() # Watch for changes scope.$watch 'model.$modelValue.id', (id) -> scope.thread = annotator.threading.idTable[id] # Publish the controller scope.model = controller controller: 'AnnotationController' priority: 100 # Must run before ngModel require: '?ngModel' restrict: 'C' scope: {} templateUrl: 'annotation.html' ] authentication = -> base = username: null email: null password: <PASSWORD> code: null link: (scope, elem, attr, ctrl) -> angular.extend scope, base controller: [ '$scope', 'authentication', ($scope, authentication) -> $scope.$on '$reset', => angular.extend $scope, base $scope.submit = (form) -> return unless form.$valid params = {} for name, control of form when control.$modelValue? params[name] = control.$modelValue method = "$#{form.$name}" authentication[method] params, -> $scope.$emit 'success', form.$name ] scope: model: '=authentication' markdown = ['$filter', '$timeout', ($filter, $timeout) -> link: (scope, elem, attr, ctrl) -> return unless ctrl? input = elem.find('textarea') output = elem.find('div') # Re-render the markdown when the view needs updating. ctrl.$render = -> input.attr('value', ctrl.$viewValue or '') scope.rendered = ($filter 'converter') (ctrl.$viewValue or '') # React to the changes to the text area input.bind 'blur change keyup', -> ctrl.$setViewValue input[0].value scope.$digest() # Auto-focus the input box when the widget becomes editable. # Re-render when it becomes uneditable. scope.$watch 'readonly', (readonly) -> ctrl.$render() unless readonly then $timeout -> input.focus() require: '?ngModel' restrict: 'E' scope: readonly: '@' required: '@' templateUrl: 'markdown.html' ] privacy = -> levels = ['Public', 'Private'] link: (scope, elem, attrs, controller) -> return unless controller? controller.$formatters.push (permissions) -> return unless permissions? if 'group:__world__' in (permissions.read or []) 'Public' else 'Private' controller.$parsers.push (privacy) -> return unless privacy? permissions = controller.$modelValue if privacy is 'Public' if permissions.read unless 'group:__world__' in permissions.read permissions.read.push 'group:__world__' else permissions.read = ['group:__world__'] else read = permissions.read or [] read = (role for role in read when role isnt 'group:__world__') permissions.read = read permissions scope.model = controller scope.levels = levels require: '?ngModel' restrict: 'E' scope: true templateUrl: 'privacy.html' recursive = ['$compile', '$timeout', ($compile, $timeout) -> compile: (tElement, tAttrs, transclude) -> placeholder = angular.element '<!-- recursive -->' attachQueue = [] tick = false template = tElement.contents().clone() tElement.html '' transclude = $compile template, (scope, cloneAttachFn) -> clone = placeholder.clone() cloneAttachFn clone $timeout -> transclude scope, (el, scope) -> attachQueue.push [clone, el] unless tick tick = true requestAnimationFrame -> tick = false for [clone, el] in attachQueue clone.after el clone.bind '$destroy', -> el.remove() attachQueue = [] clone post: (scope, iElement, iAttrs, controller) -> transclude scope, (contents) -> iElement.append contents restrict: 'A' terminal: true ] resettable = -> compile: (tElement, tAttrs, transclude) -> post: (scope, iElement, iAttrs) -> reset = -> transclude scope, (el) -> iElement.replaceWith el iElement = el reset() scope.$on '$reset', reset priority: 5000 restrict: 'A' transclude: 'element' ### # The slow validation directive ties an to a model controller and hides # it while the model is being edited. This behavior improves the user # experience of filling out forms by delaying validation messages until # after the user has made a mistake. ### slowValidate = ['$parse', '$timeout', ($parse, $timeout) -> link: (scope, elem, attr, ctrl) -> return unless ctrl? promise = null elem.addClass 'slow-validate' ctrl[attr.slowValidate]?.$viewChangeListeners?.push (value) -> elem.removeClass 'slow-validate-show' if promise $timeout.cancel promise promise = null promise = $timeout -> elem.addClass 'slow-validate-show' require: '^form' restrict: 'A' ] tabReveal = ['$parse', ($parse) -> compile: (tElement, tAttrs, transclude) -> panes = [] hiddenPanesGet = $parse tAttrs.tabReveal pre: (scope, iElement, iAttrs, [ngModel, tabbable] = controller) -> # Hijack the tabbable controller's addPane so that the visibility of the # secret ones can be managed. This avoids traversing the DOM to find # the tab panes. addPane = tabbable.addPane tabbable.addPane = (element, attr) => removePane = addPane.call tabbable, element, attr panes.push element: element attr: attr => for i in [0..panes.length] if panes[i].element is element panes.splice i, 1 break removePane() post: (scope, iElement, iAttrs, [ngModel, tabbable] = controller) -> tabs = angular.element(iElement.children()[0].childNodes) render = angular.bind ngModel, ngModel.$render ngModel.$render = -> render() hiddenPanes = hiddenPanesGet scope return unless angular.isArray hiddenPanes for i in [0..panes.length-1] pane = panes[i] value = pane.attr.value || pane.attr.title if value == ngModel.$viewValue pane.element.css 'display', '' angular.element(tabs[i]).css 'display', '' else if value in hiddenPanes pane.element.css 'display', 'none' angular.element(tabs[i]).css 'display', 'none' require: ['ngModel', 'tabbable'] ] thread = -> link: (scope, iElement, iAttrs, controller) -> scope.collapsed = false restrict: 'C' scope: true userPicker = -> restrict: 'ACE' scope: model: '=userPickerModel' options: '=userPickerOptions' templateUrl: 'userPicker.html' #Directive will be removed once the angularjs official version will have this directive ngBlur = ['$parse', ($parse) -> (scope, element, attr) -> fn = $parse attr['ngBlur'] element.bind 'blur', (event) -> scope.$apply -> fn scope, $event: event ] repeatAnim = -> restrict: 'A' scope: array: '=' template: '<div ng-init="runAnimOnLast()"><div ng-transclude></div></div>' transclude: true controller: ($scope, $element, $attrs) -> $scope.runAnimOnLast = -> #Run anim on the item's element #(which will be last child of directive element) item=$scope.array[0] itemElm = jQuery($element) .children() .first() .children() unless item._anim? return if item._anim is 'fade' itemElm .css({ opacity: 0 }) .animate({ opacity: 1 }, 1500) else if item._anim is 'slide' itemElm .css({ 'margin-left': itemElm.width() }) .animate({ 'margin-left': '0px' }, 1500) angular.module('h.directives', ['ngSanitize']) .directive('annotation', annotation) .directive('authentication', authentication) .directive('markdown', markdown) .directive('privacy', privacy) .directive('recursive', recursive) .directive('resettable', resettable) .directive('slowValidate', slowValidate) .directive('tabReveal', tabReveal) .directive('thread', thread) .directive('userPicker', userPicker) .directive('ngBlur', ngBlur) .directive('repeatAnim', repeatAnim)
true
annotation = ['$filter', 'annotator', ($filter, annotator) -> link: (scope, elem, attrs, controller) -> return unless controller? # Bind shift+enter to save elem.bind keydown: (e) -> if e.keyCode == 13 && e.shiftKey e.preventDefault() scope.save() # Watch for changes scope.$watch 'model.$modelValue.id', (id) -> scope.thread = annotator.threading.idTable[id] # Publish the controller scope.model = controller controller: 'AnnotationController' priority: 100 # Must run before ngModel require: '?ngModel' restrict: 'C' scope: {} templateUrl: 'annotation.html' ] authentication = -> base = username: null email: null password: PI:PASSWORD:<PASSWORD>END_PI code: null link: (scope, elem, attr, ctrl) -> angular.extend scope, base controller: [ '$scope', 'authentication', ($scope, authentication) -> $scope.$on '$reset', => angular.extend $scope, base $scope.submit = (form) -> return unless form.$valid params = {} for name, control of form when control.$modelValue? params[name] = control.$modelValue method = "$#{form.$name}" authentication[method] params, -> $scope.$emit 'success', form.$name ] scope: model: '=authentication' markdown = ['$filter', '$timeout', ($filter, $timeout) -> link: (scope, elem, attr, ctrl) -> return unless ctrl? input = elem.find('textarea') output = elem.find('div') # Re-render the markdown when the view needs updating. ctrl.$render = -> input.attr('value', ctrl.$viewValue or '') scope.rendered = ($filter 'converter') (ctrl.$viewValue or '') # React to the changes to the text area input.bind 'blur change keyup', -> ctrl.$setViewValue input[0].value scope.$digest() # Auto-focus the input box when the widget becomes editable. # Re-render when it becomes uneditable. scope.$watch 'readonly', (readonly) -> ctrl.$render() unless readonly then $timeout -> input.focus() require: '?ngModel' restrict: 'E' scope: readonly: '@' required: '@' templateUrl: 'markdown.html' ] privacy = -> levels = ['Public', 'Private'] link: (scope, elem, attrs, controller) -> return unless controller? controller.$formatters.push (permissions) -> return unless permissions? if 'group:__world__' in (permissions.read or []) 'Public' else 'Private' controller.$parsers.push (privacy) -> return unless privacy? permissions = controller.$modelValue if privacy is 'Public' if permissions.read unless 'group:__world__' in permissions.read permissions.read.push 'group:__world__' else permissions.read = ['group:__world__'] else read = permissions.read or [] read = (role for role in read when role isnt 'group:__world__') permissions.read = read permissions scope.model = controller scope.levels = levels require: '?ngModel' restrict: 'E' scope: true templateUrl: 'privacy.html' recursive = ['$compile', '$timeout', ($compile, $timeout) -> compile: (tElement, tAttrs, transclude) -> placeholder = angular.element '<!-- recursive -->' attachQueue = [] tick = false template = tElement.contents().clone() tElement.html '' transclude = $compile template, (scope, cloneAttachFn) -> clone = placeholder.clone() cloneAttachFn clone $timeout -> transclude scope, (el, scope) -> attachQueue.push [clone, el] unless tick tick = true requestAnimationFrame -> tick = false for [clone, el] in attachQueue clone.after el clone.bind '$destroy', -> el.remove() attachQueue = [] clone post: (scope, iElement, iAttrs, controller) -> transclude scope, (contents) -> iElement.append contents restrict: 'A' terminal: true ] resettable = -> compile: (tElement, tAttrs, transclude) -> post: (scope, iElement, iAttrs) -> reset = -> transclude scope, (el) -> iElement.replaceWith el iElement = el reset() scope.$on '$reset', reset priority: 5000 restrict: 'A' transclude: 'element' ### # The slow validation directive ties an to a model controller and hides # it while the model is being edited. This behavior improves the user # experience of filling out forms by delaying validation messages until # after the user has made a mistake. ### slowValidate = ['$parse', '$timeout', ($parse, $timeout) -> link: (scope, elem, attr, ctrl) -> return unless ctrl? promise = null elem.addClass 'slow-validate' ctrl[attr.slowValidate]?.$viewChangeListeners?.push (value) -> elem.removeClass 'slow-validate-show' if promise $timeout.cancel promise promise = null promise = $timeout -> elem.addClass 'slow-validate-show' require: '^form' restrict: 'A' ] tabReveal = ['$parse', ($parse) -> compile: (tElement, tAttrs, transclude) -> panes = [] hiddenPanesGet = $parse tAttrs.tabReveal pre: (scope, iElement, iAttrs, [ngModel, tabbable] = controller) -> # Hijack the tabbable controller's addPane so that the visibility of the # secret ones can be managed. This avoids traversing the DOM to find # the tab panes. addPane = tabbable.addPane tabbable.addPane = (element, attr) => removePane = addPane.call tabbable, element, attr panes.push element: element attr: attr => for i in [0..panes.length] if panes[i].element is element panes.splice i, 1 break removePane() post: (scope, iElement, iAttrs, [ngModel, tabbable] = controller) -> tabs = angular.element(iElement.children()[0].childNodes) render = angular.bind ngModel, ngModel.$render ngModel.$render = -> render() hiddenPanes = hiddenPanesGet scope return unless angular.isArray hiddenPanes for i in [0..panes.length-1] pane = panes[i] value = pane.attr.value || pane.attr.title if value == ngModel.$viewValue pane.element.css 'display', '' angular.element(tabs[i]).css 'display', '' else if value in hiddenPanes pane.element.css 'display', 'none' angular.element(tabs[i]).css 'display', 'none' require: ['ngModel', 'tabbable'] ] thread = -> link: (scope, iElement, iAttrs, controller) -> scope.collapsed = false restrict: 'C' scope: true userPicker = -> restrict: 'ACE' scope: model: '=userPickerModel' options: '=userPickerOptions' templateUrl: 'userPicker.html' #Directive will be removed once the angularjs official version will have this directive ngBlur = ['$parse', ($parse) -> (scope, element, attr) -> fn = $parse attr['ngBlur'] element.bind 'blur', (event) -> scope.$apply -> fn scope, $event: event ] repeatAnim = -> restrict: 'A' scope: array: '=' template: '<div ng-init="runAnimOnLast()"><div ng-transclude></div></div>' transclude: true controller: ($scope, $element, $attrs) -> $scope.runAnimOnLast = -> #Run anim on the item's element #(which will be last child of directive element) item=$scope.array[0] itemElm = jQuery($element) .children() .first() .children() unless item._anim? return if item._anim is 'fade' itemElm .css({ opacity: 0 }) .animate({ opacity: 1 }, 1500) else if item._anim is 'slide' itemElm .css({ 'margin-left': itemElm.width() }) .animate({ 'margin-left': '0px' }, 1500) angular.module('h.directives', ['ngSanitize']) .directive('annotation', annotation) .directive('authentication', authentication) .directive('markdown', markdown) .directive('privacy', privacy) .directive('recursive', recursive) .directive('resettable', resettable) .directive('slowValidate', slowValidate) .directive('tabReveal', tabReveal) .directive('thread', thread) .directive('userPicker', userPicker) .directive('ngBlur', ngBlur) .directive('repeatAnim', repeatAnim)
[ { "context": "tails and small heads.\n '''\n\n scientificName: '(Caracal caracal)'\n mainImage: 'assets/fieldguide-conte", "end": 444, "score": 0.7094383239746094, "start": 439, "tag": "NAME", "value": "Carac" } ]
app/lib/field-guide-content/caracal.coffee
zooniverse/snapshot-wisconsin
0
module.exports = description: ''' The caracal is a strongly built cat with a long, slender body covered in short hair that is reddish brown with white around the belly, chin, and throat. A ring of white surrounds the eyes, and a black line runs from each eye to the nose. The caracal has pointed ears with black tufts on the ends and legs that are long and powerful. They have short tails and small heads. ''' scientificName: '(Caracal caracal)' mainImage: 'assets/fieldguide-content/mammals/caracal/caracal-feature.jpg' conservationStatus: 'Least Concern' # Options are Least Concern, Near Threatened, Vulnerable, and Endangered; all have their own little icons as well. information: [{ label: 'Length' value: '62-91 cm' }, { label: 'Height' value: '45 cm' }, { label: 'Weight' value: '10-18 kg' }, { label: 'Lifespan' value: 'up to 12 years' }, { label: 'Gestation' value: '62-81 days' }, { label: 'Avg. number of offspring' value: '1-4' }] sections: [{ title: 'Habitat' content: 'The caracal inhabits a variety of habitats from semidesert to relatively open savanna and scrubland to moist woodlands and savanna regions with lower rainfall.' }, { title: 'Diet' content: 'Small to medium-sized mammals (including antelopes), birds, reptiles, invertebrates, fish, and some plant matter; also known to scavenge.' }, { title: 'Predators' content: 'Lions, Leopards, Hyenas' }, { title: 'Behavior' content: ''' Caracals are said to be nocturnal but are often seen during the day. Social behavior is limited to courtship and mating. They are extremely fast runners, labeled as the fastest cat of their size. They are also skilled jumpers, making vertical leaps several feet high to catch birds. When they hunt antelopes for food, they suffocate them with a strong grip on their throat or muzzle. The caracal produces a range of vocalizations including meows, growls, hisses, and coughing calls. ''' }, { title: 'Breeding' content: ''' Caracals breed year-round. After a gestation period of 62 to 81 days, females give birth to a litter of one to four kittens. Births peak during the rainy season. After 45 days, kittens start to eat meat and are fully weaned after four to six months. Kittens remain with their mothers for about a year. ''' }, { title: 'Fun Facts' style: 'focus-box' content: ''' <ol> <li>A caracal’s ears are controlled by about 20 muscles.</li> <li>Caracals are such accomplished jumpers that they are able to catch birds from the air.</li> <li>The name caracal is derived from a Turkish word, “karakulak,” meaning “black ear.”</li> </ol> ''' },{ title: 'Distribution' content: '<img src="assets/fieldguide-content/mammals/caracal/caracal-map.jpg"/>' }]
188721
module.exports = description: ''' The caracal is a strongly built cat with a long, slender body covered in short hair that is reddish brown with white around the belly, chin, and throat. A ring of white surrounds the eyes, and a black line runs from each eye to the nose. The caracal has pointed ears with black tufts on the ends and legs that are long and powerful. They have short tails and small heads. ''' scientificName: '(<NAME>al caracal)' mainImage: 'assets/fieldguide-content/mammals/caracal/caracal-feature.jpg' conservationStatus: 'Least Concern' # Options are Least Concern, Near Threatened, Vulnerable, and Endangered; all have their own little icons as well. information: [{ label: 'Length' value: '62-91 cm' }, { label: 'Height' value: '45 cm' }, { label: 'Weight' value: '10-18 kg' }, { label: 'Lifespan' value: 'up to 12 years' }, { label: 'Gestation' value: '62-81 days' }, { label: 'Avg. number of offspring' value: '1-4' }] sections: [{ title: 'Habitat' content: 'The caracal inhabits a variety of habitats from semidesert to relatively open savanna and scrubland to moist woodlands and savanna regions with lower rainfall.' }, { title: 'Diet' content: 'Small to medium-sized mammals (including antelopes), birds, reptiles, invertebrates, fish, and some plant matter; also known to scavenge.' }, { title: 'Predators' content: 'Lions, Leopards, Hyenas' }, { title: 'Behavior' content: ''' Caracals are said to be nocturnal but are often seen during the day. Social behavior is limited to courtship and mating. They are extremely fast runners, labeled as the fastest cat of their size. They are also skilled jumpers, making vertical leaps several feet high to catch birds. When they hunt antelopes for food, they suffocate them with a strong grip on their throat or muzzle. The caracal produces a range of vocalizations including meows, growls, hisses, and coughing calls. ''' }, { title: 'Breeding' content: ''' Caracals breed year-round. After a gestation period of 62 to 81 days, females give birth to a litter of one to four kittens. Births peak during the rainy season. After 45 days, kittens start to eat meat and are fully weaned after four to six months. Kittens remain with their mothers for about a year. ''' }, { title: 'Fun Facts' style: 'focus-box' content: ''' <ol> <li>A caracal’s ears are controlled by about 20 muscles.</li> <li>Caracals are such accomplished jumpers that they are able to catch birds from the air.</li> <li>The name caracal is derived from a Turkish word, “karakulak,” meaning “black ear.”</li> </ol> ''' },{ title: 'Distribution' content: '<img src="assets/fieldguide-content/mammals/caracal/caracal-map.jpg"/>' }]
true
module.exports = description: ''' The caracal is a strongly built cat with a long, slender body covered in short hair that is reddish brown with white around the belly, chin, and throat. A ring of white surrounds the eyes, and a black line runs from each eye to the nose. The caracal has pointed ears with black tufts on the ends and legs that are long and powerful. They have short tails and small heads. ''' scientificName: '(PI:NAME:<NAME>END_PIal caracal)' mainImage: 'assets/fieldguide-content/mammals/caracal/caracal-feature.jpg' conservationStatus: 'Least Concern' # Options are Least Concern, Near Threatened, Vulnerable, and Endangered; all have their own little icons as well. information: [{ label: 'Length' value: '62-91 cm' }, { label: 'Height' value: '45 cm' }, { label: 'Weight' value: '10-18 kg' }, { label: 'Lifespan' value: 'up to 12 years' }, { label: 'Gestation' value: '62-81 days' }, { label: 'Avg. number of offspring' value: '1-4' }] sections: [{ title: 'Habitat' content: 'The caracal inhabits a variety of habitats from semidesert to relatively open savanna and scrubland to moist woodlands and savanna regions with lower rainfall.' }, { title: 'Diet' content: 'Small to medium-sized mammals (including antelopes), birds, reptiles, invertebrates, fish, and some plant matter; also known to scavenge.' }, { title: 'Predators' content: 'Lions, Leopards, Hyenas' }, { title: 'Behavior' content: ''' Caracals are said to be nocturnal but are often seen during the day. Social behavior is limited to courtship and mating. They are extremely fast runners, labeled as the fastest cat of their size. They are also skilled jumpers, making vertical leaps several feet high to catch birds. When they hunt antelopes for food, they suffocate them with a strong grip on their throat or muzzle. The caracal produces a range of vocalizations including meows, growls, hisses, and coughing calls. ''' }, { title: 'Breeding' content: ''' Caracals breed year-round. After a gestation period of 62 to 81 days, females give birth to a litter of one to four kittens. Births peak during the rainy season. After 45 days, kittens start to eat meat and are fully weaned after four to six months. Kittens remain with their mothers for about a year. ''' }, { title: 'Fun Facts' style: 'focus-box' content: ''' <ol> <li>A caracal’s ears are controlled by about 20 muscles.</li> <li>Caracals are such accomplished jumpers that they are able to catch birds from the air.</li> <li>The name caracal is derived from a Turkish word, “karakulak,” meaning “black ear.”</li> </ol> ''' },{ title: 'Distribution' content: '<img src="assets/fieldguide-content/mammals/caracal/caracal-map.jpg"/>' }]
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.9983146786689758, "start": 12, "tag": "NAME", "value": "Joyent" } ]
test/simple/test-stream-unshift-read-race.coffee
lxe/io.coffee
0
# Copyright Joyent, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. # This test verifies that: # 1. unshift() does not cause colliding _read() calls. # 2. unshift() after the 'end' event is an error, but after the EOF # signalling null, it is ok, and just creates a new readable chunk. # 3. push() after the EOF signaling null is an error. # 4. _read() is not called after pushing the EOF null chunk. # every third chunk is fast pushError = -> assert.throws -> r.push new Buffer(1) return return common = require("../common") assert = require("assert") stream = require("stream") hwm = 10 r = stream.Readable(highWaterMark: hwm) chunks = 10 t = (chunks * 5) data = new Buffer(chunks * hwm + Math.ceil(hwm / 2)) i = 0 while i < data.length c = "asdf".charCodeAt(i % 4) data[i] = c i++ pos = 0 pushedNull = false r._read = (n) -> push = (fast) -> assert not pushedNull, "push() after null push" c = (if pos >= data.length then null else data.slice(pos, pos + n)) pushedNull = c is null if fast pos += n r.push c pushError() if c is null else setTimeout -> pos += n r.push c pushError() if c is null return return assert not pushedNull, "_read after null push" push not (chunks % 3) return w = stream.Writable() written = [] w._write = (chunk, encoding, cb) -> written.push chunk.toString() cb() return ended = false r.on "end", -> assert not ended, "end emitted more than once" assert.throws -> r.unshift new Buffer(1) return ended = true w.end() return r.on "readable", -> chunk = undefined while null isnt (chunk = r.read(10)) w.write chunk r.unshift new Buffer("1234") if chunk.length > 4 return finished = false w.on "finish", -> finished = true # each chunk should start with 1234, and then be asfdasdfasdf... # The first got pulled out before the first unshift('1234'), so it's # lacking that piece. assert.equal written[0], "asdfasdfas" asdf = "d" console.error "0: %s", written[0] i = 1 while i < written.length console.error "%s: %s", i.toString(32), written[i] assert.equal written[i].slice(0, 4), "1234" j = 4 while j < written[i].length c = written[i].charAt(j) assert.equal c, asdf switch asdf when "a" asdf = "s" when "s" asdf = "d" when "d" asdf = "f" when "f" asdf = "a" j++ i++ return process.on "exit", -> assert.equal written.length, 18 assert ended, "stream ended" assert finished, "stream finished" console.log "ok" return
57549
# Copyright <NAME>, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. # This test verifies that: # 1. unshift() does not cause colliding _read() calls. # 2. unshift() after the 'end' event is an error, but after the EOF # signalling null, it is ok, and just creates a new readable chunk. # 3. push() after the EOF signaling null is an error. # 4. _read() is not called after pushing the EOF null chunk. # every third chunk is fast pushError = -> assert.throws -> r.push new Buffer(1) return return common = require("../common") assert = require("assert") stream = require("stream") hwm = 10 r = stream.Readable(highWaterMark: hwm) chunks = 10 t = (chunks * 5) data = new Buffer(chunks * hwm + Math.ceil(hwm / 2)) i = 0 while i < data.length c = "asdf".charCodeAt(i % 4) data[i] = c i++ pos = 0 pushedNull = false r._read = (n) -> push = (fast) -> assert not pushedNull, "push() after null push" c = (if pos >= data.length then null else data.slice(pos, pos + n)) pushedNull = c is null if fast pos += n r.push c pushError() if c is null else setTimeout -> pos += n r.push c pushError() if c is null return return assert not pushedNull, "_read after null push" push not (chunks % 3) return w = stream.Writable() written = [] w._write = (chunk, encoding, cb) -> written.push chunk.toString() cb() return ended = false r.on "end", -> assert not ended, "end emitted more than once" assert.throws -> r.unshift new Buffer(1) return ended = true w.end() return r.on "readable", -> chunk = undefined while null isnt (chunk = r.read(10)) w.write chunk r.unshift new Buffer("1234") if chunk.length > 4 return finished = false w.on "finish", -> finished = true # each chunk should start with 1234, and then be asfdasdfasdf... # The first got pulled out before the first unshift('1234'), so it's # lacking that piece. assert.equal written[0], "asdfasdfas" asdf = "d" console.error "0: %s", written[0] i = 1 while i < written.length console.error "%s: %s", i.toString(32), written[i] assert.equal written[i].slice(0, 4), "1234" j = 4 while j < written[i].length c = written[i].charAt(j) assert.equal c, asdf switch asdf when "a" asdf = "s" when "s" asdf = "d" when "d" asdf = "f" when "f" asdf = "a" j++ i++ return process.on "exit", -> assert.equal written.length, 18 assert ended, "stream ended" assert finished, "stream finished" console.log "ok" return
true
# Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. # This test verifies that: # 1. unshift() does not cause colliding _read() calls. # 2. unshift() after the 'end' event is an error, but after the EOF # signalling null, it is ok, and just creates a new readable chunk. # 3. push() after the EOF signaling null is an error. # 4. _read() is not called after pushing the EOF null chunk. # every third chunk is fast pushError = -> assert.throws -> r.push new Buffer(1) return return common = require("../common") assert = require("assert") stream = require("stream") hwm = 10 r = stream.Readable(highWaterMark: hwm) chunks = 10 t = (chunks * 5) data = new Buffer(chunks * hwm + Math.ceil(hwm / 2)) i = 0 while i < data.length c = "asdf".charCodeAt(i % 4) data[i] = c i++ pos = 0 pushedNull = false r._read = (n) -> push = (fast) -> assert not pushedNull, "push() after null push" c = (if pos >= data.length then null else data.slice(pos, pos + n)) pushedNull = c is null if fast pos += n r.push c pushError() if c is null else setTimeout -> pos += n r.push c pushError() if c is null return return assert not pushedNull, "_read after null push" push not (chunks % 3) return w = stream.Writable() written = [] w._write = (chunk, encoding, cb) -> written.push chunk.toString() cb() return ended = false r.on "end", -> assert not ended, "end emitted more than once" assert.throws -> r.unshift new Buffer(1) return ended = true w.end() return r.on "readable", -> chunk = undefined while null isnt (chunk = r.read(10)) w.write chunk r.unshift new Buffer("1234") if chunk.length > 4 return finished = false w.on "finish", -> finished = true # each chunk should start with 1234, and then be asfdasdfasdf... # The first got pulled out before the first unshift('1234'), so it's # lacking that piece. assert.equal written[0], "asdfasdfas" asdf = "d" console.error "0: %s", written[0] i = 1 while i < written.length console.error "%s: %s", i.toString(32), written[i] assert.equal written[i].slice(0, 4), "1234" j = 4 while j < written[i].length c = written[i].charAt(j) assert.equal c, asdf switch asdf when "a" asdf = "s" when "s" asdf = "d" when "d" asdf = "f" when "f" asdf = "a" j++ i++ return process.on "exit", -> assert.equal written.length, 18 assert ended, "stream ended" assert finished, "stream finished" console.log "ok" return
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.999143660068512, "start": 12, "tag": "NAME", "value": "Joyent" } ]
test/simple/test-cluster-shared-handle-bind-error.coffee
lxe/io.coffee
0
# Copyright Joyent, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. common = require("../common") assert = require("assert") cluster = require("cluster") net = require("net") if cluster.isMaster # Master opens and binds the socket and shares it with the worker. cluster.schedulingPolicy = cluster.SCHED_NONE # Hog the TCP port so that when the worker tries to bind, it'll fail. net.createServer(assert.fail).listen common.PORT, -> server = this worker = cluster.fork() worker.on "exit", common.mustCall((exitCode) -> assert.equal exitCode, 0 server.close() return ) return else s = net.createServer(assert.fail) s.listen common.PORT, assert.fail.bind(null, "listen should have failed") s.on "error", common.mustCall((err) -> assert.equal err.code, "EADDRINUSE" process.disconnect() return )
199209
# Copyright <NAME>, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. common = require("../common") assert = require("assert") cluster = require("cluster") net = require("net") if cluster.isMaster # Master opens and binds the socket and shares it with the worker. cluster.schedulingPolicy = cluster.SCHED_NONE # Hog the TCP port so that when the worker tries to bind, it'll fail. net.createServer(assert.fail).listen common.PORT, -> server = this worker = cluster.fork() worker.on "exit", common.mustCall((exitCode) -> assert.equal exitCode, 0 server.close() return ) return else s = net.createServer(assert.fail) s.listen common.PORT, assert.fail.bind(null, "listen should have failed") s.on "error", common.mustCall((err) -> assert.equal err.code, "EADDRINUSE" process.disconnect() return )
true
# Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. common = require("../common") assert = require("assert") cluster = require("cluster") net = require("net") if cluster.isMaster # Master opens and binds the socket and shares it with the worker. cluster.schedulingPolicy = cluster.SCHED_NONE # Hog the TCP port so that when the worker tries to bind, it'll fail. net.createServer(assert.fail).listen common.PORT, -> server = this worker = cluster.fork() worker.on "exit", common.mustCall((exitCode) -> assert.equal exitCode, 0 server.close() return ) return else s = net.createServer(assert.fail) s.listen common.PORT, assert.fail.bind(null, "listen should have failed") s.on "error", common.mustCall((err) -> assert.equal err.code, "EADDRINUSE" process.disconnect() return )
[ { "context": "fining interface tests\n#\n# Copyright (C) 2011-2013 Nikolay Nemshilov\n#\n\n{Test,should} = require('lovely')\n\neval(core =", "end": 94, "score": 0.99988853931427, "start": 77, "tag": "NAME", "value": "Nikolay Nemshilov" } ]
stl/core/test/lovely_test.coffee
lovely-io/lovely.io-stl
2
# # The modules loading/defining interface tests # # Copyright (C) 2011-2013 Nikolay Nemshilov # {Test,should} = require('lovely') eval(core = Test.build) Lovely = this.Lovely Test.set '/load.html': """ <html><head> <script src="/core.js"></script> <script> Lovely(["module1", "module2"], function(m1, m2) { alert("Received: "+ m1); alert("Received: "+ m2); alert("Done!"); }); </script> </head></html> """ '/module1.js': """ Lovely("module1", ["module3", "module4"], function(m3, m4) { alert("Received: "+ m3); alert("Received: "+ m4); alert("Initializing: module1"); return "module1"; }); """ '/module2.js': """ Lovely("module2", ["module5"], function(m5) { alert("Received: "+ m5); alert("Initializing: module2"); return "module2"; }); """ '/module3.js': """ Lovely("module3", function() { alert("Initializing: module3"); return "module3"; }); """ '/module4.js': """ Lovely("module4", function() { alert("Initializing: module4"); return "module4"; }); """ '/module5.js': """ Lovely("module5", function() { alert("Initializing: module5"); return "module5"; }); """ '/double.html': """ <html><head> <script src="/core.js"></script> <script> Lovely(["module5", "module5"], function(m1, m2) { alert("Received: "+ m1); alert("Received: "+ m2); alert("Done!"); }); </script> </head></html> """ '/local.html': """ <html><head> <script src="/core.js"></script> <script> Lovely( {baseUrl: "/my/scripts/"}, ["module1", "./module6", "../../module8"], function(m1, m6, m8) { alert("Received: "+ m1); alert("Received: "+ m6); alert("Received: "+ m8); alert("Done!"); } ); </script> </head></html> """ '/my/scripts/module6.js': """ Lovely("module6", {baseUrl: "/other/scripts"}, ["./module7"], function(m7) { alert("Received: "+ m7); alert("Initializing: module6"); return "module6"; } ); """ '/other/scripts/module7.js': """ Lovely("module7", function() { alert("Initializing: module7"); return "module7"; }); """ '/module8.js': """ Lovely("module8", function() { alert("Initializing: module8"); return "module8"; }); """ "/relocated.html": """ <html><head> <script src="/lovely.io/core.js"></script> <script> Lovely(['module11', 'module12'], function(m1, m2) { alert("Received: "+ m1); alert("Received: "+ m2); alert("Done!"); }); </script> </head></html> """ "/lovely.io/core.js": core "/lovely.io/module11.js": """ Lovely('module11', function() { alert("Initializing: m11"); return "m11"; }); """ "/lovely.io/module12.js": """ Lovely('module12', function() { alert("Initializing: m12"); return "m12"; }); """ "/version-configured.html": """ <html><head> <script src="/lovely.io/core.js"></script> <script> Lovely.bundle = { 'versioned-module' : '2.0.0' }; Lovely(['versioned-module'], function(m) { alert('Version '+ m.version); }) </script> </head></html> """ "/lovely.io/versioned-module.js": """ Lovely('versioned-module', function() { return { version: '0.0.0' }; }); """ "/lovely.io/versioned-module-1.0.0.js": """ Lovely('versioned-module-1.0.0', function() { return { version: '1.0.0' }; }); """ "/lovely.io/versioned-module-2.0.0.js": """ Lovely('versioned-module-2.0.0', function() { return { version: '2.0.0' }; }); """ "/local-modules.html" : """ <html><head> <script src="/core.js"></script> <script src="/local-modules/module1.js"></script> <script src="/local-modules/module2.js"></script> </head></html> """ "/local-modules/module1.js" : """ Lovely(['local-module~'], function(LocalModule) { alert('Done!'); }) """ "/local-modules/module2.js" : """ Lovely('local-module', ['module1'], function() { alert('Initializing local-module'); return { version: '0.0.0' }; }) """ describe 'Lovely AMD', -> it 'should find itself by a short name', -> Lovely.module('core').should.equal Lovely it 'should find itself by a long name', -> Lovely.module("core-#{Lovely.version}").should.equal Lovely it "should return nothing if a module doesn't exist", -> (Lovely.module('unknown') is undefined).should.be.true it 'should load the scripts and initialize them in order', (done)-> Test.get '/load.html', (browser)-> browser.alerts.sort().should.eql [ 'Initializing: module3', 'Initializing: module4', 'Initializing: module5', 'Received: module5', 'Initializing: module2', 'Received: module3', 'Received: module4', 'Initializing: module1', 'Received: module1', 'Received: module2', 'Done!' ].sort() done() it 'should not load the same module twice', (done)-> Test.get '/double.html', (browser)-> browser.alerts.sort().should.eql [ 'Initializing: module5', 'Received: module5', 'Received: module5', 'Done!' ].sort() done() it 'should load local modules', (done)-> Test.get '/local.html', (browser)-> browser.alerts.sort().should.eql [ 'Initializing: module8', 'Initializing: module3', 'Initializing: module4', 'Initializing: module7', 'Received: module7', 'Initializing: module6', 'Received: module3', 'Received: module4', 'Initializing: module1', 'Received: module1', 'Received: module6', 'Received: module8', 'Done!' ].sort() done() it "should still load everything properly", (done)-> Test.get '/relocated.html', (browser) -> browser.alerts.should.eql [ 'Initializing: m11', 'Initializing: m12', 'Received: m11', 'Received: m12', 'Done!' ] done() it "should load the bundled version", (done)-> Test.get '/version-configured.html', (browser)-> browser.alerts.should.eql [ 'Version 2.0.0' ] done() it "should just wait on the ~ marked modules", (done)-> Test.get '/local-modules.html', (browser)-> browser.alerts.should.eql [ 'Initializing: module3', 'Initializing: module4', 'Received: module3', 'Received: module4', 'Initializing: module1', 'Initializing local-module', 'Done!' ] done()
87577
# # The modules loading/defining interface tests # # Copyright (C) 2011-2013 <NAME> # {Test,should} = require('lovely') eval(core = Test.build) Lovely = this.Lovely Test.set '/load.html': """ <html><head> <script src="/core.js"></script> <script> Lovely(["module1", "module2"], function(m1, m2) { alert("Received: "+ m1); alert("Received: "+ m2); alert("Done!"); }); </script> </head></html> """ '/module1.js': """ Lovely("module1", ["module3", "module4"], function(m3, m4) { alert("Received: "+ m3); alert("Received: "+ m4); alert("Initializing: module1"); return "module1"; }); """ '/module2.js': """ Lovely("module2", ["module5"], function(m5) { alert("Received: "+ m5); alert("Initializing: module2"); return "module2"; }); """ '/module3.js': """ Lovely("module3", function() { alert("Initializing: module3"); return "module3"; }); """ '/module4.js': """ Lovely("module4", function() { alert("Initializing: module4"); return "module4"; }); """ '/module5.js': """ Lovely("module5", function() { alert("Initializing: module5"); return "module5"; }); """ '/double.html': """ <html><head> <script src="/core.js"></script> <script> Lovely(["module5", "module5"], function(m1, m2) { alert("Received: "+ m1); alert("Received: "+ m2); alert("Done!"); }); </script> </head></html> """ '/local.html': """ <html><head> <script src="/core.js"></script> <script> Lovely( {baseUrl: "/my/scripts/"}, ["module1", "./module6", "../../module8"], function(m1, m6, m8) { alert("Received: "+ m1); alert("Received: "+ m6); alert("Received: "+ m8); alert("Done!"); } ); </script> </head></html> """ '/my/scripts/module6.js': """ Lovely("module6", {baseUrl: "/other/scripts"}, ["./module7"], function(m7) { alert("Received: "+ m7); alert("Initializing: module6"); return "module6"; } ); """ '/other/scripts/module7.js': """ Lovely("module7", function() { alert("Initializing: module7"); return "module7"; }); """ '/module8.js': """ Lovely("module8", function() { alert("Initializing: module8"); return "module8"; }); """ "/relocated.html": """ <html><head> <script src="/lovely.io/core.js"></script> <script> Lovely(['module11', 'module12'], function(m1, m2) { alert("Received: "+ m1); alert("Received: "+ m2); alert("Done!"); }); </script> </head></html> """ "/lovely.io/core.js": core "/lovely.io/module11.js": """ Lovely('module11', function() { alert("Initializing: m11"); return "m11"; }); """ "/lovely.io/module12.js": """ Lovely('module12', function() { alert("Initializing: m12"); return "m12"; }); """ "/version-configured.html": """ <html><head> <script src="/lovely.io/core.js"></script> <script> Lovely.bundle = { 'versioned-module' : '2.0.0' }; Lovely(['versioned-module'], function(m) { alert('Version '+ m.version); }) </script> </head></html> """ "/lovely.io/versioned-module.js": """ Lovely('versioned-module', function() { return { version: '0.0.0' }; }); """ "/lovely.io/versioned-module-1.0.0.js": """ Lovely('versioned-module-1.0.0', function() { return { version: '1.0.0' }; }); """ "/lovely.io/versioned-module-2.0.0.js": """ Lovely('versioned-module-2.0.0', function() { return { version: '2.0.0' }; }); """ "/local-modules.html" : """ <html><head> <script src="/core.js"></script> <script src="/local-modules/module1.js"></script> <script src="/local-modules/module2.js"></script> </head></html> """ "/local-modules/module1.js" : """ Lovely(['local-module~'], function(LocalModule) { alert('Done!'); }) """ "/local-modules/module2.js" : """ Lovely('local-module', ['module1'], function() { alert('Initializing local-module'); return { version: '0.0.0' }; }) """ describe 'Lovely AMD', -> it 'should find itself by a short name', -> Lovely.module('core').should.equal Lovely it 'should find itself by a long name', -> Lovely.module("core-#{Lovely.version}").should.equal Lovely it "should return nothing if a module doesn't exist", -> (Lovely.module('unknown') is undefined).should.be.true it 'should load the scripts and initialize them in order', (done)-> Test.get '/load.html', (browser)-> browser.alerts.sort().should.eql [ 'Initializing: module3', 'Initializing: module4', 'Initializing: module5', 'Received: module5', 'Initializing: module2', 'Received: module3', 'Received: module4', 'Initializing: module1', 'Received: module1', 'Received: module2', 'Done!' ].sort() done() it 'should not load the same module twice', (done)-> Test.get '/double.html', (browser)-> browser.alerts.sort().should.eql [ 'Initializing: module5', 'Received: module5', 'Received: module5', 'Done!' ].sort() done() it 'should load local modules', (done)-> Test.get '/local.html', (browser)-> browser.alerts.sort().should.eql [ 'Initializing: module8', 'Initializing: module3', 'Initializing: module4', 'Initializing: module7', 'Received: module7', 'Initializing: module6', 'Received: module3', 'Received: module4', 'Initializing: module1', 'Received: module1', 'Received: module6', 'Received: module8', 'Done!' ].sort() done() it "should still load everything properly", (done)-> Test.get '/relocated.html', (browser) -> browser.alerts.should.eql [ 'Initializing: m11', 'Initializing: m12', 'Received: m11', 'Received: m12', 'Done!' ] done() it "should load the bundled version", (done)-> Test.get '/version-configured.html', (browser)-> browser.alerts.should.eql [ 'Version 2.0.0' ] done() it "should just wait on the ~ marked modules", (done)-> Test.get '/local-modules.html', (browser)-> browser.alerts.should.eql [ 'Initializing: module3', 'Initializing: module4', 'Received: module3', 'Received: module4', 'Initializing: module1', 'Initializing local-module', 'Done!' ] done()
true
# # The modules loading/defining interface tests # # Copyright (C) 2011-2013 PI:NAME:<NAME>END_PI # {Test,should} = require('lovely') eval(core = Test.build) Lovely = this.Lovely Test.set '/load.html': """ <html><head> <script src="/core.js"></script> <script> Lovely(["module1", "module2"], function(m1, m2) { alert("Received: "+ m1); alert("Received: "+ m2); alert("Done!"); }); </script> </head></html> """ '/module1.js': """ Lovely("module1", ["module3", "module4"], function(m3, m4) { alert("Received: "+ m3); alert("Received: "+ m4); alert("Initializing: module1"); return "module1"; }); """ '/module2.js': """ Lovely("module2", ["module5"], function(m5) { alert("Received: "+ m5); alert("Initializing: module2"); return "module2"; }); """ '/module3.js': """ Lovely("module3", function() { alert("Initializing: module3"); return "module3"; }); """ '/module4.js': """ Lovely("module4", function() { alert("Initializing: module4"); return "module4"; }); """ '/module5.js': """ Lovely("module5", function() { alert("Initializing: module5"); return "module5"; }); """ '/double.html': """ <html><head> <script src="/core.js"></script> <script> Lovely(["module5", "module5"], function(m1, m2) { alert("Received: "+ m1); alert("Received: "+ m2); alert("Done!"); }); </script> </head></html> """ '/local.html': """ <html><head> <script src="/core.js"></script> <script> Lovely( {baseUrl: "/my/scripts/"}, ["module1", "./module6", "../../module8"], function(m1, m6, m8) { alert("Received: "+ m1); alert("Received: "+ m6); alert("Received: "+ m8); alert("Done!"); } ); </script> </head></html> """ '/my/scripts/module6.js': """ Lovely("module6", {baseUrl: "/other/scripts"}, ["./module7"], function(m7) { alert("Received: "+ m7); alert("Initializing: module6"); return "module6"; } ); """ '/other/scripts/module7.js': """ Lovely("module7", function() { alert("Initializing: module7"); return "module7"; }); """ '/module8.js': """ Lovely("module8", function() { alert("Initializing: module8"); return "module8"; }); """ "/relocated.html": """ <html><head> <script src="/lovely.io/core.js"></script> <script> Lovely(['module11', 'module12'], function(m1, m2) { alert("Received: "+ m1); alert("Received: "+ m2); alert("Done!"); }); </script> </head></html> """ "/lovely.io/core.js": core "/lovely.io/module11.js": """ Lovely('module11', function() { alert("Initializing: m11"); return "m11"; }); """ "/lovely.io/module12.js": """ Lovely('module12', function() { alert("Initializing: m12"); return "m12"; }); """ "/version-configured.html": """ <html><head> <script src="/lovely.io/core.js"></script> <script> Lovely.bundle = { 'versioned-module' : '2.0.0' }; Lovely(['versioned-module'], function(m) { alert('Version '+ m.version); }) </script> </head></html> """ "/lovely.io/versioned-module.js": """ Lovely('versioned-module', function() { return { version: '0.0.0' }; }); """ "/lovely.io/versioned-module-1.0.0.js": """ Lovely('versioned-module-1.0.0', function() { return { version: '1.0.0' }; }); """ "/lovely.io/versioned-module-2.0.0.js": """ Lovely('versioned-module-2.0.0', function() { return { version: '2.0.0' }; }); """ "/local-modules.html" : """ <html><head> <script src="/core.js"></script> <script src="/local-modules/module1.js"></script> <script src="/local-modules/module2.js"></script> </head></html> """ "/local-modules/module1.js" : """ Lovely(['local-module~'], function(LocalModule) { alert('Done!'); }) """ "/local-modules/module2.js" : """ Lovely('local-module', ['module1'], function() { alert('Initializing local-module'); return { version: '0.0.0' }; }) """ describe 'Lovely AMD', -> it 'should find itself by a short name', -> Lovely.module('core').should.equal Lovely it 'should find itself by a long name', -> Lovely.module("core-#{Lovely.version}").should.equal Lovely it "should return nothing if a module doesn't exist", -> (Lovely.module('unknown') is undefined).should.be.true it 'should load the scripts and initialize them in order', (done)-> Test.get '/load.html', (browser)-> browser.alerts.sort().should.eql [ 'Initializing: module3', 'Initializing: module4', 'Initializing: module5', 'Received: module5', 'Initializing: module2', 'Received: module3', 'Received: module4', 'Initializing: module1', 'Received: module1', 'Received: module2', 'Done!' ].sort() done() it 'should not load the same module twice', (done)-> Test.get '/double.html', (browser)-> browser.alerts.sort().should.eql [ 'Initializing: module5', 'Received: module5', 'Received: module5', 'Done!' ].sort() done() it 'should load local modules', (done)-> Test.get '/local.html', (browser)-> browser.alerts.sort().should.eql [ 'Initializing: module8', 'Initializing: module3', 'Initializing: module4', 'Initializing: module7', 'Received: module7', 'Initializing: module6', 'Received: module3', 'Received: module4', 'Initializing: module1', 'Received: module1', 'Received: module6', 'Received: module8', 'Done!' ].sort() done() it "should still load everything properly", (done)-> Test.get '/relocated.html', (browser) -> browser.alerts.should.eql [ 'Initializing: m11', 'Initializing: m12', 'Received: m11', 'Received: m12', 'Done!' ] done() it "should load the bundled version", (done)-> Test.get '/version-configured.html', (browser)-> browser.alerts.should.eql [ 'Version 2.0.0' ] done() it "should just wait on the ~ marked modules", (done)-> Test.get '/local-modules.html', (browser)-> browser.alerts.should.eql [ 'Initializing: module3', 'Initializing: module4', 'Received: module3', 'Received: module4', 'Initializing: module1', 'Initializing local-module', 'Done!' ] done()
[ { "context": " req.connection.remoteAddress\n\nGITHUB_IP_RANGE = \"192.30.252.0/22\"\n\nipIsFromGithub = (ip) ->\n range_check.in_ra", "end": 530, "score": 0.9997480511665344, "start": 518, "tag": "IP_ADDRESS", "value": "192.30.252.0" } ]
server/controllers/deploy.coffee
unepwcmc/NRT
0
AppConfig = require('../initializers/config') Deploy = require('../lib/deploy') range_check = require('range_check') _ = require('underscore') tagRefersToServer = (tag, serverTags) -> chunks = tag.split('-') if chunks[0] is 'deploy' deploymentTags = chunks[1] deploymentTags = deploymentTags.split(',') return _.intersection(deploymentTags, serverTags).length isnt 0 else return false getIpFromRequest = (req) -> req.headers['x-real-ip'] or req.connection.remoteAddress GITHUB_IP_RANGE = "192.30.252.0/22" ipIsFromGithub = (ip) -> range_check.in_range(ip, GITHUB_IP_RANGE) exports.index = (req, res) -> remoteIp = getIpFromRequest(req) env = process.env.NODE_ENV env ||= 'development' if env isnt 'development' return res.send 401 unless ipIsFromGithub(remoteIp) console.log "Got deploy message from #{req.body.ref}" serverTags = AppConfig.get('deploy')?.tags || [] serverName = AppConfig.get('server')?.name serverTags.unshift(serverName) if serverName? tagName = req.body.ref unless tagRefersToServer(tagName, serverTags) errMessage = "Only deploys with tag(s) #{serverTags.join(',')} are accepted" console.log errMessage return res.send 500, errMessage console.log "Updating code from #{tagName}..." Deploy.deploy(tagName).then(-> console.log "Code update finished, restarting server" process.exit() ).catch((err)-> console.log "Error updating code:" console.error err ) res.send 200
117114
AppConfig = require('../initializers/config') Deploy = require('../lib/deploy') range_check = require('range_check') _ = require('underscore') tagRefersToServer = (tag, serverTags) -> chunks = tag.split('-') if chunks[0] is 'deploy' deploymentTags = chunks[1] deploymentTags = deploymentTags.split(',') return _.intersection(deploymentTags, serverTags).length isnt 0 else return false getIpFromRequest = (req) -> req.headers['x-real-ip'] or req.connection.remoteAddress GITHUB_IP_RANGE = "172.16.17.32/22" ipIsFromGithub = (ip) -> range_check.in_range(ip, GITHUB_IP_RANGE) exports.index = (req, res) -> remoteIp = getIpFromRequest(req) env = process.env.NODE_ENV env ||= 'development' if env isnt 'development' return res.send 401 unless ipIsFromGithub(remoteIp) console.log "Got deploy message from #{req.body.ref}" serverTags = AppConfig.get('deploy')?.tags || [] serverName = AppConfig.get('server')?.name serverTags.unshift(serverName) if serverName? tagName = req.body.ref unless tagRefersToServer(tagName, serverTags) errMessage = "Only deploys with tag(s) #{serverTags.join(',')} are accepted" console.log errMessage return res.send 500, errMessage console.log "Updating code from #{tagName}..." Deploy.deploy(tagName).then(-> console.log "Code update finished, restarting server" process.exit() ).catch((err)-> console.log "Error updating code:" console.error err ) res.send 200
true
AppConfig = require('../initializers/config') Deploy = require('../lib/deploy') range_check = require('range_check') _ = require('underscore') tagRefersToServer = (tag, serverTags) -> chunks = tag.split('-') if chunks[0] is 'deploy' deploymentTags = chunks[1] deploymentTags = deploymentTags.split(',') return _.intersection(deploymentTags, serverTags).length isnt 0 else return false getIpFromRequest = (req) -> req.headers['x-real-ip'] or req.connection.remoteAddress GITHUB_IP_RANGE = "PI:IP_ADDRESS:172.16.17.32END_PI/22" ipIsFromGithub = (ip) -> range_check.in_range(ip, GITHUB_IP_RANGE) exports.index = (req, res) -> remoteIp = getIpFromRequest(req) env = process.env.NODE_ENV env ||= 'development' if env isnt 'development' return res.send 401 unless ipIsFromGithub(remoteIp) console.log "Got deploy message from #{req.body.ref}" serverTags = AppConfig.get('deploy')?.tags || [] serverName = AppConfig.get('server')?.name serverTags.unshift(serverName) if serverName? tagName = req.body.ref unless tagRefersToServer(tagName, serverTags) errMessage = "Only deploys with tag(s) #{serverTags.join(',')} are accepted" console.log errMessage return res.send 500, errMessage console.log "Updating code from #{tagName}..." Deploy.deploy(tagName).then(-> console.log "Code update finished, restarting server" process.exit() ).catch((err)-> console.log "Error updating code:" console.error err ) res.send 200
[ { "context": " socket.emit \"login\",\n username: username,\n password: password,\n if roomn", "end": 4671, "score": 0.9838566780090332, "start": 4663, "tag": "USERNAME", "value": "username" }, { "context": " username: username,\n ...
v0.5/TinyChat/js/main.coffee
KingSann/TinyChat
1
socket = io() colors = [ "#e21400", "#91580f", "#f8a700", "#f78b00", "#58dc00", "#287b00", "#a8f07a", "#4ae8c4", "#3b88eb", "#3824aa", "#a700ff", "#d300e7", ] $window = $ window $message = $ ".message" $inputbox = $ ".inputbox" disable = time: false notice: true manual = {} # 读取base64编码 filereader = (callback, fr = null, $file = null) -> fr = new FileReader() $file = $ "<input></input>" .attr "type", "file" .css "display", "none" .appendTo $ "body" .change -> fr.readAsDataURL(this.files[0]) if this.files.length $file.click() fr.onload = (data) -> callback data.target.result $file.remove() newnotice = (title, body) -> new Notification title, body: body, noscreen: true if disable.notice addmsg = (username, msg, time, ishist) -> $ "<div></div>" .addClass "msg" .append($ "<span></span>" .addClass "username" .text "#{if ishist then "(leave)" else ""} #{username}" .css "color", colors[parseInt($.md5(username), 16) % colors.length]) .append($ "<span></span>" .addClass "time" .text time .css "display", if disable.time then "none" else "") .append($ "<span></span>" .addClass "say" .text msg) .hide() .fadeIn "normal", -> $message[0].scrollTop = $message[0].scrollHeight .appendTo $message newnotice "通知", "新消息" addsys = (msg, time) -> $ "<div></div>" .append($ "<span></span>" .addClass "time" .text time .css "display", if disable.time then "none" else "") .addClass "sys" .append($ "<span></span>" .text msg) .hide() .fadeIn "normal", -> $message[0].scrollTop = $message[0].scrollHeight .appendTo $message newnotice "通知", "新系统消息" addimg = (username, msg, time, ishist) -> $ "<div></div>" .append($ "<span></span>" .addClass "username" .text "#{if ishist then "(leave)" else ""} #{username}" .css "color", colors[parseInt($.md5(username), 16) % colors.length]) .append($ "<span></span>" .addClass "time" .text time .css "display", if disable.time then "none" else "") .append($ "<img></img>" .addClass "img" .attr "src", msg) .hide() .fadeIn "normal", -> $message[0].scrollTop = $message[0].scrollHeight .appendTo $message newnotice "通知", "新图片" socket.on "sys", (data) -> addsys data.data, data.time socket.on "new message", (data) -> addmsg data.username, data.data, data.time, data.ishist socket.on "new image", (data) -> addimg data.username, data.data, data.time, data.ishist socket.on "disconnect", (data) -> $("body").empty() socket = null class Cmd @cache = {} @info = {} @nodefault = {} @set = (key, info, val) -> @info[key] = info @cache[key] = val @feed = (str) -> for key, val of @cache if (str[0 .. key.length - 1] is key and str[key.length] is " ") or (str is key) val str[key.length + 1 ..] return true return false @nodef = (str) -> for key, val of @cache if (str[0 .. key.length - 1] is key and str[key.length] is " ") and @nodefault[key] return true else if (str is key) and @nodefault[key] return true return false $window.keydown (ent) -> $inputbox.focus() if ent.which is 13 str = $inputbox.val() if str[0] is "/" if Cmd.feed str if not Cmd.nodef str $inputbox.val "" $inputbox.blur() else addsys "command not found: #{str}", "" else socket.emit "message", type: "text", data: str, ishist: false, $inputbox.val "" $inputbox.blur() Cmd.set "/img", "如果需要发送图片, 使用: /img", -> filereader (data) -> socket.emit "message", type: "image", data: data, ishist: false, Cmd.set "/login", "如果需要登录, 使用: /login 用户名 密码", (data) -> [username, password, roomname, roompassword] = data.split " " socket.emit "login", username: username, password: password, if roomname # 事实上这么些有点小问题,如果由于网络原因,join比login先emit到server,会返回加入房间失败 socket.emit "join", roomname: roomname, roompassword: roompassword Cmd.set "/join", "如果需要加入房间, 使用: /join 房间名 房间密码", (data) -> [roomname, roompassword] = data.split " " socket.emit "join", roomname: roomname, roompassword: roompassword Cmd.set "/logout", "如果需要登出, 使用: /logout", -> socket.emit "logout" Cmd.set "/eraseHist", "如果需要清空留言, 使用: /eraseHist", -> socket.emit "eraseHist" Cmd.set "/leave", "如果需要离开房间, 使用: /leave", -> $message.empty() socket.emit "leave" Cmd.set "/lvmsg", "如果需要留言, 使用: /lvmsg 文字", (data) -> socket.emit "message", type: "text", data: data, ishist: true, Cmd.set "/lvimg", "如果需要留图, 使用: /lvimg", -> filereader (data) -> socket.emit "message", type: "image", data: data, ishist: true, Cmd.set "/help", "如果需要查看命令, 使用: /help", (data) -> if Cmd.info[data] addsys Cmd.info[data], "" else addsys "command not found: /help #{data}", "" Cmd.set "/manual", "如果需要查看命令列表, 使用: /manual", -> addsys val, "" for key, val of Cmd.info Cmd.set "/info", "如果需要获取信息, 使用: /info [curuser | me | room | leftmsg]", (data) -> socket.emit "info", data: data Cmd.set "/clear", "如果需要清空消息, 使用: /clear [sys | all]", (data) -> switch data when "sys" $(".message>*").filter(".sys").fadeOut "normal", -> $(this).remove() when "all" $(".message>*").fadeOut "normal", -> $(this).remove() else addsys "command not found: /clear #{data}", "" Cmd.set "/switch", "如果需要修改开关, 使用: /switch [disable | enable] [time | notice]", (data) -> [type, obj] = data.split " " if obj is "time" if type is "disable" disable.time = true $(".time").fadeOut() else if type is "enable" disable.time = false $(".time").fadeIn() else addsys "command not found: /switch #{data}", "" else if obj is "notice" if type is "disable" disable.notice = true else if type is "enable" disable.notice = false else addsys "command not found: /switch #{data}", "" else addsys "command not found: /switch #{data}", "" Cmd.set "/emoji", "如果需要添加表情, 使用: /emoji 表情名拼音{xiaoku: 😂 | lenghan: 😓 | shuijiao: 😪 | ku: 😢 | gaoxing: 😊}", (data) -> Cmd.nodefault["/emoji"] = true dt = xiaoku: "😂", lenghan: "😓", shuijiao: "😪", ku: "😢", gaoxing: "😊" if dt[data] $inputbox.val dt[data] else addsys "command not found: /emoji #{data}", "" # 申请通知权限 Notification.requestPermission()
17144
socket = io() colors = [ "#e21400", "#91580f", "#f8a700", "#f78b00", "#58dc00", "#287b00", "#a8f07a", "#4ae8c4", "#3b88eb", "#3824aa", "#a700ff", "#d300e7", ] $window = $ window $message = $ ".message" $inputbox = $ ".inputbox" disable = time: false notice: true manual = {} # 读取base64编码 filereader = (callback, fr = null, $file = null) -> fr = new FileReader() $file = $ "<input></input>" .attr "type", "file" .css "display", "none" .appendTo $ "body" .change -> fr.readAsDataURL(this.files[0]) if this.files.length $file.click() fr.onload = (data) -> callback data.target.result $file.remove() newnotice = (title, body) -> new Notification title, body: body, noscreen: true if disable.notice addmsg = (username, msg, time, ishist) -> $ "<div></div>" .addClass "msg" .append($ "<span></span>" .addClass "username" .text "#{if ishist then "(leave)" else ""} #{username}" .css "color", colors[parseInt($.md5(username), 16) % colors.length]) .append($ "<span></span>" .addClass "time" .text time .css "display", if disable.time then "none" else "") .append($ "<span></span>" .addClass "say" .text msg) .hide() .fadeIn "normal", -> $message[0].scrollTop = $message[0].scrollHeight .appendTo $message newnotice "通知", "新消息" addsys = (msg, time) -> $ "<div></div>" .append($ "<span></span>" .addClass "time" .text time .css "display", if disable.time then "none" else "") .addClass "sys" .append($ "<span></span>" .text msg) .hide() .fadeIn "normal", -> $message[0].scrollTop = $message[0].scrollHeight .appendTo $message newnotice "通知", "新系统消息" addimg = (username, msg, time, ishist) -> $ "<div></div>" .append($ "<span></span>" .addClass "username" .text "#{if ishist then "(leave)" else ""} #{username}" .css "color", colors[parseInt($.md5(username), 16) % colors.length]) .append($ "<span></span>" .addClass "time" .text time .css "display", if disable.time then "none" else "") .append($ "<img></img>" .addClass "img" .attr "src", msg) .hide() .fadeIn "normal", -> $message[0].scrollTop = $message[0].scrollHeight .appendTo $message newnotice "通知", "新图片" socket.on "sys", (data) -> addsys data.data, data.time socket.on "new message", (data) -> addmsg data.username, data.data, data.time, data.ishist socket.on "new image", (data) -> addimg data.username, data.data, data.time, data.ishist socket.on "disconnect", (data) -> $("body").empty() socket = null class Cmd @cache = {} @info = {} @nodefault = {} @set = (key, info, val) -> @info[key] = info @cache[key] = val @feed = (str) -> for key, val of @cache if (str[0 .. key.length - 1] is key and str[key.length] is " ") or (str is key) val str[key.length + 1 ..] return true return false @nodef = (str) -> for key, val of @cache if (str[0 .. key.length - 1] is key and str[key.length] is " ") and @nodefault[key] return true else if (str is key) and @nodefault[key] return true return false $window.keydown (ent) -> $inputbox.focus() if ent.which is 13 str = $inputbox.val() if str[0] is "/" if Cmd.feed str if not Cmd.nodef str $inputbox.val "" $inputbox.blur() else addsys "command not found: #{str}", "" else socket.emit "message", type: "text", data: str, ishist: false, $inputbox.val "" $inputbox.blur() Cmd.set "/img", "如果需要发送图片, 使用: /img", -> filereader (data) -> socket.emit "message", type: "image", data: data, ishist: false, Cmd.set "/login", "如果需要登录, 使用: /login 用户名 密码", (data) -> [username, password, roomname, roompassword] = data.split " " socket.emit "login", username: username, password: <PASSWORD>, if roomname # 事实上这么些有点小问题,如果由于网络原因,join比login先emit到server,会返回加入房间失败 socket.emit "join", roomname: roomname, roompassword: roompassword Cmd.set "/join", "如果需要加入房间, 使用: /join 房间名 房间密码", (data) -> [roomname, roompassword] = data.split " " socket.emit "join", roomname: roomname, roompassword: <PASSWORD> Cmd.set "/logout", "如果需要登出, 使用: /logout", -> socket.emit "logout" Cmd.set "/eraseHist", "如果需要清空留言, 使用: /eraseHist", -> socket.emit "eraseHist" Cmd.set "/leave", "如果需要离开房间, 使用: /leave", -> $message.empty() socket.emit "leave" Cmd.set "/lvmsg", "如果需要留言, 使用: /lvmsg 文字", (data) -> socket.emit "message", type: "text", data: data, ishist: true, Cmd.set "/lvimg", "如果需要留图, 使用: /lvimg", -> filereader (data) -> socket.emit "message", type: "image", data: data, ishist: true, Cmd.set "/help", "如果需要查看命令, 使用: /help", (data) -> if Cmd.info[data] addsys Cmd.info[data], "" else addsys "command not found: /help #{data}", "" Cmd.set "/manual", "如果需要查看命令列表, 使用: /manual", -> addsys val, "" for key, val of Cmd.info Cmd.set "/info", "如果需要获取信息, 使用: /info [curuser | me | room | leftmsg]", (data) -> socket.emit "info", data: data Cmd.set "/clear", "如果需要清空消息, 使用: /clear [sys | all]", (data) -> switch data when "sys" $(".message>*").filter(".sys").fadeOut "normal", -> $(this).remove() when "all" $(".message>*").fadeOut "normal", -> $(this).remove() else addsys "command not found: /clear #{data}", "" Cmd.set "/switch", "如果需要修改开关, 使用: /switch [disable | enable] [time | notice]", (data) -> [type, obj] = data.split " " if obj is "time" if type is "disable" disable.time = true $(".time").fadeOut() else if type is "enable" disable.time = false $(".time").fadeIn() else addsys "command not found: /switch #{data}", "" else if obj is "notice" if type is "disable" disable.notice = true else if type is "enable" disable.notice = false else addsys "command not found: /switch #{data}", "" else addsys "command not found: /switch #{data}", "" Cmd.set "/emoji", "如果需要添加表情, 使用: /emoji 表情名拼音{xiaoku: 😂 | lenghan: 😓 | shuijiao: 😪 | ku: 😢 | gaoxing: 😊}", (data) -> Cmd.nodefault["/emoji"] = true dt = xiaoku: "😂", lenghan: "😓", shuijiao: "😪", ku: "😢", gaoxing: "😊" if dt[data] $inputbox.val dt[data] else addsys "command not found: /emoji #{data}", "" # 申请通知权限 Notification.requestPermission()
true
socket = io() colors = [ "#e21400", "#91580f", "#f8a700", "#f78b00", "#58dc00", "#287b00", "#a8f07a", "#4ae8c4", "#3b88eb", "#3824aa", "#a700ff", "#d300e7", ] $window = $ window $message = $ ".message" $inputbox = $ ".inputbox" disable = time: false notice: true manual = {} # 读取base64编码 filereader = (callback, fr = null, $file = null) -> fr = new FileReader() $file = $ "<input></input>" .attr "type", "file" .css "display", "none" .appendTo $ "body" .change -> fr.readAsDataURL(this.files[0]) if this.files.length $file.click() fr.onload = (data) -> callback data.target.result $file.remove() newnotice = (title, body) -> new Notification title, body: body, noscreen: true if disable.notice addmsg = (username, msg, time, ishist) -> $ "<div></div>" .addClass "msg" .append($ "<span></span>" .addClass "username" .text "#{if ishist then "(leave)" else ""} #{username}" .css "color", colors[parseInt($.md5(username), 16) % colors.length]) .append($ "<span></span>" .addClass "time" .text time .css "display", if disable.time then "none" else "") .append($ "<span></span>" .addClass "say" .text msg) .hide() .fadeIn "normal", -> $message[0].scrollTop = $message[0].scrollHeight .appendTo $message newnotice "通知", "新消息" addsys = (msg, time) -> $ "<div></div>" .append($ "<span></span>" .addClass "time" .text time .css "display", if disable.time then "none" else "") .addClass "sys" .append($ "<span></span>" .text msg) .hide() .fadeIn "normal", -> $message[0].scrollTop = $message[0].scrollHeight .appendTo $message newnotice "通知", "新系统消息" addimg = (username, msg, time, ishist) -> $ "<div></div>" .append($ "<span></span>" .addClass "username" .text "#{if ishist then "(leave)" else ""} #{username}" .css "color", colors[parseInt($.md5(username), 16) % colors.length]) .append($ "<span></span>" .addClass "time" .text time .css "display", if disable.time then "none" else "") .append($ "<img></img>" .addClass "img" .attr "src", msg) .hide() .fadeIn "normal", -> $message[0].scrollTop = $message[0].scrollHeight .appendTo $message newnotice "通知", "新图片" socket.on "sys", (data) -> addsys data.data, data.time socket.on "new message", (data) -> addmsg data.username, data.data, data.time, data.ishist socket.on "new image", (data) -> addimg data.username, data.data, data.time, data.ishist socket.on "disconnect", (data) -> $("body").empty() socket = null class Cmd @cache = {} @info = {} @nodefault = {} @set = (key, info, val) -> @info[key] = info @cache[key] = val @feed = (str) -> for key, val of @cache if (str[0 .. key.length - 1] is key and str[key.length] is " ") or (str is key) val str[key.length + 1 ..] return true return false @nodef = (str) -> for key, val of @cache if (str[0 .. key.length - 1] is key and str[key.length] is " ") and @nodefault[key] return true else if (str is key) and @nodefault[key] return true return false $window.keydown (ent) -> $inputbox.focus() if ent.which is 13 str = $inputbox.val() if str[0] is "/" if Cmd.feed str if not Cmd.nodef str $inputbox.val "" $inputbox.blur() else addsys "command not found: #{str}", "" else socket.emit "message", type: "text", data: str, ishist: false, $inputbox.val "" $inputbox.blur() Cmd.set "/img", "如果需要发送图片, 使用: /img", -> filereader (data) -> socket.emit "message", type: "image", data: data, ishist: false, Cmd.set "/login", "如果需要登录, 使用: /login 用户名 密码", (data) -> [username, password, roomname, roompassword] = data.split " " socket.emit "login", username: username, password: PI:PASSWORD:<PASSWORD>END_PI, if roomname # 事实上这么些有点小问题,如果由于网络原因,join比login先emit到server,会返回加入房间失败 socket.emit "join", roomname: roomname, roompassword: roompassword Cmd.set "/join", "如果需要加入房间, 使用: /join 房间名 房间密码", (data) -> [roomname, roompassword] = data.split " " socket.emit "join", roomname: roomname, roompassword: PI:PASSWORD:<PASSWORD>END_PI Cmd.set "/logout", "如果需要登出, 使用: /logout", -> socket.emit "logout" Cmd.set "/eraseHist", "如果需要清空留言, 使用: /eraseHist", -> socket.emit "eraseHist" Cmd.set "/leave", "如果需要离开房间, 使用: /leave", -> $message.empty() socket.emit "leave" Cmd.set "/lvmsg", "如果需要留言, 使用: /lvmsg 文字", (data) -> socket.emit "message", type: "text", data: data, ishist: true, Cmd.set "/lvimg", "如果需要留图, 使用: /lvimg", -> filereader (data) -> socket.emit "message", type: "image", data: data, ishist: true, Cmd.set "/help", "如果需要查看命令, 使用: /help", (data) -> if Cmd.info[data] addsys Cmd.info[data], "" else addsys "command not found: /help #{data}", "" Cmd.set "/manual", "如果需要查看命令列表, 使用: /manual", -> addsys val, "" for key, val of Cmd.info Cmd.set "/info", "如果需要获取信息, 使用: /info [curuser | me | room | leftmsg]", (data) -> socket.emit "info", data: data Cmd.set "/clear", "如果需要清空消息, 使用: /clear [sys | all]", (data) -> switch data when "sys" $(".message>*").filter(".sys").fadeOut "normal", -> $(this).remove() when "all" $(".message>*").fadeOut "normal", -> $(this).remove() else addsys "command not found: /clear #{data}", "" Cmd.set "/switch", "如果需要修改开关, 使用: /switch [disable | enable] [time | notice]", (data) -> [type, obj] = data.split " " if obj is "time" if type is "disable" disable.time = true $(".time").fadeOut() else if type is "enable" disable.time = false $(".time").fadeIn() else addsys "command not found: /switch #{data}", "" else if obj is "notice" if type is "disable" disable.notice = true else if type is "enable" disable.notice = false else addsys "command not found: /switch #{data}", "" else addsys "command not found: /switch #{data}", "" Cmd.set "/emoji", "如果需要添加表情, 使用: /emoji 表情名拼音{xiaoku: 😂 | lenghan: 😓 | shuijiao: 😪 | ku: 😢 | gaoxing: 😊}", (data) -> Cmd.nodefault["/emoji"] = true dt = xiaoku: "😂", lenghan: "😓", shuijiao: "😪", ku: "😢", gaoxing: "😊" if dt[data] $inputbox.val dt[data] else addsys "command not found: /emoji #{data}", "" # 申请通知权限 Notification.requestPermission()
[ { "context": ": [42]})\n assert.deepEqual {key: {NS: ['4', '5', '42']}}, @objToDDB({key: [4, 5, 42]})\n\n it '", "end": 3834, "score": 0.7754788398742676, "start": 3833, "tag": "KEY", "value": "5" }, { "context": "]})\n assert.deepEqual {key: {NS: ['4', '5', '42']}}, @ob...
test/conversion.coffee
Ubix/node-dynamodb
1
### // Copyright Teleportd Ltd. and other Contributors // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. ### {assert, expect} = require 'chai' async = require 'async' util = require './util' describe 'ddb conversion API', -> before (done) => util.before done, => {@ddb, @didThrowDone, @didNotThrowDone} = util {@scToDDB, @objToDDB, @objFromDDB, @arrFromDDB} = util.ddb @complexJsObj = str: 'string' strSet: ['foo', 'bar'] num: 1234 numSet: [1234, 5678] @complexDdbObj = str: {'S': 'string'} strSet: {SS: ['foo', 'bar']} num: {N: '1234'} numSet: {'NS': ['1234', '5678']} after util.after it 'should have .scToDDB() method', => expect(@ddb).to.respondTo 'scToDDB' it 'should have .objToDDB() method', => expect(@ddb).to.respondTo 'objToDDB' it 'should have .objFromDDB() method', => expect(@ddb).to.respondTo 'objFromDDB' it 'should have .arrFromDDB() method', => expect(@ddb).to.respondTo 'arrFromDDB' describe '.scToDDB()', => it 'should convert scalar JS values to scalar DDB objects', => assert.deepEqual {S: 'str'}, @scToDDB('str') assert.deepEqual {N: '1234'}, @scToDDB(1234) assert.deepEqual {SS: ['a', 'b']}, @scToDDB(['a', 'b']) assert.deepEqual {NS: ['1', '2', '3']}, @scToDDB([1, 2, 3]) assert.deepEqual {NS: []}, @scToDDB([]) it 'should not throw when converting valid type scalar JS values to DDB objects', (done) => async.parallel [ @didNotThrowDone => @scToDDB 'str' @didNotThrowDone => @scToDDB 1234 @didNotThrowDone => @scToDDB ['a', 'b'] @didNotThrowDone => @scToDDB [1, 2, 3] @didNotThrowDone => @scToDDB [] ], done it 'should throw when converting invalid type scalar JS values to DDB objects', (done) => # JS type reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof async.parallel [ @didThrowDone => @scToDDB true @didThrowDone => @scToDDB false @didThrowDone => @scToDDB undefined @didThrowDone => @scToDDB {} @didThrowDone => @scToDDB -> ], done describe '.objToDDB()', => it 'should convert JS objects with scalar fields to DDB objects with scalar fields', => assert.deepEqual {key: {S: 'str'}}, @objToDDB({key: 'str'}) assert.deepEqual {key: {N: '1234'}}, @objToDDB({key: 1234}) it 'should convert JS objects with array fields to DDB objects with array fields', => assert.deepEqual {key: {SS: ['foo']}}, @objToDDB({key: ['foo']}) assert.deepEqual {key: {SS: ['foo', 'bar']}}, @objToDDB({key: ['foo', 'bar']}) assert.deepEqual {key: {NS: ['42']}}, @objToDDB({key: [42]}) assert.deepEqual {key: {NS: ['4', '5', '42']}}, @objToDDB({key: [4, 5, 42]}) it 'should convert result of .objFromDDB() to original DDB object', => ddbObj = {key: {SS: ['foo']}} assert.deepEqual ddbObj, @objToDDB(@objFromDDB(ddbObj)) it 'should convert complex JS objects to corresponding complex DDB objects', => assert.deepEqual @complexDdbObj, @objToDDB(@complexJsObj) it 'should exclude null/undefined fields in JS objects from conversion to DDB objects', => assert.deepEqual {}, @objToDDB({key: null}) assert.deepEqual {'key1': {'S': 'str'}}, @objToDDB({key1: 'str', key: null}) assert.deepEqual {'key1': {'N': '1234'}}, @objToDDB({key1: 1234, key: null}) it 'should not throw when converting JS objects with valid type fields to DDB objects', (done) => async.parallel [ @didNotThrowDone => @objToDDB {key: 'a'} @didNotThrowDone => @objToDDB {key: 1} @didNotThrowDone => @objToDDB {key: ['a', 'b']} @didNotThrowDone => @objToDDB {key: [1, 2, 3]} ], done it 'should throw when converting JS objects with invalid type fields to DDB objects', (done) => async.parallel [ @didThrowDone => @objToDDB {key: true} @didThrowDone => @objToDDB {key: false} @didThrowDone => @objToDDB {key: undefined} @didThrowDone => @objToDDB {key: {}} @didThrowDone => @objToDDB {key: ->} ], done describe '.objFromDDB()', => it 'should convert DDB objects with scalar fields to JS objects', => assert.deepEqual {key: 'str'}, @objFromDDB({key: {S: 'str'}}) assert.deepEqual {key: 1234}, @objFromDDB({key: {N: '1234'}}) it 'should convert DDB objects with array fields to JS objects with array fields', => assert.deepEqual {key: ['foo']}, @objFromDDB({key: {SS: ['foo']}}) assert.deepEqual {key: ['foo', 'bar']}, @objFromDDB({key: {SS: ['foo', 'bar']}}) assert.deepEqual {key: [42]}, @objFromDDB({key: {NS: ['42']}}) assert.deepEqual {key: [4, 5, 42]}, @objFromDDB({key: {NS: ['4', '5', '42']}}) it 'should convert result of .objToDDB() to original JS object', => jsObj = {key: [55, 66]} assert.deepEqual jsObj, @objFromDDB(@objToDDB(jsObj)) it 'should convert complex DDB objects to corresponding complex JS objects', => assert.deepEqual @complexJsObj, @objFromDDB(@complexDdbObj) it 'should not throw when converting DDB objects with valid type fields to JS objects', (done) => async.parallel [ @didNotThrowDone => @objFromDDB {key: {'N': '1'}} @didNotThrowDone => @objFromDDB {key: {'N': 1}} @didNotThrowDone => @objFromDDB {key: {'S': 'a'}} @didNotThrowDone => @objFromDDB {key: {'S': 1}} @didNotThrowDone => @objFromDDB {key: {'NS': ['a', 'a']}} @didNotThrowDone => @objFromDDB {key: {'SS': [1, 2, 3]}} ], done it 'should throw when converting DDB objects with invalid type fields to JS objects', (done) => async.parallel [ @didThrowDone => @objFromDDB {key: {'BAD': 'a'}} @didThrowDone => @objFromDDB {key: {'BAD': '1'}} @didThrowDone => @objFromDDB {key: {'BAD': ['a', 'b']}} @didThrowDone => @objFromDDB {key: {'BAD': [1, 2, 3]}} @didThrowDone => @objFromDDB {key: {'': 'str'}} @didThrowDone => @objFromDDB {key: {'': 1}} ], done describe '.arrFromDDB()', => it 'should convert arrays of DDB objects into arrays of JS objects', => @jsArr = [ {str: 'a'} {num: 1} {strArr: ['a', 'b']} {numArr: [1, 2, 3]} ] @ddbArr = [ {str: {S: 'a'}} {num: {N: '1'}} {strArr: {SS: ['a', 'b']}} {numArr: {NS: ['1', '2', '3']}} ] assert.deepEqual @jsArr, @arrFromDDB(@ddbArr) it 'should replace elements of DDB object arrays with JS objects', => assert.deepEqual @jsArr, @ddbArr it 'should not throw when converting arrays of DDB objects into arrays of JS objects', (done) => @ddbArr = [ {str: {S: 'a'}} {num: {N: '1'}} {strArr: {SS: ['a', 'b']}} {numArr: {NS: ['1', '2', '3']}} ] async.parallel [ @didNotThrowDone => @arrFromDDB @ddbArr ], done
140471
### // Copyright Teleportd Ltd. and other Contributors // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. ### {assert, expect} = require 'chai' async = require 'async' util = require './util' describe 'ddb conversion API', -> before (done) => util.before done, => {@ddb, @didThrowDone, @didNotThrowDone} = util {@scToDDB, @objToDDB, @objFromDDB, @arrFromDDB} = util.ddb @complexJsObj = str: 'string' strSet: ['foo', 'bar'] num: 1234 numSet: [1234, 5678] @complexDdbObj = str: {'S': 'string'} strSet: {SS: ['foo', 'bar']} num: {N: '1234'} numSet: {'NS': ['1234', '5678']} after util.after it 'should have .scToDDB() method', => expect(@ddb).to.respondTo 'scToDDB' it 'should have .objToDDB() method', => expect(@ddb).to.respondTo 'objToDDB' it 'should have .objFromDDB() method', => expect(@ddb).to.respondTo 'objFromDDB' it 'should have .arrFromDDB() method', => expect(@ddb).to.respondTo 'arrFromDDB' describe '.scToDDB()', => it 'should convert scalar JS values to scalar DDB objects', => assert.deepEqual {S: 'str'}, @scToDDB('str') assert.deepEqual {N: '1234'}, @scToDDB(1234) assert.deepEqual {SS: ['a', 'b']}, @scToDDB(['a', 'b']) assert.deepEqual {NS: ['1', '2', '3']}, @scToDDB([1, 2, 3]) assert.deepEqual {NS: []}, @scToDDB([]) it 'should not throw when converting valid type scalar JS values to DDB objects', (done) => async.parallel [ @didNotThrowDone => @scToDDB 'str' @didNotThrowDone => @scToDDB 1234 @didNotThrowDone => @scToDDB ['a', 'b'] @didNotThrowDone => @scToDDB [1, 2, 3] @didNotThrowDone => @scToDDB [] ], done it 'should throw when converting invalid type scalar JS values to DDB objects', (done) => # JS type reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof async.parallel [ @didThrowDone => @scToDDB true @didThrowDone => @scToDDB false @didThrowDone => @scToDDB undefined @didThrowDone => @scToDDB {} @didThrowDone => @scToDDB -> ], done describe '.objToDDB()', => it 'should convert JS objects with scalar fields to DDB objects with scalar fields', => assert.deepEqual {key: {S: 'str'}}, @objToDDB({key: 'str'}) assert.deepEqual {key: {N: '1234'}}, @objToDDB({key: 1234}) it 'should convert JS objects with array fields to DDB objects with array fields', => assert.deepEqual {key: {SS: ['foo']}}, @objToDDB({key: ['foo']}) assert.deepEqual {key: {SS: ['foo', 'bar']}}, @objToDDB({key: ['foo', 'bar']}) assert.deepEqual {key: {NS: ['42']}}, @objToDDB({key: [42]}) assert.deepEqual {key: {NS: ['4', '<KEY>', '<KEY>']}}, @objToDDB({key: [4, 5, 42]}) it 'should convert result of .objFromDDB() to original DDB object', => ddbObj = {key: {SS: ['foo']}} assert.deepEqual ddbObj, @objToDDB(@objFromDDB(ddbObj)) it 'should convert complex JS objects to corresponding complex DDB objects', => assert.deepEqual @complexDdbObj, @objToDDB(@complexJsObj) it 'should exclude null/undefined fields in JS objects from conversion to DDB objects', => assert.deepEqual {}, @objToDDB({key: null}) assert.deepEqual {'key1': {'S': 'str'}}, @objToDDB({key1: 'str', key: null}) assert.deepEqual {'key1': {'N': '1234'}}, @objToDDB({key1: 1234, key: null}) it 'should not throw when converting JS objects with valid type fields to DDB objects', (done) => async.parallel [ @didNotThrowDone => @objToDDB {key: 'a'} @didNotThrowDone => @objToDDB {key: 1} @didNotThrowDone => @objToDDB {key: ['a', 'b']} @didNotThrowDone => @objToDDB {key: [1, 2, 3]} ], done it 'should throw when converting JS objects with invalid type fields to DDB objects', (done) => async.parallel [ @didThrowDone => @objToDDB {key: true} @didThrowDone => @objToDDB {key: false} @didThrowDone => @objToDDB {key: undefined} @didThrowDone => @objToDDB {key: {}} @didThrowDone => @objToDDB {key: ->} ], done describe '.objFromDDB()', => it 'should convert DDB objects with scalar fields to JS objects', => assert.deepEqual {key: 'str'}, @objFromDDB({key: {S: 'str'}}) assert.deepEqual {key: 1234}, @objFromDDB({key: {N: '1234'}}) it 'should convert DDB objects with array fields to JS objects with array fields', => assert.deepEqual {key: ['foo']}, @objFromDDB({key: {SS: ['foo']}}) assert.deepEqual {key: ['foo', 'bar']}, @objFromDDB({key: {SS: ['foo', 'bar']}}) assert.deepEqual {key: [42]}, @objFromDDB({key: {NS: ['42']}}) assert.deepEqual {key: [4, 5, 42]}, @objFromDDB({key: {NS: ['4', '5', '42']}}) it 'should convert result of .objToDDB() to original JS object', => jsObj = {key: [55, 66]} assert.deepEqual jsObj, @objFromDDB(@objToDDB(jsObj)) it 'should convert complex DDB objects to corresponding complex JS objects', => assert.deepEqual @complexJsObj, @objFromDDB(@complexDdbObj) it 'should not throw when converting DDB objects with valid type fields to JS objects', (done) => async.parallel [ @didNotThrowDone => @objFromDDB {key: {'N': '1'}} @didNotThrowDone => @objFromDDB {key: {'N': 1}} @didNotThrowDone => @objFromDDB {key: {'S': 'a'}} @didNotThrowDone => @objFromDDB {key: {'S': 1}} @didNotThrowDone => @objFromDDB {key: {'NS': ['a', 'a']}} @didNotThrowDone => @objFromDDB {key: {'SS': [1, 2, 3]}} ], done it 'should throw when converting DDB objects with invalid type fields to JS objects', (done) => async.parallel [ @didThrowDone => @objFromDDB {key: {'BAD': 'a'}} @didThrowDone => @objFromDDB {key: {'BAD': '1'}} @didThrowDone => @objFromDDB {key: {'BAD': ['a', 'b']}} @didThrowDone => @objFromDDB {key: {'BAD': [1, 2, 3]}} @didThrowDone => @objFromDDB {key: {'': 'str'}} @didThrowDone => @objFromDDB {key: {'': 1}} ], done describe '.arrFromDDB()', => it 'should convert arrays of DDB objects into arrays of JS objects', => @jsArr = [ {str: 'a'} {num: 1} {strArr: ['a', 'b']} {numArr: [1, 2, 3]} ] @ddbArr = [ {str: {S: 'a'}} {num: {N: '1'}} {strArr: {SS: ['a', 'b']}} {numArr: {NS: ['1', '2', '3']}} ] assert.deepEqual @jsArr, @arrFromDDB(@ddbArr) it 'should replace elements of DDB object arrays with JS objects', => assert.deepEqual @jsArr, @ddbArr it 'should not throw when converting arrays of DDB objects into arrays of JS objects', (done) => @ddbArr = [ {str: {S: 'a'}} {num: {N: '1'}} {strArr: {SS: ['a', 'b']}} {numArr: {NS: ['1', '2', '3']}} ] async.parallel [ @didNotThrowDone => @arrFromDDB @ddbArr ], done
true
### // Copyright Teleportd Ltd. and other Contributors // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. ### {assert, expect} = require 'chai' async = require 'async' util = require './util' describe 'ddb conversion API', -> before (done) => util.before done, => {@ddb, @didThrowDone, @didNotThrowDone} = util {@scToDDB, @objToDDB, @objFromDDB, @arrFromDDB} = util.ddb @complexJsObj = str: 'string' strSet: ['foo', 'bar'] num: 1234 numSet: [1234, 5678] @complexDdbObj = str: {'S': 'string'} strSet: {SS: ['foo', 'bar']} num: {N: '1234'} numSet: {'NS': ['1234', '5678']} after util.after it 'should have .scToDDB() method', => expect(@ddb).to.respondTo 'scToDDB' it 'should have .objToDDB() method', => expect(@ddb).to.respondTo 'objToDDB' it 'should have .objFromDDB() method', => expect(@ddb).to.respondTo 'objFromDDB' it 'should have .arrFromDDB() method', => expect(@ddb).to.respondTo 'arrFromDDB' describe '.scToDDB()', => it 'should convert scalar JS values to scalar DDB objects', => assert.deepEqual {S: 'str'}, @scToDDB('str') assert.deepEqual {N: '1234'}, @scToDDB(1234) assert.deepEqual {SS: ['a', 'b']}, @scToDDB(['a', 'b']) assert.deepEqual {NS: ['1', '2', '3']}, @scToDDB([1, 2, 3]) assert.deepEqual {NS: []}, @scToDDB([]) it 'should not throw when converting valid type scalar JS values to DDB objects', (done) => async.parallel [ @didNotThrowDone => @scToDDB 'str' @didNotThrowDone => @scToDDB 1234 @didNotThrowDone => @scToDDB ['a', 'b'] @didNotThrowDone => @scToDDB [1, 2, 3] @didNotThrowDone => @scToDDB [] ], done it 'should throw when converting invalid type scalar JS values to DDB objects', (done) => # JS type reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof async.parallel [ @didThrowDone => @scToDDB true @didThrowDone => @scToDDB false @didThrowDone => @scToDDB undefined @didThrowDone => @scToDDB {} @didThrowDone => @scToDDB -> ], done describe '.objToDDB()', => it 'should convert JS objects with scalar fields to DDB objects with scalar fields', => assert.deepEqual {key: {S: 'str'}}, @objToDDB({key: 'str'}) assert.deepEqual {key: {N: '1234'}}, @objToDDB({key: 1234}) it 'should convert JS objects with array fields to DDB objects with array fields', => assert.deepEqual {key: {SS: ['foo']}}, @objToDDB({key: ['foo']}) assert.deepEqual {key: {SS: ['foo', 'bar']}}, @objToDDB({key: ['foo', 'bar']}) assert.deepEqual {key: {NS: ['42']}}, @objToDDB({key: [42]}) assert.deepEqual {key: {NS: ['4', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI']}}, @objToDDB({key: [4, 5, 42]}) it 'should convert result of .objFromDDB() to original DDB object', => ddbObj = {key: {SS: ['foo']}} assert.deepEqual ddbObj, @objToDDB(@objFromDDB(ddbObj)) it 'should convert complex JS objects to corresponding complex DDB objects', => assert.deepEqual @complexDdbObj, @objToDDB(@complexJsObj) it 'should exclude null/undefined fields in JS objects from conversion to DDB objects', => assert.deepEqual {}, @objToDDB({key: null}) assert.deepEqual {'key1': {'S': 'str'}}, @objToDDB({key1: 'str', key: null}) assert.deepEqual {'key1': {'N': '1234'}}, @objToDDB({key1: 1234, key: null}) it 'should not throw when converting JS objects with valid type fields to DDB objects', (done) => async.parallel [ @didNotThrowDone => @objToDDB {key: 'a'} @didNotThrowDone => @objToDDB {key: 1} @didNotThrowDone => @objToDDB {key: ['a', 'b']} @didNotThrowDone => @objToDDB {key: [1, 2, 3]} ], done it 'should throw when converting JS objects with invalid type fields to DDB objects', (done) => async.parallel [ @didThrowDone => @objToDDB {key: true} @didThrowDone => @objToDDB {key: false} @didThrowDone => @objToDDB {key: undefined} @didThrowDone => @objToDDB {key: {}} @didThrowDone => @objToDDB {key: ->} ], done describe '.objFromDDB()', => it 'should convert DDB objects with scalar fields to JS objects', => assert.deepEqual {key: 'str'}, @objFromDDB({key: {S: 'str'}}) assert.deepEqual {key: 1234}, @objFromDDB({key: {N: '1234'}}) it 'should convert DDB objects with array fields to JS objects with array fields', => assert.deepEqual {key: ['foo']}, @objFromDDB({key: {SS: ['foo']}}) assert.deepEqual {key: ['foo', 'bar']}, @objFromDDB({key: {SS: ['foo', 'bar']}}) assert.deepEqual {key: [42]}, @objFromDDB({key: {NS: ['42']}}) assert.deepEqual {key: [4, 5, 42]}, @objFromDDB({key: {NS: ['4', '5', '42']}}) it 'should convert result of .objToDDB() to original JS object', => jsObj = {key: [55, 66]} assert.deepEqual jsObj, @objFromDDB(@objToDDB(jsObj)) it 'should convert complex DDB objects to corresponding complex JS objects', => assert.deepEqual @complexJsObj, @objFromDDB(@complexDdbObj) it 'should not throw when converting DDB objects with valid type fields to JS objects', (done) => async.parallel [ @didNotThrowDone => @objFromDDB {key: {'N': '1'}} @didNotThrowDone => @objFromDDB {key: {'N': 1}} @didNotThrowDone => @objFromDDB {key: {'S': 'a'}} @didNotThrowDone => @objFromDDB {key: {'S': 1}} @didNotThrowDone => @objFromDDB {key: {'NS': ['a', 'a']}} @didNotThrowDone => @objFromDDB {key: {'SS': [1, 2, 3]}} ], done it 'should throw when converting DDB objects with invalid type fields to JS objects', (done) => async.parallel [ @didThrowDone => @objFromDDB {key: {'BAD': 'a'}} @didThrowDone => @objFromDDB {key: {'BAD': '1'}} @didThrowDone => @objFromDDB {key: {'BAD': ['a', 'b']}} @didThrowDone => @objFromDDB {key: {'BAD': [1, 2, 3]}} @didThrowDone => @objFromDDB {key: {'': 'str'}} @didThrowDone => @objFromDDB {key: {'': 1}} ], done describe '.arrFromDDB()', => it 'should convert arrays of DDB objects into arrays of JS objects', => @jsArr = [ {str: 'a'} {num: 1} {strArr: ['a', 'b']} {numArr: [1, 2, 3]} ] @ddbArr = [ {str: {S: 'a'}} {num: {N: '1'}} {strArr: {SS: ['a', 'b']}} {numArr: {NS: ['1', '2', '3']}} ] assert.deepEqual @jsArr, @arrFromDDB(@ddbArr) it 'should replace elements of DDB object arrays with JS objects', => assert.deepEqual @jsArr, @ddbArr it 'should not throw when converting arrays of DDB objects into arrays of JS objects', (done) => @ddbArr = [ {str: {S: 'a'}} {num: {N: '1'}} {strArr: {SS: ['a', 'b']}} {numArr: {NS: ['1', '2', '3']}} ] async.parallel [ @didNotThrowDone => @arrFromDDB @ddbArr ], done
[ { "context": "\"\n contact: \"Contate-nos\"\n twitter_follow: \"Seguir\"\n\n forms:\n name: \"Nome\"\n email: \"Email\"\n ", "end": 582, "score": 0.9995090961456299, "start": 576, "tag": "USERNAME", "value": "Seguir" }, { "context": " twitter_follow: \"Seguir\"\n\n ...
app/locale/pt.coffee
cochee/codecombat
1
module.exports = nativeDescription: "português", englishDescription: "Portuguese", translation: common: loading: "Carregando..." modal: close: "Fechar" okay: "Ok" not_found: page_not_found: "Página não encontrada" nav: # Header sign_up: "Criar conta" log_in: "Entrar" log_out: "Sair" play: "Jogar" editor: "Editor" blog: "Blog" forum: "Fórum" admin: "Administrador" # Footer home: "Início" contribute: "Contribuir" legal: "Legal" about: "Sobre" contact: "Contate-nos" twitter_follow: "Seguir" forms: name: "Nome" email: "Email" message: "Mensagem" cancel: "Cancelar" login: log_in: "Entrar" sign_up: "Criar uma nova conta" or: ", ou " recover: "recuperar sua conta" signup: description: "É grátis. Precisamos apenas de umas coisinhas e você estará pronto para seguir:" email_announcements: "Receber notícias por email." coppa: "acima de 13 anos ou não estadunidense" coppa_why: "(Por quê?)" creating: "Criando a nova conta..." sign_up: "Criar conta" or: "ou " log_in: "Entre com a senha" home: slogan: "Aprenda a programar em JavaScript enquanto se diverte com um jogo." no_ie: "CodeCombat não roda em versões mais antigas que o Internet Explorer 10. Desculpe!" no_mobile: "CodeCombat não foi projetado para dispositivos móveis e pode não funcionar!" play: "Jogar" play: choose_your_level: "Escolha seu estágio" adventurer_prefix: "Você pode ir para qualquer um dos estágios abaixo, ou discutir sobre eles no " adventurer_forum: "Fórum do Aventureiro" adventurer_suffix: "." campaign_beginner: "Campanha Iniciante" campaign_beginner_description: "... na qual você aprenderá a magia da programação." campaign_dev: "Fases Difíceis Aleatórias" campaign_dev_description: "... nas quais você aprenderá a interface enquanto faz algo um pouco mais difícil." campaign_multiplayer: "Arenas Multijogador" campaign_multiplayer_description: "... nas quais você programará cara-a-cara contra outros jogadores." campaign_player_created: "Criados por Jogadores" campaign_player_created_description: "... nos quais você batalhará contra a criatividade dos seus companheiros <a href=\"/contribute#artisan\">feiticeiros Artesãos</a>." level_difficulty: "Dificuldade: " contact: contact_us: "Contate-nos" welcome: "É bom escutar suas opiniões! Use este formulário para nos enviar um email." contribute_prefix: "Se você se interessar em contribuir conosco, dê uma conferida na nossa " contribute_page: "página de contribuição" contribute_suffix: "!" forum_prefix: "Para algo público, por favor acesse " forum_page: "nosso fórum" forum_suffix: " ao invés disso." sending: "Enviando..." send: "Enviar opinião" diplomat_suggestion: title: "Ajude a traduzir o CodeCombat!" sub_heading: "Nós precisamos de suas habilidades linguísticas." pitch_body: "Desenvolvemos o CodeCombat em Inglês, mas já temos jogadores de todo o mundo. Muitos deles querem jogar em Português Brasileiro mas não falam Inglês, por isso, se você conhece os dois idiomas, por favor, considere inscrever-se para ser um Diplomata e ajudar a traduzir tanto o site do CodeCombat quanto todos os estágios para o Português Brasileiro." missing_translations: "Até que possamos traduzir tudo para o Português Brasileiro, você lerá em Inglês quando a versão em Português Brasileiro ainda não estiver disponível." learn_more: "Saiba mais sobre ser um Diplomata" subscribe_as_diplomat: "Assinar como um Diplomata" account_settings: title: "Configurações da Conta" not_logged_in: "Entre com seu usuário e senha ou crie uma conta para poder alterar suas configurações." autosave: "As alterações serão salvas automaticamente." me_tab: "Eu" picture_tab: "Foto" wizard_tab: "Feiticeiro" password_tab: "Senha" emails_tab: "Emails" language_tab: "Idioma" gravatar_select: "Selecione qual foto do Gravatar usar" gravatar_add_photos: "Adicione miniaturas e fotos a uma conta do Gravatar ligada ao seu email para poder escolher uma imagem." gravatar_add_more_photos: "Adicione mais fotos à sua conta do Gravatar para acessá-las aqui." wizard_color: "Cor das Roupas do Feiticeiro" new_password: "Nova Senha" new_password_verify: "Confirmação" email_subscriptions: "Assinaturas para Notícias por Email" email_announcements: "Notícias" email_announcements_description: "Receba emails com as últimas notícias e desenvolvimentos do CodeCombat." contributor_emails: "Emails para as Classes de Contribuidores" contribute_prefix: "Estamos procurando pessoas para se juntar à nossa turma! Confira a nossa " contribute_page: "página de contribuição" contribute_suffix: " para saber mais." email_toggle: "Ativar todos" language: "Idioma" saving: "Salvando..." error_saving: "Erro no salvamento" saved: "Alterações Salvas" password_mismatch: "As senhas não estão iguais" account_profile: edit_settings: "Editar as configurações" profile_for_prefix: "Perfil de " profile_for_suffix: "" profile: "Perfil" user_not_found: "Nenhum usuário encontrado. Checou o endereço de internet?" gravatar_not_found_mine: "Não conseguimos encontrar o perfil que está associado a:" gravatar_signup_prefix: "Crie uma conta no " gravatar_signup_suffix: " para poder configurar!" gravatar_not_found_other: "Infelizmente, não há perfil associado ao endereço de e-mail dessa pessoa." gravatar_contact: "Contate-nos" gravatar_websites: "Websites" gravatar_accounts: "Como visto no" gravatar_profile_link: "Perfil Completo do Gravatar" play_level: level_load_error: "O estágio não pôde ser carregado." done: "Pronto" grid: "Grade" customize_wizard: "Personalize o feiticeiro" home: "Início" guide: "Guia" multiplayer: "Multiplayer" restart: "Reiniciar" goals: "Objetivos" action_timeline: "Linha do Tempo das Ações" click_to_select: "Clique em um personagem para selecioná-lo." reload_title: "Recarregar Todo o Código?" reload_really: "Você tem certeza que quer reiniciar o estágio?" reload_confirm: "Recarregar Tudo" victory_title_prefix: "" victory_title_suffix: " Completado!" victory_sign_up: "Assine para atualizações" victory_sign_up_poke: "Quer receber as últimas novidades por email? Crie uma conta grátis e nós o manteremos informado!" victory_rate_the_level: "Avalie o estágio: " victory_play_next_level: "Jogar o próximo estágio" victory_go_home: "Ir à página inicial" victory_review: "Diga-nos mais!" victory_hour_of_code_done: "Terminou?" victory_hour_of_code_done_yes: "Sim, eu terminei minha Hora da Programação!" multiplayer_title: "Configurações do Multiplayer" multiplayer_link_description: "Passe este link para quem você quiser que se una à partida." multiplayer_hint_label: "Dica:" multiplayer_hint: " Clique no link para selecionar tudo, então dê Ctrl+C ou ⌘+C para copiar o link. " multiplayer_coming_soon: "Mais novidades no multiplayer estão chegando!" guide_title: "Guia" tome_minion_spells: "Magias dos seus subordinados" tome_read_only_spells: "Magias não editáveis" tome_other_units: "Outras Unidades" tome_cast_button_castable: "Lançar" tome_cast_button_casting: "Conjurando" tome_cast_button_cast: "Feitiço" tome_autocast_delay: "Atraso na autoconjuração" tome_autocast_1: "1 segundo" tome_autocast_3: "3 segundos" tome_autocast_5: "5 segundos" tome_autocast_manual: "Manual" tome_select_spell: "Selecione um Feitiço" tome_select_a_thang: "Selecione alguém para " tome_available_spells: "Feitiços Disponíveis" hud_continue: "Continue (tecle Shift+Space)"
23101
module.exports = nativeDescription: "português", englishDescription: "Portuguese", translation: common: loading: "Carregando..." modal: close: "Fechar" okay: "Ok" not_found: page_not_found: "Página não encontrada" nav: # Header sign_up: "Criar conta" log_in: "Entrar" log_out: "Sair" play: "Jogar" editor: "Editor" blog: "Blog" forum: "Fórum" admin: "Administrador" # Footer home: "Início" contribute: "Contribuir" legal: "Legal" about: "Sobre" contact: "Contate-nos" twitter_follow: "Seguir" forms: name: "<NAME>" email: "Email" message: "Mensagem" cancel: "Cancelar" login: log_in: "Entrar" sign_up: "Criar uma nova conta" or: ", ou " recover: "recuperar sua conta" signup: description: "É grátis. Precisamos apenas de umas coisinhas e você estará pronto para seguir:" email_announcements: "Receber notícias por email." coppa: "acima de 13 anos ou não estadunidense" coppa_why: "(Por quê?)" creating: "Criando a nova conta..." sign_up: "Criar conta" or: "ou " log_in: "Entre com a senha" home: slogan: "Aprenda a programar em JavaScript enquanto se diverte com um jogo." no_ie: "CodeCombat não roda em versões mais antigas que o Internet Explorer 10. Desculpe!" no_mobile: "CodeCombat não foi projetado para dispositivos móveis e pode não funcionar!" play: "Jogar" play: choose_your_level: "Escolha seu estágio" adventurer_prefix: "Você pode ir para qualquer um dos estágios abaixo, ou discutir sobre eles no " adventurer_forum: "Fórum do Aventureiro" adventurer_suffix: "." campaign_beginner: "Campanha Iniciante" campaign_beginner_description: "... na qual você aprenderá a magia da programação." campaign_dev: "Fases Difíceis Aleatórias" campaign_dev_description: "... nas quais você aprenderá a interface enquanto faz algo um pouco mais difícil." campaign_multiplayer: "Arenas Multijogador" campaign_multiplayer_description: "... nas quais você programará cara-a-cara contra outros jogadores." campaign_player_created: "Criados por Jogadores" campaign_player_created_description: "... nos quais você batalhará contra a criatividade dos seus companheiros <a href=\"/contribute#artisan\">feiticeiros Artesãos</a>." level_difficulty: "Dificuldade: " contact: contact_us: "Contate-nos" welcome: "É bom escutar suas opiniões! Use este formulário para nos enviar um email." contribute_prefix: "Se você se interessar em contribuir conosco, dê uma conferida na nossa " contribute_page: "página de contribuição" contribute_suffix: "!" forum_prefix: "Para algo público, por favor acesse " forum_page: "nosso fórum" forum_suffix: " ao invés disso." sending: "Enviando..." send: "Enviar opinião" diplomat_suggestion: title: "Ajude a traduzir o CodeCombat!" sub_heading: "Nós precisamos de suas habilidades linguísticas." pitch_body: "Desenvolvemos o CodeCombat em Inglês, mas já temos jogadores de todo o mundo. Muitos deles querem jogar em Português Brasileiro mas não falam Inglês, por isso, se você conhece os dois idiomas, por favor, considere inscrever-se para ser um Diplomata e ajudar a traduzir tanto o site do CodeCombat quanto todos os estágios para o Português Brasileiro." missing_translations: "Até que possamos traduzir tudo para o Português Brasileiro, você lerá em Inglês quando a versão em Português Brasileiro ainda não estiver disponível." learn_more: "Saiba mais sobre ser um Diplomata" subscribe_as_diplomat: "Assinar como um Diplomata" account_settings: title: "Configurações da Conta" not_logged_in: "Entre com seu usuário e senha ou crie uma conta para poder alterar suas configurações." autosave: "As alterações serão salvas automaticamente." me_tab: "Eu" picture_tab: "Foto" wizard_tab: "Feiticeiro" password_tab: "Senha" emails_tab: "Emails" language_tab: "Idioma" gravatar_select: "Selecione qual foto do Gravatar usar" gravatar_add_photos: "Adicione miniaturas e fotos a uma conta do Gravatar ligada ao seu email para poder escolher uma imagem." gravatar_add_more_photos: "Adicione mais fotos à sua conta do Gravatar para acessá-las aqui." wizard_color: "Cor das Roupas do Feiticeiro" new_password: "<PASSWORD>" new_password_verify: "<PASSWORD>" email_subscriptions: "Assinaturas para Notícias por Email" email_announcements: "Notícias" email_announcements_description: "Receba emails com as últimas notícias e desenvolvimentos do CodeCombat." contributor_emails: "Emails para as Classes de Contribuidores" contribute_prefix: "Estamos procurando pessoas para se juntar à nossa turma! Confira a nossa " contribute_page: "página de contribuição" contribute_suffix: " para saber mais." email_toggle: "Ativar todos" language: "Idioma" saving: "Salvando..." error_saving: "Erro no salvamento" saved: "Alterações Salvas" password_mismatch: "As senhas não estão iguais" account_profile: edit_settings: "Editar as configurações" profile_for_prefix: "Perfil de " profile_for_suffix: "" profile: "Perfil" user_not_found: "Nenhum usuário encontrado. Checou o endereço de internet?" gravatar_not_found_mine: "Não conseguimos encontrar o perfil que está associado a:" gravatar_signup_prefix: "Crie uma conta no " gravatar_signup_suffix: " para poder configurar!" gravatar_not_found_other: "Infelizmente, não há perfil associado ao endereço de e-mail dessa pessoa." gravatar_contact: "Contate-nos" gravatar_websites: "Websites" gravatar_accounts: "Como visto no" gravatar_profile_link: "Perfil Completo do Gravatar" play_level: level_load_error: "O estágio não pôde ser carregado." done: "Pronto" grid: "Grade" customize_wizard: "Personalize o feiticeiro" home: "Início" guide: "Guia" multiplayer: "Multiplayer" restart: "Reiniciar" goals: "Objetivos" action_timeline: "Linha do Tempo das Ações" click_to_select: "Clique em um personagem para selecioná-lo." reload_title: "Recarregar Todo o Código?" reload_really: "Você tem certeza que quer reiniciar o estágio?" reload_confirm: "Recarregar Tudo" victory_title_prefix: "" victory_title_suffix: " Completado!" victory_sign_up: "Assine para atualizações" victory_sign_up_poke: "Quer receber as últimas novidades por email? Crie uma conta grátis e nós o manteremos informado!" victory_rate_the_level: "Avalie o estágio: " victory_play_next_level: "Jogar o próximo estágio" victory_go_home: "Ir à página inicial" victory_review: "Diga-nos mais!" victory_hour_of_code_done: "Terminou?" victory_hour_of_code_done_yes: "Sim, eu terminei minha Hora da Programação!" multiplayer_title: "Configurações do Multiplayer" multiplayer_link_description: "Passe este link para quem você quiser que se una à partida." multiplayer_hint_label: "Dica:" multiplayer_hint: " Clique no link para selecionar tudo, então dê Ctrl+C ou ⌘+C para copiar o link. " multiplayer_coming_soon: "Mais novidades no multiplayer estão chegando!" guide_title: "Guia" tome_minion_spells: "Magias dos seus subordinados" tome_read_only_spells: "Magias não editáveis" tome_other_units: "Outras Unidades" tome_cast_button_castable: "Lançar" tome_cast_button_casting: "Conjurando" tome_cast_button_cast: "Feitiço" tome_autocast_delay: "Atraso na autoconjuração" tome_autocast_1: "1 segundo" tome_autocast_3: "3 segundos" tome_autocast_5: "5 segundos" tome_autocast_manual: "Manual" tome_select_spell: "Selecione um Feitiço" tome_select_a_thang: "Selecione alguém para " tome_available_spells: "Feitiços Disponíveis" hud_continue: "Continue (tecle Shift+Space)"
true
module.exports = nativeDescription: "português", englishDescription: "Portuguese", translation: common: loading: "Carregando..." modal: close: "Fechar" okay: "Ok" not_found: page_not_found: "Página não encontrada" nav: # Header sign_up: "Criar conta" log_in: "Entrar" log_out: "Sair" play: "Jogar" editor: "Editor" blog: "Blog" forum: "Fórum" admin: "Administrador" # Footer home: "Início" contribute: "Contribuir" legal: "Legal" about: "Sobre" contact: "Contate-nos" twitter_follow: "Seguir" forms: name: "PI:NAME:<NAME>END_PI" email: "Email" message: "Mensagem" cancel: "Cancelar" login: log_in: "Entrar" sign_up: "Criar uma nova conta" or: ", ou " recover: "recuperar sua conta" signup: description: "É grátis. Precisamos apenas de umas coisinhas e você estará pronto para seguir:" email_announcements: "Receber notícias por email." coppa: "acima de 13 anos ou não estadunidense" coppa_why: "(Por quê?)" creating: "Criando a nova conta..." sign_up: "Criar conta" or: "ou " log_in: "Entre com a senha" home: slogan: "Aprenda a programar em JavaScript enquanto se diverte com um jogo." no_ie: "CodeCombat não roda em versões mais antigas que o Internet Explorer 10. Desculpe!" no_mobile: "CodeCombat não foi projetado para dispositivos móveis e pode não funcionar!" play: "Jogar" play: choose_your_level: "Escolha seu estágio" adventurer_prefix: "Você pode ir para qualquer um dos estágios abaixo, ou discutir sobre eles no " adventurer_forum: "Fórum do Aventureiro" adventurer_suffix: "." campaign_beginner: "Campanha Iniciante" campaign_beginner_description: "... na qual você aprenderá a magia da programação." campaign_dev: "Fases Difíceis Aleatórias" campaign_dev_description: "... nas quais você aprenderá a interface enquanto faz algo um pouco mais difícil." campaign_multiplayer: "Arenas Multijogador" campaign_multiplayer_description: "... nas quais você programará cara-a-cara contra outros jogadores." campaign_player_created: "Criados por Jogadores" campaign_player_created_description: "... nos quais você batalhará contra a criatividade dos seus companheiros <a href=\"/contribute#artisan\">feiticeiros Artesãos</a>." level_difficulty: "Dificuldade: " contact: contact_us: "Contate-nos" welcome: "É bom escutar suas opiniões! Use este formulário para nos enviar um email." contribute_prefix: "Se você se interessar em contribuir conosco, dê uma conferida na nossa " contribute_page: "página de contribuição" contribute_suffix: "!" forum_prefix: "Para algo público, por favor acesse " forum_page: "nosso fórum" forum_suffix: " ao invés disso." sending: "Enviando..." send: "Enviar opinião" diplomat_suggestion: title: "Ajude a traduzir o CodeCombat!" sub_heading: "Nós precisamos de suas habilidades linguísticas." pitch_body: "Desenvolvemos o CodeCombat em Inglês, mas já temos jogadores de todo o mundo. Muitos deles querem jogar em Português Brasileiro mas não falam Inglês, por isso, se você conhece os dois idiomas, por favor, considere inscrever-se para ser um Diplomata e ajudar a traduzir tanto o site do CodeCombat quanto todos os estágios para o Português Brasileiro." missing_translations: "Até que possamos traduzir tudo para o Português Brasileiro, você lerá em Inglês quando a versão em Português Brasileiro ainda não estiver disponível." learn_more: "Saiba mais sobre ser um Diplomata" subscribe_as_diplomat: "Assinar como um Diplomata" account_settings: title: "Configurações da Conta" not_logged_in: "Entre com seu usuário e senha ou crie uma conta para poder alterar suas configurações." autosave: "As alterações serão salvas automaticamente." me_tab: "Eu" picture_tab: "Foto" wizard_tab: "Feiticeiro" password_tab: "Senha" emails_tab: "Emails" language_tab: "Idioma" gravatar_select: "Selecione qual foto do Gravatar usar" gravatar_add_photos: "Adicione miniaturas e fotos a uma conta do Gravatar ligada ao seu email para poder escolher uma imagem." gravatar_add_more_photos: "Adicione mais fotos à sua conta do Gravatar para acessá-las aqui." wizard_color: "Cor das Roupas do Feiticeiro" new_password: "PI:PASSWORD:<PASSWORD>END_PI" new_password_verify: "PI:PASSWORD:<PASSWORD>END_PI" email_subscriptions: "Assinaturas para Notícias por Email" email_announcements: "Notícias" email_announcements_description: "Receba emails com as últimas notícias e desenvolvimentos do CodeCombat." contributor_emails: "Emails para as Classes de Contribuidores" contribute_prefix: "Estamos procurando pessoas para se juntar à nossa turma! Confira a nossa " contribute_page: "página de contribuição" contribute_suffix: " para saber mais." email_toggle: "Ativar todos" language: "Idioma" saving: "Salvando..." error_saving: "Erro no salvamento" saved: "Alterações Salvas" password_mismatch: "As senhas não estão iguais" account_profile: edit_settings: "Editar as configurações" profile_for_prefix: "Perfil de " profile_for_suffix: "" profile: "Perfil" user_not_found: "Nenhum usuário encontrado. Checou o endereço de internet?" gravatar_not_found_mine: "Não conseguimos encontrar o perfil que está associado a:" gravatar_signup_prefix: "Crie uma conta no " gravatar_signup_suffix: " para poder configurar!" gravatar_not_found_other: "Infelizmente, não há perfil associado ao endereço de e-mail dessa pessoa." gravatar_contact: "Contate-nos" gravatar_websites: "Websites" gravatar_accounts: "Como visto no" gravatar_profile_link: "Perfil Completo do Gravatar" play_level: level_load_error: "O estágio não pôde ser carregado." done: "Pronto" grid: "Grade" customize_wizard: "Personalize o feiticeiro" home: "Início" guide: "Guia" multiplayer: "Multiplayer" restart: "Reiniciar" goals: "Objetivos" action_timeline: "Linha do Tempo das Ações" click_to_select: "Clique em um personagem para selecioná-lo." reload_title: "Recarregar Todo o Código?" reload_really: "Você tem certeza que quer reiniciar o estágio?" reload_confirm: "Recarregar Tudo" victory_title_prefix: "" victory_title_suffix: " Completado!" victory_sign_up: "Assine para atualizações" victory_sign_up_poke: "Quer receber as últimas novidades por email? Crie uma conta grátis e nós o manteremos informado!" victory_rate_the_level: "Avalie o estágio: " victory_play_next_level: "Jogar o próximo estágio" victory_go_home: "Ir à página inicial" victory_review: "Diga-nos mais!" victory_hour_of_code_done: "Terminou?" victory_hour_of_code_done_yes: "Sim, eu terminei minha Hora da Programação!" multiplayer_title: "Configurações do Multiplayer" multiplayer_link_description: "Passe este link para quem você quiser que se una à partida." multiplayer_hint_label: "Dica:" multiplayer_hint: " Clique no link para selecionar tudo, então dê Ctrl+C ou ⌘+C para copiar o link. " multiplayer_coming_soon: "Mais novidades no multiplayer estão chegando!" guide_title: "Guia" tome_minion_spells: "Magias dos seus subordinados" tome_read_only_spells: "Magias não editáveis" tome_other_units: "Outras Unidades" tome_cast_button_castable: "Lançar" tome_cast_button_casting: "Conjurando" tome_cast_button_cast: "Feitiço" tome_autocast_delay: "Atraso na autoconjuração" tome_autocast_1: "1 segundo" tome_autocast_3: "3 segundos" tome_autocast_5: "5 segundos" tome_autocast_manual: "Manual" tome_select_spell: "Selecione um Feitiço" tome_select_a_thang: "Selecione alguém para " tome_available_spells: "Feitiços Disponíveis" hud_continue: "Continue (tecle Shift+Space)"
[ { "context": "ew Rest\n config: Config\n access_token: 'qwerty'\n expect(rest._options.access_token).toBe 'qwe", "end": 1559, "score": 0.686526894569397, "start": 1553, "tag": "KEY", "value": "qwerty" }, { "context": "rty'\n expect(rest._options.access_token).toBe 'qw...
src/spec/connect/rest.spec.coffee
commercetools/sphere-node-sdk
13
_ = require 'underscore' _.mixin require('underscore-mixins') {Rest} = require '../../lib/main' Config = require('../../config').config describe 'Rest', -> it 'should initialize with default options', -> rest = new Rest config: Config expect(rest).toBeDefined() expect(rest._oauth).toBeDefined() expect(rest._options.host).toBe 'api.sphere.io' expect(rest._options.protocol).toBe 'https' expect(rest._options.access_token).not.toBeDefined() expect(rest._options.uri).toBe "https://api.sphere.io/#{Config.project_key}" expect(rest._options.timeout).toBe 20000 expect(rest._options.rejectUnauthorized).toBe true expect(rest._options.headers['User-Agent']).toBe 'sphere-node-connect' it 'should throw error if no credentials are given', -> rest = -> new Rest expect(rest).toThrow new Error 'Missing credentials' _.each ['client_id', 'client_secret', 'project_key'], (key) -> it "should throw error if no '#{key}' is defined", -> opt = _.clone(Config) delete opt[key] rest = -> new Rest config: opt expect(rest).toThrow new Error "Missing '#{key}'" it 'should pass \'host\' option', -> rest = new Rest config: Config host: 'example.com' expect(rest._options.host).toBe 'example.com' it 'should pass \'protocol\' option', -> rest = new Rest config: Config protocol: 'http' expect(rest._options.protocol).toBe 'http' it 'should pass \'access_token\' option', -> rest = new Rest config: Config access_token: 'qwerty' expect(rest._options.access_token).toBe 'qwerty' it 'should pass \'timeout\' option', -> rest = new Rest config: Config timeout: 100 expect(rest._options.timeout).toBe 100 it 'should pass \'rejectUnauthorized\' option', -> rest = new Rest config: Config rejectUnauthorized: false expect(rest._options.rejectUnauthorized).toBe false it 'should pass \'oauth_host\' option', -> rest = new Rest config: Config oauth_host: 'auth.escemo.com' expect(rest._oauth._options.host).toBe 'auth.escemo.com' it 'should pass \'oauth_protocol\' option', -> rest = new Rest config: Config oauth_protocol: 'http' expect(rest._oauth._options.protocol).toBe 'http' it 'should pass \'user_agent\' option', -> rest = new Rest config: Config user_agent: 'commercetools' expect(rest._options.headers['User-Agent']).toBe 'commercetools' describe ':: requests', -> beforeEach -> opts = config: Config access_token: 'foo' @rest = new Rest opts spyOn(@rest, '_doRequest').andCallFake (options, callback) -> callback(null, null, {id: '123'}) spyOn(@rest._oauth, 'getAccessToken').andCallFake (callback) -> callback(null, {statusCode: 200}, {access_token: 'foo', expires_in: 2 * 24 * 60 * 60}) afterEach -> @rest = null prepareRequest = (done, method, endpoint, f) -> callMe = (e, r, b) -> expect(b.id).toBe '123' done() expected_options = uri: "https://api.sphere.io/#{Config.project_key}#{endpoint}" json: true gzip: true method: method host: 'api.sphere.io' headers: 'User-Agent': 'sphere-node-connect' 'Authorization': 'Bearer foo' timeout: 20000 rejectUnauthorized: true f(callMe, expected_options) it 'should not fail to log if request times out', (done) -> rest = new Rest config: Config timeout: 1 access_token: 'qwerty1234567890' callMe = -> done() expect(-> rest.GET('/products', callMe)).not.toThrow() describe ':: _preRequest', -> it 'should fail to getting an access_token after 10 attempts', (done) -> rest = new Rest config: Config spyOn(rest._oauth, 'getAccessToken').andCallFake (callback) -> callback(null, {statusCode: 401}, {error: 'invalid_client'}) rest._preRequest({}, (error, response, body) -> expect(body).toEqual({ error: 'invalid_client' }) done() ) it 'should request new token when it expires', (done) -> rest = new Rest config: Config spyOn(rest, '_doRequest').andCallFake (options, callback) -> callback(null, {statusCode: 200}, {id: '123'}) spyOn(rest._oauth, 'getAccessToken').andCallFake (callback) -> expiresIn = if rest._oauth.getAccessToken.calls.length > 1 then (2 * 24 * 60 * 60) else 1 authResponse = {access_token: 'foo', expires_in: expiresIn} callback(null, {statusCode: 200}, authResponse) rest._preRequest({}, (error, response, body) -> rest._preRequest({}, (error, response, body) -> expect(rest._oauth.getAccessToken.calls.length).toBe(2) done() ) ) it 'should fail on error', (done) -> rest = new Rest config: Config spyOn(rest._oauth, 'getAccessToken').andCallFake (callback) -> callback('Connection read timeout', {statusCode: 401}, null) rest._preRequest({}, (error, response, body) -> expect(error).toEqual('Connection read timeout') done() ) describe ':: GET', -> it 'should send GET request', (done) -> prepareRequest done, 'GET', '/products', (callMe, expected_options) => @rest.GET('/products', callMe) expect(@rest._doRequest).toHaveBeenCalledWith(expected_options, jasmine.any(Function)) it 'should send GET request with OAuth', (done) -> rest = new Rest config: Config spyOn(rest._oauth, 'getAccessToken').andCallFake (callback) -> callback(null, {statusCode: 200}, {access_token: 'foo'}) spyOn(rest, '_doRequest').andCallFake (options, callback) -> callback(null, null, {id: '123'}) prepareRequest done, 'GET', '/products', (callMe, expected_options) -> rest.GET('/products', callMe) expect(rest._oauth.getAccessToken).toHaveBeenCalledWith(jasmine.any(Function)) expect(rest._doRequest).toHaveBeenCalledWith(expected_options, jasmine.any(Function)) describe ':: POST', -> it 'should send POST request', (done) -> prepareRequest done, 'POST', '/products', (callMe, expected_options) => @rest.POST('/products', {name: 'Foo'}, callMe) _.extend expected_options, uri: "https://api.sphere.io/#{Config.project_key}/products" method: 'POST' body: {name: 'Foo'} expect(@rest._doRequest).toHaveBeenCalledWith(expected_options, jasmine.any(Function)) it 'should send POST request with OAuth', (done) -> rest = new Rest config: Config spyOn(rest._oauth, 'getAccessToken').andCallFake (callback) -> callback(null, {statusCode: 200}, {access_token: 'foo'}) spyOn(rest, '_doRequest').andCallFake (options, callback) -> callback(null, null, {id: '123'}) prepareRequest done, 'POST', '/products', (callMe, expected_options) -> rest.POST('/products', {name: 'Foo'}, callMe) _.extend expected_options, uri: "https://api.sphere.io/#{Config.project_key}/products" method: 'POST' body: {name: 'Foo'} expect(rest._oauth.getAccessToken).toHaveBeenCalledWith(jasmine.any(Function)) expect(rest._doRequest).toHaveBeenCalledWith(expected_options, jasmine.any(Function)) describe ':: PUT', -> it 'should throw error for unimplented PUT request', -> rest = new Rest config: Config expect(-> rest.PUT()).toThrow new Error 'Not implemented yet' describe ':: DELETE', -> it 'should send DELETE request', (done) -> prepareRequest done, 'DELETE', '/products?version=1', (callMe, expected_options) => @rest.DELETE('/products?version=1', callMe) expect(@rest._doRequest).toHaveBeenCalledWith(expected_options, jasmine.any(Function)) it 'should send DELETE request with OAuth', (done) -> rest = new Rest config: Config spyOn(rest._oauth, 'getAccessToken').andCallFake (callback) -> callback(null, {statusCode: 200}, {access_token: 'foo'}) spyOn(rest, '_doRequest').andCallFake (options, callback) -> callback(null, null, {id: '123'}) prepareRequest done, 'DELETE', '/products?version=1', (callMe, expected_options) -> rest.DELETE('/products?version=1', callMe) expect(rest._oauth.getAccessToken).toHaveBeenCalledWith(jasmine.any(Function)) expect(rest._doRequest).toHaveBeenCalledWith(expected_options, jasmine.any(Function)) describe ':: PAGED', -> idCounter = 0 uniqueId = (prefix) -> id = ++idCounter + '' if prefix then prefix + id else id resetUniqueIdCounter = () -> idCounter = 0 beforeEach -> opts = config: Config access_token: 'foo' @pagedRest = new Rest opts offset = -50 count = 50 spyOn(@pagedRest, '_doRequest').andCallFake (options, callback) -> offset += 50 callback null, {statusCode: 200}, total: 1004 count: if offset is 1000 then 4 else count offset: offset results: _.map (if offset is 1000 then [1..4] else [1..50]), (i) -> {id: uniqueId("_#{i}") , value: 'foo'} spyOn(@pagedRest._oauth, 'getAccessToken') .andCallFake (callback) -> callback(null, null, {access_token: 'foo'}) afterEach -> resetUniqueIdCounter() @pagedRest = null it 'should send PAGED request', (done) -> @pagedRest.PAGED '/products', (e, r, b) => expect(e).toBe null expect(r.statusCode).toBe 200 expect(b.total).toBe 1004 expect(b.count).toBe 1004 expect(b.offset).toBe 1000 expect(b.results.length).toBe 1004 expect(@pagedRest._doRequest.calls.length).toBe 21 done() it 'should send PAGED request and preserving query parameters', (done) -> queryParams = _.stringifyQuery where: encodeURIComponent('sku in ("123", "456")') expand: 'productType' staged: true sort: encodeURIComponent('createdAt asc') @pagedRest.PAGED "/products?#{queryParams}", (e, r, b) => expect(e).toBe null expect(r.statusCode).toBe 200 expect(b.total).toBe 1004 expect(b.count).toBe 1004 expect(b.offset).toBe 1000 expect(b.results.length).toBe 1004 expect(@pagedRest._doRequest.calls.length).toBe 21 expect(@pagedRest._doRequest.calls[0].args[0].uri).toEqual "https://api.sphere.io/#{Config.project_key}/products?" + _.stringifyQuery limit: 50 where: encodeURIComponent('sku in ("123", "456")') expand: 'productType' staged: true sort: encodeURIComponent('createdAt asc') withTotal: false expect(@pagedRest._doRequest.calls[1].args[0].uri).toEqual "https://api.sphere.io/#{Config.project_key}/products?" + _.stringifyQuery limit: 50 where: encodeURIComponent('(sku in ("123", "456")) and id > "_5050"') expand: 'productType' staged: true sort: encodeURIComponent('createdAt asc') withTotal: false done() it 'should not overwrite duplicate url parameters', (done) -> spyOn(@pagedRest, 'GET').andCallThrough() @pagedRest.PAGED "/products?expand=foo&expand=bar", (e, r, b) => url = @pagedRest.GET.calls[0].args[0] query = url.split('?')[1] query = query.split('&') expect(query[1]).toEqual('expand=foo') expect(query[2]).toEqual('expand=bar') done() it 'should correctly return error', (done) -> spyOn(@pagedRest, 'GET').andCallFake (endpoint, callback) -> callback('Oops', {statusCode: 500}, null) @pagedRest.PAGED "/products", (e, r, b) => expect(e).toBe 'Oops' expect(r.statusCode).toBe 500 expect(b).toBe null done() it 'should correctly return error response body', (done) -> spyOn(@pagedRest, 'GET').andCallFake (endpoint, callback) -> callback(null, {statusCode: 400}, {statusCode: 400, message: 'Something went wrong'}) @pagedRest.PAGED "/products", (e, r, b) => expect(e).toBe null expect(r.statusCode).toBe 400 expect(b.statusCode).toBe 400 expect(b.message).toBe 'Something went wrong' done() it 'should not throw if limit param is 0', (done) -> expect(=> @pagedRest.PAGED '/products?limit=0', -> done()).not.toThrow()
139921
_ = require 'underscore' _.mixin require('underscore-mixins') {Rest} = require '../../lib/main' Config = require('../../config').config describe 'Rest', -> it 'should initialize with default options', -> rest = new Rest config: Config expect(rest).toBeDefined() expect(rest._oauth).toBeDefined() expect(rest._options.host).toBe 'api.sphere.io' expect(rest._options.protocol).toBe 'https' expect(rest._options.access_token).not.toBeDefined() expect(rest._options.uri).toBe "https://api.sphere.io/#{Config.project_key}" expect(rest._options.timeout).toBe 20000 expect(rest._options.rejectUnauthorized).toBe true expect(rest._options.headers['User-Agent']).toBe 'sphere-node-connect' it 'should throw error if no credentials are given', -> rest = -> new Rest expect(rest).toThrow new Error 'Missing credentials' _.each ['client_id', 'client_secret', 'project_key'], (key) -> it "should throw error if no '#{key}' is defined", -> opt = _.clone(Config) delete opt[key] rest = -> new Rest config: opt expect(rest).toThrow new Error "Missing '#{key}'" it 'should pass \'host\' option', -> rest = new Rest config: Config host: 'example.com' expect(rest._options.host).toBe 'example.com' it 'should pass \'protocol\' option', -> rest = new Rest config: Config protocol: 'http' expect(rest._options.protocol).toBe 'http' it 'should pass \'access_token\' option', -> rest = new Rest config: Config access_token: '<KEY>' expect(rest._options.access_token).toBe '<KEY>' it 'should pass \'timeout\' option', -> rest = new Rest config: Config timeout: 100 expect(rest._options.timeout).toBe 100 it 'should pass \'rejectUnauthorized\' option', -> rest = new Rest config: Config rejectUnauthorized: false expect(rest._options.rejectUnauthorized).toBe false it 'should pass \'oauth_host\' option', -> rest = new Rest config: Config oauth_host: 'auth.escemo.com' expect(rest._oauth._options.host).toBe 'auth.escemo.com' it 'should pass \'oauth_protocol\' option', -> rest = new Rest config: Config oauth_protocol: 'http' expect(rest._oauth._options.protocol).toBe 'http' it 'should pass \'user_agent\' option', -> rest = new Rest config: Config user_agent: 'commercetools' expect(rest._options.headers['User-Agent']).toBe 'commercetools' describe ':: requests', -> beforeEach -> opts = config: Config access_token: 'foo' @rest = new Rest opts spyOn(@rest, '_doRequest').andCallFake (options, callback) -> callback(null, null, {id: '123'}) spyOn(@rest._oauth, 'getAccessToken').andCallFake (callback) -> callback(null, {statusCode: 200}, {access_token: 'foo', expires_in: 2 * 24 * 60 * 60}) afterEach -> @rest = null prepareRequest = (done, method, endpoint, f) -> callMe = (e, r, b) -> expect(b.id).toBe '123' done() expected_options = uri: "https://api.sphere.io/#{Config.project_key}#{endpoint}" json: true gzip: true method: method host: 'api.sphere.io' headers: 'User-Agent': 'sphere-node-connect' 'Authorization': 'Bearer foo' timeout: 20000 rejectUnauthorized: true f(callMe, expected_options) it 'should not fail to log if request times out', (done) -> rest = new Rest config: Config timeout: 1 access_token: '<KEY>' callMe = -> done() expect(-> rest.GET('/products', callMe)).not.toThrow() describe ':: _preRequest', -> it 'should fail to getting an access_token after 10 attempts', (done) -> rest = new Rest config: Config spyOn(rest._oauth, 'getAccessToken').andCallFake (callback) -> callback(null, {statusCode: 401}, {error: 'invalid_client'}) rest._preRequest({}, (error, response, body) -> expect(body).toEqual({ error: 'invalid_client' }) done() ) it 'should request new token when it expires', (done) -> rest = new Rest config: Config spyOn(rest, '_doRequest').andCallFake (options, callback) -> callback(null, {statusCode: 200}, {id: '123'}) spyOn(rest._oauth, 'getAccessToken').andCallFake (callback) -> expiresIn = if rest._oauth.getAccessToken.calls.length > 1 then (2 * 24 * 60 * 60) else 1 authResponse = {access_token: '<PASSWORD>', expires_in: expiresIn} callback(null, {statusCode: 200}, authResponse) rest._preRequest({}, (error, response, body) -> rest._preRequest({}, (error, response, body) -> expect(rest._oauth.getAccessToken.calls.length).toBe(2) done() ) ) it 'should fail on error', (done) -> rest = new Rest config: Config spyOn(rest._oauth, 'getAccessToken').andCallFake (callback) -> callback('Connection read timeout', {statusCode: 401}, null) rest._preRequest({}, (error, response, body) -> expect(error).toEqual('Connection read timeout') done() ) describe ':: GET', -> it 'should send GET request', (done) -> prepareRequest done, 'GET', '/products', (callMe, expected_options) => @rest.GET('/products', callMe) expect(@rest._doRequest).toHaveBeenCalledWith(expected_options, jasmine.any(Function)) it 'should send GET request with OAuth', (done) -> rest = new Rest config: Config spyOn(rest._oauth, 'getAccessToken').andCallFake (callback) -> callback(null, {statusCode: 200}, {access_token: 'foo'}) spyOn(rest, '_doRequest').andCallFake (options, callback) -> callback(null, null, {id: '123'}) prepareRequest done, 'GET', '/products', (callMe, expected_options) -> rest.GET('/products', callMe) expect(rest._oauth.getAccessToken).toHaveBeenCalledWith(jasmine.any(Function)) expect(rest._doRequest).toHaveBeenCalledWith(expected_options, jasmine.any(Function)) describe ':: POST', -> it 'should send POST request', (done) -> prepareRequest done, 'POST', '/products', (callMe, expected_options) => @rest.POST('/products', {name: 'Foo'}, callMe) _.extend expected_options, uri: "https://api.sphere.io/#{Config.project_key}/products" method: 'POST' body: {name: 'Foo'} expect(@rest._doRequest).toHaveBeenCalledWith(expected_options, jasmine.any(Function)) it 'should send POST request with OAuth', (done) -> rest = new Rest config: Config spyOn(rest._oauth, 'getAccessToken').andCallFake (callback) -> callback(null, {statusCode: 200}, {access_token: 'foo'}) spyOn(rest, '_doRequest').andCallFake (options, callback) -> callback(null, null, {id: '123'}) prepareRequest done, 'POST', '/products', (callMe, expected_options) -> rest.POST('/products', {name: 'Foo'}, callMe) _.extend expected_options, uri: "https://api.sphere.io/#{Config.project_key}/products" method: 'POST' body: {name: 'Foo'} expect(rest._oauth.getAccessToken).toHaveBeenCalledWith(jasmine.any(Function)) expect(rest._doRequest).toHaveBeenCalledWith(expected_options, jasmine.any(Function)) describe ':: PUT', -> it 'should throw error for unimplented PUT request', -> rest = new Rest config: Config expect(-> rest.PUT()).toThrow new Error 'Not implemented yet' describe ':: DELETE', -> it 'should send DELETE request', (done) -> prepareRequest done, 'DELETE', '/products?version=1', (callMe, expected_options) => @rest.DELETE('/products?version=1', callMe) expect(@rest._doRequest).toHaveBeenCalledWith(expected_options, jasmine.any(Function)) it 'should send DELETE request with OAuth', (done) -> rest = new Rest config: Config spyOn(rest._oauth, 'getAccessToken').andCallFake (callback) -> callback(null, {statusCode: 200}, {access_token: 'foo'}) spyOn(rest, '_doRequest').andCallFake (options, callback) -> callback(null, null, {id: '123'}) prepareRequest done, 'DELETE', '/products?version=1', (callMe, expected_options) -> rest.DELETE('/products?version=1', callMe) expect(rest._oauth.getAccessToken).toHaveBeenCalledWith(jasmine.any(Function)) expect(rest._doRequest).toHaveBeenCalledWith(expected_options, jasmine.any(Function)) describe ':: PAGED', -> idCounter = 0 uniqueId = (prefix) -> id = ++idCounter + '' if prefix then prefix + id else id resetUniqueIdCounter = () -> idCounter = 0 beforeEach -> opts = config: Config access_token: 'foo' @pagedRest = new Rest opts offset = -50 count = 50 spyOn(@pagedRest, '_doRequest').andCallFake (options, callback) -> offset += 50 callback null, {statusCode: 200}, total: 1004 count: if offset is 1000 then 4 else count offset: offset results: _.map (if offset is 1000 then [1..4] else [1..50]), (i) -> {id: uniqueId("_#{i}") , value: 'foo'} spyOn(@pagedRest._oauth, 'getAccessToken') .andCallFake (callback) -> callback(null, null, {access_token: 'foo'}) afterEach -> resetUniqueIdCounter() @pagedRest = null it 'should send PAGED request', (done) -> @pagedRest.PAGED '/products', (e, r, b) => expect(e).toBe null expect(r.statusCode).toBe 200 expect(b.total).toBe 1004 expect(b.count).toBe 1004 expect(b.offset).toBe 1000 expect(b.results.length).toBe 1004 expect(@pagedRest._doRequest.calls.length).toBe 21 done() it 'should send PAGED request and preserving query parameters', (done) -> queryParams = _.stringifyQuery where: encodeURIComponent('sku in ("123", "456")') expand: 'productType' staged: true sort: encodeURIComponent('createdAt asc') @pagedRest.PAGED "/products?#{queryParams}", (e, r, b) => expect(e).toBe null expect(r.statusCode).toBe 200 expect(b.total).toBe 1004 expect(b.count).toBe 1004 expect(b.offset).toBe 1000 expect(b.results.length).toBe 1004 expect(@pagedRest._doRequest.calls.length).toBe 21 expect(@pagedRest._doRequest.calls[0].args[0].uri).toEqual "https://api.sphere.io/#{Config.project_key}/products?" + _.stringifyQuery limit: 50 where: encodeURIComponent('sku in ("123", "456")') expand: 'productType' staged: true sort: encodeURIComponent('createdAt asc') withTotal: false expect(@pagedRest._doRequest.calls[1].args[0].uri).toEqual "https://api.sphere.io/#{Config.project_key}/products?" + _.stringifyQuery limit: 50 where: encodeURIComponent('(sku in ("123", "456")) and id > "_5050"') expand: 'productType' staged: true sort: encodeURIComponent('createdAt asc') withTotal: false done() it 'should not overwrite duplicate url parameters', (done) -> spyOn(@pagedRest, 'GET').andCallThrough() @pagedRest.PAGED "/products?expand=foo&expand=bar", (e, r, b) => url = @pagedRest.GET.calls[0].args[0] query = url.split('?')[1] query = query.split('&') expect(query[1]).toEqual('expand=foo') expect(query[2]).toEqual('expand=bar') done() it 'should correctly return error', (done) -> spyOn(@pagedRest, 'GET').andCallFake (endpoint, callback) -> callback('Oops', {statusCode: 500}, null) @pagedRest.PAGED "/products", (e, r, b) => expect(e).toBe 'Oops' expect(r.statusCode).toBe 500 expect(b).toBe null done() it 'should correctly return error response body', (done) -> spyOn(@pagedRest, 'GET').andCallFake (endpoint, callback) -> callback(null, {statusCode: 400}, {statusCode: 400, message: 'Something went wrong'}) @pagedRest.PAGED "/products", (e, r, b) => expect(e).toBe null expect(r.statusCode).toBe 400 expect(b.statusCode).toBe 400 expect(b.message).toBe 'Something went wrong' done() it 'should not throw if limit param is 0', (done) -> expect(=> @pagedRest.PAGED '/products?limit=0', -> done()).not.toThrow()
true
_ = require 'underscore' _.mixin require('underscore-mixins') {Rest} = require '../../lib/main' Config = require('../../config').config describe 'Rest', -> it 'should initialize with default options', -> rest = new Rest config: Config expect(rest).toBeDefined() expect(rest._oauth).toBeDefined() expect(rest._options.host).toBe 'api.sphere.io' expect(rest._options.protocol).toBe 'https' expect(rest._options.access_token).not.toBeDefined() expect(rest._options.uri).toBe "https://api.sphere.io/#{Config.project_key}" expect(rest._options.timeout).toBe 20000 expect(rest._options.rejectUnauthorized).toBe true expect(rest._options.headers['User-Agent']).toBe 'sphere-node-connect' it 'should throw error if no credentials are given', -> rest = -> new Rest expect(rest).toThrow new Error 'Missing credentials' _.each ['client_id', 'client_secret', 'project_key'], (key) -> it "should throw error if no '#{key}' is defined", -> opt = _.clone(Config) delete opt[key] rest = -> new Rest config: opt expect(rest).toThrow new Error "Missing '#{key}'" it 'should pass \'host\' option', -> rest = new Rest config: Config host: 'example.com' expect(rest._options.host).toBe 'example.com' it 'should pass \'protocol\' option', -> rest = new Rest config: Config protocol: 'http' expect(rest._options.protocol).toBe 'http' it 'should pass \'access_token\' option', -> rest = new Rest config: Config access_token: 'PI:KEY:<KEY>END_PI' expect(rest._options.access_token).toBe 'PI:KEY:<KEY>END_PI' it 'should pass \'timeout\' option', -> rest = new Rest config: Config timeout: 100 expect(rest._options.timeout).toBe 100 it 'should pass \'rejectUnauthorized\' option', -> rest = new Rest config: Config rejectUnauthorized: false expect(rest._options.rejectUnauthorized).toBe false it 'should pass \'oauth_host\' option', -> rest = new Rest config: Config oauth_host: 'auth.escemo.com' expect(rest._oauth._options.host).toBe 'auth.escemo.com' it 'should pass \'oauth_protocol\' option', -> rest = new Rest config: Config oauth_protocol: 'http' expect(rest._oauth._options.protocol).toBe 'http' it 'should pass \'user_agent\' option', -> rest = new Rest config: Config user_agent: 'commercetools' expect(rest._options.headers['User-Agent']).toBe 'commercetools' describe ':: requests', -> beforeEach -> opts = config: Config access_token: 'foo' @rest = new Rest opts spyOn(@rest, '_doRequest').andCallFake (options, callback) -> callback(null, null, {id: '123'}) spyOn(@rest._oauth, 'getAccessToken').andCallFake (callback) -> callback(null, {statusCode: 200}, {access_token: 'foo', expires_in: 2 * 24 * 60 * 60}) afterEach -> @rest = null prepareRequest = (done, method, endpoint, f) -> callMe = (e, r, b) -> expect(b.id).toBe '123' done() expected_options = uri: "https://api.sphere.io/#{Config.project_key}#{endpoint}" json: true gzip: true method: method host: 'api.sphere.io' headers: 'User-Agent': 'sphere-node-connect' 'Authorization': 'Bearer foo' timeout: 20000 rejectUnauthorized: true f(callMe, expected_options) it 'should not fail to log if request times out', (done) -> rest = new Rest config: Config timeout: 1 access_token: 'PI:KEY:<KEY>END_PI' callMe = -> done() expect(-> rest.GET('/products', callMe)).not.toThrow() describe ':: _preRequest', -> it 'should fail to getting an access_token after 10 attempts', (done) -> rest = new Rest config: Config spyOn(rest._oauth, 'getAccessToken').andCallFake (callback) -> callback(null, {statusCode: 401}, {error: 'invalid_client'}) rest._preRequest({}, (error, response, body) -> expect(body).toEqual({ error: 'invalid_client' }) done() ) it 'should request new token when it expires', (done) -> rest = new Rest config: Config spyOn(rest, '_doRequest').andCallFake (options, callback) -> callback(null, {statusCode: 200}, {id: '123'}) spyOn(rest._oauth, 'getAccessToken').andCallFake (callback) -> expiresIn = if rest._oauth.getAccessToken.calls.length > 1 then (2 * 24 * 60 * 60) else 1 authResponse = {access_token: 'PI:PASSWORD:<PASSWORD>END_PI', expires_in: expiresIn} callback(null, {statusCode: 200}, authResponse) rest._preRequest({}, (error, response, body) -> rest._preRequest({}, (error, response, body) -> expect(rest._oauth.getAccessToken.calls.length).toBe(2) done() ) ) it 'should fail on error', (done) -> rest = new Rest config: Config spyOn(rest._oauth, 'getAccessToken').andCallFake (callback) -> callback('Connection read timeout', {statusCode: 401}, null) rest._preRequest({}, (error, response, body) -> expect(error).toEqual('Connection read timeout') done() ) describe ':: GET', -> it 'should send GET request', (done) -> prepareRequest done, 'GET', '/products', (callMe, expected_options) => @rest.GET('/products', callMe) expect(@rest._doRequest).toHaveBeenCalledWith(expected_options, jasmine.any(Function)) it 'should send GET request with OAuth', (done) -> rest = new Rest config: Config spyOn(rest._oauth, 'getAccessToken').andCallFake (callback) -> callback(null, {statusCode: 200}, {access_token: 'foo'}) spyOn(rest, '_doRequest').andCallFake (options, callback) -> callback(null, null, {id: '123'}) prepareRequest done, 'GET', '/products', (callMe, expected_options) -> rest.GET('/products', callMe) expect(rest._oauth.getAccessToken).toHaveBeenCalledWith(jasmine.any(Function)) expect(rest._doRequest).toHaveBeenCalledWith(expected_options, jasmine.any(Function)) describe ':: POST', -> it 'should send POST request', (done) -> prepareRequest done, 'POST', '/products', (callMe, expected_options) => @rest.POST('/products', {name: 'Foo'}, callMe) _.extend expected_options, uri: "https://api.sphere.io/#{Config.project_key}/products" method: 'POST' body: {name: 'Foo'} expect(@rest._doRequest).toHaveBeenCalledWith(expected_options, jasmine.any(Function)) it 'should send POST request with OAuth', (done) -> rest = new Rest config: Config spyOn(rest._oauth, 'getAccessToken').andCallFake (callback) -> callback(null, {statusCode: 200}, {access_token: 'foo'}) spyOn(rest, '_doRequest').andCallFake (options, callback) -> callback(null, null, {id: '123'}) prepareRequest done, 'POST', '/products', (callMe, expected_options) -> rest.POST('/products', {name: 'Foo'}, callMe) _.extend expected_options, uri: "https://api.sphere.io/#{Config.project_key}/products" method: 'POST' body: {name: 'Foo'} expect(rest._oauth.getAccessToken).toHaveBeenCalledWith(jasmine.any(Function)) expect(rest._doRequest).toHaveBeenCalledWith(expected_options, jasmine.any(Function)) describe ':: PUT', -> it 'should throw error for unimplented PUT request', -> rest = new Rest config: Config expect(-> rest.PUT()).toThrow new Error 'Not implemented yet' describe ':: DELETE', -> it 'should send DELETE request', (done) -> prepareRequest done, 'DELETE', '/products?version=1', (callMe, expected_options) => @rest.DELETE('/products?version=1', callMe) expect(@rest._doRequest).toHaveBeenCalledWith(expected_options, jasmine.any(Function)) it 'should send DELETE request with OAuth', (done) -> rest = new Rest config: Config spyOn(rest._oauth, 'getAccessToken').andCallFake (callback) -> callback(null, {statusCode: 200}, {access_token: 'foo'}) spyOn(rest, '_doRequest').andCallFake (options, callback) -> callback(null, null, {id: '123'}) prepareRequest done, 'DELETE', '/products?version=1', (callMe, expected_options) -> rest.DELETE('/products?version=1', callMe) expect(rest._oauth.getAccessToken).toHaveBeenCalledWith(jasmine.any(Function)) expect(rest._doRequest).toHaveBeenCalledWith(expected_options, jasmine.any(Function)) describe ':: PAGED', -> idCounter = 0 uniqueId = (prefix) -> id = ++idCounter + '' if prefix then prefix + id else id resetUniqueIdCounter = () -> idCounter = 0 beforeEach -> opts = config: Config access_token: 'foo' @pagedRest = new Rest opts offset = -50 count = 50 spyOn(@pagedRest, '_doRequest').andCallFake (options, callback) -> offset += 50 callback null, {statusCode: 200}, total: 1004 count: if offset is 1000 then 4 else count offset: offset results: _.map (if offset is 1000 then [1..4] else [1..50]), (i) -> {id: uniqueId("_#{i}") , value: 'foo'} spyOn(@pagedRest._oauth, 'getAccessToken') .andCallFake (callback) -> callback(null, null, {access_token: 'foo'}) afterEach -> resetUniqueIdCounter() @pagedRest = null it 'should send PAGED request', (done) -> @pagedRest.PAGED '/products', (e, r, b) => expect(e).toBe null expect(r.statusCode).toBe 200 expect(b.total).toBe 1004 expect(b.count).toBe 1004 expect(b.offset).toBe 1000 expect(b.results.length).toBe 1004 expect(@pagedRest._doRequest.calls.length).toBe 21 done() it 'should send PAGED request and preserving query parameters', (done) -> queryParams = _.stringifyQuery where: encodeURIComponent('sku in ("123", "456")') expand: 'productType' staged: true sort: encodeURIComponent('createdAt asc') @pagedRest.PAGED "/products?#{queryParams}", (e, r, b) => expect(e).toBe null expect(r.statusCode).toBe 200 expect(b.total).toBe 1004 expect(b.count).toBe 1004 expect(b.offset).toBe 1000 expect(b.results.length).toBe 1004 expect(@pagedRest._doRequest.calls.length).toBe 21 expect(@pagedRest._doRequest.calls[0].args[0].uri).toEqual "https://api.sphere.io/#{Config.project_key}/products?" + _.stringifyQuery limit: 50 where: encodeURIComponent('sku in ("123", "456")') expand: 'productType' staged: true sort: encodeURIComponent('createdAt asc') withTotal: false expect(@pagedRest._doRequest.calls[1].args[0].uri).toEqual "https://api.sphere.io/#{Config.project_key}/products?" + _.stringifyQuery limit: 50 where: encodeURIComponent('(sku in ("123", "456")) and id > "_5050"') expand: 'productType' staged: true sort: encodeURIComponent('createdAt asc') withTotal: false done() it 'should not overwrite duplicate url parameters', (done) -> spyOn(@pagedRest, 'GET').andCallThrough() @pagedRest.PAGED "/products?expand=foo&expand=bar", (e, r, b) => url = @pagedRest.GET.calls[0].args[0] query = url.split('?')[1] query = query.split('&') expect(query[1]).toEqual('expand=foo') expect(query[2]).toEqual('expand=bar') done() it 'should correctly return error', (done) -> spyOn(@pagedRest, 'GET').andCallFake (endpoint, callback) -> callback('Oops', {statusCode: 500}, null) @pagedRest.PAGED "/products", (e, r, b) => expect(e).toBe 'Oops' expect(r.statusCode).toBe 500 expect(b).toBe null done() it 'should correctly return error response body', (done) -> spyOn(@pagedRest, 'GET').andCallFake (endpoint, callback) -> callback(null, {statusCode: 400}, {statusCode: 400, message: 'Something went wrong'}) @pagedRest.PAGED "/products", (e, r, b) => expect(e).toBe null expect(r.statusCode).toBe 400 expect(b.statusCode).toBe 400 expect(b.message).toBe 'Something went wrong' done() it 'should not throw if limit param is 0', (done) -> expect(=> @pagedRest.PAGED '/products?limit=0', -> done()).not.toThrow()
[ { "context": "can be used as Promise rejection reasons\n# @author Teddy Katz\n###\n'use strict'\n\n#------------------------------", "end": 103, "score": 0.9998335838317871, "start": 93, "tag": "NAME", "value": "Teddy Katz" } ]
src/tests/rules/prefer-promise-reject-errors.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview restrict values that can be used as Promise rejection reasons # @author Teddy Katz ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require 'eslint/lib/rules/prefer-promise-reject-errors' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'prefer-promise-reject-errors', rule, valid: [ 'Promise.resolve(5)' 'Foo.reject(5)' 'Promise.reject(foo)' 'Promise.reject(foo.bar)' 'Promise.reject(foo.bar())' 'Promise.reject(new Error())' 'Promise.reject(new TypeError)' "Promise.reject(new Error('foo'))" 'new Foo((resolve, reject) => reject(5))' 'new Promise (resolve, reject) -> (reject) -> reject 5' # ''' # new Promise (resolve, reject) -> # if foo # reject = somethingElse # reject(5) # ''' 'new Promise((resolve, {apply}) -> apply(5))' 'new Promise((resolve, reject) -> resolve(5, reject))' '-> Promise.reject await foo' , code: 'Promise.reject()' options: [allowEmptyReject: yes] , code: 'new Promise((resolve, reject) -> reject())' options: [allowEmptyReject: yes] ] invalid: [ 'Promise.reject(5)' "Promise.reject('foo')" 'Promise.reject(!foo)' 'Promise.reject()' 'Promise.reject(undefined)' 'Promise.reject({ foo: 1 })' 'Promise.reject([1, 2, 3])' , code: 'Promise.reject()' options: [allowEmptyReject: no] , code: 'new Promise((resolve, reject) -> reject())' options: [allowEmptyReject: no] , code: 'Promise.reject(undefined)' options: [allowEmptyReject: yes] , "Promise.reject('foo', somethingElse)" 'new Promise((resolve, reject) => reject(5))' 'new Promise((resolve, reject) => reject())' 'new Promise (y, n) -> n(5)' ''' new Promise (resolve, reject) => fs.readFile 'foo.txt', (err, file) => if err reject 'File not found' else resolve file ''' 'new Promise(({foo, bar, baz}, reject) => reject(5))' # 'new Promise((reject, reject) -> reject(5))' 'new Promise(({}, reject) -> reject(5))' 'new Promise((resolve, reject, somethingElse = reject(5)) =>)' ].map (invalidCase) -> errors = errors: [ message: 'Expected the Promise rejection reason to be an Error.' type: 'CallExpression' ] { ...errors ...( if typeof invalidCase is 'string' code: invalidCase else invalidCase ) }
161658
###* # @fileoverview restrict values that can be used as Promise rejection reasons # @author <NAME> ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require 'eslint/lib/rules/prefer-promise-reject-errors' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'prefer-promise-reject-errors', rule, valid: [ 'Promise.resolve(5)' 'Foo.reject(5)' 'Promise.reject(foo)' 'Promise.reject(foo.bar)' 'Promise.reject(foo.bar())' 'Promise.reject(new Error())' 'Promise.reject(new TypeError)' "Promise.reject(new Error('foo'))" 'new Foo((resolve, reject) => reject(5))' 'new Promise (resolve, reject) -> (reject) -> reject 5' # ''' # new Promise (resolve, reject) -> # if foo # reject = somethingElse # reject(5) # ''' 'new Promise((resolve, {apply}) -> apply(5))' 'new Promise((resolve, reject) -> resolve(5, reject))' '-> Promise.reject await foo' , code: 'Promise.reject()' options: [allowEmptyReject: yes] , code: 'new Promise((resolve, reject) -> reject())' options: [allowEmptyReject: yes] ] invalid: [ 'Promise.reject(5)' "Promise.reject('foo')" 'Promise.reject(!foo)' 'Promise.reject()' 'Promise.reject(undefined)' 'Promise.reject({ foo: 1 })' 'Promise.reject([1, 2, 3])' , code: 'Promise.reject()' options: [allowEmptyReject: no] , code: 'new Promise((resolve, reject) -> reject())' options: [allowEmptyReject: no] , code: 'Promise.reject(undefined)' options: [allowEmptyReject: yes] , "Promise.reject('foo', somethingElse)" 'new Promise((resolve, reject) => reject(5))' 'new Promise((resolve, reject) => reject())' 'new Promise (y, n) -> n(5)' ''' new Promise (resolve, reject) => fs.readFile 'foo.txt', (err, file) => if err reject 'File not found' else resolve file ''' 'new Promise(({foo, bar, baz}, reject) => reject(5))' # 'new Promise((reject, reject) -> reject(5))' 'new Promise(({}, reject) -> reject(5))' 'new Promise((resolve, reject, somethingElse = reject(5)) =>)' ].map (invalidCase) -> errors = errors: [ message: 'Expected the Promise rejection reason to be an Error.' type: 'CallExpression' ] { ...errors ...( if typeof invalidCase is 'string' code: invalidCase else invalidCase ) }
true
###* # @fileoverview restrict values that can be used as Promise rejection reasons # @author PI:NAME:<NAME>END_PI ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require 'eslint/lib/rules/prefer-promise-reject-errors' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'prefer-promise-reject-errors', rule, valid: [ 'Promise.resolve(5)' 'Foo.reject(5)' 'Promise.reject(foo)' 'Promise.reject(foo.bar)' 'Promise.reject(foo.bar())' 'Promise.reject(new Error())' 'Promise.reject(new TypeError)' "Promise.reject(new Error('foo'))" 'new Foo((resolve, reject) => reject(5))' 'new Promise (resolve, reject) -> (reject) -> reject 5' # ''' # new Promise (resolve, reject) -> # if foo # reject = somethingElse # reject(5) # ''' 'new Promise((resolve, {apply}) -> apply(5))' 'new Promise((resolve, reject) -> resolve(5, reject))' '-> Promise.reject await foo' , code: 'Promise.reject()' options: [allowEmptyReject: yes] , code: 'new Promise((resolve, reject) -> reject())' options: [allowEmptyReject: yes] ] invalid: [ 'Promise.reject(5)' "Promise.reject('foo')" 'Promise.reject(!foo)' 'Promise.reject()' 'Promise.reject(undefined)' 'Promise.reject({ foo: 1 })' 'Promise.reject([1, 2, 3])' , code: 'Promise.reject()' options: [allowEmptyReject: no] , code: 'new Promise((resolve, reject) -> reject())' options: [allowEmptyReject: no] , code: 'Promise.reject(undefined)' options: [allowEmptyReject: yes] , "Promise.reject('foo', somethingElse)" 'new Promise((resolve, reject) => reject(5))' 'new Promise((resolve, reject) => reject())' 'new Promise (y, n) -> n(5)' ''' new Promise (resolve, reject) => fs.readFile 'foo.txt', (err, file) => if err reject 'File not found' else resolve file ''' 'new Promise(({foo, bar, baz}, reject) => reject(5))' # 'new Promise((reject, reject) -> reject(5))' 'new Promise(({}, reject) -> reject(5))' 'new Promise((resolve, reject, somethingElse = reject(5)) =>)' ].map (invalidCase) -> errors = errors: [ message: 'Expected the Promise rejection reason to be an Error.' type: 'CallExpression' ] { ...errors ...( if typeof invalidCase is 'string' code: invalidCase else invalidCase ) }
[ { "context": "d\n localStorage.setItem \"password\", q.password\n closeWindow win\n #", "end": 6741, "score": 0.8431366086006165, "start": 6731, "tag": "PASSWORD", "value": "q.password" }, { "context": "hangeProfile\", {\n ...
client/code/app/util.coffee
mm018347/jinrou
3
app=require '/app' util=require '/util' exports.showWindow=showWindow=(templatename,tmpl)-> de = document.documentElement bd = document.body sclf = bd.scrollLeft || de.scrollLeft sctp = bd.scrollTop || de.scrollTop x=Math.max 50,sclf+Math.floor(Math.random()*100-200+document.documentElement.clientWidth/2) y=Math.max 50,sctp+Math.floor(Math.random()*100-200+document.documentElement.clientHeight/2) # iconはspecialにhandleする unless tmpl? tmpl = {} tmpl.title ?= "" tmpl.icon = makeIconHTML tmpl.icon win=$(JT["#{templatename}"](tmpl)).hide().css({left:"#{x}px",top:"#{y}px",}).appendTo("body").fadeIn().draggable() $(".getfocus",win.get(0)).focus() win makeIconHTML = (icon)-> unless icon? return '' if 'string' == typeof icon return FontAwesome.icon({iconName: icon}).html if icon instanceof Array result = "<span class='fa-stack'>" for name in icon result += FontAwesome.icon({iconName: name}).html result += "</span>" return result return '' #編集域を返す exports.blankWindow=(options, onclose)-> win=showWindow "util-blank", options div=document.createElement "div" div.classList.add "window-content" $("form[name='okform']",win).before div win.submit (je)-> je.preventDefault() win.click (je)-> t=je.target while t? if t.name=="ok" closeWindow t onclose?() break t = t.parentNode $(div) #要素を含むWindowを消す exports.closeWindow=closeWindow= (node)-> w=$(node).closest(".window") w.hide "normal",-> w.remove() w.triggerHandler "close.window" exports.formQuery=(form)-> q={} el=form.elements for e in el if !e.disabled && e.name if (tag=e.tagName.toLowerCase())=="input" if e.type in ["radio","checkbox"] if e.checked q[e.name]=e.value else if e.type!="submit" && e.type!="reset" && e.type!="button" q[e.name]=e.value else if tag in["select","output","textarea"] q[e.name]=e.value q #true,false exports.ask=(title,message,cb)-> win = showWindow "util-ask",{title:title,message:message} win.submit (je)-> je.preventDefault() win.click (je)-> t=je.target while t? if t.name=="yes" cb true closeWindow t break else if t.name=="no" cb false closeWindow t break t = t.parentNode #String / null exports.prompt=(title,message,opt,cb)-> win = showWindow "util-prompt",{title:title,message:message} inp=win.find("input.prompt").get(0) for opv of opt inp[opv]=opt[opv] win.submit (je)-> je.preventDefault() win.click (je)-> t=je.target while t? if t.name=="ok" cb? inp.value closeWindow t break else if t.name=="cancel" cb? null closeWindow t break t = t.parentNode #arr: [{name:"aaa",value:"foo"}, ...] exports.selectprompt=(options,cb)-> { title, message, options: arr, icon, } = options win = showWindow "util-selectprompt",{ title: title message: message icon: icon } sel=win.find("select.prompt").get(0) for obj in arr opt=document.createElement "option" opt.textContent=obj.name opt.value=obj.value sel.add opt win.submit (je)-> je.preventDefault() win.click (je)-> t=je.target while t? if t.name=="ok" cb? sel.value closeWindow t break else if t.name=="cancel" cb? null closeWindow t break t = t.parentNode exports.kickprompt=(options,cb)-> { title, message, options: arr, icon, } = options win = showWindow "util-kick",{ title: title ? "踢出" message: message ? "請選擇欲踢出房間的對象" icon: icon ? 'user-times' } sel=win.find("select.prompt").get(0) for obj in arr opt=document.createElement "option" opt.textContent=obj.name opt.value=obj.value sel.add opt win.submit (je)-> je.preventDefault() win.click (je)-> t=je.target while t? if t.name=="ok" cb? { value: sel.value ban: win.find('input[name="noentry"]').get(0).checked } closeWindow t break else if t.name=="cancel" cb? null closeWindow t break else if t.name=="list" cb? { list: true } closeWindow t break t = t.parentNode exports.message=(title,message,cb)-> win = showWindow "util-wmessage",{title:title,message:message} win.submit (je)-> je.preventDefault() win.click (je)-> t=je.target while t? if t.name=="ok" cb? true closeWindow t break t = t.parentNode exports.loginWindow=(cb=->app.refresh())-> win = showWindow "util-login" win.click (je)-> t=je.target while t? if t.name=="cancel" closeWindow win break t = t.parentNode $("#loginform").submit (je)-> je.preventDefault() form=je.target app.login form.elements["userid"].value, form.elements["password"].value,(result)-> if result if form.elements["remember_me"].checked # 記憶 localStorage.setItem "userid",form.elements["userid"].value localStorage.setItem "password", form.elements["password"].value cb() closeWindow win else $("#loginerror").text "帳號或密碼錯誤。" $("#newentryform").submit (je)-> je.preventDefault() form=je.target q= userid: form.elements["userid"].value password: form.elements["password"].value ss.rpc "user.newentry",q,(result)-> unless result.login $("#newentryerror").text result else localStorage.setItem "userid",q.userid localStorage.setItem "password", q.password closeWindow win # 初期情報を入力してもらう util.blindName {title:"輸入情報",message:"請設定玩家帳號"},(obj)-> # 登録する感じの ss.rpc "user.changeProfile", { password:q.password name:obj.name icon:obj.icon },(obj)-> if obj?.error? #錯誤 util.message "錯誤",obj.error else util.message "註冊","註冊成功。" app.setUserid q.userid cb() exports.iconSelectWindow=(def,cb)-> win = showWindow "util-iconselect" form=$("#iconform").get 0 # 頭像決定 okicon=(url)-> setHTTPSicon $("#selecticondisp").get(0), url def=url # 書き換え okicon def # さいしょ win.click (je)-> t=je.target while t? if t.name=="cancel" closeWindow win cb def # 変わっていない break else if t.name=="urliconbutton" util.prompt "頭像","請輸入頭像圖片的網址",null,(url)-> okicon url ? "" break else if t.name=="twittericonbutton" util.prompt "頭像","請輸入 Twitter 帳號",null,(id)-> if id # It's 1.0! # okicon "http://api.twitter.com/1/users/profile_image/#{id}" ss.rpc "user.getTwitterIcon",id,(url)-> # 頭像を取得 unless url util.message "錯誤","頭像讀取失敗,請稍後再試。" okicon "" else okicon url else okicon "" break t = t.parentNode $("#iconform").submit (je)-> je.preventDefault() closeWindow win cb def #結果通知 exports.blindName=(opt={},cb)-> win = showWindow "util-blindname",{ title:opt.title ? "參與房間" message:opt.message ? "請輸入暱稱" icon: "user-secret" } def=null win.click (je)-> t=je.target while t? if t.name=="cancel" closeWindow win cb null # 変わっていない break else if t.name=="iconselectbutton" util.iconSelectWindow null,(url)-> def=url ? null $("#icondisp").attr "src",def break t = t.parentNode $("#nameform").submit (je)-> je.preventDefault() closeWindow win cb {name:je.target.elements["name"].value, icon:def} # Dateをtime要素に exports.timeFromDate=(date)-> zero2=(num)-> "00#{num}".slice -2 # 0埋め dat="#{date.getFullYear()}-#{zero2(date.getMonth()+1)}-#{zero2(date.getDate())}" tim="#{zero2(date.getHours())}:#{zero2(date.getMinutes())}:#{zero2(date.getSeconds())}" time=document.createElement "time" time.datetime="#{dat}T#{tim}+09:00" time.textContent="#{dat} #{tim}" time # search文字列をdictに exports.searchHash=(search)-> result = {} arr = search.slice(1).split '&' for chunk in arr continue unless chunk [key, value] = chunk.split '=' result[decodeURIComponent key] = decodeURIComponent(value ? 'on') return result exports.hashSearch=(hash)-> arr = [] for key, value of hash arr.push "#{encodeURIComponent key}=#{encodeURIComponent value}" if arr.length == 0 return '' else return "?#{arr.join '&'}" # HTTPS優先iconを表示 exports.setHTTPSicon = setHTTPSicon = (img, url, cacheObject)-> if cacheObject?[url]? # If this url is already cached, use it. img.src = cacheObject?[url] return original_url = url # HTTPSに直す if /^http:/.test url url = "https:" + url.slice 5 # HTTPSが錯誤だったらHTTPになる handler1 = (ev)-> img.removeEventListener "error", handler1, false img.removeEventListener "load", handler2, false cacheObject?[original_url] = original_url img.src = original_url handler2 = ()-> img.removeEventListener "error", handler1, false img.removeEventListener "load", handler2, false cacheObject?[original_url] = url img.addEventListener "error", handler1, false img.addEventListener "load", handler2, false # URLをset img.src = url # Font Awesomeアイコンを一時的にloadingに変える exports.LoadingIcon = class LoadingIcon constructor:(@icon)-> # spinnerアイコンを作成 @newicon = FontAwesome.icon({iconName: 'spinner'}, { classes: ['fa-fw', 'fa-pulse', 'fa-spinner'] }).node[0] start:()-> # 一時的に古いアイコンを隠す @icon.parentNode.replaceChild @newicon, @icon stop:()-> # 戻す @newicon.parentNode.replaceChild @icon, @newicon #猝死懲罰 exports.punish=(title,message,cb)-> win = showWindow "util-punish",{title:title,time:message.time} for user in message.userlist a = document.createElement "input" a.type="checkbox" a.name="userList" a.class="punish" a.value=user.userid b = document.createElement "label" $(b).append(a).append(user.name) $("#prePunishUser").append(b).append("<br>") ipt =-> user=document.punish.userList userChecked=[] if !user[0] a=[] a.push user user=a for pl in user if pl.checked then userChecked.push pl.value userChecked win.submit (je)-> je.preventDefault() win.click (je)-> t=je.target if t.name=="ok" cb? ipt() closeWindow t else if t.name=="cancel" # cb? null closeWindow t
33314
app=require '/app' util=require '/util' exports.showWindow=showWindow=(templatename,tmpl)-> de = document.documentElement bd = document.body sclf = bd.scrollLeft || de.scrollLeft sctp = bd.scrollTop || de.scrollTop x=Math.max 50,sclf+Math.floor(Math.random()*100-200+document.documentElement.clientWidth/2) y=Math.max 50,sctp+Math.floor(Math.random()*100-200+document.documentElement.clientHeight/2) # iconはspecialにhandleする unless tmpl? tmpl = {} tmpl.title ?= "" tmpl.icon = makeIconHTML tmpl.icon win=$(JT["#{templatename}"](tmpl)).hide().css({left:"#{x}px",top:"#{y}px",}).appendTo("body").fadeIn().draggable() $(".getfocus",win.get(0)).focus() win makeIconHTML = (icon)-> unless icon? return '' if 'string' == typeof icon return FontAwesome.icon({iconName: icon}).html if icon instanceof Array result = "<span class='fa-stack'>" for name in icon result += FontAwesome.icon({iconName: name}).html result += "</span>" return result return '' #編集域を返す exports.blankWindow=(options, onclose)-> win=showWindow "util-blank", options div=document.createElement "div" div.classList.add "window-content" $("form[name='okform']",win).before div win.submit (je)-> je.preventDefault() win.click (je)-> t=je.target while t? if t.name=="ok" closeWindow t onclose?() break t = t.parentNode $(div) #要素を含むWindowを消す exports.closeWindow=closeWindow= (node)-> w=$(node).closest(".window") w.hide "normal",-> w.remove() w.triggerHandler "close.window" exports.formQuery=(form)-> q={} el=form.elements for e in el if !e.disabled && e.name if (tag=e.tagName.toLowerCase())=="input" if e.type in ["radio","checkbox"] if e.checked q[e.name]=e.value else if e.type!="submit" && e.type!="reset" && e.type!="button" q[e.name]=e.value else if tag in["select","output","textarea"] q[e.name]=e.value q #true,false exports.ask=(title,message,cb)-> win = showWindow "util-ask",{title:title,message:message} win.submit (je)-> je.preventDefault() win.click (je)-> t=je.target while t? if t.name=="yes" cb true closeWindow t break else if t.name=="no" cb false closeWindow t break t = t.parentNode #String / null exports.prompt=(title,message,opt,cb)-> win = showWindow "util-prompt",{title:title,message:message} inp=win.find("input.prompt").get(0) for opv of opt inp[opv]=opt[opv] win.submit (je)-> je.preventDefault() win.click (je)-> t=je.target while t? if t.name=="ok" cb? inp.value closeWindow t break else if t.name=="cancel" cb? null closeWindow t break t = t.parentNode #arr: [{name:"aaa",value:"foo"}, ...] exports.selectprompt=(options,cb)-> { title, message, options: arr, icon, } = options win = showWindow "util-selectprompt",{ title: title message: message icon: icon } sel=win.find("select.prompt").get(0) for obj in arr opt=document.createElement "option" opt.textContent=obj.name opt.value=obj.value sel.add opt win.submit (je)-> je.preventDefault() win.click (je)-> t=je.target while t? if t.name=="ok" cb? sel.value closeWindow t break else if t.name=="cancel" cb? null closeWindow t break t = t.parentNode exports.kickprompt=(options,cb)-> { title, message, options: arr, icon, } = options win = showWindow "util-kick",{ title: title ? "踢出" message: message ? "請選擇欲踢出房間的對象" icon: icon ? 'user-times' } sel=win.find("select.prompt").get(0) for obj in arr opt=document.createElement "option" opt.textContent=obj.name opt.value=obj.value sel.add opt win.submit (je)-> je.preventDefault() win.click (je)-> t=je.target while t? if t.name=="ok" cb? { value: sel.value ban: win.find('input[name="noentry"]').get(0).checked } closeWindow t break else if t.name=="cancel" cb? null closeWindow t break else if t.name=="list" cb? { list: true } closeWindow t break t = t.parentNode exports.message=(title,message,cb)-> win = showWindow "util-wmessage",{title:title,message:message} win.submit (je)-> je.preventDefault() win.click (je)-> t=je.target while t? if t.name=="ok" cb? true closeWindow t break t = t.parentNode exports.loginWindow=(cb=->app.refresh())-> win = showWindow "util-login" win.click (je)-> t=je.target while t? if t.name=="cancel" closeWindow win break t = t.parentNode $("#loginform").submit (je)-> je.preventDefault() form=je.target app.login form.elements["userid"].value, form.elements["password"].value,(result)-> if result if form.elements["remember_me"].checked # 記憶 localStorage.setItem "userid",form.elements["userid"].value localStorage.setItem "password", form.elements["password"].value cb() closeWindow win else $("#loginerror").text "帳號或密碼錯誤。" $("#newentryform").submit (je)-> je.preventDefault() form=je.target q= userid: form.elements["userid"].value password: form.elements["password"].value ss.rpc "user.newentry",q,(result)-> unless result.login $("#newentryerror").text result else localStorage.setItem "userid",q.userid localStorage.setItem "password", <PASSWORD> closeWindow win # 初期情報を入力してもらう util.blindName {title:"輸入情報",message:"請設定玩家帳號"},(obj)-> # 登録する感じの ss.rpc "user.changeProfile", { password:<PASSWORD> name:obj.name icon:obj.icon },(obj)-> if obj?.error? #錯誤 util.message "錯誤",obj.error else util.message "註冊","註冊成功。" app.setUserid q.userid cb() exports.iconSelectWindow=(def,cb)-> win = showWindow "util-iconselect" form=$("#iconform").get 0 # 頭像決定 okicon=(url)-> setHTTPSicon $("#selecticondisp").get(0), url def=url # 書き換え okicon def # さいしょ win.click (je)-> t=je.target while t? if t.name=="cancel" closeWindow win cb def # 変わっていない break else if t.name=="urliconbutton" util.prompt "頭像","請輸入頭像圖片的網址",null,(url)-> okicon url ? "" break else if t.name=="twittericonbutton" util.prompt "頭像","請輸入 Twitter 帳號",null,(id)-> if id # It's 1.0! # okicon "http://api.twitter.com/1/users/profile_image/#{id}" ss.rpc "user.getTwitterIcon",id,(url)-> # 頭像を取得 unless url util.message "錯誤","頭像讀取失敗,請稍後再試。" okicon "" else okicon url else okicon "" break t = t.parentNode $("#iconform").submit (je)-> je.preventDefault() closeWindow win cb def #結果通知 exports.blindName=(opt={},cb)-> win = showWindow "util-blindname",{ title:opt.title ? "參與房間" message:opt.message ? "請輸入暱稱" icon: "user-secret" } def=null win.click (je)-> t=je.target while t? if t.name=="cancel" closeWindow win cb null # 変わっていない break else if t.name=="iconselectbutton" util.iconSelectWindow null,(url)-> def=url ? null $("#icondisp").attr "src",def break t = t.parentNode $("#nameform").submit (je)-> je.preventDefault() closeWindow win cb {name:je.target.elements["name"].value, icon:def} # Dateをtime要素に exports.timeFromDate=(date)-> zero2=(num)-> "00#{num}".slice -2 # 0埋め dat="#{date.getFullYear()}-#{zero2(date.getMonth()+1)}-#{zero2(date.getDate())}" tim="#{zero2(date.getHours())}:#{zero2(date.getMinutes())}:#{zero2(date.getSeconds())}" time=document.createElement "time" time.datetime="#{dat}T#{tim}+09:00" time.textContent="#{dat} #{tim}" time # search文字列をdictに exports.searchHash=(search)-> result = {} arr = search.slice(1).split '&' for chunk in arr continue unless chunk [key, value] = chunk.split '=' result[decodeURIComponent key] = decodeURIComponent(value ? 'on') return result exports.hashSearch=(hash)-> arr = [] for key, value of hash arr.push "#{encodeURIComponent key}=#{encodeURIComponent value}" if arr.length == 0 return '' else return "?#{arr.join '&'}" # HTTPS優先iconを表示 exports.setHTTPSicon = setHTTPSicon = (img, url, cacheObject)-> if cacheObject?[url]? # If this url is already cached, use it. img.src = cacheObject?[url] return original_url = url # HTTPSに直す if /^http:/.test url url = "https:" + url.slice 5 # HTTPSが錯誤だったらHTTPになる handler1 = (ev)-> img.removeEventListener "error", handler1, false img.removeEventListener "load", handler2, false cacheObject?[original_url] = original_url img.src = original_url handler2 = ()-> img.removeEventListener "error", handler1, false img.removeEventListener "load", handler2, false cacheObject?[original_url] = url img.addEventListener "error", handler1, false img.addEventListener "load", handler2, false # URLをset img.src = url # Font Awesomeアイコンを一時的にloadingに変える exports.LoadingIcon = class LoadingIcon constructor:(@icon)-> # spinnerアイコンを作成 @newicon = FontAwesome.icon({iconName: 'spinner'}, { classes: ['fa-fw', 'fa-pulse', 'fa-spinner'] }).node[0] start:()-> # 一時的に古いアイコンを隠す @icon.parentNode.replaceChild @newicon, @icon stop:()-> # 戻す @newicon.parentNode.replaceChild @icon, @newicon #猝死懲罰 exports.punish=(title,message,cb)-> win = showWindow "util-punish",{title:title,time:message.time} for user in message.userlist a = document.createElement "input" a.type="checkbox" a.name="userList" a.class="punish" a.value=user.userid b = document.createElement "label" $(b).append(a).append(user.name) $("#prePunishUser").append(b).append("<br>") ipt =-> user=document.punish.userList userChecked=[] if !user[0] a=[] a.push user user=a for pl in user if pl.checked then userChecked.push pl.value userChecked win.submit (je)-> je.preventDefault() win.click (je)-> t=je.target if t.name=="ok" cb? ipt() closeWindow t else if t.name=="cancel" # cb? null closeWindow t
true
app=require '/app' util=require '/util' exports.showWindow=showWindow=(templatename,tmpl)-> de = document.documentElement bd = document.body sclf = bd.scrollLeft || de.scrollLeft sctp = bd.scrollTop || de.scrollTop x=Math.max 50,sclf+Math.floor(Math.random()*100-200+document.documentElement.clientWidth/2) y=Math.max 50,sctp+Math.floor(Math.random()*100-200+document.documentElement.clientHeight/2) # iconはspecialにhandleする unless tmpl? tmpl = {} tmpl.title ?= "" tmpl.icon = makeIconHTML tmpl.icon win=$(JT["#{templatename}"](tmpl)).hide().css({left:"#{x}px",top:"#{y}px",}).appendTo("body").fadeIn().draggable() $(".getfocus",win.get(0)).focus() win makeIconHTML = (icon)-> unless icon? return '' if 'string' == typeof icon return FontAwesome.icon({iconName: icon}).html if icon instanceof Array result = "<span class='fa-stack'>" for name in icon result += FontAwesome.icon({iconName: name}).html result += "</span>" return result return '' #編集域を返す exports.blankWindow=(options, onclose)-> win=showWindow "util-blank", options div=document.createElement "div" div.classList.add "window-content" $("form[name='okform']",win).before div win.submit (je)-> je.preventDefault() win.click (je)-> t=je.target while t? if t.name=="ok" closeWindow t onclose?() break t = t.parentNode $(div) #要素を含むWindowを消す exports.closeWindow=closeWindow= (node)-> w=$(node).closest(".window") w.hide "normal",-> w.remove() w.triggerHandler "close.window" exports.formQuery=(form)-> q={} el=form.elements for e in el if !e.disabled && e.name if (tag=e.tagName.toLowerCase())=="input" if e.type in ["radio","checkbox"] if e.checked q[e.name]=e.value else if e.type!="submit" && e.type!="reset" && e.type!="button" q[e.name]=e.value else if tag in["select","output","textarea"] q[e.name]=e.value q #true,false exports.ask=(title,message,cb)-> win = showWindow "util-ask",{title:title,message:message} win.submit (je)-> je.preventDefault() win.click (je)-> t=je.target while t? if t.name=="yes" cb true closeWindow t break else if t.name=="no" cb false closeWindow t break t = t.parentNode #String / null exports.prompt=(title,message,opt,cb)-> win = showWindow "util-prompt",{title:title,message:message} inp=win.find("input.prompt").get(0) for opv of opt inp[opv]=opt[opv] win.submit (je)-> je.preventDefault() win.click (je)-> t=je.target while t? if t.name=="ok" cb? inp.value closeWindow t break else if t.name=="cancel" cb? null closeWindow t break t = t.parentNode #arr: [{name:"aaa",value:"foo"}, ...] exports.selectprompt=(options,cb)-> { title, message, options: arr, icon, } = options win = showWindow "util-selectprompt",{ title: title message: message icon: icon } sel=win.find("select.prompt").get(0) for obj in arr opt=document.createElement "option" opt.textContent=obj.name opt.value=obj.value sel.add opt win.submit (je)-> je.preventDefault() win.click (je)-> t=je.target while t? if t.name=="ok" cb? sel.value closeWindow t break else if t.name=="cancel" cb? null closeWindow t break t = t.parentNode exports.kickprompt=(options,cb)-> { title, message, options: arr, icon, } = options win = showWindow "util-kick",{ title: title ? "踢出" message: message ? "請選擇欲踢出房間的對象" icon: icon ? 'user-times' } sel=win.find("select.prompt").get(0) for obj in arr opt=document.createElement "option" opt.textContent=obj.name opt.value=obj.value sel.add opt win.submit (je)-> je.preventDefault() win.click (je)-> t=je.target while t? if t.name=="ok" cb? { value: sel.value ban: win.find('input[name="noentry"]').get(0).checked } closeWindow t break else if t.name=="cancel" cb? null closeWindow t break else if t.name=="list" cb? { list: true } closeWindow t break t = t.parentNode exports.message=(title,message,cb)-> win = showWindow "util-wmessage",{title:title,message:message} win.submit (je)-> je.preventDefault() win.click (je)-> t=je.target while t? if t.name=="ok" cb? true closeWindow t break t = t.parentNode exports.loginWindow=(cb=->app.refresh())-> win = showWindow "util-login" win.click (je)-> t=je.target while t? if t.name=="cancel" closeWindow win break t = t.parentNode $("#loginform").submit (je)-> je.preventDefault() form=je.target app.login form.elements["userid"].value, form.elements["password"].value,(result)-> if result if form.elements["remember_me"].checked # 記憶 localStorage.setItem "userid",form.elements["userid"].value localStorage.setItem "password", form.elements["password"].value cb() closeWindow win else $("#loginerror").text "帳號或密碼錯誤。" $("#newentryform").submit (je)-> je.preventDefault() form=je.target q= userid: form.elements["userid"].value password: form.elements["password"].value ss.rpc "user.newentry",q,(result)-> unless result.login $("#newentryerror").text result else localStorage.setItem "userid",q.userid localStorage.setItem "password", PI:PASSWORD:<PASSWORD>END_PI closeWindow win # 初期情報を入力してもらう util.blindName {title:"輸入情報",message:"請設定玩家帳號"},(obj)-> # 登録する感じの ss.rpc "user.changeProfile", { password:PI:PASSWORD:<PASSWORD>END_PI name:obj.name icon:obj.icon },(obj)-> if obj?.error? #錯誤 util.message "錯誤",obj.error else util.message "註冊","註冊成功。" app.setUserid q.userid cb() exports.iconSelectWindow=(def,cb)-> win = showWindow "util-iconselect" form=$("#iconform").get 0 # 頭像決定 okicon=(url)-> setHTTPSicon $("#selecticondisp").get(0), url def=url # 書き換え okicon def # さいしょ win.click (je)-> t=je.target while t? if t.name=="cancel" closeWindow win cb def # 変わっていない break else if t.name=="urliconbutton" util.prompt "頭像","請輸入頭像圖片的網址",null,(url)-> okicon url ? "" break else if t.name=="twittericonbutton" util.prompt "頭像","請輸入 Twitter 帳號",null,(id)-> if id # It's 1.0! # okicon "http://api.twitter.com/1/users/profile_image/#{id}" ss.rpc "user.getTwitterIcon",id,(url)-> # 頭像を取得 unless url util.message "錯誤","頭像讀取失敗,請稍後再試。" okicon "" else okicon url else okicon "" break t = t.parentNode $("#iconform").submit (je)-> je.preventDefault() closeWindow win cb def #結果通知 exports.blindName=(opt={},cb)-> win = showWindow "util-blindname",{ title:opt.title ? "參與房間" message:opt.message ? "請輸入暱稱" icon: "user-secret" } def=null win.click (je)-> t=je.target while t? if t.name=="cancel" closeWindow win cb null # 変わっていない break else if t.name=="iconselectbutton" util.iconSelectWindow null,(url)-> def=url ? null $("#icondisp").attr "src",def break t = t.parentNode $("#nameform").submit (je)-> je.preventDefault() closeWindow win cb {name:je.target.elements["name"].value, icon:def} # Dateをtime要素に exports.timeFromDate=(date)-> zero2=(num)-> "00#{num}".slice -2 # 0埋め dat="#{date.getFullYear()}-#{zero2(date.getMonth()+1)}-#{zero2(date.getDate())}" tim="#{zero2(date.getHours())}:#{zero2(date.getMinutes())}:#{zero2(date.getSeconds())}" time=document.createElement "time" time.datetime="#{dat}T#{tim}+09:00" time.textContent="#{dat} #{tim}" time # search文字列をdictに exports.searchHash=(search)-> result = {} arr = search.slice(1).split '&' for chunk in arr continue unless chunk [key, value] = chunk.split '=' result[decodeURIComponent key] = decodeURIComponent(value ? 'on') return result exports.hashSearch=(hash)-> arr = [] for key, value of hash arr.push "#{encodeURIComponent key}=#{encodeURIComponent value}" if arr.length == 0 return '' else return "?#{arr.join '&'}" # HTTPS優先iconを表示 exports.setHTTPSicon = setHTTPSicon = (img, url, cacheObject)-> if cacheObject?[url]? # If this url is already cached, use it. img.src = cacheObject?[url] return original_url = url # HTTPSに直す if /^http:/.test url url = "https:" + url.slice 5 # HTTPSが錯誤だったらHTTPになる handler1 = (ev)-> img.removeEventListener "error", handler1, false img.removeEventListener "load", handler2, false cacheObject?[original_url] = original_url img.src = original_url handler2 = ()-> img.removeEventListener "error", handler1, false img.removeEventListener "load", handler2, false cacheObject?[original_url] = url img.addEventListener "error", handler1, false img.addEventListener "load", handler2, false # URLをset img.src = url # Font Awesomeアイコンを一時的にloadingに変える exports.LoadingIcon = class LoadingIcon constructor:(@icon)-> # spinnerアイコンを作成 @newicon = FontAwesome.icon({iconName: 'spinner'}, { classes: ['fa-fw', 'fa-pulse', 'fa-spinner'] }).node[0] start:()-> # 一時的に古いアイコンを隠す @icon.parentNode.replaceChild @newicon, @icon stop:()-> # 戻す @newicon.parentNode.replaceChild @icon, @newicon #猝死懲罰 exports.punish=(title,message,cb)-> win = showWindow "util-punish",{title:title,time:message.time} for user in message.userlist a = document.createElement "input" a.type="checkbox" a.name="userList" a.class="punish" a.value=user.userid b = document.createElement "label" $(b).append(a).append(user.name) $("#prePunishUser").append(b).append("<br>") ipt =-> user=document.punish.userList userChecked=[] if !user[0] a=[] a.push user user=a for pl in user if pl.checked then userChecked.push pl.value userChecked win.submit (je)-> je.preventDefault() win.click (je)-> t=je.target if t.name=="ok" cb? ipt() closeWindow t else if t.name=="cancel" # cb? null closeWindow t
[ { "context": "ar.google.com/events'\n query = {\n key: 'AIzaSyDrsxDDJrf8liR4IKfkOfCPFCByMMq3OJY',\n timeMin: moment().format('YYYY-MM-DD') ", "end": 3158, "score": 0.9997401237487793, "start": 3119, "tag": "KEY", "value": "AIzaSyDrsxDDJrf8liR4IKfkOfCPFCByMMq3OJY" } ]
scripts/cron.coffee
ikd9684/ReminderBot4Slack
0
# Description: # 決められた日時になったら実施する処理 # Log = require('log') @logger = new Log process.env.HUBOT_LOG_LEVEL or 'info' request = require('request') cronJob = require('cron').CronJob moment = require('moment') moment.locale('ja') YMD = 'YYYYMMDD' roomName = 'test' # module.exports = (robot) -> # cronjob = new cronJob( # cronTime: '0 0 * * * *' # 毎時00分00秒(秒 分 時 日 月 週) # start: true # すぐにcronのjobを実行するか # timeZone: 'Asia/Tokyo' # タイムゾーン指定 # onTick: -> # 時間が来た時に実行する処理 # message = moment().format('YYYY年M月D日 H時になりました。') # robot.send {room: 'test'}, message # ) module.exports = (robot) -> # cronjobTest = new cronJob( # cronTime: '* * * * * *' # 毎日07:00:00に以下の処理を実施(秒 分 時 日 月 週) # start: true # すぐにcronのjobを実行するか # timeZone: 'Asia/Tokyo' # タイムゾーン指定 # onTick: -> # 時間が来た時に実行する処理 # today = moment().format('YYYY-MM-DD HH:mm:ss') # robot.logger.debug 'cron test: ' + today # ) cronjobA = new cronJob( cronTime: '00 00 07 * * *' # 毎日07:00:00に以下の処理を実施(秒 分 時 日 月 週) start: true # すぐにcronのjobを実行するか timeZone: 'Asia/Tokyo' # タイムゾーン指定 onTick: -> # 時間が来た時に実行する処理 robot.logger.debug 'cron07' getNextEvent( (result) -> today = moment().format(YMD) next = moment(result).format(YMD) robot.logger.debug 'cron07: today=' + today + ' ? next=' + next if today is next # 今日がBandroid開催日ならメッセージを出力 md = moment(result).format('M月D日(ddd)') hm = moment(result).format('HH:mm') message = '今日 ' + md + ' は Bandroid の開催日です!\n開始予定時刻は ' + hm + ' です。' robot.send {room: roomName}, message ) ) cronjobB = new cronJob( cronTime: '00 00 18 * * *' # 毎日18:00:00に以下の処理を実施(秒 分 時 日 月 週) start: true # すぐにcronのjobを実行するか timeZone: 'Asia/Tokyo' # タイムゾーン指定 onTick: -> # 時間が来た時に実行する処理 robot.logger.debug 'cron18' getNextEvent( (result) -> today = moment().format(YMD) beforeNext = moment(result).add(-1, 'days').format(YMD) next = moment(result).format(YMD) robot.logger.debug 'cron18: today=' + today + ' ? beforeNext=' + beforeNext if today is beforeNext # 明日がBandroid開催日ならメッセージを出力 md = moment(result).format('M月D日(ddd)') hm = moment(result).format('HH:mm') message = '明日 ' + md + ' は Bandroid の開催日です!\n開始予定時刻は ' + hm + ' です。' robot.send {room: roomName}, message ) ) getNextEvent = (func) -> uri = 'https://www.googleapis.com/calendar/v3/calendars/excite-software.net_uvouli16riv9sq2s89liof0n4s@group.calendar.google.com/events' query = { key: 'AIzaSyDrsxDDJrf8liR4IKfkOfCPFCByMMq3OJY', timeMin: moment().format('YYYY-MM-DD') + 'T18:00:00.000Z', maxResult: 1, orderBy: 'startTime', singleEvents: true, } request( { url: uri, qs: query }, (err, res, body) -> if err console.log err else json = JSON.parse body if 0 < Object.keys(json).length func(json['items'][0]['start']['dateTime']) )
81929
# Description: # 決められた日時になったら実施する処理 # Log = require('log') @logger = new Log process.env.HUBOT_LOG_LEVEL or 'info' request = require('request') cronJob = require('cron').CronJob moment = require('moment') moment.locale('ja') YMD = 'YYYYMMDD' roomName = 'test' # module.exports = (robot) -> # cronjob = new cronJob( # cronTime: '0 0 * * * *' # 毎時00分00秒(秒 分 時 日 月 週) # start: true # すぐにcronのjobを実行するか # timeZone: 'Asia/Tokyo' # タイムゾーン指定 # onTick: -> # 時間が来た時に実行する処理 # message = moment().format('YYYY年M月D日 H時になりました。') # robot.send {room: 'test'}, message # ) module.exports = (robot) -> # cronjobTest = new cronJob( # cronTime: '* * * * * *' # 毎日07:00:00に以下の処理を実施(秒 分 時 日 月 週) # start: true # すぐにcronのjobを実行するか # timeZone: 'Asia/Tokyo' # タイムゾーン指定 # onTick: -> # 時間が来た時に実行する処理 # today = moment().format('YYYY-MM-DD HH:mm:ss') # robot.logger.debug 'cron test: ' + today # ) cronjobA = new cronJob( cronTime: '00 00 07 * * *' # 毎日07:00:00に以下の処理を実施(秒 分 時 日 月 週) start: true # すぐにcronのjobを実行するか timeZone: 'Asia/Tokyo' # タイムゾーン指定 onTick: -> # 時間が来た時に実行する処理 robot.logger.debug 'cron07' getNextEvent( (result) -> today = moment().format(YMD) next = moment(result).format(YMD) robot.logger.debug 'cron07: today=' + today + ' ? next=' + next if today is next # 今日がBandroid開催日ならメッセージを出力 md = moment(result).format('M月D日(ddd)') hm = moment(result).format('HH:mm') message = '今日 ' + md + ' は Bandroid の開催日です!\n開始予定時刻は ' + hm + ' です。' robot.send {room: roomName}, message ) ) cronjobB = new cronJob( cronTime: '00 00 18 * * *' # 毎日18:00:00に以下の処理を実施(秒 分 時 日 月 週) start: true # すぐにcronのjobを実行するか timeZone: 'Asia/Tokyo' # タイムゾーン指定 onTick: -> # 時間が来た時に実行する処理 robot.logger.debug 'cron18' getNextEvent( (result) -> today = moment().format(YMD) beforeNext = moment(result).add(-1, 'days').format(YMD) next = moment(result).format(YMD) robot.logger.debug 'cron18: today=' + today + ' ? beforeNext=' + beforeNext if today is beforeNext # 明日がBandroid開催日ならメッセージを出力 md = moment(result).format('M月D日(ddd)') hm = moment(result).format('HH:mm') message = '明日 ' + md + ' は Bandroid の開催日です!\n開始予定時刻は ' + hm + ' です。' robot.send {room: roomName}, message ) ) getNextEvent = (func) -> uri = 'https://www.googleapis.com/calendar/v3/calendars/excite-software.net_uvouli16riv9sq2s89liof0n4s@group.calendar.google.com/events' query = { key: '<KEY>', timeMin: moment().format('YYYY-MM-DD') + 'T18:00:00.000Z', maxResult: 1, orderBy: 'startTime', singleEvents: true, } request( { url: uri, qs: query }, (err, res, body) -> if err console.log err else json = JSON.parse body if 0 < Object.keys(json).length func(json['items'][0]['start']['dateTime']) )
true
# Description: # 決められた日時になったら実施する処理 # Log = require('log') @logger = new Log process.env.HUBOT_LOG_LEVEL or 'info' request = require('request') cronJob = require('cron').CronJob moment = require('moment') moment.locale('ja') YMD = 'YYYYMMDD' roomName = 'test' # module.exports = (robot) -> # cronjob = new cronJob( # cronTime: '0 0 * * * *' # 毎時00分00秒(秒 分 時 日 月 週) # start: true # すぐにcronのjobを実行するか # timeZone: 'Asia/Tokyo' # タイムゾーン指定 # onTick: -> # 時間が来た時に実行する処理 # message = moment().format('YYYY年M月D日 H時になりました。') # robot.send {room: 'test'}, message # ) module.exports = (robot) -> # cronjobTest = new cronJob( # cronTime: '* * * * * *' # 毎日07:00:00に以下の処理を実施(秒 分 時 日 月 週) # start: true # すぐにcronのjobを実行するか # timeZone: 'Asia/Tokyo' # タイムゾーン指定 # onTick: -> # 時間が来た時に実行する処理 # today = moment().format('YYYY-MM-DD HH:mm:ss') # robot.logger.debug 'cron test: ' + today # ) cronjobA = new cronJob( cronTime: '00 00 07 * * *' # 毎日07:00:00に以下の処理を実施(秒 分 時 日 月 週) start: true # すぐにcronのjobを実行するか timeZone: 'Asia/Tokyo' # タイムゾーン指定 onTick: -> # 時間が来た時に実行する処理 robot.logger.debug 'cron07' getNextEvent( (result) -> today = moment().format(YMD) next = moment(result).format(YMD) robot.logger.debug 'cron07: today=' + today + ' ? next=' + next if today is next # 今日がBandroid開催日ならメッセージを出力 md = moment(result).format('M月D日(ddd)') hm = moment(result).format('HH:mm') message = '今日 ' + md + ' は Bandroid の開催日です!\n開始予定時刻は ' + hm + ' です。' robot.send {room: roomName}, message ) ) cronjobB = new cronJob( cronTime: '00 00 18 * * *' # 毎日18:00:00に以下の処理を実施(秒 分 時 日 月 週) start: true # すぐにcronのjobを実行するか timeZone: 'Asia/Tokyo' # タイムゾーン指定 onTick: -> # 時間が来た時に実行する処理 robot.logger.debug 'cron18' getNextEvent( (result) -> today = moment().format(YMD) beforeNext = moment(result).add(-1, 'days').format(YMD) next = moment(result).format(YMD) robot.logger.debug 'cron18: today=' + today + ' ? beforeNext=' + beforeNext if today is beforeNext # 明日がBandroid開催日ならメッセージを出力 md = moment(result).format('M月D日(ddd)') hm = moment(result).format('HH:mm') message = '明日 ' + md + ' は Bandroid の開催日です!\n開始予定時刻は ' + hm + ' です。' robot.send {room: roomName}, message ) ) getNextEvent = (func) -> uri = 'https://www.googleapis.com/calendar/v3/calendars/excite-software.net_uvouli16riv9sq2s89liof0n4s@group.calendar.google.com/events' query = { key: 'PI:KEY:<KEY>END_PI', timeMin: moment().format('YYYY-MM-DD') + 'T18:00:00.000Z', maxResult: 1, orderBy: 'startTime', singleEvents: true, } request( { url: uri, qs: query }, (err, res, body) -> if err console.log err else json = JSON.parse body if 0 < Object.keys(json).length func(json['items'][0]['start']['dateTime']) )
[ { "context": "k = require('../stack')\n\ns = new Stack()\n\ns.push(\"David\")\ns.push(\"Raymond\")\ns.push(\"Bryan\")\nconsole.log \"", "end": 59, "score": 0.9998680353164673, "start": 54, "tag": "NAME", "value": "David" }, { "context": "stack')\n\ns = new Stack()\n\ns.push(\"David\"...
stack/test/test-method.coffee
youqingkui/DataStructure
0
Stack = require('../stack') s = new Stack() s.push("David") s.push("Raymond") s.push("Bryan") console.log "s =>", s console.log "s.length()", s.length() console.log "s.peek()", s.peek() console.log "s.pop()", s.pop() console.log "s ==>", s
195590
Stack = require('../stack') s = new Stack() s.push("<NAME>") s.push("<NAME>") s.push("<NAME>") console.log "s =>", s console.log "s.length()", s.length() console.log "s.peek()", s.peek() console.log "s.pop()", s.pop() console.log "s ==>", s
true
Stack = require('../stack') s = new Stack() s.push("PI:NAME:<NAME>END_PI") s.push("PI:NAME:<NAME>END_PI") s.push("PI:NAME:<NAME>END_PI") console.log "s =>", s console.log "s.length()", s.length() console.log "s.peek()", s.peek() console.log "s.pop()", s.pop() console.log "s ==>", s
[ { "context": "TeamSendInvites()\n input = {'firstname':'', 'lastname':'', 'email':'', 'role':'admin' }\n inviteInp", "end": 1563, "score": 0.8142068982124329, "start": 1555, "tag": "NAME", "value": "lastname" } ]
client/home/lib/myteam/components/hometeamsendinvites/test.coffee
ezgikaysi/koding
1
kd = require 'kd' React = require 'kd-react' ReactDOM = require 'react-dom' expect = require 'expect' TeamSendInvites = require './view' TestUtils = require 'react-addons-test-utils' toImmutable = require 'app/util/toImmutable' Encoder = require 'htmlencode' mock = require '../../../../../mocks/mockingjay' immutable = require 'immutable' describe 'HomeTeamSendInvites', -> { createRenderer, renderIntoDocument, findRenderedDOMComponentWithClass, scryRenderedDOMComponentsWithClass } = TestUtils describe '::render', -> it 'should render invite labels', -> teamSendInvites = renderIntoDocument <TeamSendInvites /> inviteLabels = findRenderedDOMComponentWithClass teamSendInvites, 'invite-labels' actualText = 'EmailFirst NameLast NameAdmin' expect(inviteLabels.textContent).toEqual actualText it 'should render correct invite inputs', -> inviteInputs = mock.getTeamSendInvites() inviteInputs = immutable.fromJS inviteInputs teamSendInvites = renderIntoDocument <TeamSendInvites inviteInputs={inviteInputs} onInputChange={kd.noop}/> inputs = scryRenderedDOMComponentsWithClass teamSendInvites, 'kdview invite-inputs' expect(inputs.length).toEqual 3 it 'should render correct invite inputs and admin checks', -> inviteInputs = mock.getTeamSendInvites() input = {'firstname':'', 'lastname':'', 'email':'', 'role':'admin' } inviteInputs[3] = input inviteInputs = immutable.fromJS inviteInputs teamSendInvites = renderIntoDocument <TeamSendInvites inviteInputs={inviteInputs} onInputChange={kd.noop}/> inputs = scryRenderedDOMComponentsWithClass teamSendInvites, 'kdview invite-inputs' expect(inputs.length).toEqual 4 inputs = inputs.filter (input) -> input.innerHTML.indexOf("checked=") > 0 expect(inputs.length).toEqual 2 it 'should render correct buttons', -> teamSendInvites = renderIntoDocument <TeamSendInvites /> buttons = scryRenderedDOMComponentsWithClass teamSendInvites,'custom-link-view HomeAppView--button' buttons = buttons.map (button) -> button.innerText buttons = buttons.sort() actualButtons = ['SEND INVITES', 'UPLOAD CSV'] expect(buttons).toEqual actualButtons
17136
kd = require 'kd' React = require 'kd-react' ReactDOM = require 'react-dom' expect = require 'expect' TeamSendInvites = require './view' TestUtils = require 'react-addons-test-utils' toImmutable = require 'app/util/toImmutable' Encoder = require 'htmlencode' mock = require '../../../../../mocks/mockingjay' immutable = require 'immutable' describe 'HomeTeamSendInvites', -> { createRenderer, renderIntoDocument, findRenderedDOMComponentWithClass, scryRenderedDOMComponentsWithClass } = TestUtils describe '::render', -> it 'should render invite labels', -> teamSendInvites = renderIntoDocument <TeamSendInvites /> inviteLabels = findRenderedDOMComponentWithClass teamSendInvites, 'invite-labels' actualText = 'EmailFirst NameLast NameAdmin' expect(inviteLabels.textContent).toEqual actualText it 'should render correct invite inputs', -> inviteInputs = mock.getTeamSendInvites() inviteInputs = immutable.fromJS inviteInputs teamSendInvites = renderIntoDocument <TeamSendInvites inviteInputs={inviteInputs} onInputChange={kd.noop}/> inputs = scryRenderedDOMComponentsWithClass teamSendInvites, 'kdview invite-inputs' expect(inputs.length).toEqual 3 it 'should render correct invite inputs and admin checks', -> inviteInputs = mock.getTeamSendInvites() input = {'firstname':'', '<NAME>':'', 'email':'', 'role':'admin' } inviteInputs[3] = input inviteInputs = immutable.fromJS inviteInputs teamSendInvites = renderIntoDocument <TeamSendInvites inviteInputs={inviteInputs} onInputChange={kd.noop}/> inputs = scryRenderedDOMComponentsWithClass teamSendInvites, 'kdview invite-inputs' expect(inputs.length).toEqual 4 inputs = inputs.filter (input) -> input.innerHTML.indexOf("checked=") > 0 expect(inputs.length).toEqual 2 it 'should render correct buttons', -> teamSendInvites = renderIntoDocument <TeamSendInvites /> buttons = scryRenderedDOMComponentsWithClass teamSendInvites,'custom-link-view HomeAppView--button' buttons = buttons.map (button) -> button.innerText buttons = buttons.sort() actualButtons = ['SEND INVITES', 'UPLOAD CSV'] expect(buttons).toEqual actualButtons
true
kd = require 'kd' React = require 'kd-react' ReactDOM = require 'react-dom' expect = require 'expect' TeamSendInvites = require './view' TestUtils = require 'react-addons-test-utils' toImmutable = require 'app/util/toImmutable' Encoder = require 'htmlencode' mock = require '../../../../../mocks/mockingjay' immutable = require 'immutable' describe 'HomeTeamSendInvites', -> { createRenderer, renderIntoDocument, findRenderedDOMComponentWithClass, scryRenderedDOMComponentsWithClass } = TestUtils describe '::render', -> it 'should render invite labels', -> teamSendInvites = renderIntoDocument <TeamSendInvites /> inviteLabels = findRenderedDOMComponentWithClass teamSendInvites, 'invite-labels' actualText = 'EmailFirst NameLast NameAdmin' expect(inviteLabels.textContent).toEqual actualText it 'should render correct invite inputs', -> inviteInputs = mock.getTeamSendInvites() inviteInputs = immutable.fromJS inviteInputs teamSendInvites = renderIntoDocument <TeamSendInvites inviteInputs={inviteInputs} onInputChange={kd.noop}/> inputs = scryRenderedDOMComponentsWithClass teamSendInvites, 'kdview invite-inputs' expect(inputs.length).toEqual 3 it 'should render correct invite inputs and admin checks', -> inviteInputs = mock.getTeamSendInvites() input = {'firstname':'', 'PI:NAME:<NAME>END_PI':'', 'email':'', 'role':'admin' } inviteInputs[3] = input inviteInputs = immutable.fromJS inviteInputs teamSendInvites = renderIntoDocument <TeamSendInvites inviteInputs={inviteInputs} onInputChange={kd.noop}/> inputs = scryRenderedDOMComponentsWithClass teamSendInvites, 'kdview invite-inputs' expect(inputs.length).toEqual 4 inputs = inputs.filter (input) -> input.innerHTML.indexOf("checked=") > 0 expect(inputs.length).toEqual 2 it 'should render correct buttons', -> teamSendInvites = renderIntoDocument <TeamSendInvites /> buttons = scryRenderedDOMComponentsWithClass teamSendInvites,'custom-link-view HomeAppView--button' buttons = buttons.map (button) -> button.innerText buttons = buttons.sort() actualButtons = ['SEND INVITES', 'UPLOAD CSV'] expect(buttons).toEqual actualButtons
[ { "context": "###\nCopyright (c) 2013, Alexander Cherniuk <ts33kr@gmail.com>\nAll rights reserved.\n\nRedistri", "end": 42, "score": 0.999842643737793, "start": 24, "tag": "NAME", "value": "Alexander Cherniuk" }, { "context": "###\nCopyright (c) 2013, Alexander Cherniuk <ts33kr@gmail...
library/shipped/caching.coffee
ts33kr/granite
6
### Copyright (c) 2013, Alexander Cherniuk <ts33kr@gmail.com> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ### _ = require "lodash" bower = require "bower" asciify = require "asciify" connect = require "connect" logger = require "winston" events = require "eventemitter2" assert = require "assert" colors = require "colors" crypto = require "crypto" nconf = require "nconf" https = require "https" path = require "path" http = require "http" util = require "util" {Extending} = require "../nucleus/extends" {Composition} = require "../nucleus/compose" {Barebones} = require "../membrane/skeleton" {Archetype} = require "../nucleus/arche" # This toolkit contains a set of routines that help to define the # caching strategies. All of them are simple and definitely not for # the heavy or production usage, but rather for most simple cases. # Generally, you would only apply these strategies when implementing # an API endpoint, within the `ApiService` abstract base class tool. # Please refer to each strategy for more relevant information on it. module.exports.CachingToolkit = class CachingToolkit extends Barebones # This is a marker that indicates to some internal subsystems # that this class has to be considered abstract and therefore # can not be treated as a complete class implementation. This # mainly is used to exclude or account for abstract classes. # Once inherited from, the inheritee is not abstract anymore. @abstract yes # A decorator strategy for wrapping the API endpoint function # with an LRU (least-recently-used) type of cache that normally # uses the `request.path` as its key. This given cache strategy # is highly dependent on the usage of the `response.send` func # in order for the cache to work. Please see `plumbs` module # for more info on that. Also, depends on the spin off engine. # Please see the `lru-cache` package for more relevant info. @memoryCache: (size, time, keys) -> (implement) -> noSize = "no maximum size of cache supplied" noTime = "no TTL timeout for cache var given" noImpl = "no implementation endpoint supplied" noSpin = "not spin-off engine valuess detected" invKey = "the generated cache key is not valid" noReq = "no request in the spinned-off object" noRes = "no response in the spinned-off object" assert _.isFunction lru = require "lru-cache" assert _.isNumber(size or undefined), noSize assert _.isNumber(time or undefined), noTime assert _.isFunction(implement or no), noImpl assert options = try max: size, maxAge: time assert _.isObject caching = try lru options assert keys = (-> @request.path) unless keys assert i = -> _.isString _.first arguments hits = "Hit memory cache of %s at %s".green miss = "Missed memory cache of %s at %s".red return (captured...) -> # decorative wrapper assert @__isolated and @__origin, noSpin assert _.isObject(@request or 0), noReq assert _.isObject(@response or 0), noRes assert key = keys.call(this) or 0, invKey ident = @constructor.identify().underline set = (dx) -> caching.set key, dx if i(dx) c = cached = caching.get(key) or undefined logger.debug hits, key.bold, ident if c? return @response.send cached if cached? try logger.debug miss, key.bold, ident @response.once "sdat", (dx) => set dx implement.apply this, captured # call
220183
### Copyright (c) 2013, <NAME> <<EMAIL>> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ### _ = require "lodash" bower = require "bower" asciify = require "asciify" connect = require "connect" logger = require "winston" events = require "eventemitter2" assert = require "assert" colors = require "colors" crypto = require "crypto" nconf = require "nconf" https = require "https" path = require "path" http = require "http" util = require "util" {Extending} = require "../nucleus/extends" {Composition} = require "../nucleus/compose" {Barebones} = require "../membrane/skeleton" {Archetype} = require "../nucleus/arche" # This toolkit contains a set of routines that help to define the # caching strategies. All of them are simple and definitely not for # the heavy or production usage, but rather for most simple cases. # Generally, you would only apply these strategies when implementing # an API endpoint, within the `ApiService` abstract base class tool. # Please refer to each strategy for more relevant information on it. module.exports.CachingToolkit = class CachingToolkit extends Barebones # This is a marker that indicates to some internal subsystems # that this class has to be considered abstract and therefore # can not be treated as a complete class implementation. This # mainly is used to exclude or account for abstract classes. # Once inherited from, the inheritee is not abstract anymore. @abstract yes # A decorator strategy for wrapping the API endpoint function # with an LRU (least-recently-used) type of cache that normally # uses the `request.path` as its key. This given cache strategy # is highly dependent on the usage of the `response.send` func # in order for the cache to work. Please see `plumbs` module # for more info on that. Also, depends on the spin off engine. # Please see the `lru-cache` package for more relevant info. @memoryCache: (size, time, keys) -> (implement) -> noSize = "no maximum size of cache supplied" noTime = "no TTL timeout for cache var given" noImpl = "no implementation endpoint supplied" noSpin = "not spin-off engine valuess detected" invKey = "the generated cache key is not valid" noReq = "no request in the spinned-off object" noRes = "no response in the spinned-off object" assert _.isFunction lru = require "lru-cache" assert _.isNumber(size or undefined), noSize assert _.isNumber(time or undefined), noTime assert _.isFunction(implement or no), noImpl assert options = try max: size, maxAge: time assert _.isObject caching = try lru options assert keys = (-> @request.path) unless keys assert i = -> _.isString _.first arguments hits = "Hit memory cache of %s at %s".green miss = "Missed memory cache of %s at %s".red return (captured...) -> # decorative wrapper assert @__isolated and @__origin, noSpin assert _.isObject(@request or 0), noReq assert _.isObject(@response or 0), noRes assert key = keys.call(this) or 0, invKey ident = @constructor.identify().underline set = (dx) -> caching.set key, dx if i(dx) c = cached = caching.get(key) or undefined logger.debug hits, key.bold, ident if c? return @response.send cached if cached? try logger.debug miss, key.bold, ident @response.once "sdat", (dx) => set dx implement.apply this, captured # call
true
### Copyright (c) 2013, PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ### _ = require "lodash" bower = require "bower" asciify = require "asciify" connect = require "connect" logger = require "winston" events = require "eventemitter2" assert = require "assert" colors = require "colors" crypto = require "crypto" nconf = require "nconf" https = require "https" path = require "path" http = require "http" util = require "util" {Extending} = require "../nucleus/extends" {Composition} = require "../nucleus/compose" {Barebones} = require "../membrane/skeleton" {Archetype} = require "../nucleus/arche" # This toolkit contains a set of routines that help to define the # caching strategies. All of them are simple and definitely not for # the heavy or production usage, but rather for most simple cases. # Generally, you would only apply these strategies when implementing # an API endpoint, within the `ApiService` abstract base class tool. # Please refer to each strategy for more relevant information on it. module.exports.CachingToolkit = class CachingToolkit extends Barebones # This is a marker that indicates to some internal subsystems # that this class has to be considered abstract and therefore # can not be treated as a complete class implementation. This # mainly is used to exclude or account for abstract classes. # Once inherited from, the inheritee is not abstract anymore. @abstract yes # A decorator strategy for wrapping the API endpoint function # with an LRU (least-recently-used) type of cache that normally # uses the `request.path` as its key. This given cache strategy # is highly dependent on the usage of the `response.send` func # in order for the cache to work. Please see `plumbs` module # for more info on that. Also, depends on the spin off engine. # Please see the `lru-cache` package for more relevant info. @memoryCache: (size, time, keys) -> (implement) -> noSize = "no maximum size of cache supplied" noTime = "no TTL timeout for cache var given" noImpl = "no implementation endpoint supplied" noSpin = "not spin-off engine valuess detected" invKey = "the generated cache key is not valid" noReq = "no request in the spinned-off object" noRes = "no response in the spinned-off object" assert _.isFunction lru = require "lru-cache" assert _.isNumber(size or undefined), noSize assert _.isNumber(time or undefined), noTime assert _.isFunction(implement or no), noImpl assert options = try max: size, maxAge: time assert _.isObject caching = try lru options assert keys = (-> @request.path) unless keys assert i = -> _.isString _.first arguments hits = "Hit memory cache of %s at %s".green miss = "Missed memory cache of %s at %s".red return (captured...) -> # decorative wrapper assert @__isolated and @__origin, noSpin assert _.isObject(@request or 0), noReq assert _.isObject(@response or 0), noRes assert key = keys.call(this) or 0, invKey ident = @constructor.identify().underline set = (dx) -> caching.set key, dx if i(dx) c = cached = caching.get(key) or undefined logger.debug hits, key.bold, ident if c? return @response.send cached if cached? try logger.debug miss, key.bold, ident @response.once "sdat", (dx) => set dx implement.apply this, captured # call
[ { "context": "###*\n@author Mat Groves http://matgroves.com/ @Doormat23\n###\n\ndefine 'Cof", "end": 23, "score": 0.9998860359191895, "start": 13, "tag": "NAME", "value": "Mat Groves" }, { "context": "###*\n@author Mat Groves http://matgroves.com/ @Doormat23\n###\n\ndefine 'Coffixi/r...
src/Coffixi/renderers/canvas/CanvasRenderer.coffee
namuol/Coffixi
1
###* @author Mat Groves http://matgroves.com/ @Doormat23 ### define 'Coffixi/renderers/canvas/CanvasRenderer', [ 'Coffixi/textures/Texture' 'Coffixi/textures/BaseTexture' './CanvasGraphics' 'Coffixi/core/RenderTypes' ], ( Texture BaseTexture CanvasGraphics RenderTypes ) -> RENDERTYPE_SPRITE = RenderTypes.SPRITE RENDERTYPE_BATCH = RenderTypes.BATCH RENDERTYPE_TILINGSPRITE = RenderTypes.TILINGSPRITE RENDERTYPE_STRIP = RenderTypes.STRIP RENDERTYPE_GRAPHICS = RenderTypes.GRAPHICS RENDERTYPE_FILTERBLOCK = RenderTypes.FILTERBLOCK RENDERTYPE_CUSTOMRENDERABLE = RenderTypes.CUSTOMRENDERABLE ###* the CanvasRenderer draws the stage and all its content onto a 2d canvas. This renderer should be used for browsers that do not support webGL. Dont forget to add the view to your DOM or you will not see anything :) @class CanvasRenderer @constructor @param width=0 {Number} the width of the canvas view @param height=0 {Number} the height of the canvas view @param view {Canvas} the canvas to use as a view, optional @param transparent=false {Boolean} the transparency of the render view, default false ### class CanvasRenderer constructor: (width, height, view, transparent, @textureFilter=BaseTexture.filterModes.LINEAR) -> @transparent = transparent ###* The width of the canvas view @property width @type Number @default 800 ### @width = width or 800 ###* The height of the canvas view @property height @type Number @default 600 ### @height = height or 600 ###* The canvas element that the everything is drawn to @property view @type Canvas ### @view = view or document.createElement("canvas") ###* The canvas context that the everything is drawn to @property context @type Canvas 2d Context ### @context = @view.getContext("2d") @refresh = true # hack to enable some hardware acceleration! #this.view.style["transform"] = "translatez(0)"; @view.width = @width @view.height = @height @count = 0 ###* Renders the stage to its canvas view @method render @param stage {Stage} the Stage element to be rendered ### render: (stage) -> # update textures if need be BaseTexture.texturesToUpdate = [] BaseTexture.texturesToDestroy = [] stage.updateTransform() imageSmoothingEnabled = @textureFilter not in [BaseTexture.filterModes.NEAREST, 'nearest'] @context.imageSmoothingEnabled = imageSmoothingEnabled @context.webkitImageSmoothingEnabled = imageSmoothingEnabled @context.mozImageSmoothingEnabled = imageSmoothingEnabled # update the background color @view.style.backgroundColor = stage.backgroundColorString if @view.style.backgroundColor isnt stage.backgroundColorString and not @transparent @context.setTransform 1, 0, 0, 1, 0, 0 @context.clearRect 0, 0, @width, @height @renderDisplayObject stage # remove frame updates.. Texture.frameUpdates = [] if Texture.frameUpdates.length > 0 ###* resizes the canvas view to the specified width and height @method resize @param width {Number} the new width of the canvas view @param height {Number} the new height of the canvas view ### resize: (width, height, viewportWidth, viewportHeight, viewportX, viewportY) -> @width = width @height = height @viewportX = viewportX ? 0 @viewportY = viewportY ? 0 @viewportWidth = viewportWidth ? @width @viewportHeight = viewportHeight ? @height @view.width = width @view.height = height getView: -> @view ###* Renders a display object @method renderDisplayObject @param displayObject {DisplayObject} The displayObject to render @private ### renderDisplayObject: (displayObject) -> # no loger recurrsive! transform = undefined context = @context context.globalCompositeOperation = "source-over" # one the display object hits this. we can break the loop testObject = displayObject.last._iNext displayObject = displayObject.first loop transform = displayObject.worldTransform unless displayObject.visible displayObject = displayObject.last._iNext break if displayObject is testObject continue unless displayObject.renderable displayObject = displayObject._iNext break if displayObject is testObject continue switch displayObject.__renderType when RENDERTYPE_SPRITE frame = displayObject.texture.frame if frame context.globalAlpha = displayObject.worldAlpha context.setTransform transform[0], transform[3], transform[1], transform[4], transform[2], transform[5] context.drawImage displayObject.texture.baseTexture.source, frame.x, frame.y, frame.width, frame.height, (displayObject.anchorX) * -frame.width, (displayObject.anchorY) * -frame.height, frame.width, frame.height when RENDERTYPE_STRIP context.setTransform transform[0], transform[3], transform[1], transform[4], transform[2], transform[5] @renderStrip displayObject when RENDERTYPE_TILINGSPRITE context.setTransform transform[0], transform[3], transform[1], transform[4], transform[2], transform[5] @renderTilingSprite displayObject when RENDERTYPE_CUSTOMRENDERABLE displayObject.renderCanvas this when RENDERTYPE_GRAPHICS context.setTransform transform[0], transform[3], transform[1], transform[4], transform[2], transform[5] CanvasGraphics.renderGraphics displayObject, context when RENDERTYPE_FILTERBLOCK if displayObject.open context.save() cacheAlpha = displayObject.mask.alpha maskTransform = displayObject.mask.worldTransform context.setTransform maskTransform[0], maskTransform[3], maskTransform[1], maskTransform[4], maskTransform[2], maskTransform[5] displayObject.mask.worldAlpha = 0.5 context.worldAlpha = 0 CanvasGraphics.renderGraphicsMask displayObject.mask, context context.clip() displayObject.mask.worldAlpha = cacheAlpha else context.restore() displayObject = displayObject._iNext break if displayObject is testObject return ###* Renders a flat strip @method renderStripFlat @param strip {Strip} The Strip to render @private ### renderStripFlat: (strip) -> context = @context verticies = strip.verticies uvs = strip.uvs length = verticies.length / 2 @count++ context.beginPath() i = 1 while i < length - 2 # draw some triangles! index = i * 2 x0 = verticies[index] x1 = verticies[index + 2] x2 = verticies[index + 4] y0 = verticies[index + 1] y1 = verticies[index + 3] y2 = verticies[index + 5] context.moveTo x0, y0 context.lineTo x1, y1 context.lineTo x2, y2 i++ context.fillStyle = "#FF0000" context.fill() context.closePath() ###* Renders a tiling sprite @method renderTilingSprite @param sprite {TilingSprite} The tilingsprite to render @private ### renderTilingSprite: (sprite) -> context = @context context.globalAlpha = sprite.worldAlpha sprite.__tilePattern = context.createPattern(sprite.texture.baseTexture.source, "repeat") unless sprite.__tilePattern context.beginPath() tilePosition = sprite.tilePosition tileScale = sprite.tileScale # offset context.scale tileScale.x, tileScale.y context.translate tilePosition.x, tilePosition.y context.fillStyle = sprite.__tilePattern context.fillRect -tilePosition.x, -tilePosition.y, sprite.width / tileScale.x, sprite.height / tileScale.y context.scale 1 / tileScale.x, 1 / tileScale.y context.translate -tilePosition.x, -tilePosition.y context.closePath() ###* Renders a strip @method renderStrip @param strip {Strip} The Strip to render @private ### renderStrip: (strip) -> context = @context verticies = strip.verticies uvs = strip.uvs length = verticies.length / 2 @count++ i = 1 while i < length - 2 # draw some triangles! index = i * 2 x0 = verticies[index] x1 = verticies[index + 2] x2 = verticies[index + 4] y0 = verticies[index + 1] y1 = verticies[index + 3] y2 = verticies[index + 5] u0 = uvs[index] * strip.texture.width u1 = uvs[index + 2] * strip.texture.width u2 = uvs[index + 4] * strip.texture.width v0 = uvs[index + 1] * strip.texture.height v1 = uvs[index + 3] * strip.texture.height v2 = uvs[index + 5] * strip.texture.height context.save() context.beginPath() context.moveTo x0, y0 context.lineTo x1, y1 context.lineTo x2, y2 context.closePath() context.clip() # Compute matrix transform delta = u0 * v1 + v0 * u2 + u1 * v2 - v1 * u2 - v0 * u1 - u0 * v2 delta_a = x0 * v1 + v0 * x2 + x1 * v2 - v1 * x2 - v0 * x1 - x0 * v2 delta_b = u0 * x1 + x0 * u2 + u1 * x2 - x1 * u2 - x0 * u1 - u0 * x2 delta_c = u0 * v1 * x2 + v0 * x1 * u2 + x0 * u1 * v2 - x0 * v1 * u2 - v0 * u1 * x2 - u0 * x1 * v2 delta_d = y0 * v1 + v0 * y2 + y1 * v2 - v1 * y2 - v0 * y1 - y0 * v2 delta_e = u0 * y1 + y0 * u2 + u1 * y2 - y1 * u2 - y0 * u1 - u0 * y2 delta_f = u0 * v1 * y2 + v0 * y1 * u2 + y0 * u1 * v2 - y0 * v1 * u2 - v0 * u1 * y2 - u0 * y1 * v2 context.transform delta_a / delta, delta_d / delta, delta_b / delta, delta_e / delta, delta_c / delta, delta_f / delta context.drawImage strip.texture.baseTexture.source, 0, 0 context.restore() i++ return
95207
###* @author <NAME> http://matgroves.com/ @Doormat23 ### define 'Coffixi/renderers/canvas/CanvasRenderer', [ 'Coffixi/textures/Texture' 'Coffixi/textures/BaseTexture' './CanvasGraphics' 'Coffixi/core/RenderTypes' ], ( Texture BaseTexture CanvasGraphics RenderTypes ) -> RENDERTYPE_SPRITE = RenderTypes.SPRITE RENDERTYPE_BATCH = RenderTypes.BATCH RENDERTYPE_TILINGSPRITE = RenderTypes.TILINGSPRITE RENDERTYPE_STRIP = RenderTypes.STRIP RENDERTYPE_GRAPHICS = RenderTypes.GRAPHICS RENDERTYPE_FILTERBLOCK = RenderTypes.FILTERBLOCK RENDERTYPE_CUSTOMRENDERABLE = RenderTypes.CUSTOMRENDERABLE ###* the CanvasRenderer draws the stage and all its content onto a 2d canvas. This renderer should be used for browsers that do not support webGL. Dont forget to add the view to your DOM or you will not see anything :) @class CanvasRenderer @constructor @param width=0 {Number} the width of the canvas view @param height=0 {Number} the height of the canvas view @param view {Canvas} the canvas to use as a view, optional @param transparent=false {Boolean} the transparency of the render view, default false ### class CanvasRenderer constructor: (width, height, view, transparent, @textureFilter=BaseTexture.filterModes.LINEAR) -> @transparent = transparent ###* The width of the canvas view @property width @type Number @default 800 ### @width = width or 800 ###* The height of the canvas view @property height @type Number @default 600 ### @height = height or 600 ###* The canvas element that the everything is drawn to @property view @type Canvas ### @view = view or document.createElement("canvas") ###* The canvas context that the everything is drawn to @property context @type Canvas 2d Context ### @context = @view.getContext("2d") @refresh = true # hack to enable some hardware acceleration! #this.view.style["transform"] = "translatez(0)"; @view.width = @width @view.height = @height @count = 0 ###* Renders the stage to its canvas view @method render @param stage {Stage} the Stage element to be rendered ### render: (stage) -> # update textures if need be BaseTexture.texturesToUpdate = [] BaseTexture.texturesToDestroy = [] stage.updateTransform() imageSmoothingEnabled = @textureFilter not in [BaseTexture.filterModes.NEAREST, 'nearest'] @context.imageSmoothingEnabled = imageSmoothingEnabled @context.webkitImageSmoothingEnabled = imageSmoothingEnabled @context.mozImageSmoothingEnabled = imageSmoothingEnabled # update the background color @view.style.backgroundColor = stage.backgroundColorString if @view.style.backgroundColor isnt stage.backgroundColorString and not @transparent @context.setTransform 1, 0, 0, 1, 0, 0 @context.clearRect 0, 0, @width, @height @renderDisplayObject stage # remove frame updates.. Texture.frameUpdates = [] if Texture.frameUpdates.length > 0 ###* resizes the canvas view to the specified width and height @method resize @param width {Number} the new width of the canvas view @param height {Number} the new height of the canvas view ### resize: (width, height, viewportWidth, viewportHeight, viewportX, viewportY) -> @width = width @height = height @viewportX = viewportX ? 0 @viewportY = viewportY ? 0 @viewportWidth = viewportWidth ? @width @viewportHeight = viewportHeight ? @height @view.width = width @view.height = height getView: -> @view ###* Renders a display object @method renderDisplayObject @param displayObject {DisplayObject} The displayObject to render @private ### renderDisplayObject: (displayObject) -> # no loger recurrsive! transform = undefined context = @context context.globalCompositeOperation = "source-over" # one the display object hits this. we can break the loop testObject = displayObject.last._iNext displayObject = displayObject.first loop transform = displayObject.worldTransform unless displayObject.visible displayObject = displayObject.last._iNext break if displayObject is testObject continue unless displayObject.renderable displayObject = displayObject._iNext break if displayObject is testObject continue switch displayObject.__renderType when RENDERTYPE_SPRITE frame = displayObject.texture.frame if frame context.globalAlpha = displayObject.worldAlpha context.setTransform transform[0], transform[3], transform[1], transform[4], transform[2], transform[5] context.drawImage displayObject.texture.baseTexture.source, frame.x, frame.y, frame.width, frame.height, (displayObject.anchorX) * -frame.width, (displayObject.anchorY) * -frame.height, frame.width, frame.height when RENDERTYPE_STRIP context.setTransform transform[0], transform[3], transform[1], transform[4], transform[2], transform[5] @renderStrip displayObject when RENDERTYPE_TILINGSPRITE context.setTransform transform[0], transform[3], transform[1], transform[4], transform[2], transform[5] @renderTilingSprite displayObject when RENDERTYPE_CUSTOMRENDERABLE displayObject.renderCanvas this when RENDERTYPE_GRAPHICS context.setTransform transform[0], transform[3], transform[1], transform[4], transform[2], transform[5] CanvasGraphics.renderGraphics displayObject, context when RENDERTYPE_FILTERBLOCK if displayObject.open context.save() cacheAlpha = displayObject.mask.alpha maskTransform = displayObject.mask.worldTransform context.setTransform maskTransform[0], maskTransform[3], maskTransform[1], maskTransform[4], maskTransform[2], maskTransform[5] displayObject.mask.worldAlpha = 0.5 context.worldAlpha = 0 CanvasGraphics.renderGraphicsMask displayObject.mask, context context.clip() displayObject.mask.worldAlpha = cacheAlpha else context.restore() displayObject = displayObject._iNext break if displayObject is testObject return ###* Renders a flat strip @method renderStripFlat @param strip {Strip} The Strip to render @private ### renderStripFlat: (strip) -> context = @context verticies = strip.verticies uvs = strip.uvs length = verticies.length / 2 @count++ context.beginPath() i = 1 while i < length - 2 # draw some triangles! index = i * 2 x0 = verticies[index] x1 = verticies[index + 2] x2 = verticies[index + 4] y0 = verticies[index + 1] y1 = verticies[index + 3] y2 = verticies[index + 5] context.moveTo x0, y0 context.lineTo x1, y1 context.lineTo x2, y2 i++ context.fillStyle = "#FF0000" context.fill() context.closePath() ###* Renders a tiling sprite @method renderTilingSprite @param sprite {TilingSprite} The tilingsprite to render @private ### renderTilingSprite: (sprite) -> context = @context context.globalAlpha = sprite.worldAlpha sprite.__tilePattern = context.createPattern(sprite.texture.baseTexture.source, "repeat") unless sprite.__tilePattern context.beginPath() tilePosition = sprite.tilePosition tileScale = sprite.tileScale # offset context.scale tileScale.x, tileScale.y context.translate tilePosition.x, tilePosition.y context.fillStyle = sprite.__tilePattern context.fillRect -tilePosition.x, -tilePosition.y, sprite.width / tileScale.x, sprite.height / tileScale.y context.scale 1 / tileScale.x, 1 / tileScale.y context.translate -tilePosition.x, -tilePosition.y context.closePath() ###* Renders a strip @method renderStrip @param strip {Strip} The Strip to render @private ### renderStrip: (strip) -> context = @context verticies = strip.verticies uvs = strip.uvs length = verticies.length / 2 @count++ i = 1 while i < length - 2 # draw some triangles! index = i * 2 x0 = verticies[index] x1 = verticies[index + 2] x2 = verticies[index + 4] y0 = verticies[index + 1] y1 = verticies[index + 3] y2 = verticies[index + 5] u0 = uvs[index] * strip.texture.width u1 = uvs[index + 2] * strip.texture.width u2 = uvs[index + 4] * strip.texture.width v0 = uvs[index + 1] * strip.texture.height v1 = uvs[index + 3] * strip.texture.height v2 = uvs[index + 5] * strip.texture.height context.save() context.beginPath() context.moveTo x0, y0 context.lineTo x1, y1 context.lineTo x2, y2 context.closePath() context.clip() # Compute matrix transform delta = u0 * v1 + v0 * u2 + u1 * v2 - v1 * u2 - v0 * u1 - u0 * v2 delta_a = x0 * v1 + v0 * x2 + x1 * v2 - v1 * x2 - v0 * x1 - x0 * v2 delta_b = u0 * x1 + x0 * u2 + u1 * x2 - x1 * u2 - x0 * u1 - u0 * x2 delta_c = u0 * v1 * x2 + v0 * x1 * u2 + x0 * u1 * v2 - x0 * v1 * u2 - v0 * u1 * x2 - u0 * x1 * v2 delta_d = y0 * v1 + v0 * y2 + y1 * v2 - v1 * y2 - v0 * y1 - y0 * v2 delta_e = u0 * y1 + y0 * u2 + u1 * y2 - y1 * u2 - y0 * u1 - u0 * y2 delta_f = u0 * v1 * y2 + v0 * y1 * u2 + y0 * u1 * v2 - y0 * v1 * u2 - v0 * u1 * y2 - u0 * y1 * v2 context.transform delta_a / delta, delta_d / delta, delta_b / delta, delta_e / delta, delta_c / delta, delta_f / delta context.drawImage strip.texture.baseTexture.source, 0, 0 context.restore() i++ return
true
###* @author PI:NAME:<NAME>END_PI http://matgroves.com/ @Doormat23 ### define 'Coffixi/renderers/canvas/CanvasRenderer', [ 'Coffixi/textures/Texture' 'Coffixi/textures/BaseTexture' './CanvasGraphics' 'Coffixi/core/RenderTypes' ], ( Texture BaseTexture CanvasGraphics RenderTypes ) -> RENDERTYPE_SPRITE = RenderTypes.SPRITE RENDERTYPE_BATCH = RenderTypes.BATCH RENDERTYPE_TILINGSPRITE = RenderTypes.TILINGSPRITE RENDERTYPE_STRIP = RenderTypes.STRIP RENDERTYPE_GRAPHICS = RenderTypes.GRAPHICS RENDERTYPE_FILTERBLOCK = RenderTypes.FILTERBLOCK RENDERTYPE_CUSTOMRENDERABLE = RenderTypes.CUSTOMRENDERABLE ###* the CanvasRenderer draws the stage and all its content onto a 2d canvas. This renderer should be used for browsers that do not support webGL. Dont forget to add the view to your DOM or you will not see anything :) @class CanvasRenderer @constructor @param width=0 {Number} the width of the canvas view @param height=0 {Number} the height of the canvas view @param view {Canvas} the canvas to use as a view, optional @param transparent=false {Boolean} the transparency of the render view, default false ### class CanvasRenderer constructor: (width, height, view, transparent, @textureFilter=BaseTexture.filterModes.LINEAR) -> @transparent = transparent ###* The width of the canvas view @property width @type Number @default 800 ### @width = width or 800 ###* The height of the canvas view @property height @type Number @default 600 ### @height = height or 600 ###* The canvas element that the everything is drawn to @property view @type Canvas ### @view = view or document.createElement("canvas") ###* The canvas context that the everything is drawn to @property context @type Canvas 2d Context ### @context = @view.getContext("2d") @refresh = true # hack to enable some hardware acceleration! #this.view.style["transform"] = "translatez(0)"; @view.width = @width @view.height = @height @count = 0 ###* Renders the stage to its canvas view @method render @param stage {Stage} the Stage element to be rendered ### render: (stage) -> # update textures if need be BaseTexture.texturesToUpdate = [] BaseTexture.texturesToDestroy = [] stage.updateTransform() imageSmoothingEnabled = @textureFilter not in [BaseTexture.filterModes.NEAREST, 'nearest'] @context.imageSmoothingEnabled = imageSmoothingEnabled @context.webkitImageSmoothingEnabled = imageSmoothingEnabled @context.mozImageSmoothingEnabled = imageSmoothingEnabled # update the background color @view.style.backgroundColor = stage.backgroundColorString if @view.style.backgroundColor isnt stage.backgroundColorString and not @transparent @context.setTransform 1, 0, 0, 1, 0, 0 @context.clearRect 0, 0, @width, @height @renderDisplayObject stage # remove frame updates.. Texture.frameUpdates = [] if Texture.frameUpdates.length > 0 ###* resizes the canvas view to the specified width and height @method resize @param width {Number} the new width of the canvas view @param height {Number} the new height of the canvas view ### resize: (width, height, viewportWidth, viewportHeight, viewportX, viewportY) -> @width = width @height = height @viewportX = viewportX ? 0 @viewportY = viewportY ? 0 @viewportWidth = viewportWidth ? @width @viewportHeight = viewportHeight ? @height @view.width = width @view.height = height getView: -> @view ###* Renders a display object @method renderDisplayObject @param displayObject {DisplayObject} The displayObject to render @private ### renderDisplayObject: (displayObject) -> # no loger recurrsive! transform = undefined context = @context context.globalCompositeOperation = "source-over" # one the display object hits this. we can break the loop testObject = displayObject.last._iNext displayObject = displayObject.first loop transform = displayObject.worldTransform unless displayObject.visible displayObject = displayObject.last._iNext break if displayObject is testObject continue unless displayObject.renderable displayObject = displayObject._iNext break if displayObject is testObject continue switch displayObject.__renderType when RENDERTYPE_SPRITE frame = displayObject.texture.frame if frame context.globalAlpha = displayObject.worldAlpha context.setTransform transform[0], transform[3], transform[1], transform[4], transform[2], transform[5] context.drawImage displayObject.texture.baseTexture.source, frame.x, frame.y, frame.width, frame.height, (displayObject.anchorX) * -frame.width, (displayObject.anchorY) * -frame.height, frame.width, frame.height when RENDERTYPE_STRIP context.setTransform transform[0], transform[3], transform[1], transform[4], transform[2], transform[5] @renderStrip displayObject when RENDERTYPE_TILINGSPRITE context.setTransform transform[0], transform[3], transform[1], transform[4], transform[2], transform[5] @renderTilingSprite displayObject when RENDERTYPE_CUSTOMRENDERABLE displayObject.renderCanvas this when RENDERTYPE_GRAPHICS context.setTransform transform[0], transform[3], transform[1], transform[4], transform[2], transform[5] CanvasGraphics.renderGraphics displayObject, context when RENDERTYPE_FILTERBLOCK if displayObject.open context.save() cacheAlpha = displayObject.mask.alpha maskTransform = displayObject.mask.worldTransform context.setTransform maskTransform[0], maskTransform[3], maskTransform[1], maskTransform[4], maskTransform[2], maskTransform[5] displayObject.mask.worldAlpha = 0.5 context.worldAlpha = 0 CanvasGraphics.renderGraphicsMask displayObject.mask, context context.clip() displayObject.mask.worldAlpha = cacheAlpha else context.restore() displayObject = displayObject._iNext break if displayObject is testObject return ###* Renders a flat strip @method renderStripFlat @param strip {Strip} The Strip to render @private ### renderStripFlat: (strip) -> context = @context verticies = strip.verticies uvs = strip.uvs length = verticies.length / 2 @count++ context.beginPath() i = 1 while i < length - 2 # draw some triangles! index = i * 2 x0 = verticies[index] x1 = verticies[index + 2] x2 = verticies[index + 4] y0 = verticies[index + 1] y1 = verticies[index + 3] y2 = verticies[index + 5] context.moveTo x0, y0 context.lineTo x1, y1 context.lineTo x2, y2 i++ context.fillStyle = "#FF0000" context.fill() context.closePath() ###* Renders a tiling sprite @method renderTilingSprite @param sprite {TilingSprite} The tilingsprite to render @private ### renderTilingSprite: (sprite) -> context = @context context.globalAlpha = sprite.worldAlpha sprite.__tilePattern = context.createPattern(sprite.texture.baseTexture.source, "repeat") unless sprite.__tilePattern context.beginPath() tilePosition = sprite.tilePosition tileScale = sprite.tileScale # offset context.scale tileScale.x, tileScale.y context.translate tilePosition.x, tilePosition.y context.fillStyle = sprite.__tilePattern context.fillRect -tilePosition.x, -tilePosition.y, sprite.width / tileScale.x, sprite.height / tileScale.y context.scale 1 / tileScale.x, 1 / tileScale.y context.translate -tilePosition.x, -tilePosition.y context.closePath() ###* Renders a strip @method renderStrip @param strip {Strip} The Strip to render @private ### renderStrip: (strip) -> context = @context verticies = strip.verticies uvs = strip.uvs length = verticies.length / 2 @count++ i = 1 while i < length - 2 # draw some triangles! index = i * 2 x0 = verticies[index] x1 = verticies[index + 2] x2 = verticies[index + 4] y0 = verticies[index + 1] y1 = verticies[index + 3] y2 = verticies[index + 5] u0 = uvs[index] * strip.texture.width u1 = uvs[index + 2] * strip.texture.width u2 = uvs[index + 4] * strip.texture.width v0 = uvs[index + 1] * strip.texture.height v1 = uvs[index + 3] * strip.texture.height v2 = uvs[index + 5] * strip.texture.height context.save() context.beginPath() context.moveTo x0, y0 context.lineTo x1, y1 context.lineTo x2, y2 context.closePath() context.clip() # Compute matrix transform delta = u0 * v1 + v0 * u2 + u1 * v2 - v1 * u2 - v0 * u1 - u0 * v2 delta_a = x0 * v1 + v0 * x2 + x1 * v2 - v1 * x2 - v0 * x1 - x0 * v2 delta_b = u0 * x1 + x0 * u2 + u1 * x2 - x1 * u2 - x0 * u1 - u0 * x2 delta_c = u0 * v1 * x2 + v0 * x1 * u2 + x0 * u1 * v2 - x0 * v1 * u2 - v0 * u1 * x2 - u0 * x1 * v2 delta_d = y0 * v1 + v0 * y2 + y1 * v2 - v1 * y2 - v0 * y1 - y0 * v2 delta_e = u0 * y1 + y0 * u2 + u1 * y2 - y1 * u2 - y0 * u1 - u0 * y2 delta_f = u0 * v1 * y2 + v0 * y1 * u2 + y0 * u1 * v2 - y0 * v1 * u2 - v0 * u1 * y2 - u0 * y1 * v2 context.transform delta_a / delta, delta_d / delta, delta_b / delta, delta_e / delta, delta_c / delta, delta_f / delta context.drawImage strip.texture.baseTexture.source, 0, 0 context.restore() i++ return
[ { "context": " constructor: ->\n super\n @set 'name', \"Cool Snowboard\"\n @set 'cost', 10\n\n @encode 'name', 'cost", "end": 267, "score": 0.9440047144889832, "start": 253, "tag": "NAME", "value": "Cool Snowboard" } ]
tests/prof/tests/model/model_memory_usage.coffee
airhorns/batman
1
Batman = require '../../../../lib/batman' Watson = require 'watson' TestStorageAdapter = require '../lib/test_storage_adapter' Watson.ensureCommitted 'v0.6.1', -> class Product extends Batman.Model constructor: -> super @set 'name', "Cool Snowboard" @set 'cost', 10 @encode 'name', 'cost' @persist TestStorageAdapter Watson.trackMemory 'model memory usage', 2000, (i) -> (new Product).save (err) -> throw err if err if i % 500 == 0 Product.get('loaded').forEach (p) -> p.destroy (err) -> throw err if err
190836
Batman = require '../../../../lib/batman' Watson = require 'watson' TestStorageAdapter = require '../lib/test_storage_adapter' Watson.ensureCommitted 'v0.6.1', -> class Product extends Batman.Model constructor: -> super @set 'name', "<NAME>" @set 'cost', 10 @encode 'name', 'cost' @persist TestStorageAdapter Watson.trackMemory 'model memory usage', 2000, (i) -> (new Product).save (err) -> throw err if err if i % 500 == 0 Product.get('loaded').forEach (p) -> p.destroy (err) -> throw err if err
true
Batman = require '../../../../lib/batman' Watson = require 'watson' TestStorageAdapter = require '../lib/test_storage_adapter' Watson.ensureCommitted 'v0.6.1', -> class Product extends Batman.Model constructor: -> super @set 'name', "PI:NAME:<NAME>END_PI" @set 'cost', 10 @encode 'name', 'cost' @persist TestStorageAdapter Watson.trackMemory 'model memory usage', 2000, (i) -> (new Product).save (err) -> throw err if err if i % 500 == 0 Product.get('loaded').forEach (p) -> p.destroy (err) -> throw err if err
[ { "context": " \"\"\n \"Copyright (c) 2015 Recca Tsai <http://phpwrite.blogspot.tw/>\"\n \"", "end": 9598, "score": 0.9998694062232971, "start": 9588, "tag": "NAME", "value": "Recca Tsai" } ]
vendor/recca0120/terminal/resources/assets/coffee/app.coffee
frankzero/eznewlife
0
do ($ = jQuery, window, document) -> Loading = do -> anim = ["/", "|", "\\", "-"] intervalId = null delay = 50 defaultPrompt = null show: (term) -> term.disable() defaultPrompt = term.get_prompt() i = 0 intervalId = setInterval -> term.set_prompt anim[i++] if i > anim.length-1 i = 0 , delay hide: (term) -> clearInterval intervalId term.enable() term.set_prompt defaultPrompt class OutputFormatterStyle colorList: 30: 'black', 31: 'red', 32: 'green', 33: 'yellow', 34: 'blue', 35: 'magenta', 36: 'cyan', 37: 'white', 39: 'white' backgroundList: 40: 'black', 41: 'red', 42: 'green', 43: 'yellow', 44: 'blue', 45: 'magenta', 46: 'cyan', 47: 'white', 49: 'black' # normal, faited, bold colors: $.extend {}, $.terminal.ansi_colors.bold, white: $.terminal.ansi_colors.normal.white red: $.terminal.ansi_colors.normal.red constructor: (foreground = "white", background = "black", @options = []) -> @foreground = @ansi foreground @background = @ansi background is: (foreground = "white", background = "black", @options = []) => return foreground is @foreground and background is @background ansi: (color) => if @colors[color] return @colors[color] else return color apply: (text) => text = $.terminal.escape_brackets text "[[;#{@foreground};#{@background}]#{text}]" class OutputFormatter formatters: error: new OutputFormatterStyle "white", "red" info: new OutputFormatterStyle "green" comment: new OutputFormatterStyle "yellow" question: new OutputFormatterStyle "magenta" error: (text) => @formatters.error.apply text info: (text) => @formatters.info.apply text comment: (text) => @formatters.comment.apply text question: (text) => @formatters.question.apply text apply: (text, term) => re = new RegExp "(\\033\\[(\\d+)(;\\d+)?m(((?!\\033\\[\\d+).)*)\\033\\[(\\d+)(;\\d+)?m)|(\\[|\\])", "g" text = text .replace re, => m = arguments return switch when $.inArray(m[0], ["[", "]"]) isnt -1 $.terminal.escape_brackets m[0] else content = $.terminal.escape_brackets m[4] return switch when m[2] is "32" @info content when m[2] is "33" @comment content when m[2] is "37" @error content else m[0] if term $.each text.split("\n"), (i, line) => if line is "" line = " " term.echo line text class @Term ids: {}, formatter: new OutputFormatter colors: $.terminal.ansi_colors term: null, prompt: "$ " color: (color, background, type = "bold") => if @colors[type] and @colors[type][color] return @colors[type][color] else return color error: (text) => @formatter.error text info: (text) => @formatter.info text comment: (text) => @formatter.comment text question: (text) => @formatter.question text confirm: (term, message, title = "") => deferred = $.Deferred() if title term.echo " #{title}" term.echo message history = term.history() history.disable() term.push (result) => if @toBoolean result deferred.resolve true else deferred.resolve false @serverInfo() term.pop() history.enable() return , prompt: " > " deferred.promise() toBoolean: (result) => return switch (result.toLowerCase()) when 'y', 'yes' then true else false request: (cmd, callback = null) => @ids[cmd.method] = @ids[cmd.method] || 0; Loading.show @term $.ajax url: @options.endpoint, dataType: 'json' type: 'post' headers: 'X-CSRF-TOKEN': @options.csrfToken data: jsonrpc: "2.0" id: ++@ids[cmd.method] cmd: cmd .success (response) => if response.error is 1 @formatter.apply response.result, @term return if ($.inArray("-h", cmd.args) isnt -1) or ($.inArray("--help", cmd.args) isnt -1) @formatter.apply response.result, @term return if callback isnt null setTimeout => callback response , 100 else @formatter.apply response.result, @term .error (jqXhr, json, errorThrown) => @formatter.error("#{jqXhr.status}: #{errorThrown}", @term) .complete => Loading.hide @term @serverInfo() interpreter: (commandPrefix, prompt) => unless prompt prompt = commandPrefix @term.push (command) => command = command.trim() if command @execute "#{commandPrefix.replace(/\s+/g, '-')} #{command}", @term return false , prompt: "#{prompt}> " return false capitalize = (str) => "#{str.charAt(0).toUpperCase()}#{str.slice(1)}" confirmToProceed: (cmd, warning = "Application In Production!") => @term.echo @comment("**************************************") @term.echo @comment("* #{warning} *") @term.echo @comment("**************************************") @term.echo " " @confirm @term, "#{@info('Do you really wish to run this command? [y/N] (yes/no)')} #{@comment('[no]')}: " .done (result) => if result is true @request cmd else @term.echo " " @term.echo "#{@comment('Command Cancelled!')}" @term.echo " " commandArtisan: (cmd) => restCmd = $.terminal.parseCommand cmd.rest.trim() if @options.environment is "production" and $.inArray("--force", restCmd.args) is -1 if $.inArray(restCmd.name, @options.confirmToProceed[cmd.name]) isnt -1 @confirmToProceed cmd return @request cmd commandVi: (cmd) => path = cmd.rest @request cmd, (response) => @term.disable() editor = $(@options.editor) editor.html response.result vi editor.get(0), onSave: => val = JSON.stringify(editor.val()) cmd.command += " --text=#{val}" cmd.rest += " --text=#{val}" cmd.args.push "--text=#{val}" @request cmd onExit: => @term.enable() @term.focus() execute: (command, term) => command = command.trim() switch command when "help", "list" @formatter.apply @options.helpInfo, @term @serverInfo() when "" return else for interpreter, prompt of @options.interpreters if command is interpreter @interpreter prompt return cmd = $.terminal.parseCommand command.trim() if @["command#{capitalize(cmd.name)}"] @["command#{capitalize(cmd.name)}"](cmd) else @request cmd return greetings: => [ " __ _ _____ _ _ " "| | ___ ___ ___ _ _ ___| | |_ ____ ___ _____|_|___ ___| |" "| |__| .'| _| .'| | | -_| | | || -_| _| | | | .'| |" "|_____|__,|_| |__,|\\_/|___|_| |_||___|_| |_|_|_|_|_|_|__,|_|" "" "Copyright (c) 2015 Recca Tsai <http://phpwrite.blogspot.tw/>" "" "Type a command, or type `#{@info('help')}`, for a list of commands." "" ].join "\n" serverInfo: => if @term.level() > 1 return host = @info "#{@options.username}@#{@options.hostname}" os = @question "#{@options.os}" path = @comment "#{@options.basePath}" @term.echo "#{host} #{os} #{path}" onInit: (term) => @term = term @execute 'list', term onClear: (term) => @serverInfo() constructor: (@element, @options)-> @element = $(@element) @element.terminal @execute, onInit: @onInit onClear: @onClear greetings: @greetings() prompt: @prompt win = $(window) win.on "resize", => @element.width(@element.parent().width()) @element.height(@element.parent().height()) win.trigger "resize"
134636
do ($ = jQuery, window, document) -> Loading = do -> anim = ["/", "|", "\\", "-"] intervalId = null delay = 50 defaultPrompt = null show: (term) -> term.disable() defaultPrompt = term.get_prompt() i = 0 intervalId = setInterval -> term.set_prompt anim[i++] if i > anim.length-1 i = 0 , delay hide: (term) -> clearInterval intervalId term.enable() term.set_prompt defaultPrompt class OutputFormatterStyle colorList: 30: 'black', 31: 'red', 32: 'green', 33: 'yellow', 34: 'blue', 35: 'magenta', 36: 'cyan', 37: 'white', 39: 'white' backgroundList: 40: 'black', 41: 'red', 42: 'green', 43: 'yellow', 44: 'blue', 45: 'magenta', 46: 'cyan', 47: 'white', 49: 'black' # normal, faited, bold colors: $.extend {}, $.terminal.ansi_colors.bold, white: $.terminal.ansi_colors.normal.white red: $.terminal.ansi_colors.normal.red constructor: (foreground = "white", background = "black", @options = []) -> @foreground = @ansi foreground @background = @ansi background is: (foreground = "white", background = "black", @options = []) => return foreground is @foreground and background is @background ansi: (color) => if @colors[color] return @colors[color] else return color apply: (text) => text = $.terminal.escape_brackets text "[[;#{@foreground};#{@background}]#{text}]" class OutputFormatter formatters: error: new OutputFormatterStyle "white", "red" info: new OutputFormatterStyle "green" comment: new OutputFormatterStyle "yellow" question: new OutputFormatterStyle "magenta" error: (text) => @formatters.error.apply text info: (text) => @formatters.info.apply text comment: (text) => @formatters.comment.apply text question: (text) => @formatters.question.apply text apply: (text, term) => re = new RegExp "(\\033\\[(\\d+)(;\\d+)?m(((?!\\033\\[\\d+).)*)\\033\\[(\\d+)(;\\d+)?m)|(\\[|\\])", "g" text = text .replace re, => m = arguments return switch when $.inArray(m[0], ["[", "]"]) isnt -1 $.terminal.escape_brackets m[0] else content = $.terminal.escape_brackets m[4] return switch when m[2] is "32" @info content when m[2] is "33" @comment content when m[2] is "37" @error content else m[0] if term $.each text.split("\n"), (i, line) => if line is "" line = " " term.echo line text class @Term ids: {}, formatter: new OutputFormatter colors: $.terminal.ansi_colors term: null, prompt: "$ " color: (color, background, type = "bold") => if @colors[type] and @colors[type][color] return @colors[type][color] else return color error: (text) => @formatter.error text info: (text) => @formatter.info text comment: (text) => @formatter.comment text question: (text) => @formatter.question text confirm: (term, message, title = "") => deferred = $.Deferred() if title term.echo " #{title}" term.echo message history = term.history() history.disable() term.push (result) => if @toBoolean result deferred.resolve true else deferred.resolve false @serverInfo() term.pop() history.enable() return , prompt: " > " deferred.promise() toBoolean: (result) => return switch (result.toLowerCase()) when 'y', 'yes' then true else false request: (cmd, callback = null) => @ids[cmd.method] = @ids[cmd.method] || 0; Loading.show @term $.ajax url: @options.endpoint, dataType: 'json' type: 'post' headers: 'X-CSRF-TOKEN': @options.csrfToken data: jsonrpc: "2.0" id: ++@ids[cmd.method] cmd: cmd .success (response) => if response.error is 1 @formatter.apply response.result, @term return if ($.inArray("-h", cmd.args) isnt -1) or ($.inArray("--help", cmd.args) isnt -1) @formatter.apply response.result, @term return if callback isnt null setTimeout => callback response , 100 else @formatter.apply response.result, @term .error (jqXhr, json, errorThrown) => @formatter.error("#{jqXhr.status}: #{errorThrown}", @term) .complete => Loading.hide @term @serverInfo() interpreter: (commandPrefix, prompt) => unless prompt prompt = commandPrefix @term.push (command) => command = command.trim() if command @execute "#{commandPrefix.replace(/\s+/g, '-')} #{command}", @term return false , prompt: "#{prompt}> " return false capitalize = (str) => "#{str.charAt(0).toUpperCase()}#{str.slice(1)}" confirmToProceed: (cmd, warning = "Application In Production!") => @term.echo @comment("**************************************") @term.echo @comment("* #{warning} *") @term.echo @comment("**************************************") @term.echo " " @confirm @term, "#{@info('Do you really wish to run this command? [y/N] (yes/no)')} #{@comment('[no]')}: " .done (result) => if result is true @request cmd else @term.echo " " @term.echo "#{@comment('Command Cancelled!')}" @term.echo " " commandArtisan: (cmd) => restCmd = $.terminal.parseCommand cmd.rest.trim() if @options.environment is "production" and $.inArray("--force", restCmd.args) is -1 if $.inArray(restCmd.name, @options.confirmToProceed[cmd.name]) isnt -1 @confirmToProceed cmd return @request cmd commandVi: (cmd) => path = cmd.rest @request cmd, (response) => @term.disable() editor = $(@options.editor) editor.html response.result vi editor.get(0), onSave: => val = JSON.stringify(editor.val()) cmd.command += " --text=#{val}" cmd.rest += " --text=#{val}" cmd.args.push "--text=#{val}" @request cmd onExit: => @term.enable() @term.focus() execute: (command, term) => command = command.trim() switch command when "help", "list" @formatter.apply @options.helpInfo, @term @serverInfo() when "" return else for interpreter, prompt of @options.interpreters if command is interpreter @interpreter prompt return cmd = $.terminal.parseCommand command.trim() if @["command#{capitalize(cmd.name)}"] @["command#{capitalize(cmd.name)}"](cmd) else @request cmd return greetings: => [ " __ _ _____ _ _ " "| | ___ ___ ___ _ _ ___| | |_ ____ ___ _____|_|___ ___| |" "| |__| .'| _| .'| | | -_| | | || -_| _| | | | .'| |" "|_____|__,|_| |__,|\\_/|___|_| |_||___|_| |_|_|_|_|_|_|__,|_|" "" "Copyright (c) 2015 <NAME> <http://phpwrite.blogspot.tw/>" "" "Type a command, or type `#{@info('help')}`, for a list of commands." "" ].join "\n" serverInfo: => if @term.level() > 1 return host = @info "#{@options.username}@#{@options.hostname}" os = @question "#{@options.os}" path = @comment "#{@options.basePath}" @term.echo "#{host} #{os} #{path}" onInit: (term) => @term = term @execute 'list', term onClear: (term) => @serverInfo() constructor: (@element, @options)-> @element = $(@element) @element.terminal @execute, onInit: @onInit onClear: @onClear greetings: @greetings() prompt: @prompt win = $(window) win.on "resize", => @element.width(@element.parent().width()) @element.height(@element.parent().height()) win.trigger "resize"
true
do ($ = jQuery, window, document) -> Loading = do -> anim = ["/", "|", "\\", "-"] intervalId = null delay = 50 defaultPrompt = null show: (term) -> term.disable() defaultPrompt = term.get_prompt() i = 0 intervalId = setInterval -> term.set_prompt anim[i++] if i > anim.length-1 i = 0 , delay hide: (term) -> clearInterval intervalId term.enable() term.set_prompt defaultPrompt class OutputFormatterStyle colorList: 30: 'black', 31: 'red', 32: 'green', 33: 'yellow', 34: 'blue', 35: 'magenta', 36: 'cyan', 37: 'white', 39: 'white' backgroundList: 40: 'black', 41: 'red', 42: 'green', 43: 'yellow', 44: 'blue', 45: 'magenta', 46: 'cyan', 47: 'white', 49: 'black' # normal, faited, bold colors: $.extend {}, $.terminal.ansi_colors.bold, white: $.terminal.ansi_colors.normal.white red: $.terminal.ansi_colors.normal.red constructor: (foreground = "white", background = "black", @options = []) -> @foreground = @ansi foreground @background = @ansi background is: (foreground = "white", background = "black", @options = []) => return foreground is @foreground and background is @background ansi: (color) => if @colors[color] return @colors[color] else return color apply: (text) => text = $.terminal.escape_brackets text "[[;#{@foreground};#{@background}]#{text}]" class OutputFormatter formatters: error: new OutputFormatterStyle "white", "red" info: new OutputFormatterStyle "green" comment: new OutputFormatterStyle "yellow" question: new OutputFormatterStyle "magenta" error: (text) => @formatters.error.apply text info: (text) => @formatters.info.apply text comment: (text) => @formatters.comment.apply text question: (text) => @formatters.question.apply text apply: (text, term) => re = new RegExp "(\\033\\[(\\d+)(;\\d+)?m(((?!\\033\\[\\d+).)*)\\033\\[(\\d+)(;\\d+)?m)|(\\[|\\])", "g" text = text .replace re, => m = arguments return switch when $.inArray(m[0], ["[", "]"]) isnt -1 $.terminal.escape_brackets m[0] else content = $.terminal.escape_brackets m[4] return switch when m[2] is "32" @info content when m[2] is "33" @comment content when m[2] is "37" @error content else m[0] if term $.each text.split("\n"), (i, line) => if line is "" line = " " term.echo line text class @Term ids: {}, formatter: new OutputFormatter colors: $.terminal.ansi_colors term: null, prompt: "$ " color: (color, background, type = "bold") => if @colors[type] and @colors[type][color] return @colors[type][color] else return color error: (text) => @formatter.error text info: (text) => @formatter.info text comment: (text) => @formatter.comment text question: (text) => @formatter.question text confirm: (term, message, title = "") => deferred = $.Deferred() if title term.echo " #{title}" term.echo message history = term.history() history.disable() term.push (result) => if @toBoolean result deferred.resolve true else deferred.resolve false @serverInfo() term.pop() history.enable() return , prompt: " > " deferred.promise() toBoolean: (result) => return switch (result.toLowerCase()) when 'y', 'yes' then true else false request: (cmd, callback = null) => @ids[cmd.method] = @ids[cmd.method] || 0; Loading.show @term $.ajax url: @options.endpoint, dataType: 'json' type: 'post' headers: 'X-CSRF-TOKEN': @options.csrfToken data: jsonrpc: "2.0" id: ++@ids[cmd.method] cmd: cmd .success (response) => if response.error is 1 @formatter.apply response.result, @term return if ($.inArray("-h", cmd.args) isnt -1) or ($.inArray("--help", cmd.args) isnt -1) @formatter.apply response.result, @term return if callback isnt null setTimeout => callback response , 100 else @formatter.apply response.result, @term .error (jqXhr, json, errorThrown) => @formatter.error("#{jqXhr.status}: #{errorThrown}", @term) .complete => Loading.hide @term @serverInfo() interpreter: (commandPrefix, prompt) => unless prompt prompt = commandPrefix @term.push (command) => command = command.trim() if command @execute "#{commandPrefix.replace(/\s+/g, '-')} #{command}", @term return false , prompt: "#{prompt}> " return false capitalize = (str) => "#{str.charAt(0).toUpperCase()}#{str.slice(1)}" confirmToProceed: (cmd, warning = "Application In Production!") => @term.echo @comment("**************************************") @term.echo @comment("* #{warning} *") @term.echo @comment("**************************************") @term.echo " " @confirm @term, "#{@info('Do you really wish to run this command? [y/N] (yes/no)')} #{@comment('[no]')}: " .done (result) => if result is true @request cmd else @term.echo " " @term.echo "#{@comment('Command Cancelled!')}" @term.echo " " commandArtisan: (cmd) => restCmd = $.terminal.parseCommand cmd.rest.trim() if @options.environment is "production" and $.inArray("--force", restCmd.args) is -1 if $.inArray(restCmd.name, @options.confirmToProceed[cmd.name]) isnt -1 @confirmToProceed cmd return @request cmd commandVi: (cmd) => path = cmd.rest @request cmd, (response) => @term.disable() editor = $(@options.editor) editor.html response.result vi editor.get(0), onSave: => val = JSON.stringify(editor.val()) cmd.command += " --text=#{val}" cmd.rest += " --text=#{val}" cmd.args.push "--text=#{val}" @request cmd onExit: => @term.enable() @term.focus() execute: (command, term) => command = command.trim() switch command when "help", "list" @formatter.apply @options.helpInfo, @term @serverInfo() when "" return else for interpreter, prompt of @options.interpreters if command is interpreter @interpreter prompt return cmd = $.terminal.parseCommand command.trim() if @["command#{capitalize(cmd.name)}"] @["command#{capitalize(cmd.name)}"](cmd) else @request cmd return greetings: => [ " __ _ _____ _ _ " "| | ___ ___ ___ _ _ ___| | |_ ____ ___ _____|_|___ ___| |" "| |__| .'| _| .'| | | -_| | | || -_| _| | | | .'| |" "|_____|__,|_| |__,|\\_/|___|_| |_||___|_| |_|_|_|_|_|_|__,|_|" "" "Copyright (c) 2015 PI:NAME:<NAME>END_PI <http://phpwrite.blogspot.tw/>" "" "Type a command, or type `#{@info('help')}`, for a list of commands." "" ].join "\n" serverInfo: => if @term.level() > 1 return host = @info "#{@options.username}@#{@options.hostname}" os = @question "#{@options.os}" path = @comment "#{@options.basePath}" @term.echo "#{host} #{os} #{path}" onInit: (term) => @term = term @execute 'list', term onClear: (term) => @serverInfo() constructor: (@element, @options)-> @element = $(@element) @element.terminal @execute, onInit: @onInit onClear: @onClear greetings: @greetings() prompt: @prompt win = $(window) win.on "resize", => @element.width(@element.parent().width()) @element.height(@element.parent().height()) win.trigger "resize"
[ { "context": "# Copyright 2015 SASAKI, Shunsuke. All rights reserved.\n#\n# Licensed under", "end": 23, "score": 0.9641577005386353, "start": 17, "tag": "NAME", "value": "SASAKI" }, { "context": "# Copyright 2015 SASAKI, Shunsuke. All rights reserved.\n#\n# Licensed under the Apac", ...
src/bit_array.coffee
erukiti/cerebrums
7
# Copyright 2015 SASAKI, Shunsuke. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class BitArray constructor: (size) -> @buf = new Buffer(Math.floor(size / 8) + 1) @buf.fill(0) @size = size @lergeCount = new Uint32Array(Math.floor(size / 8 / 64 + 1 + 1)) @smallCount = new Uint16Array(Math.floor(size / 8 / 8 + 1 + 1)) @dirty = false toString: () -> s = '' size = @size for byte in @buf bitmask = 0x80 while bitmask > 0 if byte & bitmask s += '1' else s += '0' bitmask >>>= 1 size-- return s if size <= 0 s get: (pos) -> n = @buf[Math.floor(pos / 8)] n & (128 >> (pos % 8)) ? 1 : 0 set0: (pos) -> n = @buf[Math.floor(pos / 8)] n &= 255 ^ (128 >> (pos % 8)) @buf.writeUInt8(n, Math.floor(pos / 8)) @dirty = true set1: (pos) -> # console.log "set1: #{pos}/#{@size}" n = @buf[Math.floor(pos / 8)] n |= 128 >> (pos % 8) @buf.writeUInt8(n, Math.floor(pos / 8)) @dirty = true _popcount_1byte = (n) -> # console.log "popcount:#{n.toString(2)}" n = ((n & 0xaa) >>> 1) + (n & 0x55) n = ((n & 0xcc) >>> 2) + (n & 0x33) n = ((n & 0xf0) >>> 4) + (n & 0x0f) n _popcount_4byte = (buf, p) -> n = buf.readUInt32LE(p) n = ((n & 0xaaaaaaaa) >>> 1) + (n & 0x55555555) n = ((n & 0xcccccccc) >>> 2) + (n & 0x33333333) n = ((n & 0xf0f0f0f0) >>> 4) + (n & 0x0f0f0f0f) n = ((n & 0xff00ff00) >>> 8) + (n & 0x00ff00ff) n = ((n & 0xffff0000) >>> 16) + (n & 0x0000ffff) n build: -> popCount = 0 ptr = 0 while ptr <= Math.floor(@size / 8) lergeCount = popCount @lergeCount[Math.floor(ptr / 64)] = lergeCount @smallCount[Math.floor(ptr / 8)] = 0 break unless ptr + 8 <= Math.floor(@size / 8) # console.log "ptr8" popCount += _popcount_4byte(@buf, ptr) popCount += _popcount_4byte(@buf, ptr + 4) @smallCount[Math.floor(ptr / 8) + 1] = popCount - lergeCount ptr += 8 break unless ptr + 8 <= Math.floor(@size / 8) # console.log "ptr16" popCount += _popcount_4byte(@buf, ptr) popCount += _popcount_4byte(@buf, ptr + 4) @smallCount[Math.floor(ptr / 8) + 1] = popCount - lergeCount ptr += 8 break unless ptr + 8 <= Math.floor(@size / 8) popCount += _popcount_4byte(@buf, ptr) popCount += _popcount_4byte(@buf, ptr + 4) @smallCount[Math.floor(ptr / 8) + 1] = popCount - lergeCount ptr += 8 break unless ptr + 8 <= Math.floor(@size / 8) popCount += _popcount_4byte(@buf, ptr) popCount += _popcount_4byte(@buf, ptr + 4) @smallCount[Math.floor(ptr / 8) + 1] = popCount - lergeCount ptr += 8 break unless ptr + 8 <= Math.floor(@size / 8) popCount += _popcount_4byte(@buf, ptr) popCount += _popcount_4byte(@buf, ptr + 4) @smallCount[Math.floor(ptr / 8) + 1] = popCount - lergeCount ptr += 8 break unless ptr + 8 <= Math.floor(@size / 8) popCount += _popcount_4byte(@buf, ptr) popCount += _popcount_4byte(@buf, ptr + 4) @smallCount[Math.floor(ptr / 8) + 1] = popCount - lergeCount ptr += 8 break unless ptr + 8 <= Math.floor(@size / 8) popCount += _popcount_4byte(@buf, ptr) popCount += _popcount_4byte(@buf, ptr + 4) @smallCount[Math.floor(ptr / 8) + 1] = popCount - lergeCount ptr += 8 break unless ptr + 8 <= Math.floor(@size / 8) popCount += _popcount_4byte(@buf, ptr) popCount += _popcount_4byte(@buf, ptr + 4) ptr += 8 @dirty = false rank0: (pos) -> # console.log "rank0:#{pos}" return 0 if pos == 0 @build() if @dirty pos-- popCount = Math.floor(pos / 8 / 64) * 8 * 64 - @lergeCount[Math.floor(pos / 8 / 64)] + Math.floor(pos / 8 / 8) % 8 * 8 * 8 - @smallCount[Math.floor(pos / 8 / 8)] popCount += 8 - _popcount_1byte(@buf[Math.floor(pos / 8 / 8) * 8 + 0]) if Math.floor(pos / 8) % 8 > 0 popCount += 8 - _popcount_1byte(@buf[Math.floor(pos / 8 / 8) * 8 + 1]) if Math.floor(pos / 8) % 8 > 1 popCount += 8 - _popcount_1byte(@buf[Math.floor(pos / 8 / 8) * 8 + 2]) if Math.floor(pos / 8) % 8 > 2 popCount += 8 - _popcount_1byte(@buf[Math.floor(pos / 8 / 8) * 8 + 3]) if Math.floor(pos / 8) % 8 > 3 popCount += 8 - _popcount_1byte(@buf[Math.floor(pos / 8 / 8) * 8 + 4]) if Math.floor(pos / 8) % 8 > 4 popCount += 8 - _popcount_1byte(@buf[Math.floor(pos / 8 / 8) * 8 + 5]) if Math.floor(pos / 8) % 8 > 5 popCount += 8 - _popcount_1byte(@buf[Math.floor(pos / 8 / 8) * 8 + 6]) if Math.floor(pos / 8) % 8 > 6 bitmask = ((255 << 8) >>> (pos % 8 + 1)) popCount += pos % 8 + 1 - _popcount_1byte(@buf[Math.floor(pos / 8)] & bitmask) popCount rank1: (pos) -> # console.log "rank1:#{pos}" return 0 if pos == 0 @build() if @dirty pos-- lergePos = Math.floor(pos / 8 / 64) smallPos = Math.floor(pos / 8 / 8) bufPos = Math.floor(pos / 8) popCount = @lergeCount[lergePos] + @smallCount[smallPos] popCount += _popcount_1byte(@buf[Math.floor(bufPos / 8) * 8 + 0]) if bufPos % 8 > 0 popCount += _popcount_1byte(@buf[Math.floor(bufPos / 8) * 8 + 1]) if bufPos % 8 > 1 popCount += _popcount_1byte(@buf[Math.floor(bufPos / 8) * 8 + 2]) if bufPos % 8 > 2 popCount += _popcount_1byte(@buf[Math.floor(bufPos / 8) * 8 + 3]) if bufPos % 8 > 3 popCount += _popcount_1byte(@buf[Math.floor(bufPos / 8) * 8 + 4]) if bufPos % 8 > 4 popCount += _popcount_1byte(@buf[Math.floor(bufPos / 8) * 8 + 5]) if bufPos % 8 > 5 popCount += _popcount_1byte(@buf[Math.floor(bufPos / 8) * 8 + 6]) if bufPos % 8 > 6 bitmask = ((255 << 8) >>> (pos % 8 + 1)) popCount += _popcount_1byte(@buf[Math.floor(pos / 8)] & bitmask) popCount rank: (pos, bit) -> if bit rank1(pos) else rank0(pos) select: (ind, bit) -> # console.log "select #{ind}, #{bit}" throw new Error "index #{ind} is error." if ind < 0 left = 0 right = Math.floor(@size / 8 / 64) if left == right right++ # console.dir @lergeCount # console.log "lerge: #{left}, #{right}" while left < right ptr = Math.floor((left + right) / 2) if bit rank = @lergeCount[ptr] else rank = ptr * 8 * 64 - @lergeCount[ptr] if ind <= rank right = ptr else left = ptr + 1 right-- if bit ind -= @lergeCount[right] else ind -= right * 8 * 64 - @lergeCount[right] posSmall = right * 8 + Math.floor(@size / 8 / 8) % 8 while posSmall >= right * 8 if bit rank = @smallCount[posSmall] else rank = (posSmall % 8) * 8 * 8 - @smallCount[posSmall] if ind > rank ind -= rank break posSmall-- if posSmall < right * 8 posSmall = right * 8 pos = posSmall * 8 # console.log "-- #{ind}, #{pos}" cnt = 0 while ind > 0 && pos * 8 < @size n = @buf[pos] bitmask = 0x80 cnt = 0 # console.log n.toString(2) while bitmask > 0 # console.log "*#{ind}, #{cnt}" # console.dir (n & bitmask).toString(2) if (bit && n & bitmask) || (!bit && (n & bitmask) == 0) ind-- break if ind == 0 bitmask >>>= 1 cnt++ break if ind == 0 pos++ pos * 8 + cnt select0: (ind) -> @select(ind, 0) select1: (ind) -> @select(ind, 1) module.exports = BitArray
27940
# Copyright 2015 <NAME>, <NAME>. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class BitArray constructor: (size) -> @buf = new Buffer(Math.floor(size / 8) + 1) @buf.fill(0) @size = size @lergeCount = new Uint32Array(Math.floor(size / 8 / 64 + 1 + 1)) @smallCount = new Uint16Array(Math.floor(size / 8 / 8 + 1 + 1)) @dirty = false toString: () -> s = '' size = @size for byte in @buf bitmask = 0x80 while bitmask > 0 if byte & bitmask s += '1' else s += '0' bitmask >>>= 1 size-- return s if size <= 0 s get: (pos) -> n = @buf[Math.floor(pos / 8)] n & (128 >> (pos % 8)) ? 1 : 0 set0: (pos) -> n = @buf[Math.floor(pos / 8)] n &= 255 ^ (128 >> (pos % 8)) @buf.writeUInt8(n, Math.floor(pos / 8)) @dirty = true set1: (pos) -> # console.log "set1: #{pos}/#{@size}" n = @buf[Math.floor(pos / 8)] n |= 128 >> (pos % 8) @buf.writeUInt8(n, Math.floor(pos / 8)) @dirty = true _popcount_1byte = (n) -> # console.log "popcount:#{n.toString(2)}" n = ((n & 0xaa) >>> 1) + (n & 0x55) n = ((n & 0xcc) >>> 2) + (n & 0x33) n = ((n & 0xf0) >>> 4) + (n & 0x0f) n _popcount_4byte = (buf, p) -> n = buf.readUInt32LE(p) n = ((n & 0xaaaaaaaa) >>> 1) + (n & 0x55555555) n = ((n & 0xcccccccc) >>> 2) + (n & 0x33333333) n = ((n & 0xf0f0f0f0) >>> 4) + (n & 0x0f0f0f0f) n = ((n & 0xff00ff00) >>> 8) + (n & 0x00ff00ff) n = ((n & 0xffff0000) >>> 16) + (n & 0x0000ffff) n build: -> popCount = 0 ptr = 0 while ptr <= Math.floor(@size / 8) lergeCount = popCount @lergeCount[Math.floor(ptr / 64)] = lergeCount @smallCount[Math.floor(ptr / 8)] = 0 break unless ptr + 8 <= Math.floor(@size / 8) # console.log "ptr8" popCount += _popcount_4byte(@buf, ptr) popCount += _popcount_4byte(@buf, ptr + 4) @smallCount[Math.floor(ptr / 8) + 1] = popCount - lergeCount ptr += 8 break unless ptr + 8 <= Math.floor(@size / 8) # console.log "ptr16" popCount += _popcount_4byte(@buf, ptr) popCount += _popcount_4byte(@buf, ptr + 4) @smallCount[Math.floor(ptr / 8) + 1] = popCount - lergeCount ptr += 8 break unless ptr + 8 <= Math.floor(@size / 8) popCount += _popcount_4byte(@buf, ptr) popCount += _popcount_4byte(@buf, ptr + 4) @smallCount[Math.floor(ptr / 8) + 1] = popCount - lergeCount ptr += 8 break unless ptr + 8 <= Math.floor(@size / 8) popCount += _popcount_4byte(@buf, ptr) popCount += _popcount_4byte(@buf, ptr + 4) @smallCount[Math.floor(ptr / 8) + 1] = popCount - lergeCount ptr += 8 break unless ptr + 8 <= Math.floor(@size / 8) popCount += _popcount_4byte(@buf, ptr) popCount += _popcount_4byte(@buf, ptr + 4) @smallCount[Math.floor(ptr / 8) + 1] = popCount - lergeCount ptr += 8 break unless ptr + 8 <= Math.floor(@size / 8) popCount += _popcount_4byte(@buf, ptr) popCount += _popcount_4byte(@buf, ptr + 4) @smallCount[Math.floor(ptr / 8) + 1] = popCount - lergeCount ptr += 8 break unless ptr + 8 <= Math.floor(@size / 8) popCount += _popcount_4byte(@buf, ptr) popCount += _popcount_4byte(@buf, ptr + 4) @smallCount[Math.floor(ptr / 8) + 1] = popCount - lergeCount ptr += 8 break unless ptr + 8 <= Math.floor(@size / 8) popCount += _popcount_4byte(@buf, ptr) popCount += _popcount_4byte(@buf, ptr + 4) ptr += 8 @dirty = false rank0: (pos) -> # console.log "rank0:#{pos}" return 0 if pos == 0 @build() if @dirty pos-- popCount = Math.floor(pos / 8 / 64) * 8 * 64 - @lergeCount[Math.floor(pos / 8 / 64)] + Math.floor(pos / 8 / 8) % 8 * 8 * 8 - @smallCount[Math.floor(pos / 8 / 8)] popCount += 8 - _popcount_1byte(@buf[Math.floor(pos / 8 / 8) * 8 + 0]) if Math.floor(pos / 8) % 8 > 0 popCount += 8 - _popcount_1byte(@buf[Math.floor(pos / 8 / 8) * 8 + 1]) if Math.floor(pos / 8) % 8 > 1 popCount += 8 - _popcount_1byte(@buf[Math.floor(pos / 8 / 8) * 8 + 2]) if Math.floor(pos / 8) % 8 > 2 popCount += 8 - _popcount_1byte(@buf[Math.floor(pos / 8 / 8) * 8 + 3]) if Math.floor(pos / 8) % 8 > 3 popCount += 8 - _popcount_1byte(@buf[Math.floor(pos / 8 / 8) * 8 + 4]) if Math.floor(pos / 8) % 8 > 4 popCount += 8 - _popcount_1byte(@buf[Math.floor(pos / 8 / 8) * 8 + 5]) if Math.floor(pos / 8) % 8 > 5 popCount += 8 - _popcount_1byte(@buf[Math.floor(pos / 8 / 8) * 8 + 6]) if Math.floor(pos / 8) % 8 > 6 bitmask = ((255 << 8) >>> (pos % 8 + 1)) popCount += pos % 8 + 1 - _popcount_1byte(@buf[Math.floor(pos / 8)] & bitmask) popCount rank1: (pos) -> # console.log "rank1:#{pos}" return 0 if pos == 0 @build() if @dirty pos-- lergePos = Math.floor(pos / 8 / 64) smallPos = Math.floor(pos / 8 / 8) bufPos = Math.floor(pos / 8) popCount = @lergeCount[lergePos] + @smallCount[smallPos] popCount += _popcount_1byte(@buf[Math.floor(bufPos / 8) * 8 + 0]) if bufPos % 8 > 0 popCount += _popcount_1byte(@buf[Math.floor(bufPos / 8) * 8 + 1]) if bufPos % 8 > 1 popCount += _popcount_1byte(@buf[Math.floor(bufPos / 8) * 8 + 2]) if bufPos % 8 > 2 popCount += _popcount_1byte(@buf[Math.floor(bufPos / 8) * 8 + 3]) if bufPos % 8 > 3 popCount += _popcount_1byte(@buf[Math.floor(bufPos / 8) * 8 + 4]) if bufPos % 8 > 4 popCount += _popcount_1byte(@buf[Math.floor(bufPos / 8) * 8 + 5]) if bufPos % 8 > 5 popCount += _popcount_1byte(@buf[Math.floor(bufPos / 8) * 8 + 6]) if bufPos % 8 > 6 bitmask = ((255 << 8) >>> (pos % 8 + 1)) popCount += _popcount_1byte(@buf[Math.floor(pos / 8)] & bitmask) popCount rank: (pos, bit) -> if bit rank1(pos) else rank0(pos) select: (ind, bit) -> # console.log "select #{ind}, #{bit}" throw new Error "index #{ind} is error." if ind < 0 left = 0 right = Math.floor(@size / 8 / 64) if left == right right++ # console.dir @lergeCount # console.log "lerge: #{left}, #{right}" while left < right ptr = Math.floor((left + right) / 2) if bit rank = @lergeCount[ptr] else rank = ptr * 8 * 64 - @lergeCount[ptr] if ind <= rank right = ptr else left = ptr + 1 right-- if bit ind -= @lergeCount[right] else ind -= right * 8 * 64 - @lergeCount[right] posSmall = right * 8 + Math.floor(@size / 8 / 8) % 8 while posSmall >= right * 8 if bit rank = @smallCount[posSmall] else rank = (posSmall % 8) * 8 * 8 - @smallCount[posSmall] if ind > rank ind -= rank break posSmall-- if posSmall < right * 8 posSmall = right * 8 pos = posSmall * 8 # console.log "-- #{ind}, #{pos}" cnt = 0 while ind > 0 && pos * 8 < @size n = @buf[pos] bitmask = 0x80 cnt = 0 # console.log n.toString(2) while bitmask > 0 # console.log "*#{ind}, #{cnt}" # console.dir (n & bitmask).toString(2) if (bit && n & bitmask) || (!bit && (n & bitmask) == 0) ind-- break if ind == 0 bitmask >>>= 1 cnt++ break if ind == 0 pos++ pos * 8 + cnt select0: (ind) -> @select(ind, 0) select1: (ind) -> @select(ind, 1) module.exports = BitArray
true
# Copyright 2015 PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class BitArray constructor: (size) -> @buf = new Buffer(Math.floor(size / 8) + 1) @buf.fill(0) @size = size @lergeCount = new Uint32Array(Math.floor(size / 8 / 64 + 1 + 1)) @smallCount = new Uint16Array(Math.floor(size / 8 / 8 + 1 + 1)) @dirty = false toString: () -> s = '' size = @size for byte in @buf bitmask = 0x80 while bitmask > 0 if byte & bitmask s += '1' else s += '0' bitmask >>>= 1 size-- return s if size <= 0 s get: (pos) -> n = @buf[Math.floor(pos / 8)] n & (128 >> (pos % 8)) ? 1 : 0 set0: (pos) -> n = @buf[Math.floor(pos / 8)] n &= 255 ^ (128 >> (pos % 8)) @buf.writeUInt8(n, Math.floor(pos / 8)) @dirty = true set1: (pos) -> # console.log "set1: #{pos}/#{@size}" n = @buf[Math.floor(pos / 8)] n |= 128 >> (pos % 8) @buf.writeUInt8(n, Math.floor(pos / 8)) @dirty = true _popcount_1byte = (n) -> # console.log "popcount:#{n.toString(2)}" n = ((n & 0xaa) >>> 1) + (n & 0x55) n = ((n & 0xcc) >>> 2) + (n & 0x33) n = ((n & 0xf0) >>> 4) + (n & 0x0f) n _popcount_4byte = (buf, p) -> n = buf.readUInt32LE(p) n = ((n & 0xaaaaaaaa) >>> 1) + (n & 0x55555555) n = ((n & 0xcccccccc) >>> 2) + (n & 0x33333333) n = ((n & 0xf0f0f0f0) >>> 4) + (n & 0x0f0f0f0f) n = ((n & 0xff00ff00) >>> 8) + (n & 0x00ff00ff) n = ((n & 0xffff0000) >>> 16) + (n & 0x0000ffff) n build: -> popCount = 0 ptr = 0 while ptr <= Math.floor(@size / 8) lergeCount = popCount @lergeCount[Math.floor(ptr / 64)] = lergeCount @smallCount[Math.floor(ptr / 8)] = 0 break unless ptr + 8 <= Math.floor(@size / 8) # console.log "ptr8" popCount += _popcount_4byte(@buf, ptr) popCount += _popcount_4byte(@buf, ptr + 4) @smallCount[Math.floor(ptr / 8) + 1] = popCount - lergeCount ptr += 8 break unless ptr + 8 <= Math.floor(@size / 8) # console.log "ptr16" popCount += _popcount_4byte(@buf, ptr) popCount += _popcount_4byte(@buf, ptr + 4) @smallCount[Math.floor(ptr / 8) + 1] = popCount - lergeCount ptr += 8 break unless ptr + 8 <= Math.floor(@size / 8) popCount += _popcount_4byte(@buf, ptr) popCount += _popcount_4byte(@buf, ptr + 4) @smallCount[Math.floor(ptr / 8) + 1] = popCount - lergeCount ptr += 8 break unless ptr + 8 <= Math.floor(@size / 8) popCount += _popcount_4byte(@buf, ptr) popCount += _popcount_4byte(@buf, ptr + 4) @smallCount[Math.floor(ptr / 8) + 1] = popCount - lergeCount ptr += 8 break unless ptr + 8 <= Math.floor(@size / 8) popCount += _popcount_4byte(@buf, ptr) popCount += _popcount_4byte(@buf, ptr + 4) @smallCount[Math.floor(ptr / 8) + 1] = popCount - lergeCount ptr += 8 break unless ptr + 8 <= Math.floor(@size / 8) popCount += _popcount_4byte(@buf, ptr) popCount += _popcount_4byte(@buf, ptr + 4) @smallCount[Math.floor(ptr / 8) + 1] = popCount - lergeCount ptr += 8 break unless ptr + 8 <= Math.floor(@size / 8) popCount += _popcount_4byte(@buf, ptr) popCount += _popcount_4byte(@buf, ptr + 4) @smallCount[Math.floor(ptr / 8) + 1] = popCount - lergeCount ptr += 8 break unless ptr + 8 <= Math.floor(@size / 8) popCount += _popcount_4byte(@buf, ptr) popCount += _popcount_4byte(@buf, ptr + 4) ptr += 8 @dirty = false rank0: (pos) -> # console.log "rank0:#{pos}" return 0 if pos == 0 @build() if @dirty pos-- popCount = Math.floor(pos / 8 / 64) * 8 * 64 - @lergeCount[Math.floor(pos / 8 / 64)] + Math.floor(pos / 8 / 8) % 8 * 8 * 8 - @smallCount[Math.floor(pos / 8 / 8)] popCount += 8 - _popcount_1byte(@buf[Math.floor(pos / 8 / 8) * 8 + 0]) if Math.floor(pos / 8) % 8 > 0 popCount += 8 - _popcount_1byte(@buf[Math.floor(pos / 8 / 8) * 8 + 1]) if Math.floor(pos / 8) % 8 > 1 popCount += 8 - _popcount_1byte(@buf[Math.floor(pos / 8 / 8) * 8 + 2]) if Math.floor(pos / 8) % 8 > 2 popCount += 8 - _popcount_1byte(@buf[Math.floor(pos / 8 / 8) * 8 + 3]) if Math.floor(pos / 8) % 8 > 3 popCount += 8 - _popcount_1byte(@buf[Math.floor(pos / 8 / 8) * 8 + 4]) if Math.floor(pos / 8) % 8 > 4 popCount += 8 - _popcount_1byte(@buf[Math.floor(pos / 8 / 8) * 8 + 5]) if Math.floor(pos / 8) % 8 > 5 popCount += 8 - _popcount_1byte(@buf[Math.floor(pos / 8 / 8) * 8 + 6]) if Math.floor(pos / 8) % 8 > 6 bitmask = ((255 << 8) >>> (pos % 8 + 1)) popCount += pos % 8 + 1 - _popcount_1byte(@buf[Math.floor(pos / 8)] & bitmask) popCount rank1: (pos) -> # console.log "rank1:#{pos}" return 0 if pos == 0 @build() if @dirty pos-- lergePos = Math.floor(pos / 8 / 64) smallPos = Math.floor(pos / 8 / 8) bufPos = Math.floor(pos / 8) popCount = @lergeCount[lergePos] + @smallCount[smallPos] popCount += _popcount_1byte(@buf[Math.floor(bufPos / 8) * 8 + 0]) if bufPos % 8 > 0 popCount += _popcount_1byte(@buf[Math.floor(bufPos / 8) * 8 + 1]) if bufPos % 8 > 1 popCount += _popcount_1byte(@buf[Math.floor(bufPos / 8) * 8 + 2]) if bufPos % 8 > 2 popCount += _popcount_1byte(@buf[Math.floor(bufPos / 8) * 8 + 3]) if bufPos % 8 > 3 popCount += _popcount_1byte(@buf[Math.floor(bufPos / 8) * 8 + 4]) if bufPos % 8 > 4 popCount += _popcount_1byte(@buf[Math.floor(bufPos / 8) * 8 + 5]) if bufPos % 8 > 5 popCount += _popcount_1byte(@buf[Math.floor(bufPos / 8) * 8 + 6]) if bufPos % 8 > 6 bitmask = ((255 << 8) >>> (pos % 8 + 1)) popCount += _popcount_1byte(@buf[Math.floor(pos / 8)] & bitmask) popCount rank: (pos, bit) -> if bit rank1(pos) else rank0(pos) select: (ind, bit) -> # console.log "select #{ind}, #{bit}" throw new Error "index #{ind} is error." if ind < 0 left = 0 right = Math.floor(@size / 8 / 64) if left == right right++ # console.dir @lergeCount # console.log "lerge: #{left}, #{right}" while left < right ptr = Math.floor((left + right) / 2) if bit rank = @lergeCount[ptr] else rank = ptr * 8 * 64 - @lergeCount[ptr] if ind <= rank right = ptr else left = ptr + 1 right-- if bit ind -= @lergeCount[right] else ind -= right * 8 * 64 - @lergeCount[right] posSmall = right * 8 + Math.floor(@size / 8 / 8) % 8 while posSmall >= right * 8 if bit rank = @smallCount[posSmall] else rank = (posSmall % 8) * 8 * 8 - @smallCount[posSmall] if ind > rank ind -= rank break posSmall-- if posSmall < right * 8 posSmall = right * 8 pos = posSmall * 8 # console.log "-- #{ind}, #{pos}" cnt = 0 while ind > 0 && pos * 8 < @size n = @buf[pos] bitmask = 0x80 cnt = 0 # console.log n.toString(2) while bitmask > 0 # console.log "*#{ind}, #{cnt}" # console.dir (n & bitmask).toString(2) if (bit && n & bitmask) || (!bit && (n & bitmask) == 0) ind-- break if ind == 0 bitmask >>>= 1 cnt++ break if ind == 0 pos++ pos * 8 + cnt select0: (ind) -> @select(ind, 0) select1: (ind) -> @select(ind, 1) module.exports = BitArray
[ { "context": "###\n * @author \t\tAbdelhakim RAFIK\n * @version \tv1.0.1\n * @license \tMIT License\n * @", "end": 33, "score": 0.9998902678489685, "start": 17, "tag": "NAME", "value": "Abdelhakim RAFIK" }, { "context": "nse \tMIT License\n * @copyright \tCopyright (c) 2021 Abdelhaki...
src/routes/index.coffee
AbdelhakimRafik/Project
1
### * @author Abdelhakim RAFIK * @version v1.0.1 * @license MIT License * @copyright Copyright (c) 2021 Abdelhakim RAFIK * @date June 2021 ### { Router } = require 'express' authMiddleware = require '../app/middlewares/authMiddleware' publicRouter = do Router privateRouter = do Router module.exports = (app) -> # authentication routes require('./authRouter')(publicRouter) # user routes require('./userRouter')(privateRouter) # set app routers app.use '/api', publicRouter # protect privateRouter with authentication middleware app.use '/api', authMiddleware, privateRouter
74158
### * @author <NAME> * @version v1.0.1 * @license MIT License * @copyright Copyright (c) 2021 <NAME> * @date June 2021 ### { Router } = require 'express' authMiddleware = require '../app/middlewares/authMiddleware' publicRouter = do Router privateRouter = do Router module.exports = (app) -> # authentication routes require('./authRouter')(publicRouter) # user routes require('./userRouter')(privateRouter) # set app routers app.use '/api', publicRouter # protect privateRouter with authentication middleware app.use '/api', authMiddleware, privateRouter
true
### * @author PI:NAME:<NAME>END_PI * @version v1.0.1 * @license MIT License * @copyright Copyright (c) 2021 PI:NAME:<NAME>END_PI * @date June 2021 ### { Router } = require 'express' authMiddleware = require '../app/middlewares/authMiddleware' publicRouter = do Router privateRouter = do Router module.exports = (app) -> # authentication routes require('./authRouter')(publicRouter) # user routes require('./userRouter')(privateRouter) # set app routers app.use '/api', publicRouter # protect privateRouter with authentication middleware app.use '/api', authMiddleware, privateRouter
[ { "context": "lastActivity = 0\n params =\n jid: \"-#{facebookId}@chat.facebook.com\"\n api_key: Conf.clientID\n s", "end": 641, "score": 0.9121357202529907, "start": 608, "tag": "EMAIL", "value": "\"-#{facebookId}@chat.facebook.com" }, { "cont...
src/server/notification/transport/facebook-xmpp/index.coffee
LaPingvino/rizzoma
88
_ = require('underscore') xmpp = require('node-xmpp') NotificationTransport = require('../').NotificationTransport Conf = require('../../../conf').Conf logger = Conf.getLogger('notification') Conf = Conf.getAuthConf().facebook NOTIFICATOR_TRANSPORT_FACEBOOK_XMPP = require('../../constants').NOTIFICATOR_TRANSPORT_FACEBOOK_XMPP PING_TIMEPOT = 21 * 1000 CONNECTION_TTL = 3 * 60 * 1000 class Connection constructor: (facebookId, token, errback=->) -> @_pingTimerHandler = null @_isOnline = false @_messageQueue = [] @_lastActivity = 0 params = jid: "-#{facebookId}@chat.facebook.com" api_key: Conf.clientID secret_key: Conf.clientSecret access_token: token @_client = new xmpp.Client(params) @_client.on('online', @_onOnline) @_client.on('stanza', (stanza) -> if stanza.name == "iq" and stanza.type == 'set' and stanza.to meta = transport: NOTIFICATOR_TRANSPORT_FACEBOOK_XMPP to: stanza.to fromFacebookId: facebookId logger.debug("Notification by '#{NOTIFICATOR_TRANSPORT_FACEBOOK_XMPP}' to #{stanza.to} has been delivered", meta) ) @_client.on('error', (err) => @destroy() errback(err) ) send: (facebookId, text) -> to = {to: "-#{facebookId}@chat.facebook.com", type: 'chat'} message = new xmpp.Element('message', to).c('body').t(text).up() @_messageQueue.push(message) @_flushQueue() @_lastActivity = Date.now() getLastActivity: () -> return @_lastActivity destroy: () -> @_isOnline = false clearInterval(@_pingTimerHandler) @_client.end() _onOnline: () => presence = new xmpp.Element('presence') @_client.send(presence) ping = () => return if not @_isOnline try @_client.send(presence) catch err logger.error("Facebook xmpp ping error: #{err}") @_pingTimerHandler = setInterval(ping, PING_TIMEPOT) ready = () => @_isOnline = true @_flushQueue() setTimeout(ready, 2000) _flushQueue: () => return if not @_isOnline while @_messageQueue.length message = @_messageQueue.shift() @_client.send(message) class FacebookXmppTransport extends NotificationTransport ### Уведомитель через xmpp ### constructor: (xmppConf) -> super(xmppConf) @_connections = {} setInterval(@_destroyConnections, CONNECTION_TTL) getName: () -> NOTIFICATOR_TRANSPORT_FACEBOOK_XMPP @getCommunicationType: () -> return "facebook-xmpp" notificateUser: (user, type, context, callback) -> super(user, type, context, callback) fromFacebookId = context.from.getExternalIds().facebook toFacebookId = context.contacts.getContact(user.email)[0].externalId token = context.contacts.getSourceData('facebook').accessToken templateName = @_getTemplate(type, true, '.txt') @_renderMessage(templateName, context, (err, message) => return callback(err) if err @_getConnection(fromFacebookId, token).send(toFacebookId, message) isNewUser = if user.firstVisit then "existing user" else "new user" meta = transport: @getName() type: type from: context.from.email or fromFacebookId to: user.email or toFacebookId subject: message isNewUser: isNewUser success: true callback(null, meta) ) _getTemplatePath: (templateName) -> return "#{super()}facebook-xmpp/#{templateName}" _getConnection: (facebookId, token) -> @_connections[facebookId] ||= new Connection(facebookId, token, (err) => @_logger.error("Facebook-xmpp transport error: #{err}") ) return @_connections[facebookId] _destroyConnections: () => now = Date.now() ids = _.keys(@_connections) for id in ids connection = @_connections[id] continue if now - connection.getLastActivity() < CONNECTION_TTL connection.destroy() delete @_connections[id] module.exports.FacebookXmppTransport = FacebookXmppTransport
23818
_ = require('underscore') xmpp = require('node-xmpp') NotificationTransport = require('../').NotificationTransport Conf = require('../../../conf').Conf logger = Conf.getLogger('notification') Conf = Conf.getAuthConf().facebook NOTIFICATOR_TRANSPORT_FACEBOOK_XMPP = require('../../constants').NOTIFICATOR_TRANSPORT_FACEBOOK_XMPP PING_TIMEPOT = 21 * 1000 CONNECTION_TTL = 3 * 60 * 1000 class Connection constructor: (facebookId, token, errback=->) -> @_pingTimerHandler = null @_isOnline = false @_messageQueue = [] @_lastActivity = 0 params = jid: <EMAIL>" api_key: Conf.clientID secret_key: Conf.clientSecret access_token: token @_client = new xmpp.Client(params) @_client.on('online', @_onOnline) @_client.on('stanza', (stanza) -> if stanza.name == "iq" and stanza.type == 'set' and stanza.to meta = transport: NOTIFICATOR_TRANSPORT_FACEBOOK_XMPP to: stanza.to fromFacebookId: facebookId logger.debug("Notification by '#{NOTIFICATOR_TRANSPORT_FACEBOOK_XMPP}' to #{stanza.to} has been delivered", meta) ) @_client.on('error', (err) => @destroy() errback(err) ) send: (facebookId, text) -> to = {to: <EMAIL>", type: 'chat'} message = new xmpp.Element('message', to).c('body').t(text).up() @_messageQueue.push(message) @_flushQueue() @_lastActivity = Date.now() getLastActivity: () -> return @_lastActivity destroy: () -> @_isOnline = false clearInterval(@_pingTimerHandler) @_client.end() _onOnline: () => presence = new xmpp.Element('presence') @_client.send(presence) ping = () => return if not @_isOnline try @_client.send(presence) catch err logger.error("Facebook xmpp ping error: #{err}") @_pingTimerHandler = setInterval(ping, PING_TIMEPOT) ready = () => @_isOnline = true @_flushQueue() setTimeout(ready, 2000) _flushQueue: () => return if not @_isOnline while @_messageQueue.length message = @_messageQueue.shift() @_client.send(message) class FacebookXmppTransport extends NotificationTransport ### Уведомитель через xmpp ### constructor: (xmppConf) -> super(xmppConf) @_connections = {} setInterval(@_destroyConnections, CONNECTION_TTL) getName: () -> NOTIFICATOR_TRANSPORT_FACEBOOK_XMPP @getCommunicationType: () -> return "facebook-xmpp" notificateUser: (user, type, context, callback) -> super(user, type, context, callback) fromFacebookId = context.from.getExternalIds().facebook toFacebookId = context.contacts.getContact(user.email)[0].externalId token = context.contacts.getSourceData('facebook').accessToken templateName = @_getTemplate(type, true, '.txt') @_renderMessage(templateName, context, (err, message) => return callback(err) if err @_getConnection(fromFacebookId, token).send(toFacebookId, message) isNewUser = if user.firstVisit then "existing user" else "new user" meta = transport: @getName() type: type from: context.from.email or fromFacebookId to: user.email or toFacebookId subject: message isNewUser: isNewUser success: true callback(null, meta) ) _getTemplatePath: (templateName) -> return "#{super()}facebook-xmpp/#{templateName}" _getConnection: (facebookId, token) -> @_connections[facebookId] ||= new Connection(facebookId, token, (err) => @_logger.error("Facebook-xmpp transport error: #{err}") ) return @_connections[facebookId] _destroyConnections: () => now = Date.now() ids = _.keys(@_connections) for id in ids connection = @_connections[id] continue if now - connection.getLastActivity() < CONNECTION_TTL connection.destroy() delete @_connections[id] module.exports.FacebookXmppTransport = FacebookXmppTransport
true
_ = require('underscore') xmpp = require('node-xmpp') NotificationTransport = require('../').NotificationTransport Conf = require('../../../conf').Conf logger = Conf.getLogger('notification') Conf = Conf.getAuthConf().facebook NOTIFICATOR_TRANSPORT_FACEBOOK_XMPP = require('../../constants').NOTIFICATOR_TRANSPORT_FACEBOOK_XMPP PING_TIMEPOT = 21 * 1000 CONNECTION_TTL = 3 * 60 * 1000 class Connection constructor: (facebookId, token, errback=->) -> @_pingTimerHandler = null @_isOnline = false @_messageQueue = [] @_lastActivity = 0 params = jid: PI:EMAIL:<EMAIL>END_PI" api_key: Conf.clientID secret_key: Conf.clientSecret access_token: token @_client = new xmpp.Client(params) @_client.on('online', @_onOnline) @_client.on('stanza', (stanza) -> if stanza.name == "iq" and stanza.type == 'set' and stanza.to meta = transport: NOTIFICATOR_TRANSPORT_FACEBOOK_XMPP to: stanza.to fromFacebookId: facebookId logger.debug("Notification by '#{NOTIFICATOR_TRANSPORT_FACEBOOK_XMPP}' to #{stanza.to} has been delivered", meta) ) @_client.on('error', (err) => @destroy() errback(err) ) send: (facebookId, text) -> to = {to: PI:EMAIL:<EMAIL>END_PI", type: 'chat'} message = new xmpp.Element('message', to).c('body').t(text).up() @_messageQueue.push(message) @_flushQueue() @_lastActivity = Date.now() getLastActivity: () -> return @_lastActivity destroy: () -> @_isOnline = false clearInterval(@_pingTimerHandler) @_client.end() _onOnline: () => presence = new xmpp.Element('presence') @_client.send(presence) ping = () => return if not @_isOnline try @_client.send(presence) catch err logger.error("Facebook xmpp ping error: #{err}") @_pingTimerHandler = setInterval(ping, PING_TIMEPOT) ready = () => @_isOnline = true @_flushQueue() setTimeout(ready, 2000) _flushQueue: () => return if not @_isOnline while @_messageQueue.length message = @_messageQueue.shift() @_client.send(message) class FacebookXmppTransport extends NotificationTransport ### Уведомитель через xmpp ### constructor: (xmppConf) -> super(xmppConf) @_connections = {} setInterval(@_destroyConnections, CONNECTION_TTL) getName: () -> NOTIFICATOR_TRANSPORT_FACEBOOK_XMPP @getCommunicationType: () -> return "facebook-xmpp" notificateUser: (user, type, context, callback) -> super(user, type, context, callback) fromFacebookId = context.from.getExternalIds().facebook toFacebookId = context.contacts.getContact(user.email)[0].externalId token = context.contacts.getSourceData('facebook').accessToken templateName = @_getTemplate(type, true, '.txt') @_renderMessage(templateName, context, (err, message) => return callback(err) if err @_getConnection(fromFacebookId, token).send(toFacebookId, message) isNewUser = if user.firstVisit then "existing user" else "new user" meta = transport: @getName() type: type from: context.from.email or fromFacebookId to: user.email or toFacebookId subject: message isNewUser: isNewUser success: true callback(null, meta) ) _getTemplatePath: (templateName) -> return "#{super()}facebook-xmpp/#{templateName}" _getConnection: (facebookId, token) -> @_connections[facebookId] ||= new Connection(facebookId, token, (err) => @_logger.error("Facebook-xmpp transport error: #{err}") ) return @_connections[facebookId] _destroyConnections: () => now = Date.now() ids = _.keys(@_connections) for id in ids connection = @_connections[id] continue if now - connection.getLastActivity() < CONNECTION_TTL connection.destroy() delete @_connections[id] module.exports.FacebookXmppTransport = FacebookXmppTransport
[ { "context": " yield utils.clearModels([User, Classroom])\n @user1 = yield utils.initUser()\n yield utils.loginUse", "end": 964, "score": 0.7217044830322266, "start": 958, "tag": "USERNAME", "value": "@user1" }, { "context": "= yield utils.initUser()\n yield utils.loginUs...
spec/server/functional/classrooms.spec.coffee
mcgilvrayb/codecombat
0
config = require '../../../server_config' require '../common' clientUtils = require '../../../app/core/utils' # Must come after require /common utils = require '../utils' _ = require 'lodash' Promise = require 'bluebird' request = require '../request' requestAsync = Promise.promisify(request, {multiArgs: true}) User = require '../../../server/models/User' Classroom = require '../../../server/models/Classroom' Course = require '../../../server/models/Course' CourseInstance = require '../../../server/models/CourseInstance' Campaign = require '../../../server/models/Campaign' LevelSession = require '../../../server/models/LevelSession' Level = require '../../../server/models/Level' mongoose = require 'mongoose' subscriptions = require '../../../server/middleware/subscriptions' classroomsURL = getURL('/db/classroom') describe 'GET /db/classroom?ownerID=:id', -> beforeEach utils.wrap (done) -> yield utils.clearModels([User, Classroom]) @user1 = yield utils.initUser() yield utils.loginUser(@user1) @classroom1 = yield new Classroom({name: 'Classroom 1', ownerID: @user1.get('_id') }).save() @user2 = yield utils.initUser() yield utils.loginUser(@user2) @classroom2 = yield new Classroom({name: 'Classroom 2', ownerID: @user2.get('_id') }).save() done() it 'returns an array of classrooms with the given owner', utils.wrap (done) -> [res, body] = yield request.getAsync getURL('/db/classroom?ownerID='+@user2.id), { json: true } expect(res.statusCode).toBe(200) expect(body.length).toBe(1) expect(body[0].name).toBe('Classroom 2') done() it 'returns 403 when a non-admin tries to get classrooms for another user', utils.wrap (done) -> [res, body] = yield request.getAsync getURL('/db/classroom?ownerID='+@user1.id), { json: true } expect(res.statusCode).toBe(403) done() describe 'GET /db/classroom/:id', -> it 'clears database users and classrooms', (done) -> clearModels [User, Classroom, Course, Campaign], (err) -> throw err if err done() it 'returns the classroom for the given id', (done) -> loginNewUser (user1) -> user1.set('role', 'teacher') user1.save (err) -> data = { name: 'Classroom 1' } request.post {uri: classroomsURL, json: data }, (err, res, body) -> expect(res.statusCode).toBe(201) classroomID = body._id request.get {uri: classroomsURL + '/' + body._id }, (err, res, body) -> expect(res.statusCode).toBe(200) expect(body._id).toBe(classroomID = body._id) done() describe 'GET /db/classroom by classCode', -> it 'Returns the class if you include spaces', utils.wrap (done) -> user = yield utils.initUser() yield utils.loginUser(user) teacher = yield utils.initUser() classroom = new Classroom({ name: "some class", ownerID: teacher.id, camelCode: "FooBarBaz", code: "foobarbaz" }) yield classroom.save() [res, body] = yield request.getAsync(getURL('/db/classroom?code=foo bar baz'), { json: true }) expect(res.statusCode).toBe(200) expect(res.body.data?.name).toBe(classroom.get('name')) done() describe 'POST /db/classroom', -> beforeEach utils.wrap (done) -> yield utils.clearModels [User, Classroom, Course, Level, Campaign] admin = yield utils.initAdmin() yield utils.loginUser(admin) levelJSONA = { name: 'Level A', permissions: [{access: 'owner', target: admin.id}], type: 'course' } [res, body] = yield request.postAsync({uri: getURL('/db/level'), json: levelJSONA}) expect(res.statusCode).toBe(200) @levelA = yield Level.findById(res.body._id) levelJSONB = { name: 'Level B', permissions: [{access: 'owner', target: admin.id}], type: 'course' } [res, body] = yield request.postAsync({uri: getURL('/db/level'), json: levelJSONB}) expect(res.statusCode).toBe(200) @levelB = yield Level.findById(res.body._id) levelJSONC = { name: 'Level C', permissions: [{access: 'owner', target: admin.id}], type: 'hero', practice: true } [res, body] = yield request.postAsync({uri: getURL('/db/level'), json: levelJSONC}) expect(res.statusCode).toBe(200) @levelC = yield Level.findById(res.body._id) levelJSONJSPrimer1 = { name: 'JS Primer 1', permissions: [{access: 'owner', target: admin.id}], type: 'hero', primerLanguage: 'javascript' } [res, body] = yield request.postAsync({uri: getURL('/db/level'), json: levelJSONJSPrimer1}) expect(res.statusCode).toBe(200) @levelJSPrimer1 = yield Level.findById(res.body._id) campaignJSON = { name: 'Campaign', levels: {} } paredLevelJSPrimer1 = _.pick(@levelJSPrimer1.toObject(), 'name', 'original', 'type', 'slug', 'primerLanguage') paredLevelJSPrimer1.campaignIndex = 3 campaignJSON.levels[@levelJSPrimer1.get('original').toString()] = paredLevelJSPrimer1 paredLevelC = _.pick(@levelC.toObject(), 'name', 'original', 'type', 'slug', 'practice') paredLevelC.campaignIndex = 2 campaignJSON.levels[@levelC.get('original').toString()] = paredLevelC paredLevelB = _.pick(@levelB.toObject(), 'name', 'original', 'type', 'slug') paredLevelB.campaignIndex = 1 campaignJSON.levels[@levelB.get('original').toString()] = paredLevelB paredLevelA = _.pick(@levelA.toObject(), 'name', 'original', 'type', 'slug') paredLevelA.campaignIndex = 0 campaignJSON.levels[@levelA.get('original').toString()] = paredLevelA [res, body] = yield request.postAsync({uri: getURL('/db/campaign'), json: campaignJSON}) @campaign = yield Campaign.findById(res.body._id) @course = Course({name: 'Course', campaignID: @campaign._id, releasePhase: 'released'}) yield @course.save() done() it 'creates a new classroom for the given user with teacher role', utils.wrap (done) -> teacher = yield utils.initUser({role: 'teacher'}) yield utils.loginUser(teacher) data = { name: 'Classroom 1' } [res, body] = yield request.postAsync {uri: classroomsURL, json: data } expect(res.statusCode).toBe(201) expect(res.body.name).toBe('Classroom 1') expect(res.body.members.length).toBe(0) expect(res.body.ownerID).toBe(teacher.id) done() it 'returns 401 for anonymous users', utils.wrap (done) -> yield utils.logout() data = { name: 'Classroom 2' } [res, body] = yield request.postAsync {uri: classroomsURL, json: data } expect(res.statusCode).toBe(401) done() it 'does not work for non-teacher users', utils.wrap (done) -> user = yield utils.initUser() yield utils.loginUser(user) data = { name: 'Classroom 1' } [res, body] = yield request.postAsync {uri: classroomsURL, json: data } expect(res.statusCode).toBe(403) done() describe 'when javascript classroom', -> beforeEach utils.wrap (done) -> teacher = yield utils.initUser({role: 'teacher'}) yield utils.loginUser(teacher) data = { name: 'Classroom 2', aceConfig: { language: 'javascript' } } [res, body] = yield request.postAsync {uri: classroomsURL, json: data } @classroom = yield Classroom.findById(res.body._id) done() it 'makes a copy of the list of all levels in all courses', utils.wrap (done) -> expect(@classroom.get('courses')[0].levels.length).toEqual(3) expect(@classroom.get('courses')[0].levels[0].original.toString()).toBe(@levelA.get('original').toString()) expect(@classroom.get('courses')[0].levels[0].type).toBe('course') expect(@classroom.get('courses')[0].levels[0].slug).toBe('level-a') expect(@classroom.get('courses')[0].levels[0].name).toBe('Level A') done() describe 'when python classroom', -> beforeEach utils.wrap (done) -> teacher = yield utils.initUser({role: 'teacher'}) yield utils.loginUser(teacher) data = { name: 'Classroom 2', aceConfig: { language: 'python' } } [res, body] = yield request.postAsync {uri: classroomsURL, json: data } @classroom = yield Classroom.findById(res.body._id) done() it 'makes a copy all levels in all courses', utils.wrap (done) -> expect(@classroom.get('courses')[0].levels.length).toEqual(4) expect(@classroom.get('courses')[0].levels[0].original.toString()).toBe(@levelA.get('original').toString()) expect(@classroom.get('courses')[0].levels[0].type).toBe('course') expect(@classroom.get('courses')[0].levels[0].slug).toBe('level-a') expect(@classroom.get('courses')[0].levels[0].name).toBe('Level A') done() describe 'when there are unreleased courses', -> beforeEach utils.wrap (done) -> admin = yield utils.initAdmin() yield utils.loginUser(admin) betaLevelJSON = { name: 'Beta Level', permissions: [{access: 'owner', target: admin.id}], type: 'course' } [res, body] = yield request.postAsync({uri: getURL('/db/level'), json: betaLevelJSON}) expect(res.statusCode).toBe(200) @betaLevel = yield Level.findById(res.body._id) betaCampaignJSON = { name: 'Beta Campaign', levels: {} } paredBetaLevel = _.pick(@betaLevel.toObject(), 'name', 'original', 'type', 'slug') paredBetaLevel.campaignIndex = 0 betaCampaignJSON.levels[@betaLevel.get('original').toString()] = paredBetaLevel [res, body] = yield request.postAsync({uri: getURL('/db/campaign'), json: betaCampaignJSON}) @betaCampaign = yield Campaign.findById(res.body._id) @betaCourse = Course({name: 'Beta Course', campaignID: @betaCampaign._id, releasePhase: 'beta'}) yield @betaCourse.save() done() it 'includes unreleased courses for admin teachers', utils.wrap (done) -> adminTeacher = yield utils.initUser({ role: 'teacher', permissions: ['admin'] }) yield utils.loginUser(adminTeacher) data = { name: 'Classroom 3' } [res, body] = yield request.postAsync {uri: classroomsURL, json: data } classroom = yield Classroom.findById(res.body._id) expect(classroom.get('courses').length).toBe(2) expect(classroom.get('courses')[0].levels[0].original.toString()).toBe(@levelA.get('original').toString()) expect(classroom.get('courses')[0].levels[0].type).toBe('course') expect(classroom.get('courses')[0].levels[0].slug).toBe('level-a') expect(classroom.get('courses')[0].levels[0].name).toBe('Level A') expect(classroom.get('courses')[1].levels[0].original.toString()).toBe(@betaLevel.get('original').toString()) expect(classroom.get('courses')[1].levels[0].type).toBe('course') expect(classroom.get('courses')[1].levels[0].slug).toBe('beta-level') expect(classroom.get('courses')[1].levels[0].name).toBe('Beta Level') done() it 'does not include unreleased courses for non-admin teachers', utils.wrap (done) -> teacher = yield utils.initUser({role: 'teacher'}) yield utils.loginUser(teacher) data = { name: 'Classroom 4' } [res, body] = yield request.postAsync {uri: classroomsURL, json: data } classroom = yield Classroom.findById(res.body._id) expect(classroom.get('courses').length).toBe(1) expect(classroom.get('courses')[0].levels[0].original.toString()).toBe(@levelA.get('original').toString()) expect(classroom.get('courses')[0].levels[0].type).toBe('course') expect(classroom.get('courses')[0].levels[0].slug).toBe('level-a') expect(classroom.get('courses')[0].levels[0].name).toBe('Level A') done() describe 'GET /db/classroom/:handle/levels', -> beforeEach utils.wrap (done) -> yield utils.clearModels [User, Classroom, Course, Level, Campaign] admin = yield utils.initAdmin() yield utils.loginUser(admin) levelJSON = { name: 'A', permissions: [{access: 'owner', target: admin.id}], type: 'course' } [res, body] = yield request.postAsync({uri: getURL('/db/level'), json: levelJSON}) expect(res.statusCode).toBe(200) @levelA = yield Level.findById(res.body._id) paredLevelA = _.pick(res.body, 'name', 'original', 'type') levelJSON = { name: 'B', permissions: [{access: 'owner', target: admin.id}], type: 'course' } [res, body] = yield request.postAsync({uri: getURL('/db/level'), json: levelJSON}) expect(res.statusCode).toBe(200) @levelB = yield Level.findById(res.body._id) paredLevelB = _.pick(res.body, 'name', 'original', 'type') levelJSON = { name: 'JS Primer 1', permissions: [{access: 'owner', target: admin.id}], type: 'course', primerLanguage: 'javascript' } [res, body] = yield request.postAsync({uri: getURL('/db/level'), json: levelJSON}) expect(res.statusCode).toBe(200) @levelJSPrimer1 = yield Level.findById(res.body._id) paredLevelJSPrimer1 = _.pick(res.body, 'name', 'original', 'type') campaignJSONA = { name: 'Campaign A', levels: {} } campaignJSONA.levels[paredLevelA.original] = paredLevelA [res, body] = yield request.postAsync({uri: getURL('/db/campaign'), json: campaignJSONA}) @campaignA = yield Campaign.findById(res.body._id) campaignJSONB = { name: 'Campaign B', levels: {} } campaignJSONB.levels[paredLevelB.original] = paredLevelB campaignJSONB.levels[paredLevelJSPrimer1.original] = paredLevelJSPrimer1 [res, body] = yield request.postAsync({uri: getURL('/db/campaign'), json: campaignJSONB}) @campaignB = yield Campaign.findById(res.body._id) @courseA = Course({name: 'Course A', campaignID: @campaignA._id, releasePhase: 'released'}) yield @courseA.save() @courseB = Course({name: 'Course B', campaignID: @campaignB._id, releasePhase: 'released'}) yield @courseB.save() done() describe 'when javascript classroom', -> beforeEach utils.wrap (done) -> teacher = yield utils.initUser({role: 'teacher'}) yield utils.loginUser(teacher) data = { name: 'Classroom 1', aceConfig: { language: 'javascript' } } [res, body] = yield request.postAsync {uri: classroomsURL, json: data } expect(res.statusCode).toBe(201) @classroom = yield Classroom.findById(res.body._id) done() it 'returns all levels referenced in in the classroom\'s copy of course levels', utils.wrap (done) -> [res, body] = yield request.getAsync { uri: getURL("/db/classroom/#{@classroom.id}/levels"), json: true } expect(res.statusCode).toBe(200) levels = res.body expect(levels.length).toBe(2) [res, body] = yield request.getAsync { uri: getURL("/db/classroom/#{@classroom.id}/courses/#{@courseA.id}/levels"), json: true } expect(res.statusCode).toBe(200) levels = res.body expect(levels.length).toBe(1) expect(levels[0].original).toBe(@levelA.get('original').toString()) [res, body] = yield request.getAsync { uri: getURL("/db/classroom/#{@classroom.id}/courses/#{@courseB.id}/levels"), json: true } expect(res.statusCode).toBe(200) levels = res.body expect(levels.length).toBe(1) expect(levels[0].original).toBe(@levelB.get('original').toString()) done() describe 'when python classroom', -> beforeEach utils.wrap (done) -> teacher = yield utils.initUser({role: 'teacher'}) yield utils.loginUser(teacher) data = { name: 'Classroom 1', aceConfig: { language: 'python' } } [res, body] = yield request.postAsync {uri: classroomsURL, json: data } expect(res.statusCode).toBe(201) @classroom = yield Classroom.findById(res.body._id) done() it 'returns all levels referenced in in the classroom\'s copy of course levels', utils.wrap (done) -> [res, body] = yield request.getAsync { uri: getURL("/db/classroom/#{@classroom.id}/levels"), json: true } expect(res.statusCode).toBe(200) levels = res.body expect(levels.length).toBe(3) [res, body] = yield request.getAsync { uri: getURL("/db/classroom/#{@classroom.id}/courses/#{@courseA.id}/levels"), json: true } expect(res.statusCode).toBe(200) levels = res.body expect(levels.length).toBe(1) expect(levels[0].original).toBe(@levelA.get('original').toString()) [res, body] = yield request.getAsync { uri: getURL("/db/classroom/#{@classroom.id}/courses/#{@courseB.id}/levels"), json: true } expect(res.statusCode).toBe(200) levels = res.body expect(levels.length).toBe(2) expect(levels[0].original).toBe(@levelB.get('original').toString()) expect(levels[1].original).toBe(@levelJSPrimer1.get('original').toString()) done() describe 'PUT /db/classroom/:handle', -> beforeEach utils.wrap (done) -> yield utils.clearModels([User, Classroom]) teacher = yield utils.initUser({role: 'teacher'}) yield utils.loginUser(teacher) @classroom = yield utils.makeClassroom() @url = utils.getURL("/db/classroom/#{@classroom.id}") done() it 'edits name and description', utils.wrap (done) -> json = { name: 'New Name!', description: 'New Description' } [res, body] = yield request.putAsync { @url, json } expect(body.name).toBe('New Name!') expect(body.description).toBe('New Description') done() it 'is not allowed if you are just a member', utils.wrap (done) -> student = yield utils.initUser() yield utils.loginUser(student) joinUrl = getURL("/db/classroom/~/members") joinJson = { code: @classroom.get('code') } [res, body] = yield request.postAsync { url: joinUrl, json: joinJson } expect(res.statusCode).toBe(200) json = { name: 'New Name!', description: 'New Description' } [res, body] = yield request.putAsync { @url, json } expect(res.statusCode).toBe(403) done() describe 'POST /db/classroom/-/members', -> beforeEach utils.wrap (done) -> yield utils.clearModels([User, Classroom, Course, Campaign]) @campaign = new Campaign({levels: {}}) yield @campaign.save() @course = new Course({free: true, campaignID: @campaign._id, releasePhase: 'released'}) yield @course.save() @teacher = yield utils.initUser({role: 'teacher'}) yield utils.loginUser(@teacher) [res, body] = yield request.postAsync({uri: classroomsURL, json: { name: 'Classroom 5' } }) expect(res.statusCode).toBe(201) @classroom = yield Classroom.findById(body._id) [res, body] = yield request.postAsync({uri: getURL('/db/course_instance'), json: { courseID: @course.id, classroomID: @classroom.id }}) expect(res.statusCode).toBe(200) @courseInstance = yield CourseInstance.findById(res.body._id) @student = yield utils.initUser() done() it 'adds the signed in user to the classroom and any free courses and sets role to student and unsubscribes', utils.wrap (done) -> spyOn(subscriptions, 'unsubscribeUser').and.returnValue(Promise.resolve()); yield utils.loginUser(@student) url = getURL("/db/classroom/anything-here/members") [res, body] = yield request.postAsync { uri: url, json: { code: @classroom.get('code') } } expect(res.statusCode).toBe(200) classroom = yield Classroom.findById(@classroom.id) expect(classroom.get('members').length).toBe(1) expect(classroom.get('members')?[0]?.equals(@student._id)).toBe(true) expect(subscriptions.unsubscribeUser).toHaveBeenCalled() student = yield User.findById(@student.id) if student.get('role') isnt 'student' fail('student role should be "student"') unless student.get('courseInstances')?[0].equals(@courseInstance._id) fail('student should be added to the free course instance.') done() it 'joins the class even with spaces in the classcode', utils.wrap (done) -> yield utils.loginUser(@student) url = getURL("/db/classroom/anything-here/members") code = @classroom.get('code') codeWithSpaces = code.split("").join(" ") [res, body] = yield request.postAsync { uri: url, json: { code: codeWithSpaces } } expect(res.statusCode).toBe(200) classroom = yield Classroom.findById(@classroom.id) if classroom.get('members').length isnt 1 fail 'expected classCode with spaces to work too' done() it 'returns 403 if the user is a teacher', utils.wrap (done) -> yield utils.loginUser(@teacher) url = getURL("/db/classroom/~/members") [res, body] = yield request.postAsync { uri: url, json: { code: @classroom.get('code') } } expect(res.statusCode).toBe(403) done() it 'returns 401 if the user is anonymous', utils.wrap (done) -> yield utils.becomeAnonymous() [res, body] = yield request.postAsync { uri: getURL("/db/classroom/-/members"), json: { code: @classroom.get('code') } } expect(res.statusCode).toBe(401) done() describe 'DELETE /db/classroom/:id/members', -> beforeEach utils.wrap (done) -> yield utils.clearModels([User, Classroom]) @teacher = yield utils.initUser({role: 'teacher'}) yield utils.loginUser(@teacher) @student = yield utils.initUser() @classroom = yield utils.makeClassroom({}, {members:[@student]}) @url = utils.getURL("/db/classroom/#{@classroom.id}/members") done() it 'removes the given user from the list of members in the classroom', utils.wrap (done) -> expect(@classroom.get('members').length).toBe(1) json = { userID: @student.id } [res, body] = yield request.delAsync { @url, json } expect(res.statusCode).toBe(200) classroom = yield Classroom.findById(@classroom.id) expect(classroom.get('members').length).toBe(0) done() describe 'POST /db/classroom/:id/invite-members', -> it 'takes a list of emails and sends invites', utils.wrap (done) -> user = yield utils.initUser({role: 'teacher', name: 'Mr Professerson'}) yield utils.loginUser(user) classroom = yield utils.makeClassroom() url = classroomsURL + "/#{classroom.id}/invite-members" data = { emails: ['test@test.com'] } sendwithus = require '../../../server/sendwithus' spyOn(sendwithus.api, 'send').and.callFake (context, cb) -> expect(context.email_id).toBe(sendwithus.templates.course_invite_email) expect(context.recipient.address).toBe('test@test.com') expect(context.email_data.teacher_name).toBe('Mr Professerson') done() [res, body] = yield request.postAsync { uri: url, json: data } expect(res.statusCode).toBe(200) describe 'GET /db/classroom/:handle/member-sessions', -> beforeEach utils.wrap (done) -> yield utils.clearModels([CourseInstance, Course, User, Classroom, Campaign, Level, LevelSession]) @teacher = yield utils.initUser({role: 'teacher'}) admin = yield utils.initAdmin() yield utils.loginUser(admin) @levelA = yield utils.makeLevel({type: 'course'}) @levelB = yield utils.makeLevel({type: 'course', primerLanguage: 'python'}) @campaignA = yield utils.makeCampaign({}, {levels: [@levelA]}) @campaignB = yield utils.makeCampaign({}, {levels: [@levelB]}) @courseA = yield utils.makeCourse({free: true, releasePhase: 'released'}, {campaign: @campaignA}) @courseB = yield utils.makeCourse({free: true, releasePhase: 'released'}, {campaign: @campaignB}) @student1 = yield utils.initUser({role: 'student'}) @student2 = yield utils.initUser({role: 'student'}) @session1A = yield utils.makeLevelSession({codeLanguage: 'javascript', state: { complete: true }}, {creator: @student1, level: @levelA}) @session1B = yield utils.makeLevelSession({codeLanguage: 'python', state: { complete: false }}, {creator: @student1, level: @levelB}) @session2A = yield utils.makeLevelSession({codeLanguage: 'javascript', state: { complete: true }}, {creator: @student2, level: @levelA}) @session2B = yield utils.makeLevelSession({codeLanguage: 'python', state: { complete: false }}, {creator: @student2, level: @levelB}) yield utils.loginUser(@teacher) @classroom = yield utils.makeClassroom({aceConfig: {language: 'javascript'}}, { members: [@student1, @student2] }) @courseInstanceA = yield utils.makeCourseInstance({courseID: @courseA.id, classroomID: @classroom.id}, { members: [@student1, @student2] }) @courseInstanceB = yield utils.makeCourseInstance({courseID: @courseB.id, classroomID: @classroom.id}, { members: [@student1] }) yield utils.logout() done() it 'returns all sessions for all members in the classroom with assigned courses', utils.wrap (done) -> yield utils.loginUser(@teacher) [res, body] = yield request.getAsync getURL("/db/classroom/#{@classroom.id}/member-sessions"), { json: true } expect(res.statusCode).toBe(200) expect(body.length).toBe(3) done() it 'does not work if you are not the owner of the classroom', utils.wrap (done) -> yield utils.loginUser(@student1) [res, body] = yield request.getAsync getURL("/db/classroom/#{@classroom.id}/member-sessions"), { json: true } expect(res.statusCode).toBe(403) done() it 'does not work if you are not logged in', utils.wrap (done) -> [res, body] = yield request.getAsync getURL("/db/classroom/#{@classroom.id}/member-sessions"), { json: true } expect(res.statusCode).toBe(401) done() it 'accepts memberSkip and memberLimit GET parameters', utils.wrap (done) -> yield utils.loginUser(@teacher) [res, body] = yield request.getAsync getURL("/db/classroom/#{@classroom.id}/member-sessions?memberLimit=1"), { json: true } expect(res.statusCode).toBe(200) expect(body.length).toBe(2) expect(session.creator).toBe(@student1.id) for session in body [res, body] = yield request.getAsync getURL("/db/classroom/#{@classroom.id}/member-sessions?memberSkip=1"), { json: true } expect(res.statusCode).toBe(200) expect(body.length).toBe(1) expect(session.creator).toBe(@student2.id) for session in body done() describe 'GET /db/classroom/:handle/members', -> beforeEach utils.wrap (done) -> yield utils.clearModels([User, Classroom]) @teacher = yield utils.initUser() @student1 = yield utils.initUser({ name: "Firstname Lastname", firstName: "Firstname", lastName: "L", coursePrepaid: { _id: mongoose.Types.ObjectId() } }) @student2 = yield utils.initUser({ name: "Student Nameynamington", firstName: "Student", lastName: "N" }) @classroom = yield new Classroom({name: 'Classroom', ownerID: @teacher._id, members: [@student1._id, @student2._id] }).save() @emptyClassroom = yield new Classroom({name: 'Empty Classroom', ownerID: @teacher._id, members: [] }).save() done() it 'does not work if you are not the owner of the classroom', utils.wrap (done) -> yield utils.loginUser(@student1) [res, body] = yield request.getAsync getURL("/db/classroom/#{@classroom.id}/member-sessions"), { json: true } expect(res.statusCode).toBe(403) done() it 'does not work if you are not logged in', utils.wrap (done) -> [res, body] = yield request.getAsync getURL("/db/classroom/#{@classroom.id}/member-sessions"), { json: true } expect(res.statusCode).toBe(401) done() it 'works on an empty classroom', utils.wrap (done) -> yield utils.loginUser(@teacher) [res, body] = yield request.getAsync getURL("/db/classroom/#{@emptyClassroom.id}/members?name=true&email=true"), { json: true } expect(res.statusCode).toBe(200) expect(body).toEqual([]) done() it 'returns all members with name, email, coursePrepaid, firstName and lastName', utils.wrap (done) -> yield utils.loginUser(@teacher) [res, body] = yield request.getAsync getURL("/db/classroom/#{@classroom.id}/members?name=true&email=true"), { json: true } expect(res.statusCode).toBe(200) expect(body.length).toBe(2) for user in body expect(user.name).toBeDefined() expect(user.email).toBeDefined() expect(user.firstName).toBeDefined() expect(user.lastName).toBeDefined() expect(user.passwordHash).toBeUndefined() student1 = _.find(body, {_id: @student1.id}) expect(student1.coursePrepaid).toBeDefined() done() describe 'POST /db/classroom/:classroomID/members/:memberID/reset-password', -> it 'changes the password', utils.wrap (done) -> yield utils.clearModels([User, Classroom]) teacher = yield utils.initUser() yield utils.loginUser(teacher) student = yield utils.initUser({ name: "Firstname Lastname" }) newPassword = "this is a new password" classroom = yield new Classroom({name: 'Classroom', ownerID: teacher._id, members: [student._id] }).save() expect(student.get('passwordHash')).not.toEqual(User.hashPassword(newPassword)) [res, body] = yield request.postAsync({ uri: getURL("/db/classroom/#{classroom.id}/members/#{student.id}/reset-password") json: { password: newPassword } }) expect(res.statusCode).toBe(200) changedStudent = yield User.findById(student.id) expect(changedStudent.get('passwordHash')).toEqual(User.hashPassword(newPassword)) done() it "doesn't change the password if you're not their teacher", utils.wrap (done) -> yield utils.clearModels([User, Classroom]) teacher = yield utils.initUser() yield utils.loginUser(teacher) student = yield utils.initUser({ name: "Firstname Lastname" }) student2 = yield utils.initUser({ name: "Firstname Lastname 2" }) newPassword = "this is a new password" classroom = yield new Classroom({name: 'Classroom', ownerID: teacher._id, members: [student2._id] }).save() expect(student.get('passwordHash')).not.toEqual(User.hashPassword(newPassword)) [res, body] = yield request.postAsync({ uri: getURL("/db/classroom/#{classroom.id}/members/#{student.id}/reset-password") json: { password: newPassword } }) expect(res.statusCode).toBe(403) changedStudent = yield User.findById(student.id) expect(changedStudent.get('passwordHash')).toEqual(student.get('passwordHash')) done() it "doesn't change the password if their email is verified", utils.wrap (done) -> yield utils.clearModels([User, Classroom]) teacher = yield utils.initUser() yield utils.loginUser(teacher) student = yield utils.initUser({ name: "Firstname Lastname", emailVerified: true }) newPassword = "this is a new password" classroom = yield new Classroom({name: 'Classroom', ownerID: teacher._id, members: [student._id] }).save() expect(student.get('passwordHash')).not.toEqual(User.hashPassword(newPassword)) [res, body] = yield request.postAsync({ uri: getURL("/db/classroom/#{classroom.id}/members/#{student.id}/reset-password") json: { password: newPassword } }) expect(res.statusCode).toBe(403) changedStudent = yield User.findById(student.id) expect(changedStudent.get('passwordHash')).toEqual(student.get('passwordHash')) done() it "doesn't let you set a 1-character password", utils.wrap (done) -> yield utils.clearModels([User, Classroom]) teacher = yield utils.initUser() yield utils.loginUser(teacher) student = yield utils.initUser({ name: "Firstname Lastname" }) newPassword = "e" classroom = yield new Classroom({name: 'Classroom', ownerID: teacher._id, members: [student._id] }).save() expect(student.get('passwordHash')).not.toEqual(User.hashPassword(newPassword)) [res, body] = yield request.postAsync({ uri: getURL("/db/classroom/#{classroom.id}/members/#{student.id}/reset-password") json: { password: newPassword } }) expect(res.statusCode).toBe(422) changedStudent = yield User.findById(student.id) expect(changedStudent.get('passwordHash')).toEqual(student.get('passwordHash')) done() describe 'GET /db/classroom/:handle/update-courses', -> it 'updates the courses property for that classroom', utils.wrap (done) -> yield utils.clearModels [User, Classroom, Course, Level, Campaign] admin = yield utils.initAdmin() teacher = yield utils.initUser({role: 'teacher'}) # make a single course yield utils.loginUser(admin) yield utils.makeCourse({releasePhase: 'released'}, {campaign: yield utils.makeCampaign()}) # make a classroom, make sure it has the one course yield utils.loginUser(teacher) data = { name: 'Classroom 2' } [res, body] = yield request.postAsync {uri: classroomsURL, json: data } classroom = yield Classroom.findById(res.body._id) expect(classroom.get('courses').length).toBe(1) # make a second course yield utils.loginUser(admin) yield utils.makeCourse({releasePhase: 'released'}, {campaign: yield utils.makeCampaign()}) # make sure classroom still has one course classroom = yield Classroom.findById(res.body._id) expect(classroom.get('courses').length).toBe(1) # update, check update happens yield utils.loginUser(teacher) [res, body] = yield request.postAsync { uri: classroomsURL + "/#{classroom.id}/update-courses", json: true } expect(body.courses.length).toBe(2) classroom = yield Classroom.findById(res.body._id) expect(classroom.get('courses').length).toBe(2) done() it 'allows admins to also update a classroom, but uses the owner\'s admin status', utils.wrap (done) -> yield utils.clearModels [User, Classroom, Course, Level, Campaign] admin = yield utils.initAdmin() teacher = yield utils.initUser({role: 'teacher'}) # make two courses, one released, one beta yield utils.loginUser(admin) yield utils.makeCourse({releasePhase: 'released'}, {campaign: yield utils.makeCampaign()}) yield utils.makeCourse({releasePhase: 'beta'}, {campaign: yield utils.makeCampaign()}) # make a classroom, make sure it has the one course yield utils.loginUser(teacher) data = { name: 'Classroom 2' } [res, body] = yield request.postAsync {uri: classroomsURL, json: data } classroom = yield Classroom.findById(res.body._id) expect(classroom.get('courses').length).toBe(1) # make another released course yield utils.loginUser(admin) yield utils.makeCourse({releasePhase: 'released'}, {campaign: yield utils.makeCampaign()}) # make sure classroom still has one course classroom = yield Classroom.findById(res.body._id) expect(classroom.get('courses').length).toBe(1) # update, check that classroom has the two released courses [res, body] = yield request.postAsync { uri: classroomsURL + "/#{classroom.id}/update-courses", json: true } expect(body.courses.length).toBe(2) classroom = yield Classroom.findById(res.body._id) expect(classroom.get('courses').length).toBe(2) done() describe 'addNewCoursesOnly', -> it 'only adds new courses, but leaves existing courses intact', utils.wrap (done) -> yield utils.clearModels [User, Classroom, Course, Level, Campaign] admin = yield utils.initAdmin() teacher = yield utils.initUser({role: 'teacher'}) # make a single course yield utils.loginUser(admin) levels = yield _.times(3, -> utils.makeLevel()) firstCampaign = yield utils.makeCampaign({}, {levels: [levels[0]]}) yield utils.makeCourse({releasePhase: 'released'}, {campaign: firstCampaign}) # make a classroom, make sure it has the one course yield utils.loginUser(teacher) data = { name: 'Classroom 2' } [res, body] = yield request.postAsync {uri: classroomsURL, json: data } classroom = yield Classroom.findById(res.body._id) expect(classroom.get('courses').length).toBe(1) expect(classroom.get('courses')[0].levels.length).toBe(1) # make a second course yield utils.loginUser(admin) yield utils.makeCourse({releasePhase: 'released'}, {campaign: yield utils.makeCampaign({}, {levels: [levels[1]]})}) # add level to first course campaignSchema = require '../../../app/schemas/models/campaign.schema' campaignLevelProperties = _.keys(campaignSchema.properties.levels.additionalProperties.properties) levelAdding = levels[2] campaignLevels = _.clone(firstCampaign.get('levels')) campaignLevels[levelAdding.get('original').valueOf()] = _.pick levelAdding.toObject(), campaignLevelProperties yield firstCampaign.update({$set: {levels: campaignLevels}}) # make sure classroom still has one course classroom = yield Classroom.findById(res.body._id) expect(classroom.get('courses').length).toBe(1) # update with addNewCoursesOnly, make sure second course is added but first keeps the same # of levels yield utils.loginUser(teacher) [res, body] = yield request.postAsync { uri: classroomsURL + "/#{classroom.id}/update-courses", json: { addNewCoursesOnly:true } } expect(body.courses.length).toBe(2) expect(body.courses[0].levels.length).toBe(1) classroom = yield Classroom.findById(res.body._id) expect(classroom.get('courses').length).toBe(2) expect(classroom.get('courses')[0].levels.length).toBe(1) # update without addNewCoursesOnly, make sure first course still updates [res, body] = yield request.postAsync { uri: classroomsURL + "/#{classroom.id}/update-courses", json: true } expect(body.courses.length).toBe(2) expect(body.courses[0].levels.length).toBe(2) classroom = yield Classroom.findById(res.body._id) expect(classroom.get('courses').length).toBe(2) expect(classroom.get('courses')[0].levels.length).toBe(2) done()
126637
config = require '../../../server_config' require '../common' clientUtils = require '../../../app/core/utils' # Must come after require /common utils = require '../utils' _ = require 'lodash' Promise = require 'bluebird' request = require '../request' requestAsync = Promise.promisify(request, {multiArgs: true}) User = require '../../../server/models/User' Classroom = require '../../../server/models/Classroom' Course = require '../../../server/models/Course' CourseInstance = require '../../../server/models/CourseInstance' Campaign = require '../../../server/models/Campaign' LevelSession = require '../../../server/models/LevelSession' Level = require '../../../server/models/Level' mongoose = require 'mongoose' subscriptions = require '../../../server/middleware/subscriptions' classroomsURL = getURL('/db/classroom') describe 'GET /db/classroom?ownerID=:id', -> beforeEach utils.wrap (done) -> yield utils.clearModels([User, Classroom]) @user1 = yield utils.initUser() yield utils.loginUser(@user1) @classroom1 = yield new Classroom({name: 'Classroom 1', ownerID: @user1.get('_id') }).save() @user2 = yield utils.initUser() yield utils.loginUser(@user2) @classroom2 = yield new Classroom({name: 'Classroom 2', ownerID: @user2.get('_id') }).save() done() it 'returns an array of classrooms with the given owner', utils.wrap (done) -> [res, body] = yield request.getAsync getURL('/db/classroom?ownerID='+@user2.id), { json: true } expect(res.statusCode).toBe(200) expect(body.length).toBe(1) expect(body[0].name).toBe('Classroom 2') done() it 'returns 403 when a non-admin tries to get classrooms for another user', utils.wrap (done) -> [res, body] = yield request.getAsync getURL('/db/classroom?ownerID='+@user1.id), { json: true } expect(res.statusCode).toBe(403) done() describe 'GET /db/classroom/:id', -> it 'clears database users and classrooms', (done) -> clearModels [User, Classroom, Course, Campaign], (err) -> throw err if err done() it 'returns the classroom for the given id', (done) -> loginNewUser (user1) -> user1.set('role', 'teacher') user1.save (err) -> data = { name: 'Classroom 1' } request.post {uri: classroomsURL, json: data }, (err, res, body) -> expect(res.statusCode).toBe(201) classroomID = body._id request.get {uri: classroomsURL + '/' + body._id }, (err, res, body) -> expect(res.statusCode).toBe(200) expect(body._id).toBe(classroomID = body._id) done() describe 'GET /db/classroom by classCode', -> it 'Returns the class if you include spaces', utils.wrap (done) -> user = yield utils.initUser() yield utils.loginUser(user) teacher = yield utils.initUser() classroom = new Classroom({ name: "some class", ownerID: teacher.id, camelCode: "FooBarBaz", code: "foobarbaz" }) yield classroom.save() [res, body] = yield request.getAsync(getURL('/db/classroom?code=foo bar baz'), { json: true }) expect(res.statusCode).toBe(200) expect(res.body.data?.name).toBe(classroom.get('name')) done() describe 'POST /db/classroom', -> beforeEach utils.wrap (done) -> yield utils.clearModels [User, Classroom, Course, Level, Campaign] admin = yield utils.initAdmin() yield utils.loginUser(admin) levelJSONA = { name: 'Level A', permissions: [{access: 'owner', target: admin.id}], type: 'course' } [res, body] = yield request.postAsync({uri: getURL('/db/level'), json: levelJSONA}) expect(res.statusCode).toBe(200) @levelA = yield Level.findById(res.body._id) levelJSONB = { name: 'Level B', permissions: [{access: 'owner', target: admin.id}], type: 'course' } [res, body] = yield request.postAsync({uri: getURL('/db/level'), json: levelJSONB}) expect(res.statusCode).toBe(200) @levelB = yield Level.findById(res.body._id) levelJSONC = { name: 'Level C', permissions: [{access: 'owner', target: admin.id}], type: 'hero', practice: true } [res, body] = yield request.postAsync({uri: getURL('/db/level'), json: levelJSONC}) expect(res.statusCode).toBe(200) @levelC = yield Level.findById(res.body._id) levelJSONJSPrimer1 = { name: 'JS Primer 1', permissions: [{access: 'owner', target: admin.id}], type: 'hero', primerLanguage: 'javascript' } [res, body] = yield request.postAsync({uri: getURL('/db/level'), json: levelJSONJSPrimer1}) expect(res.statusCode).toBe(200) @levelJSPrimer1 = yield Level.findById(res.body._id) campaignJSON = { name: 'Campaign', levels: {} } paredLevelJSPrimer1 = _.pick(@levelJSPrimer1.toObject(), 'name', 'original', 'type', 'slug', 'primerLanguage') paredLevelJSPrimer1.campaignIndex = 3 campaignJSON.levels[<EMAIL>()] = paredLevelJSPrimer1 paredLevelC = _.pick(@levelC.toObject(), 'name', 'original', 'type', 'slug', 'practice') paredLevelC.campaignIndex = 2 campaignJSON.levels[@<EMAIL>('<EMAIL>()] = paredLevelC paredLevelB = _.pick(@levelB.toObject(), 'name', 'original', 'type', 'slug') paredLevelB.campaignIndex = 1 campaignJSON.levels[@levelB.get('original').toString()] = paredLevelB paredLevelA = _.pick(@levelA.toObject(), 'name', 'original', 'type', 'slug') paredLevelA.campaignIndex = 0 campaignJSON.levels[@levelA.get('original').toString()] = paredLevelA [res, body] = yield request.postAsync({uri: getURL('/db/campaign'), json: campaignJSON}) @campaign = yield Campaign.findById(res.body._id) @course = Course({name: 'Course', campaignID: @campaign._id, releasePhase: 'released'}) yield @course.save() done() it 'creates a new classroom for the given user with teacher role', utils.wrap (done) -> teacher = yield utils.initUser({role: 'teacher'}) yield utils.loginUser(teacher) data = { name: 'Classroom 1' } [res, body] = yield request.postAsync {uri: classroomsURL, json: data } expect(res.statusCode).toBe(201) expect(res.body.name).toBe('Classroom 1') expect(res.body.members.length).toBe(0) expect(res.body.ownerID).toBe(teacher.id) done() it 'returns 401 for anonymous users', utils.wrap (done) -> yield utils.logout() data = { name: 'Classroom 2' } [res, body] = yield request.postAsync {uri: classroomsURL, json: data } expect(res.statusCode).toBe(401) done() it 'does not work for non-teacher users', utils.wrap (done) -> user = yield utils.initUser() yield utils.loginUser(user) data = { name: 'Classroom 1' } [res, body] = yield request.postAsync {uri: classroomsURL, json: data } expect(res.statusCode).toBe(403) done() describe 'when javascript classroom', -> beforeEach utils.wrap (done) -> teacher = yield utils.initUser({role: 'teacher'}) yield utils.loginUser(teacher) data = { name: 'Classroom 2', aceConfig: { language: 'javascript' } } [res, body] = yield request.postAsync {uri: classroomsURL, json: data } @classroom = yield Classroom.findById(res.body._id) done() it 'makes a copy of the list of all levels in all courses', utils.wrap (done) -> expect(@classroom.get('courses')[0].levels.length).toEqual(3) expect(@classroom.get('courses')[0].levels[0].original.toString()).toBe(@levelA.get('original').toString()) expect(@classroom.get('courses')[0].levels[0].type).toBe('course') expect(@classroom.get('courses')[0].levels[0].slug).toBe('level-a') expect(@classroom.get('courses')[0].levels[0].name).toBe('Level A') done() describe 'when python classroom', -> beforeEach utils.wrap (done) -> teacher = yield utils.initUser({role: 'teacher'}) yield utils.loginUser(teacher) data = { name: 'Classroom 2', aceConfig: { language: 'python' } } [res, body] = yield request.postAsync {uri: classroomsURL, json: data } @classroom = yield Classroom.findById(res.body._id) done() it 'makes a copy all levels in all courses', utils.wrap (done) -> expect(@classroom.get('courses')[0].levels.length).toEqual(4) expect(@classroom.get('courses')[0].levels[0].original.toString()).toBe(@levelA.get('original').toString()) expect(@classroom.get('courses')[0].levels[0].type).toBe('course') expect(@classroom.get('courses')[0].levels[0].slug).toBe('level-a') expect(@classroom.get('courses')[0].levels[0].name).toBe('Level A') done() describe 'when there are unreleased courses', -> beforeEach utils.wrap (done) -> admin = yield utils.initAdmin() yield utils.loginUser(admin) betaLevelJSON = { name: 'Beta Level', permissions: [{access: 'owner', target: admin.id}], type: 'course' } [res, body] = yield request.postAsync({uri: getURL('/db/level'), json: betaLevelJSON}) expect(res.statusCode).toBe(200) @betaLevel = yield Level.findById(res.body._id) betaCampaignJSON = { name: 'Beta Campaign', levels: {} } paredBetaLevel = _.pick(@betaLevel.toObject(), 'name', 'original', 'type', 'slug') paredBetaLevel.campaignIndex = 0 betaCampaignJSON.levels[@betaLevel.get('original').toString()] = paredBetaLevel [res, body] = yield request.postAsync({uri: getURL('/db/campaign'), json: betaCampaignJSON}) @betaCampaign = yield Campaign.findById(res.body._id) @betaCourse = Course({name: 'Beta Course', campaignID: @betaCampaign._id, releasePhase: 'beta'}) yield @betaCourse.save() done() it 'includes unreleased courses for admin teachers', utils.wrap (done) -> adminTeacher = yield utils.initUser({ role: 'teacher', permissions: ['admin'] }) yield utils.loginUser(adminTeacher) data = { name: 'Classroom 3' } [res, body] = yield request.postAsync {uri: classroomsURL, json: data } classroom = yield Classroom.findById(res.body._id) expect(classroom.get('courses').length).toBe(2) expect(classroom.get('courses')[0].levels[0].original.toString()).toBe(@levelA.get('original').toString()) expect(classroom.get('courses')[0].levels[0].type).toBe('course') expect(classroom.get('courses')[0].levels[0].slug).toBe('level-a') expect(classroom.get('courses')[0].levels[0].name).toBe('Level A') expect(classroom.get('courses')[1].levels[0].original.toString()).toBe(@betaLevel.get('original').toString()) expect(classroom.get('courses')[1].levels[0].type).toBe('course') expect(classroom.get('courses')[1].levels[0].slug).toBe('beta-level') expect(classroom.get('courses')[1].levels[0].name).toBe('Beta Level') done() it 'does not include unreleased courses for non-admin teachers', utils.wrap (done) -> teacher = yield utils.initUser({role: 'teacher'}) yield utils.loginUser(teacher) data = { name: 'Classroom 4' } [res, body] = yield request.postAsync {uri: classroomsURL, json: data } classroom = yield Classroom.findById(res.body._id) expect(classroom.get('courses').length).toBe(1) expect(classroom.get('courses')[0].levels[0].original.toString()).toBe(@levelA.get('original').toString()) expect(classroom.get('courses')[0].levels[0].type).toBe('course') expect(classroom.get('courses')[0].levels[0].slug).toBe('level-a') expect(classroom.get('courses')[0].levels[0].name).toBe('Level A') done() describe 'GET /db/classroom/:handle/levels', -> beforeEach utils.wrap (done) -> yield utils.clearModels [User, Classroom, Course, Level, Campaign] admin = yield utils.initAdmin() yield utils.loginUser(admin) levelJSON = { name: 'A', permissions: [{access: 'owner', target: admin.id}], type: 'course' } [res, body] = yield request.postAsync({uri: getURL('/db/level'), json: levelJSON}) expect(res.statusCode).toBe(200) @levelA = yield Level.findById(res.body._id) paredLevelA = _.pick(res.body, 'name', 'original', 'type') levelJSON = { name: 'B', permissions: [{access: 'owner', target: admin.id}], type: 'course' } [res, body] = yield request.postAsync({uri: getURL('/db/level'), json: levelJSON}) expect(res.statusCode).toBe(200) @levelB = yield Level.findById(res.body._id) paredLevelB = _.pick(res.body, 'name', 'original', 'type') levelJSON = { name: 'JS Primer 1', permissions: [{access: 'owner', target: admin.id}], type: 'course', primerLanguage: 'javascript' } [res, body] = yield request.postAsync({uri: getURL('/db/level'), json: levelJSON}) expect(res.statusCode).toBe(200) @levelJSPrimer1 = yield Level.findById(res.body._id) paredLevelJSPrimer1 = _.pick(res.body, 'name', 'original', 'type') campaignJSONA = { name: 'Campaign A', levels: {} } campaignJSONA.levels[paredLevelA.original] = paredLevelA [res, body] = yield request.postAsync({uri: getURL('/db/campaign'), json: campaignJSONA}) @campaignA = yield Campaign.findById(res.body._id) campaignJSONB = { name: 'Campaign B', levels: {} } campaignJSONB.levels[paredLevelB.original] = paredLevelB campaignJSONB.levels[paredLevelJSPrimer1.original] = paredLevelJSPrimer1 [res, body] = yield request.postAsync({uri: getURL('/db/campaign'), json: campaignJSONB}) @campaignB = yield Campaign.findById(res.body._id) @courseA = Course({name: 'Course A', campaignID: @campaignA._id, releasePhase: 'released'}) yield @courseA.save() @courseB = Course({name: 'Course B', campaignID: @campaignB._id, releasePhase: 'released'}) yield @courseB.save() done() describe 'when javascript classroom', -> beforeEach utils.wrap (done) -> teacher = yield utils.initUser({role: 'teacher'}) yield utils.loginUser(teacher) data = { name: 'Classroom 1', aceConfig: { language: 'javascript' } } [res, body] = yield request.postAsync {uri: classroomsURL, json: data } expect(res.statusCode).toBe(201) @classroom = yield Classroom.findById(res.body._id) done() it 'returns all levels referenced in in the classroom\'s copy of course levels', utils.wrap (done) -> [res, body] = yield request.getAsync { uri: getURL("/db/classroom/#{@classroom.id}/levels"), json: true } expect(res.statusCode).toBe(200) levels = res.body expect(levels.length).toBe(2) [res, body] = yield request.getAsync { uri: getURL("/db/classroom/#{@classroom.id}/courses/#{@courseA.id}/levels"), json: true } expect(res.statusCode).toBe(200) levels = res.body expect(levels.length).toBe(1) expect(levels[0].original).toBe(@levelA.get('original').toString()) [res, body] = yield request.getAsync { uri: getURL("/db/classroom/#{@classroom.id}/courses/#{@courseB.id}/levels"), json: true } expect(res.statusCode).toBe(200) levels = res.body expect(levels.length).toBe(1) expect(levels[0].original).toBe(@levelB.get('original').toString()) done() describe 'when python classroom', -> beforeEach utils.wrap (done) -> teacher = yield utils.initUser({role: 'teacher'}) yield utils.loginUser(teacher) data = { name: 'Classroom 1', aceConfig: { language: 'python' } } [res, body] = yield request.postAsync {uri: classroomsURL, json: data } expect(res.statusCode).toBe(201) @classroom = yield Classroom.findById(res.body._id) done() it 'returns all levels referenced in in the classroom\'s copy of course levels', utils.wrap (done) -> [res, body] = yield request.getAsync { uri: getURL("/db/classroom/#{@classroom.id}/levels"), json: true } expect(res.statusCode).toBe(200) levels = res.body expect(levels.length).toBe(3) [res, body] = yield request.getAsync { uri: getURL("/db/classroom/#{@classroom.id}/courses/#{@courseA.id}/levels"), json: true } expect(res.statusCode).toBe(200) levels = res.body expect(levels.length).toBe(1) expect(levels[0].original).toBe(@levelA.get('original').toString()) [res, body] = yield request.getAsync { uri: getURL("/db/classroom/#{@classroom.id}/courses/#{@courseB.id}/levels"), json: true } expect(res.statusCode).toBe(200) levels = res.body expect(levels.length).toBe(2) expect(levels[0].original).toBe(@levelB.get('original').toString()) expect(levels[1].original).toBe(@levelJSPrimer1.get('original').toString()) done() describe 'PUT /db/classroom/:handle', -> beforeEach utils.wrap (done) -> yield utils.clearModels([User, Classroom]) teacher = yield utils.initUser({role: 'teacher'}) yield utils.loginUser(teacher) @classroom = yield utils.makeClassroom() @url = utils.getURL("/db/classroom/#{@classroom.id}") done() it 'edits name and description', utils.wrap (done) -> json = { name: 'New Name!', description: 'New Description' } [res, body] = yield request.putAsync { @url, json } expect(body.name).toBe('New Name!') expect(body.description).toBe('New Description') done() it 'is not allowed if you are just a member', utils.wrap (done) -> student = yield utils.initUser() yield utils.loginUser(student) joinUrl = getURL("/db/classroom/~/members") joinJson = { code: @classroom.get('code') } [res, body] = yield request.postAsync { url: joinUrl, json: joinJson } expect(res.statusCode).toBe(200) json = { name: 'New Name!', description: 'New Description' } [res, body] = yield request.putAsync { @url, json } expect(res.statusCode).toBe(403) done() describe 'POST /db/classroom/-/members', -> beforeEach utils.wrap (done) -> yield utils.clearModels([User, Classroom, Course, Campaign]) @campaign = new Campaign({levels: {}}) yield @campaign.save() @course = new Course({free: true, campaignID: @campaign._id, releasePhase: 'released'}) yield @course.save() @teacher = yield utils.initUser({role: 'teacher'}) yield utils.loginUser(@teacher) [res, body] = yield request.postAsync({uri: classroomsURL, json: { name: 'Classroom 5' } }) expect(res.statusCode).toBe(201) @classroom = yield Classroom.findById(body._id) [res, body] = yield request.postAsync({uri: getURL('/db/course_instance'), json: { courseID: @course.id, classroomID: @classroom.id }}) expect(res.statusCode).toBe(200) @courseInstance = yield CourseInstance.findById(res.body._id) @student = yield utils.initUser() done() it 'adds the signed in user to the classroom and any free courses and sets role to student and unsubscribes', utils.wrap (done) -> spyOn(subscriptions, 'unsubscribeUser').and.returnValue(Promise.resolve()); yield utils.loginUser(@student) url = getURL("/db/classroom/anything-here/members") [res, body] = yield request.postAsync { uri: url, json: { code: @classroom.get('code') } } expect(res.statusCode).toBe(200) classroom = yield Classroom.findById(@classroom.id) expect(classroom.get('members').length).toBe(1) expect(classroom.get('members')?[0]?.equals(@student._id)).toBe(true) expect(subscriptions.unsubscribeUser).toHaveBeenCalled() student = yield User.findById(@student.id) if student.get('role') isnt 'student' fail('student role should be "student"') unless student.get('courseInstances')?[0].equals(@courseInstance._id) fail('student should be added to the free course instance.') done() it 'joins the class even with spaces in the classcode', utils.wrap (done) -> yield utils.loginUser(@student) url = getURL("/db/classroom/anything-here/members") code = @classroom.get('code') codeWithSpaces = code.split("").join(" ") [res, body] = yield request.postAsync { uri: url, json: { code: codeWithSpaces } } expect(res.statusCode).toBe(200) classroom = yield Classroom.findById(@classroom.id) if classroom.get('members').length isnt 1 fail 'expected classCode with spaces to work too' done() it 'returns 403 if the user is a teacher', utils.wrap (done) -> yield utils.loginUser(@teacher) url = getURL("/db/classroom/~/members") [res, body] = yield request.postAsync { uri: url, json: { code: @classroom.get('code') } } expect(res.statusCode).toBe(403) done() it 'returns 401 if the user is anonymous', utils.wrap (done) -> yield utils.becomeAnonymous() [res, body] = yield request.postAsync { uri: getURL("/db/classroom/-/members"), json: { code: @classroom.get('code') } } expect(res.statusCode).toBe(401) done() describe 'DELETE /db/classroom/:id/members', -> beforeEach utils.wrap (done) -> yield utils.clearModels([User, Classroom]) @teacher = yield utils.initUser({role: 'teacher'}) yield utils.loginUser(@teacher) @student = yield utils.initUser() @classroom = yield utils.makeClassroom({}, {members:[@student]}) @url = utils.getURL("/db/classroom/#{@classroom.id}/members") done() it 'removes the given user from the list of members in the classroom', utils.wrap (done) -> expect(@classroom.get('members').length).toBe(1) json = { userID: @student.id } [res, body] = yield request.delAsync { @url, json } expect(res.statusCode).toBe(200) classroom = yield Classroom.findById(@classroom.id) expect(classroom.get('members').length).toBe(0) done() describe 'POST /db/classroom/:id/invite-members', -> it 'takes a list of emails and sends invites', utils.wrap (done) -> user = yield utils.initUser({role: 'teacher', name: '<NAME>'}) yield utils.loginUser(user) classroom = yield utils.makeClassroom() url = classroomsURL + "/#{classroom.id}/invite-members" data = { emails: ['<EMAIL>'] } sendwithus = require '../../../server/sendwithus' spyOn(sendwithus.api, 'send').and.callFake (context, cb) -> expect(context.email_id).toBe(sendwithus.templates.course_invite_email) expect(context.recipient.address).toBe('<EMAIL>') expect(context.email_data.teacher_name).toBe('<NAME>') done() [res, body] = yield request.postAsync { uri: url, json: data } expect(res.statusCode).toBe(200) describe 'GET /db/classroom/:handle/member-sessions', -> beforeEach utils.wrap (done) -> yield utils.clearModels([CourseInstance, Course, User, Classroom, Campaign, Level, LevelSession]) @teacher = yield utils.initUser({role: 'teacher'}) admin = yield utils.initAdmin() yield utils.loginUser(admin) @levelA = yield utils.makeLevel({type: 'course'}) @levelB = yield utils.makeLevel({type: 'course', primerLanguage: 'python'}) @campaignA = yield utils.makeCampaign({}, {levels: [@levelA]}) @campaignB = yield utils.makeCampaign({}, {levels: [@levelB]}) @courseA = yield utils.makeCourse({free: true, releasePhase: 'released'}, {campaign: @campaignA}) @courseB = yield utils.makeCourse({free: true, releasePhase: 'released'}, {campaign: @campaignB}) @student1 = yield utils.initUser({role: 'student'}) @student2 = yield utils.initUser({role: 'student'}) @session1A = yield utils.makeLevelSession({codeLanguage: 'javascript', state: { complete: true }}, {creator: @student1, level: @levelA}) @session1B = yield utils.makeLevelSession({codeLanguage: 'python', state: { complete: false }}, {creator: @student1, level: @levelB}) @session2A = yield utils.makeLevelSession({codeLanguage: 'javascript', state: { complete: true }}, {creator: @student2, level: @levelA}) @session2B = yield utils.makeLevelSession({codeLanguage: 'python', state: { complete: false }}, {creator: @student2, level: @levelB}) yield utils.loginUser(@teacher) @classroom = yield utils.makeClassroom({aceConfig: {language: 'javascript'}}, { members: [@student1, @student2] }) @courseInstanceA = yield utils.makeCourseInstance({courseID: @courseA.id, classroomID: @classroom.id}, { members: [@student1, @student2] }) @courseInstanceB = yield utils.makeCourseInstance({courseID: @courseB.id, classroomID: @classroom.id}, { members: [@student1] }) yield utils.logout() done() it 'returns all sessions for all members in the classroom with assigned courses', utils.wrap (done) -> yield utils.loginUser(@teacher) [res, body] = yield request.getAsync getURL("/db/classroom/#{@classroom.id}/member-sessions"), { json: true } expect(res.statusCode).toBe(200) expect(body.length).toBe(3) done() it 'does not work if you are not the owner of the classroom', utils.wrap (done) -> yield utils.loginUser(@student1) [res, body] = yield request.getAsync getURL("/db/classroom/#{@classroom.id}/member-sessions"), { json: true } expect(res.statusCode).toBe(403) done() it 'does not work if you are not logged in', utils.wrap (done) -> [res, body] = yield request.getAsync getURL("/db/classroom/#{@classroom.id}/member-sessions"), { json: true } expect(res.statusCode).toBe(401) done() it 'accepts memberSkip and memberLimit GET parameters', utils.wrap (done) -> yield utils.loginUser(@teacher) [res, body] = yield request.getAsync getURL("/db/classroom/#{@classroom.id}/member-sessions?memberLimit=1"), { json: true } expect(res.statusCode).toBe(200) expect(body.length).toBe(2) expect(session.creator).toBe(@student1.id) for session in body [res, body] = yield request.getAsync getURL("/db/classroom/#{@classroom.id}/member-sessions?memberSkip=1"), { json: true } expect(res.statusCode).toBe(200) expect(body.length).toBe(1) expect(session.creator).toBe(@student2.id) for session in body done() describe 'GET /db/classroom/:handle/members', -> beforeEach utils.wrap (done) -> yield utils.clearModels([User, Classroom]) @teacher = yield utils.initUser() @student1 = yield utils.initUser({ name: "<NAME>", firstName: "<NAME>", lastName: "L", coursePrepaid: { _id: mongoose.Types.ObjectId() } }) @student2 = yield utils.initUser({ name: "<NAME>", firstName: "Student", lastName: "N" }) @classroom = yield new Classroom({name: 'Classroom', ownerID: @teacher._id, members: [@student1._id, @student2._id] }).save() @emptyClassroom = yield new Classroom({name: 'Empty Classroom', ownerID: @teacher._id, members: [] }).save() done() it 'does not work if you are not the owner of the classroom', utils.wrap (done) -> yield utils.loginUser(@student1) [res, body] = yield request.getAsync getURL("/db/classroom/#{@classroom.id}/member-sessions"), { json: true } expect(res.statusCode).toBe(403) done() it 'does not work if you are not logged in', utils.wrap (done) -> [res, body] = yield request.getAsync getURL("/db/classroom/#{@classroom.id}/member-sessions"), { json: true } expect(res.statusCode).toBe(401) done() it 'works on an empty classroom', utils.wrap (done) -> yield utils.loginUser(@teacher) [res, body] = yield request.getAsync getURL("/db/classroom/#{@emptyClassroom.id}/members?name=true&email=true"), { json: true } expect(res.statusCode).toBe(200) expect(body).toEqual([]) done() it 'returns all members with name, email, coursePrepaid, firstName and lastName', utils.wrap (done) -> yield utils.loginUser(@teacher) [res, body] = yield request.getAsync getURL("/db/classroom/#{@classroom.id}/members?name=true&email=true"), { json: true } expect(res.statusCode).toBe(200) expect(body.length).toBe(2) for user in body expect(user.name).toBeDefined() expect(user.email).toBeDefined() expect(user.firstName).toBeDefined() expect(user.lastName).toBeDefined() expect(user.passwordHash).toBeUndefined() student1 = _.find(body, {_id: @student1.id}) expect(student1.coursePrepaid).toBeDefined() done() describe 'POST /db/classroom/:classroomID/members/:memberID/reset-password', -> it 'changes the password', utils.wrap (done) -> yield utils.clearModels([User, Classroom]) teacher = yield utils.initUser() yield utils.loginUser(teacher) student = yield utils.initUser({ name: "<NAME> <NAME>" }) newPassword = "<PASSWORD> password" classroom = yield new Classroom({name: 'Classroom', ownerID: teacher._id, members: [student._id] }).save() expect(student.get('passwordHash')).not.toEqual(User.hashPassword(newPassword)) [res, body] = yield request.postAsync({ uri: getURL("/db/classroom/#{classroom.id}/members/#{student.id}/reset-password") json: { password: <PASSWORD> } }) expect(res.statusCode).toBe(200) changedStudent = yield User.findById(student.id) expect(changedStudent.get('passwordHash')).toEqual(User.hashPassword(newPassword)) done() it "doesn't change the password if you're not their teacher", utils.wrap (done) -> yield utils.clearModels([User, Classroom]) teacher = yield utils.initUser() yield utils.loginUser(teacher) student = yield utils.initUser({ name: "<NAME>" }) student2 = yield utils.initUser({ name: "<NAME>" }) newPassword = "<PASSWORD>" classroom = yield new Classroom({name: 'Classroom', ownerID: teacher._id, members: [student2._id] }).save() expect(student.get('passwordHash')).not.toEqual(User.hashPassword(<PASSWORD>)) [res, body] = yield request.postAsync({ uri: getURL("/db/classroom/#{classroom.id}/members/#{student.id}/reset-password") json: { password: <PASSWORD> } }) expect(res.statusCode).toBe(403) changedStudent = yield User.findById(student.id) expect(changedStudent.get('passwordHash')).toEqual(student.get('passwordHash')) done() it "doesn't change the password if their email is verified", utils.wrap (done) -> yield utils.clearModels([User, Classroom]) teacher = yield utils.initUser() yield utils.loginUser(teacher) student = yield utils.initUser({ name: "<NAME>", emailVerified: true }) newPassword = "<PASSWORD>" classroom = yield new Classroom({name: 'Classroom', ownerID: teacher._id, members: [student._id] }).save() expect(student.get('passwordHash')).not.toEqual(User.hashPassword(<PASSWORD>)) [res, body] = yield request.postAsync({ uri: getURL("/db/classroom/#{classroom.id}/members/#{student.id}/reset-password") json: { password: <PASSWORD> } }) expect(res.statusCode).toBe(403) changedStudent = yield User.findById(student.id) expect(changedStudent.get('passwordHash')).toEqual(student.get('passwordHash')) done() it "doesn't let you set a 1-character password", utils.wrap (done) -> yield utils.clearModels([User, Classroom]) teacher = yield utils.initUser() yield utils.loginUser(teacher) student = yield utils.initUser({ name: "<NAME>" }) newPassword = "<PASSWORD>" classroom = yield new Classroom({name: 'Classroom', ownerID: teacher._id, members: [student._id] }).save() expect(student.get('passwordHash')).not.toEqual(User.hashPassword(<PASSWORD>)) [res, body] = yield request.postAsync({ uri: getURL("/db/classroom/#{classroom.id}/members/#{student.id}/reset-password") json: { password: <PASSWORD> } }) expect(res.statusCode).toBe(422) changedStudent = yield User.findById(student.id) expect(changedStudent.get('passwordHash')).toEqual(student.get('passwordHash')) done() describe 'GET /db/classroom/:handle/update-courses', -> it 'updates the courses property for that classroom', utils.wrap (done) -> yield utils.clearModels [User, Classroom, Course, Level, Campaign] admin = yield utils.initAdmin() teacher = yield utils.initUser({role: 'teacher'}) # make a single course yield utils.loginUser(admin) yield utils.makeCourse({releasePhase: 'released'}, {campaign: yield utils.makeCampaign()}) # make a classroom, make sure it has the one course yield utils.loginUser(teacher) data = { name: 'Classroom 2' } [res, body] = yield request.postAsync {uri: classroomsURL, json: data } classroom = yield Classroom.findById(res.body._id) expect(classroom.get('courses').length).toBe(1) # make a second course yield utils.loginUser(admin) yield utils.makeCourse({releasePhase: 'released'}, {campaign: yield utils.makeCampaign()}) # make sure classroom still has one course classroom = yield Classroom.findById(res.body._id) expect(classroom.get('courses').length).toBe(1) # update, check update happens yield utils.loginUser(teacher) [res, body] = yield request.postAsync { uri: classroomsURL + "/#{classroom.id}/update-courses", json: true } expect(body.courses.length).toBe(2) classroom = yield Classroom.findById(res.body._id) expect(classroom.get('courses').length).toBe(2) done() it 'allows admins to also update a classroom, but uses the owner\'s admin status', utils.wrap (done) -> yield utils.clearModels [User, Classroom, Course, Level, Campaign] admin = yield utils.initAdmin() teacher = yield utils.initUser({role: 'teacher'}) # make two courses, one released, one beta yield utils.loginUser(admin) yield utils.makeCourse({releasePhase: 'released'}, {campaign: yield utils.makeCampaign()}) yield utils.makeCourse({releasePhase: 'beta'}, {campaign: yield utils.makeCampaign()}) # make a classroom, make sure it has the one course yield utils.loginUser(teacher) data = { name: 'Classroom 2' } [res, body] = yield request.postAsync {uri: classroomsURL, json: data } classroom = yield Classroom.findById(res.body._id) expect(classroom.get('courses').length).toBe(1) # make another released course yield utils.loginUser(admin) yield utils.makeCourse({releasePhase: 'released'}, {campaign: yield utils.makeCampaign()}) # make sure classroom still has one course classroom = yield Classroom.findById(res.body._id) expect(classroom.get('courses').length).toBe(1) # update, check that classroom has the two released courses [res, body] = yield request.postAsync { uri: classroomsURL + "/#{classroom.id}/update-courses", json: true } expect(body.courses.length).toBe(2) classroom = yield Classroom.findById(res.body._id) expect(classroom.get('courses').length).toBe(2) done() describe 'addNewCoursesOnly', -> it 'only adds new courses, but leaves existing courses intact', utils.wrap (done) -> yield utils.clearModels [User, Classroom, Course, Level, Campaign] admin = yield utils.initAdmin() teacher = yield utils.initUser({role: 'teacher'}) # make a single course yield utils.loginUser(admin) levels = yield _.times(3, -> utils.makeLevel()) firstCampaign = yield utils.makeCampaign({}, {levels: [levels[0]]}) yield utils.makeCourse({releasePhase: 'released'}, {campaign: firstCampaign}) # make a classroom, make sure it has the one course yield utils.loginUser(teacher) data = { name: 'Classroom 2' } [res, body] = yield request.postAsync {uri: classroomsURL, json: data } classroom = yield Classroom.findById(res.body._id) expect(classroom.get('courses').length).toBe(1) expect(classroom.get('courses')[0].levels.length).toBe(1) # make a second course yield utils.loginUser(admin) yield utils.makeCourse({releasePhase: 'released'}, {campaign: yield utils.makeCampaign({}, {levels: [levels[1]]})}) # add level to first course campaignSchema = require '../../../app/schemas/models/campaign.schema' campaignLevelProperties = _.keys(campaignSchema.properties.levels.additionalProperties.properties) levelAdding = levels[2] campaignLevels = _.clone(firstCampaign.get('levels')) campaignLevels[levelAdding.get('original').valueOf()] = _.pick levelAdding.toObject(), campaignLevelProperties yield firstCampaign.update({$set: {levels: campaignLevels}}) # make sure classroom still has one course classroom = yield Classroom.findById(res.body._id) expect(classroom.get('courses').length).toBe(1) # update with addNewCoursesOnly, make sure second course is added but first keeps the same # of levels yield utils.loginUser(teacher) [res, body] = yield request.postAsync { uri: classroomsURL + "/#{classroom.id}/update-courses", json: { addNewCoursesOnly:true } } expect(body.courses.length).toBe(2) expect(body.courses[0].levels.length).toBe(1) classroom = yield Classroom.findById(res.body._id) expect(classroom.get('courses').length).toBe(2) expect(classroom.get('courses')[0].levels.length).toBe(1) # update without addNewCoursesOnly, make sure first course still updates [res, body] = yield request.postAsync { uri: classroomsURL + "/#{classroom.id}/update-courses", json: true } expect(body.courses.length).toBe(2) expect(body.courses[0].levels.length).toBe(2) classroom = yield Classroom.findById(res.body._id) expect(classroom.get('courses').length).toBe(2) expect(classroom.get('courses')[0].levels.length).toBe(2) done()
true
config = require '../../../server_config' require '../common' clientUtils = require '../../../app/core/utils' # Must come after require /common utils = require '../utils' _ = require 'lodash' Promise = require 'bluebird' request = require '../request' requestAsync = Promise.promisify(request, {multiArgs: true}) User = require '../../../server/models/User' Classroom = require '../../../server/models/Classroom' Course = require '../../../server/models/Course' CourseInstance = require '../../../server/models/CourseInstance' Campaign = require '../../../server/models/Campaign' LevelSession = require '../../../server/models/LevelSession' Level = require '../../../server/models/Level' mongoose = require 'mongoose' subscriptions = require '../../../server/middleware/subscriptions' classroomsURL = getURL('/db/classroom') describe 'GET /db/classroom?ownerID=:id', -> beforeEach utils.wrap (done) -> yield utils.clearModels([User, Classroom]) @user1 = yield utils.initUser() yield utils.loginUser(@user1) @classroom1 = yield new Classroom({name: 'Classroom 1', ownerID: @user1.get('_id') }).save() @user2 = yield utils.initUser() yield utils.loginUser(@user2) @classroom2 = yield new Classroom({name: 'Classroom 2', ownerID: @user2.get('_id') }).save() done() it 'returns an array of classrooms with the given owner', utils.wrap (done) -> [res, body] = yield request.getAsync getURL('/db/classroom?ownerID='+@user2.id), { json: true } expect(res.statusCode).toBe(200) expect(body.length).toBe(1) expect(body[0].name).toBe('Classroom 2') done() it 'returns 403 when a non-admin tries to get classrooms for another user', utils.wrap (done) -> [res, body] = yield request.getAsync getURL('/db/classroom?ownerID='+@user1.id), { json: true } expect(res.statusCode).toBe(403) done() describe 'GET /db/classroom/:id', -> it 'clears database users and classrooms', (done) -> clearModels [User, Classroom, Course, Campaign], (err) -> throw err if err done() it 'returns the classroom for the given id', (done) -> loginNewUser (user1) -> user1.set('role', 'teacher') user1.save (err) -> data = { name: 'Classroom 1' } request.post {uri: classroomsURL, json: data }, (err, res, body) -> expect(res.statusCode).toBe(201) classroomID = body._id request.get {uri: classroomsURL + '/' + body._id }, (err, res, body) -> expect(res.statusCode).toBe(200) expect(body._id).toBe(classroomID = body._id) done() describe 'GET /db/classroom by classCode', -> it 'Returns the class if you include spaces', utils.wrap (done) -> user = yield utils.initUser() yield utils.loginUser(user) teacher = yield utils.initUser() classroom = new Classroom({ name: "some class", ownerID: teacher.id, camelCode: "FooBarBaz", code: "foobarbaz" }) yield classroom.save() [res, body] = yield request.getAsync(getURL('/db/classroom?code=foo bar baz'), { json: true }) expect(res.statusCode).toBe(200) expect(res.body.data?.name).toBe(classroom.get('name')) done() describe 'POST /db/classroom', -> beforeEach utils.wrap (done) -> yield utils.clearModels [User, Classroom, Course, Level, Campaign] admin = yield utils.initAdmin() yield utils.loginUser(admin) levelJSONA = { name: 'Level A', permissions: [{access: 'owner', target: admin.id}], type: 'course' } [res, body] = yield request.postAsync({uri: getURL('/db/level'), json: levelJSONA}) expect(res.statusCode).toBe(200) @levelA = yield Level.findById(res.body._id) levelJSONB = { name: 'Level B', permissions: [{access: 'owner', target: admin.id}], type: 'course' } [res, body] = yield request.postAsync({uri: getURL('/db/level'), json: levelJSONB}) expect(res.statusCode).toBe(200) @levelB = yield Level.findById(res.body._id) levelJSONC = { name: 'Level C', permissions: [{access: 'owner', target: admin.id}], type: 'hero', practice: true } [res, body] = yield request.postAsync({uri: getURL('/db/level'), json: levelJSONC}) expect(res.statusCode).toBe(200) @levelC = yield Level.findById(res.body._id) levelJSONJSPrimer1 = { name: 'JS Primer 1', permissions: [{access: 'owner', target: admin.id}], type: 'hero', primerLanguage: 'javascript' } [res, body] = yield request.postAsync({uri: getURL('/db/level'), json: levelJSONJSPrimer1}) expect(res.statusCode).toBe(200) @levelJSPrimer1 = yield Level.findById(res.body._id) campaignJSON = { name: 'Campaign', levels: {} } paredLevelJSPrimer1 = _.pick(@levelJSPrimer1.toObject(), 'name', 'original', 'type', 'slug', 'primerLanguage') paredLevelJSPrimer1.campaignIndex = 3 campaignJSON.levels[PI:EMAIL:<EMAIL>END_PI()] = paredLevelJSPrimer1 paredLevelC = _.pick(@levelC.toObject(), 'name', 'original', 'type', 'slug', 'practice') paredLevelC.campaignIndex = 2 campaignJSON.levels[@PI:EMAIL:<EMAIL>END_PI('PI:EMAIL:<EMAIL>END_PI()] = paredLevelC paredLevelB = _.pick(@levelB.toObject(), 'name', 'original', 'type', 'slug') paredLevelB.campaignIndex = 1 campaignJSON.levels[@levelB.get('original').toString()] = paredLevelB paredLevelA = _.pick(@levelA.toObject(), 'name', 'original', 'type', 'slug') paredLevelA.campaignIndex = 0 campaignJSON.levels[@levelA.get('original').toString()] = paredLevelA [res, body] = yield request.postAsync({uri: getURL('/db/campaign'), json: campaignJSON}) @campaign = yield Campaign.findById(res.body._id) @course = Course({name: 'Course', campaignID: @campaign._id, releasePhase: 'released'}) yield @course.save() done() it 'creates a new classroom for the given user with teacher role', utils.wrap (done) -> teacher = yield utils.initUser({role: 'teacher'}) yield utils.loginUser(teacher) data = { name: 'Classroom 1' } [res, body] = yield request.postAsync {uri: classroomsURL, json: data } expect(res.statusCode).toBe(201) expect(res.body.name).toBe('Classroom 1') expect(res.body.members.length).toBe(0) expect(res.body.ownerID).toBe(teacher.id) done() it 'returns 401 for anonymous users', utils.wrap (done) -> yield utils.logout() data = { name: 'Classroom 2' } [res, body] = yield request.postAsync {uri: classroomsURL, json: data } expect(res.statusCode).toBe(401) done() it 'does not work for non-teacher users', utils.wrap (done) -> user = yield utils.initUser() yield utils.loginUser(user) data = { name: 'Classroom 1' } [res, body] = yield request.postAsync {uri: classroomsURL, json: data } expect(res.statusCode).toBe(403) done() describe 'when javascript classroom', -> beforeEach utils.wrap (done) -> teacher = yield utils.initUser({role: 'teacher'}) yield utils.loginUser(teacher) data = { name: 'Classroom 2', aceConfig: { language: 'javascript' } } [res, body] = yield request.postAsync {uri: classroomsURL, json: data } @classroom = yield Classroom.findById(res.body._id) done() it 'makes a copy of the list of all levels in all courses', utils.wrap (done) -> expect(@classroom.get('courses')[0].levels.length).toEqual(3) expect(@classroom.get('courses')[0].levels[0].original.toString()).toBe(@levelA.get('original').toString()) expect(@classroom.get('courses')[0].levels[0].type).toBe('course') expect(@classroom.get('courses')[0].levels[0].slug).toBe('level-a') expect(@classroom.get('courses')[0].levels[0].name).toBe('Level A') done() describe 'when python classroom', -> beforeEach utils.wrap (done) -> teacher = yield utils.initUser({role: 'teacher'}) yield utils.loginUser(teacher) data = { name: 'Classroom 2', aceConfig: { language: 'python' } } [res, body] = yield request.postAsync {uri: classroomsURL, json: data } @classroom = yield Classroom.findById(res.body._id) done() it 'makes a copy all levels in all courses', utils.wrap (done) -> expect(@classroom.get('courses')[0].levels.length).toEqual(4) expect(@classroom.get('courses')[0].levels[0].original.toString()).toBe(@levelA.get('original').toString()) expect(@classroom.get('courses')[0].levels[0].type).toBe('course') expect(@classroom.get('courses')[0].levels[0].slug).toBe('level-a') expect(@classroom.get('courses')[0].levels[0].name).toBe('Level A') done() describe 'when there are unreleased courses', -> beforeEach utils.wrap (done) -> admin = yield utils.initAdmin() yield utils.loginUser(admin) betaLevelJSON = { name: 'Beta Level', permissions: [{access: 'owner', target: admin.id}], type: 'course' } [res, body] = yield request.postAsync({uri: getURL('/db/level'), json: betaLevelJSON}) expect(res.statusCode).toBe(200) @betaLevel = yield Level.findById(res.body._id) betaCampaignJSON = { name: 'Beta Campaign', levels: {} } paredBetaLevel = _.pick(@betaLevel.toObject(), 'name', 'original', 'type', 'slug') paredBetaLevel.campaignIndex = 0 betaCampaignJSON.levels[@betaLevel.get('original').toString()] = paredBetaLevel [res, body] = yield request.postAsync({uri: getURL('/db/campaign'), json: betaCampaignJSON}) @betaCampaign = yield Campaign.findById(res.body._id) @betaCourse = Course({name: 'Beta Course', campaignID: @betaCampaign._id, releasePhase: 'beta'}) yield @betaCourse.save() done() it 'includes unreleased courses for admin teachers', utils.wrap (done) -> adminTeacher = yield utils.initUser({ role: 'teacher', permissions: ['admin'] }) yield utils.loginUser(adminTeacher) data = { name: 'Classroom 3' } [res, body] = yield request.postAsync {uri: classroomsURL, json: data } classroom = yield Classroom.findById(res.body._id) expect(classroom.get('courses').length).toBe(2) expect(classroom.get('courses')[0].levels[0].original.toString()).toBe(@levelA.get('original').toString()) expect(classroom.get('courses')[0].levels[0].type).toBe('course') expect(classroom.get('courses')[0].levels[0].slug).toBe('level-a') expect(classroom.get('courses')[0].levels[0].name).toBe('Level A') expect(classroom.get('courses')[1].levels[0].original.toString()).toBe(@betaLevel.get('original').toString()) expect(classroom.get('courses')[1].levels[0].type).toBe('course') expect(classroom.get('courses')[1].levels[0].slug).toBe('beta-level') expect(classroom.get('courses')[1].levels[0].name).toBe('Beta Level') done() it 'does not include unreleased courses for non-admin teachers', utils.wrap (done) -> teacher = yield utils.initUser({role: 'teacher'}) yield utils.loginUser(teacher) data = { name: 'Classroom 4' } [res, body] = yield request.postAsync {uri: classroomsURL, json: data } classroom = yield Classroom.findById(res.body._id) expect(classroom.get('courses').length).toBe(1) expect(classroom.get('courses')[0].levels[0].original.toString()).toBe(@levelA.get('original').toString()) expect(classroom.get('courses')[0].levels[0].type).toBe('course') expect(classroom.get('courses')[0].levels[0].slug).toBe('level-a') expect(classroom.get('courses')[0].levels[0].name).toBe('Level A') done() describe 'GET /db/classroom/:handle/levels', -> beforeEach utils.wrap (done) -> yield utils.clearModels [User, Classroom, Course, Level, Campaign] admin = yield utils.initAdmin() yield utils.loginUser(admin) levelJSON = { name: 'A', permissions: [{access: 'owner', target: admin.id}], type: 'course' } [res, body] = yield request.postAsync({uri: getURL('/db/level'), json: levelJSON}) expect(res.statusCode).toBe(200) @levelA = yield Level.findById(res.body._id) paredLevelA = _.pick(res.body, 'name', 'original', 'type') levelJSON = { name: 'B', permissions: [{access: 'owner', target: admin.id}], type: 'course' } [res, body] = yield request.postAsync({uri: getURL('/db/level'), json: levelJSON}) expect(res.statusCode).toBe(200) @levelB = yield Level.findById(res.body._id) paredLevelB = _.pick(res.body, 'name', 'original', 'type') levelJSON = { name: 'JS Primer 1', permissions: [{access: 'owner', target: admin.id}], type: 'course', primerLanguage: 'javascript' } [res, body] = yield request.postAsync({uri: getURL('/db/level'), json: levelJSON}) expect(res.statusCode).toBe(200) @levelJSPrimer1 = yield Level.findById(res.body._id) paredLevelJSPrimer1 = _.pick(res.body, 'name', 'original', 'type') campaignJSONA = { name: 'Campaign A', levels: {} } campaignJSONA.levels[paredLevelA.original] = paredLevelA [res, body] = yield request.postAsync({uri: getURL('/db/campaign'), json: campaignJSONA}) @campaignA = yield Campaign.findById(res.body._id) campaignJSONB = { name: 'Campaign B', levels: {} } campaignJSONB.levels[paredLevelB.original] = paredLevelB campaignJSONB.levels[paredLevelJSPrimer1.original] = paredLevelJSPrimer1 [res, body] = yield request.postAsync({uri: getURL('/db/campaign'), json: campaignJSONB}) @campaignB = yield Campaign.findById(res.body._id) @courseA = Course({name: 'Course A', campaignID: @campaignA._id, releasePhase: 'released'}) yield @courseA.save() @courseB = Course({name: 'Course B', campaignID: @campaignB._id, releasePhase: 'released'}) yield @courseB.save() done() describe 'when javascript classroom', -> beforeEach utils.wrap (done) -> teacher = yield utils.initUser({role: 'teacher'}) yield utils.loginUser(teacher) data = { name: 'Classroom 1', aceConfig: { language: 'javascript' } } [res, body] = yield request.postAsync {uri: classroomsURL, json: data } expect(res.statusCode).toBe(201) @classroom = yield Classroom.findById(res.body._id) done() it 'returns all levels referenced in in the classroom\'s copy of course levels', utils.wrap (done) -> [res, body] = yield request.getAsync { uri: getURL("/db/classroom/#{@classroom.id}/levels"), json: true } expect(res.statusCode).toBe(200) levels = res.body expect(levels.length).toBe(2) [res, body] = yield request.getAsync { uri: getURL("/db/classroom/#{@classroom.id}/courses/#{@courseA.id}/levels"), json: true } expect(res.statusCode).toBe(200) levels = res.body expect(levels.length).toBe(1) expect(levels[0].original).toBe(@levelA.get('original').toString()) [res, body] = yield request.getAsync { uri: getURL("/db/classroom/#{@classroom.id}/courses/#{@courseB.id}/levels"), json: true } expect(res.statusCode).toBe(200) levels = res.body expect(levels.length).toBe(1) expect(levels[0].original).toBe(@levelB.get('original').toString()) done() describe 'when python classroom', -> beforeEach utils.wrap (done) -> teacher = yield utils.initUser({role: 'teacher'}) yield utils.loginUser(teacher) data = { name: 'Classroom 1', aceConfig: { language: 'python' } } [res, body] = yield request.postAsync {uri: classroomsURL, json: data } expect(res.statusCode).toBe(201) @classroom = yield Classroom.findById(res.body._id) done() it 'returns all levels referenced in in the classroom\'s copy of course levels', utils.wrap (done) -> [res, body] = yield request.getAsync { uri: getURL("/db/classroom/#{@classroom.id}/levels"), json: true } expect(res.statusCode).toBe(200) levels = res.body expect(levels.length).toBe(3) [res, body] = yield request.getAsync { uri: getURL("/db/classroom/#{@classroom.id}/courses/#{@courseA.id}/levels"), json: true } expect(res.statusCode).toBe(200) levels = res.body expect(levels.length).toBe(1) expect(levels[0].original).toBe(@levelA.get('original').toString()) [res, body] = yield request.getAsync { uri: getURL("/db/classroom/#{@classroom.id}/courses/#{@courseB.id}/levels"), json: true } expect(res.statusCode).toBe(200) levels = res.body expect(levels.length).toBe(2) expect(levels[0].original).toBe(@levelB.get('original').toString()) expect(levels[1].original).toBe(@levelJSPrimer1.get('original').toString()) done() describe 'PUT /db/classroom/:handle', -> beforeEach utils.wrap (done) -> yield utils.clearModels([User, Classroom]) teacher = yield utils.initUser({role: 'teacher'}) yield utils.loginUser(teacher) @classroom = yield utils.makeClassroom() @url = utils.getURL("/db/classroom/#{@classroom.id}") done() it 'edits name and description', utils.wrap (done) -> json = { name: 'New Name!', description: 'New Description' } [res, body] = yield request.putAsync { @url, json } expect(body.name).toBe('New Name!') expect(body.description).toBe('New Description') done() it 'is not allowed if you are just a member', utils.wrap (done) -> student = yield utils.initUser() yield utils.loginUser(student) joinUrl = getURL("/db/classroom/~/members") joinJson = { code: @classroom.get('code') } [res, body] = yield request.postAsync { url: joinUrl, json: joinJson } expect(res.statusCode).toBe(200) json = { name: 'New Name!', description: 'New Description' } [res, body] = yield request.putAsync { @url, json } expect(res.statusCode).toBe(403) done() describe 'POST /db/classroom/-/members', -> beforeEach utils.wrap (done) -> yield utils.clearModels([User, Classroom, Course, Campaign]) @campaign = new Campaign({levels: {}}) yield @campaign.save() @course = new Course({free: true, campaignID: @campaign._id, releasePhase: 'released'}) yield @course.save() @teacher = yield utils.initUser({role: 'teacher'}) yield utils.loginUser(@teacher) [res, body] = yield request.postAsync({uri: classroomsURL, json: { name: 'Classroom 5' } }) expect(res.statusCode).toBe(201) @classroom = yield Classroom.findById(body._id) [res, body] = yield request.postAsync({uri: getURL('/db/course_instance'), json: { courseID: @course.id, classroomID: @classroom.id }}) expect(res.statusCode).toBe(200) @courseInstance = yield CourseInstance.findById(res.body._id) @student = yield utils.initUser() done() it 'adds the signed in user to the classroom and any free courses and sets role to student and unsubscribes', utils.wrap (done) -> spyOn(subscriptions, 'unsubscribeUser').and.returnValue(Promise.resolve()); yield utils.loginUser(@student) url = getURL("/db/classroom/anything-here/members") [res, body] = yield request.postAsync { uri: url, json: { code: @classroom.get('code') } } expect(res.statusCode).toBe(200) classroom = yield Classroom.findById(@classroom.id) expect(classroom.get('members').length).toBe(1) expect(classroom.get('members')?[0]?.equals(@student._id)).toBe(true) expect(subscriptions.unsubscribeUser).toHaveBeenCalled() student = yield User.findById(@student.id) if student.get('role') isnt 'student' fail('student role should be "student"') unless student.get('courseInstances')?[0].equals(@courseInstance._id) fail('student should be added to the free course instance.') done() it 'joins the class even with spaces in the classcode', utils.wrap (done) -> yield utils.loginUser(@student) url = getURL("/db/classroom/anything-here/members") code = @classroom.get('code') codeWithSpaces = code.split("").join(" ") [res, body] = yield request.postAsync { uri: url, json: { code: codeWithSpaces } } expect(res.statusCode).toBe(200) classroom = yield Classroom.findById(@classroom.id) if classroom.get('members').length isnt 1 fail 'expected classCode with spaces to work too' done() it 'returns 403 if the user is a teacher', utils.wrap (done) -> yield utils.loginUser(@teacher) url = getURL("/db/classroom/~/members") [res, body] = yield request.postAsync { uri: url, json: { code: @classroom.get('code') } } expect(res.statusCode).toBe(403) done() it 'returns 401 if the user is anonymous', utils.wrap (done) -> yield utils.becomeAnonymous() [res, body] = yield request.postAsync { uri: getURL("/db/classroom/-/members"), json: { code: @classroom.get('code') } } expect(res.statusCode).toBe(401) done() describe 'DELETE /db/classroom/:id/members', -> beforeEach utils.wrap (done) -> yield utils.clearModels([User, Classroom]) @teacher = yield utils.initUser({role: 'teacher'}) yield utils.loginUser(@teacher) @student = yield utils.initUser() @classroom = yield utils.makeClassroom({}, {members:[@student]}) @url = utils.getURL("/db/classroom/#{@classroom.id}/members") done() it 'removes the given user from the list of members in the classroom', utils.wrap (done) -> expect(@classroom.get('members').length).toBe(1) json = { userID: @student.id } [res, body] = yield request.delAsync { @url, json } expect(res.statusCode).toBe(200) classroom = yield Classroom.findById(@classroom.id) expect(classroom.get('members').length).toBe(0) done() describe 'POST /db/classroom/:id/invite-members', -> it 'takes a list of emails and sends invites', utils.wrap (done) -> user = yield utils.initUser({role: 'teacher', name: 'PI:NAME:<NAME>END_PI'}) yield utils.loginUser(user) classroom = yield utils.makeClassroom() url = classroomsURL + "/#{classroom.id}/invite-members" data = { emails: ['PI:EMAIL:<EMAIL>END_PI'] } sendwithus = require '../../../server/sendwithus' spyOn(sendwithus.api, 'send').and.callFake (context, cb) -> expect(context.email_id).toBe(sendwithus.templates.course_invite_email) expect(context.recipient.address).toBe('PI:EMAIL:<EMAIL>END_PI') expect(context.email_data.teacher_name).toBe('PI:NAME:<NAME>END_PI') done() [res, body] = yield request.postAsync { uri: url, json: data } expect(res.statusCode).toBe(200) describe 'GET /db/classroom/:handle/member-sessions', -> beforeEach utils.wrap (done) -> yield utils.clearModels([CourseInstance, Course, User, Classroom, Campaign, Level, LevelSession]) @teacher = yield utils.initUser({role: 'teacher'}) admin = yield utils.initAdmin() yield utils.loginUser(admin) @levelA = yield utils.makeLevel({type: 'course'}) @levelB = yield utils.makeLevel({type: 'course', primerLanguage: 'python'}) @campaignA = yield utils.makeCampaign({}, {levels: [@levelA]}) @campaignB = yield utils.makeCampaign({}, {levels: [@levelB]}) @courseA = yield utils.makeCourse({free: true, releasePhase: 'released'}, {campaign: @campaignA}) @courseB = yield utils.makeCourse({free: true, releasePhase: 'released'}, {campaign: @campaignB}) @student1 = yield utils.initUser({role: 'student'}) @student2 = yield utils.initUser({role: 'student'}) @session1A = yield utils.makeLevelSession({codeLanguage: 'javascript', state: { complete: true }}, {creator: @student1, level: @levelA}) @session1B = yield utils.makeLevelSession({codeLanguage: 'python', state: { complete: false }}, {creator: @student1, level: @levelB}) @session2A = yield utils.makeLevelSession({codeLanguage: 'javascript', state: { complete: true }}, {creator: @student2, level: @levelA}) @session2B = yield utils.makeLevelSession({codeLanguage: 'python', state: { complete: false }}, {creator: @student2, level: @levelB}) yield utils.loginUser(@teacher) @classroom = yield utils.makeClassroom({aceConfig: {language: 'javascript'}}, { members: [@student1, @student2] }) @courseInstanceA = yield utils.makeCourseInstance({courseID: @courseA.id, classroomID: @classroom.id}, { members: [@student1, @student2] }) @courseInstanceB = yield utils.makeCourseInstance({courseID: @courseB.id, classroomID: @classroom.id}, { members: [@student1] }) yield utils.logout() done() it 'returns all sessions for all members in the classroom with assigned courses', utils.wrap (done) -> yield utils.loginUser(@teacher) [res, body] = yield request.getAsync getURL("/db/classroom/#{@classroom.id}/member-sessions"), { json: true } expect(res.statusCode).toBe(200) expect(body.length).toBe(3) done() it 'does not work if you are not the owner of the classroom', utils.wrap (done) -> yield utils.loginUser(@student1) [res, body] = yield request.getAsync getURL("/db/classroom/#{@classroom.id}/member-sessions"), { json: true } expect(res.statusCode).toBe(403) done() it 'does not work if you are not logged in', utils.wrap (done) -> [res, body] = yield request.getAsync getURL("/db/classroom/#{@classroom.id}/member-sessions"), { json: true } expect(res.statusCode).toBe(401) done() it 'accepts memberSkip and memberLimit GET parameters', utils.wrap (done) -> yield utils.loginUser(@teacher) [res, body] = yield request.getAsync getURL("/db/classroom/#{@classroom.id}/member-sessions?memberLimit=1"), { json: true } expect(res.statusCode).toBe(200) expect(body.length).toBe(2) expect(session.creator).toBe(@student1.id) for session in body [res, body] = yield request.getAsync getURL("/db/classroom/#{@classroom.id}/member-sessions?memberSkip=1"), { json: true } expect(res.statusCode).toBe(200) expect(body.length).toBe(1) expect(session.creator).toBe(@student2.id) for session in body done() describe 'GET /db/classroom/:handle/members', -> beforeEach utils.wrap (done) -> yield utils.clearModels([User, Classroom]) @teacher = yield utils.initUser() @student1 = yield utils.initUser({ name: "PI:NAME:<NAME>END_PI", firstName: "PI:NAME:<NAME>END_PI", lastName: "L", coursePrepaid: { _id: mongoose.Types.ObjectId() } }) @student2 = yield utils.initUser({ name: "PI:NAME:<NAME>END_PI", firstName: "Student", lastName: "N" }) @classroom = yield new Classroom({name: 'Classroom', ownerID: @teacher._id, members: [@student1._id, @student2._id] }).save() @emptyClassroom = yield new Classroom({name: 'Empty Classroom', ownerID: @teacher._id, members: [] }).save() done() it 'does not work if you are not the owner of the classroom', utils.wrap (done) -> yield utils.loginUser(@student1) [res, body] = yield request.getAsync getURL("/db/classroom/#{@classroom.id}/member-sessions"), { json: true } expect(res.statusCode).toBe(403) done() it 'does not work if you are not logged in', utils.wrap (done) -> [res, body] = yield request.getAsync getURL("/db/classroom/#{@classroom.id}/member-sessions"), { json: true } expect(res.statusCode).toBe(401) done() it 'works on an empty classroom', utils.wrap (done) -> yield utils.loginUser(@teacher) [res, body] = yield request.getAsync getURL("/db/classroom/#{@emptyClassroom.id}/members?name=true&email=true"), { json: true } expect(res.statusCode).toBe(200) expect(body).toEqual([]) done() it 'returns all members with name, email, coursePrepaid, firstName and lastName', utils.wrap (done) -> yield utils.loginUser(@teacher) [res, body] = yield request.getAsync getURL("/db/classroom/#{@classroom.id}/members?name=true&email=true"), { json: true } expect(res.statusCode).toBe(200) expect(body.length).toBe(2) for user in body expect(user.name).toBeDefined() expect(user.email).toBeDefined() expect(user.firstName).toBeDefined() expect(user.lastName).toBeDefined() expect(user.passwordHash).toBeUndefined() student1 = _.find(body, {_id: @student1.id}) expect(student1.coursePrepaid).toBeDefined() done() describe 'POST /db/classroom/:classroomID/members/:memberID/reset-password', -> it 'changes the password', utils.wrap (done) -> yield utils.clearModels([User, Classroom]) teacher = yield utils.initUser() yield utils.loginUser(teacher) student = yield utils.initUser({ name: "PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI" }) newPassword = "PI:PASSWORD:<PASSWORD>END_PI password" classroom = yield new Classroom({name: 'Classroom', ownerID: teacher._id, members: [student._id] }).save() expect(student.get('passwordHash')).not.toEqual(User.hashPassword(newPassword)) [res, body] = yield request.postAsync({ uri: getURL("/db/classroom/#{classroom.id}/members/#{student.id}/reset-password") json: { password: PI:PASSWORD:<PASSWORD>END_PI } }) expect(res.statusCode).toBe(200) changedStudent = yield User.findById(student.id) expect(changedStudent.get('passwordHash')).toEqual(User.hashPassword(newPassword)) done() it "doesn't change the password if you're not their teacher", utils.wrap (done) -> yield utils.clearModels([User, Classroom]) teacher = yield utils.initUser() yield utils.loginUser(teacher) student = yield utils.initUser({ name: "PI:NAME:<NAME>END_PI" }) student2 = yield utils.initUser({ name: "PI:NAME:<NAME>END_PI" }) newPassword = "PI:PASSWORD:<PASSWORD>END_PI" classroom = yield new Classroom({name: 'Classroom', ownerID: teacher._id, members: [student2._id] }).save() expect(student.get('passwordHash')).not.toEqual(User.hashPassword(PI:PASSWORD:<PASSWORD>END_PI)) [res, body] = yield request.postAsync({ uri: getURL("/db/classroom/#{classroom.id}/members/#{student.id}/reset-password") json: { password: PI:PASSWORD:<PASSWORD>END_PI } }) expect(res.statusCode).toBe(403) changedStudent = yield User.findById(student.id) expect(changedStudent.get('passwordHash')).toEqual(student.get('passwordHash')) done() it "doesn't change the password if their email is verified", utils.wrap (done) -> yield utils.clearModels([User, Classroom]) teacher = yield utils.initUser() yield utils.loginUser(teacher) student = yield utils.initUser({ name: "PI:NAME:<NAME>END_PI", emailVerified: true }) newPassword = "PI:PASSWORD:<PASSWORD>END_PI" classroom = yield new Classroom({name: 'Classroom', ownerID: teacher._id, members: [student._id] }).save() expect(student.get('passwordHash')).not.toEqual(User.hashPassword(PI:PASSWORD:<PASSWORD>END_PI)) [res, body] = yield request.postAsync({ uri: getURL("/db/classroom/#{classroom.id}/members/#{student.id}/reset-password") json: { password: PI:PASSWORD:<PASSWORD>END_PI } }) expect(res.statusCode).toBe(403) changedStudent = yield User.findById(student.id) expect(changedStudent.get('passwordHash')).toEqual(student.get('passwordHash')) done() it "doesn't let you set a 1-character password", utils.wrap (done) -> yield utils.clearModels([User, Classroom]) teacher = yield utils.initUser() yield utils.loginUser(teacher) student = yield utils.initUser({ name: "PI:NAME:<NAME>END_PI" }) newPassword = "PI:PASSWORD:<PASSWORD>END_PI" classroom = yield new Classroom({name: 'Classroom', ownerID: teacher._id, members: [student._id] }).save() expect(student.get('passwordHash')).not.toEqual(User.hashPassword(PI:PASSWORD:<PASSWORD>END_PI)) [res, body] = yield request.postAsync({ uri: getURL("/db/classroom/#{classroom.id}/members/#{student.id}/reset-password") json: { password: PI:PASSWORD:<PASSWORD>END_PI } }) expect(res.statusCode).toBe(422) changedStudent = yield User.findById(student.id) expect(changedStudent.get('passwordHash')).toEqual(student.get('passwordHash')) done() describe 'GET /db/classroom/:handle/update-courses', -> it 'updates the courses property for that classroom', utils.wrap (done) -> yield utils.clearModels [User, Classroom, Course, Level, Campaign] admin = yield utils.initAdmin() teacher = yield utils.initUser({role: 'teacher'}) # make a single course yield utils.loginUser(admin) yield utils.makeCourse({releasePhase: 'released'}, {campaign: yield utils.makeCampaign()}) # make a classroom, make sure it has the one course yield utils.loginUser(teacher) data = { name: 'Classroom 2' } [res, body] = yield request.postAsync {uri: classroomsURL, json: data } classroom = yield Classroom.findById(res.body._id) expect(classroom.get('courses').length).toBe(1) # make a second course yield utils.loginUser(admin) yield utils.makeCourse({releasePhase: 'released'}, {campaign: yield utils.makeCampaign()}) # make sure classroom still has one course classroom = yield Classroom.findById(res.body._id) expect(classroom.get('courses').length).toBe(1) # update, check update happens yield utils.loginUser(teacher) [res, body] = yield request.postAsync { uri: classroomsURL + "/#{classroom.id}/update-courses", json: true } expect(body.courses.length).toBe(2) classroom = yield Classroom.findById(res.body._id) expect(classroom.get('courses').length).toBe(2) done() it 'allows admins to also update a classroom, but uses the owner\'s admin status', utils.wrap (done) -> yield utils.clearModels [User, Classroom, Course, Level, Campaign] admin = yield utils.initAdmin() teacher = yield utils.initUser({role: 'teacher'}) # make two courses, one released, one beta yield utils.loginUser(admin) yield utils.makeCourse({releasePhase: 'released'}, {campaign: yield utils.makeCampaign()}) yield utils.makeCourse({releasePhase: 'beta'}, {campaign: yield utils.makeCampaign()}) # make a classroom, make sure it has the one course yield utils.loginUser(teacher) data = { name: 'Classroom 2' } [res, body] = yield request.postAsync {uri: classroomsURL, json: data } classroom = yield Classroom.findById(res.body._id) expect(classroom.get('courses').length).toBe(1) # make another released course yield utils.loginUser(admin) yield utils.makeCourse({releasePhase: 'released'}, {campaign: yield utils.makeCampaign()}) # make sure classroom still has one course classroom = yield Classroom.findById(res.body._id) expect(classroom.get('courses').length).toBe(1) # update, check that classroom has the two released courses [res, body] = yield request.postAsync { uri: classroomsURL + "/#{classroom.id}/update-courses", json: true } expect(body.courses.length).toBe(2) classroom = yield Classroom.findById(res.body._id) expect(classroom.get('courses').length).toBe(2) done() describe 'addNewCoursesOnly', -> it 'only adds new courses, but leaves existing courses intact', utils.wrap (done) -> yield utils.clearModels [User, Classroom, Course, Level, Campaign] admin = yield utils.initAdmin() teacher = yield utils.initUser({role: 'teacher'}) # make a single course yield utils.loginUser(admin) levels = yield _.times(3, -> utils.makeLevel()) firstCampaign = yield utils.makeCampaign({}, {levels: [levels[0]]}) yield utils.makeCourse({releasePhase: 'released'}, {campaign: firstCampaign}) # make a classroom, make sure it has the one course yield utils.loginUser(teacher) data = { name: 'Classroom 2' } [res, body] = yield request.postAsync {uri: classroomsURL, json: data } classroom = yield Classroom.findById(res.body._id) expect(classroom.get('courses').length).toBe(1) expect(classroom.get('courses')[0].levels.length).toBe(1) # make a second course yield utils.loginUser(admin) yield utils.makeCourse({releasePhase: 'released'}, {campaign: yield utils.makeCampaign({}, {levels: [levels[1]]})}) # add level to first course campaignSchema = require '../../../app/schemas/models/campaign.schema' campaignLevelProperties = _.keys(campaignSchema.properties.levels.additionalProperties.properties) levelAdding = levels[2] campaignLevels = _.clone(firstCampaign.get('levels')) campaignLevels[levelAdding.get('original').valueOf()] = _.pick levelAdding.toObject(), campaignLevelProperties yield firstCampaign.update({$set: {levels: campaignLevels}}) # make sure classroom still has one course classroom = yield Classroom.findById(res.body._id) expect(classroom.get('courses').length).toBe(1) # update with addNewCoursesOnly, make sure second course is added but first keeps the same # of levels yield utils.loginUser(teacher) [res, body] = yield request.postAsync { uri: classroomsURL + "/#{classroom.id}/update-courses", json: { addNewCoursesOnly:true } } expect(body.courses.length).toBe(2) expect(body.courses[0].levels.length).toBe(1) classroom = yield Classroom.findById(res.body._id) expect(classroom.get('courses').length).toBe(2) expect(classroom.get('courses')[0].levels.length).toBe(1) # update without addNewCoursesOnly, make sure first course still updates [res, body] = yield request.postAsync { uri: classroomsURL + "/#{classroom.id}/update-courses", json: true } expect(body.courses.length).toBe(2) expect(body.courses[0].levels.length).toBe(2) classroom = yield Classroom.findById(res.body._id) expect(classroom.get('courses').length).toBe(2) expect(classroom.get('courses')[0].levels.length).toBe(2) done()
[ { "context": "', 'Specialty'\n\nschoolsGrid.addRow 'PMG <br />', 'Burgas', 60, 'Math'\nschoolsGrid.addRow 'TUES', 'Sofia', ", "end": 180, "score": 0.9974783658981323, "start": 174, "tag": "NAME", "value": "Burgas" }, { "context": "udents = (new schoolNS.Student(\"Student - #{i}\", \"...
WebDesign/5.JavaScriptApplications/4.JQueryOverview/5.Grid/scripts/main.coffee
trinityimma/TelerikAcademy
0
'use strict' schoolsGrid = controls.GridView '#grid-view-holder' schoolsGrid.addHeader 'Name', 'Location', 'Total Students', 'Specialty' schoolsGrid.addRow 'PMG <br />', 'Burgas', 60, 'Math' schoolsGrid.addRow 'TUES', 'Sofia', 500, 'IT' academyRow = schoolsGrid.addRow 'Telerik Academy', 'Sofia', 5000, 'IT' do -> academyGrid = academyRow.getNestedGrid() academyGrid.addHeader 'Title', 'Start Date', 'Total Students' academyGrid.addRow 'JS 2', '11-april-2013', 400 academyGrid.addRow 'SEO', '15-may-2013', 400 sliceAndDiceRow = academyGrid.addRow 'Slice and Dice', '05-april-2013', 500 do -> sliceAndDiceGrid = sliceAndDiceRow.getNestedGrid() sliceAndDiceGrid.addHeader 'HTML', 'CSS' sliceAndDiceGrid.addRow 'HTML 4', 'CSS 2' sliceAndDiceGrid.addRow 'HTML 5', 'CSS 3' schoolsGrid.render() do -> students = (new schoolNS.Student("Student - #{i}", "Ivanov", J.random(1, 100)) for i in [1..40]) courses = (new schoolNS.Course(i, new Date(J.random(1e12, 2e12))) for i in ['JS I', 'JS II', 'SEO', 'S&D']) courses[0].addStudents students[0...10] courses[1].addStudents students[10...20] courses[2].addStudents students[20...30] courses[3].addStudents students[30...40] for course in courses for student in course.students student.addMark course, J.random(0, 100) schools = [ new schoolNS.School 'PMG', 'Burgas', 'Mathematics' new schoolNS.School 'TUES', 'Sofia', 'IT' new schoolNS.School 'Telerik Academy', 'Sofia', 'IT' ] schools[0].addCourse courses[0..2] schools[1].addCourse [courses[3]] # schools[2].addCourse [courses[3]] delay = 1 setTimeout -> console.log "Task 4: Save to localStorage from data" schoolNS.schoolRepository.save 'schools-repository', schools , delay++ * 500 schoolsData = null setTimeout -> console.log "Task 4: Load from localStorage" schoolsData = schoolNS.schoolRepository.load('schools-repository') console.log schoolsData , delay++ * 500 setTimeout -> console.log "Task 6: Build schools grid from the loaded data" schoolsGrid = controls.buildSchoolsGridView('#schools-grid', schoolsData) schoolsGrid.render() , delay++ * 500 setTimeout -> console.log "Task 5: Get the data from the new grid" console.log controls.getSchoolsGridViewData(schoolsGrid) , delay++ * 500
158157
'use strict' schoolsGrid = controls.GridView '#grid-view-holder' schoolsGrid.addHeader 'Name', 'Location', 'Total Students', 'Specialty' schoolsGrid.addRow 'PMG <br />', '<NAME>', 60, 'Math' schoolsGrid.addRow 'TUES', 'Sofia', 500, 'IT' academyRow = schoolsGrid.addRow 'Telerik Academy', 'Sofia', 5000, 'IT' do -> academyGrid = academyRow.getNestedGrid() academyGrid.addHeader 'Title', 'Start Date', 'Total Students' academyGrid.addRow 'JS 2', '11-april-2013', 400 academyGrid.addRow 'SEO', '15-may-2013', 400 sliceAndDiceRow = academyGrid.addRow 'Slice and Dice', '05-april-2013', 500 do -> sliceAndDiceGrid = sliceAndDiceRow.getNestedGrid() sliceAndDiceGrid.addHeader 'HTML', 'CSS' sliceAndDiceGrid.addRow 'HTML 4', 'CSS 2' sliceAndDiceGrid.addRow 'HTML 5', 'CSS 3' schoolsGrid.render() do -> students = (new schoolNS.Student("Student - #{i}", "<NAME>", J.random(1, 100)) for i in [1..40]) courses = (new schoolNS.Course(i, new Date(J.random(1e12, 2e12))) for i in ['JS I', 'JS II', 'SEO', 'S&D']) courses[0].addStudents students[0...10] courses[1].addStudents students[10...20] courses[2].addStudents students[20...30] courses[3].addStudents students[30...40] for course in courses for student in course.students student.addMark course, J.random(0, 100) schools = [ new schoolNS.School 'PMG', 'Burgas', 'Mathematics' new schoolNS.School 'TUES', 'Sofia', 'IT' new schoolNS.School 'Telerik Academy', 'Sofia', 'IT' ] schools[0].addCourse courses[0..2] schools[1].addCourse [courses[3]] # schools[2].addCourse [courses[3]] delay = 1 setTimeout -> console.log "Task 4: Save to localStorage from data" schoolNS.schoolRepository.save 'schools-repository', schools , delay++ * 500 schoolsData = null setTimeout -> console.log "Task 4: Load from localStorage" schoolsData = schoolNS.schoolRepository.load('schools-repository') console.log schoolsData , delay++ * 500 setTimeout -> console.log "Task 6: Build schools grid from the loaded data" schoolsGrid = controls.buildSchoolsGridView('#schools-grid', schoolsData) schoolsGrid.render() , delay++ * 500 setTimeout -> console.log "Task 5: Get the data from the new grid" console.log controls.getSchoolsGridViewData(schoolsGrid) , delay++ * 500
true
'use strict' schoolsGrid = controls.GridView '#grid-view-holder' schoolsGrid.addHeader 'Name', 'Location', 'Total Students', 'Specialty' schoolsGrid.addRow 'PMG <br />', 'PI:NAME:<NAME>END_PI', 60, 'Math' schoolsGrid.addRow 'TUES', 'Sofia', 500, 'IT' academyRow = schoolsGrid.addRow 'Telerik Academy', 'Sofia', 5000, 'IT' do -> academyGrid = academyRow.getNestedGrid() academyGrid.addHeader 'Title', 'Start Date', 'Total Students' academyGrid.addRow 'JS 2', '11-april-2013', 400 academyGrid.addRow 'SEO', '15-may-2013', 400 sliceAndDiceRow = academyGrid.addRow 'Slice and Dice', '05-april-2013', 500 do -> sliceAndDiceGrid = sliceAndDiceRow.getNestedGrid() sliceAndDiceGrid.addHeader 'HTML', 'CSS' sliceAndDiceGrid.addRow 'HTML 4', 'CSS 2' sliceAndDiceGrid.addRow 'HTML 5', 'CSS 3' schoolsGrid.render() do -> students = (new schoolNS.Student("Student - #{i}", "PI:NAME:<NAME>END_PI", J.random(1, 100)) for i in [1..40]) courses = (new schoolNS.Course(i, new Date(J.random(1e12, 2e12))) for i in ['JS I', 'JS II', 'SEO', 'S&D']) courses[0].addStudents students[0...10] courses[1].addStudents students[10...20] courses[2].addStudents students[20...30] courses[3].addStudents students[30...40] for course in courses for student in course.students student.addMark course, J.random(0, 100) schools = [ new schoolNS.School 'PMG', 'Burgas', 'Mathematics' new schoolNS.School 'TUES', 'Sofia', 'IT' new schoolNS.School 'Telerik Academy', 'Sofia', 'IT' ] schools[0].addCourse courses[0..2] schools[1].addCourse [courses[3]] # schools[2].addCourse [courses[3]] delay = 1 setTimeout -> console.log "Task 4: Save to localStorage from data" schoolNS.schoolRepository.save 'schools-repository', schools , delay++ * 500 schoolsData = null setTimeout -> console.log "Task 4: Load from localStorage" schoolsData = schoolNS.schoolRepository.load('schools-repository') console.log schoolsData , delay++ * 500 setTimeout -> console.log "Task 6: Build schools grid from the loaded data" schoolsGrid = controls.buildSchoolsGridView('#schools-grid', schoolsData) schoolsGrid.render() , delay++ * 500 setTimeout -> console.log "Task 5: Get the data from the new grid" console.log controls.getSchoolsGridViewData(schoolsGrid) , delay++ * 500
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.9988842010498047, "start": 12, "tag": "NAME", "value": "Joyent" } ]
test/disabled/test-http-big-proxy-responses.coffee
lxe/io.coffee
0
# Copyright Joyent, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. # Produce a very large response. # Proxy to the chargen server. call_chargen = (list) -> if list.length > 0 len = list.shift() common.debug "calling chargen for " + len + " chunks." recved = 0 req = http.request( port: 9001 host: "localhost" path: "/" headers: "x-len": len , (res) -> res.on "data", (d) -> recved += d.length assert.ok recved <= (len * chunk.length) return res.on "end", -> assert.ok recved <= (len * chunk.length) common.debug "end for " + len + " chunks." call_chargen list return return ) req.end() else console.log "End of list. closing servers" proxy.close() chargen.close() done = true return ready = -> return if ++serversRunning < 2 call_chargen [ 100 1000 10000 100000 1000000 ] return common = require("../common") assert = require("assert") util = require("util") fs = require("fs") http = require("http") url = require("url") chunk = "01234567890123456789" chargen = http.createServer((req, res) -> len = parseInt(req.headers["x-len"], 10) assert.ok len > 0 res.writeHead 200, "transfer-encoding": "chunked" i = 0 while i < len common.print "," if i % 1000 is 0 res.write chunk i++ res.end() return ) chargen.listen 9000, ready proxy = http.createServer((req, res) -> onError = (e) -> console.log "proxy client error. sent " + sent throw ereturn len = parseInt(req.headers["x-len"], 10) assert.ok len > 0 sent = 0 proxy_req = http.request( host: "localhost" port: 9000 method: req.method path: req.url headers: req.headers , (proxy_res) -> res.writeHead proxy_res.statusCode, proxy_res.headers count = 0 proxy_res.on "data", (d) -> common.print "." if count++ % 1000 is 0 res.write d sent += d.length assert.ok sent <= (len * chunk.length) return proxy_res.on "end", -> res.end() return return ) proxy_req.on "error", onError proxy_req.end() return ) proxy.listen 9001, ready done = false serversRunning = 0 process.on "exit", -> assert.ok done return
37831
# Copyright <NAME>, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. # Produce a very large response. # Proxy to the chargen server. call_chargen = (list) -> if list.length > 0 len = list.shift() common.debug "calling chargen for " + len + " chunks." recved = 0 req = http.request( port: 9001 host: "localhost" path: "/" headers: "x-len": len , (res) -> res.on "data", (d) -> recved += d.length assert.ok recved <= (len * chunk.length) return res.on "end", -> assert.ok recved <= (len * chunk.length) common.debug "end for " + len + " chunks." call_chargen list return return ) req.end() else console.log "End of list. closing servers" proxy.close() chargen.close() done = true return ready = -> return if ++serversRunning < 2 call_chargen [ 100 1000 10000 100000 1000000 ] return common = require("../common") assert = require("assert") util = require("util") fs = require("fs") http = require("http") url = require("url") chunk = "01234567890123456789" chargen = http.createServer((req, res) -> len = parseInt(req.headers["x-len"], 10) assert.ok len > 0 res.writeHead 200, "transfer-encoding": "chunked" i = 0 while i < len common.print "," if i % 1000 is 0 res.write chunk i++ res.end() return ) chargen.listen 9000, ready proxy = http.createServer((req, res) -> onError = (e) -> console.log "proxy client error. sent " + sent throw ereturn len = parseInt(req.headers["x-len"], 10) assert.ok len > 0 sent = 0 proxy_req = http.request( host: "localhost" port: 9000 method: req.method path: req.url headers: req.headers , (proxy_res) -> res.writeHead proxy_res.statusCode, proxy_res.headers count = 0 proxy_res.on "data", (d) -> common.print "." if count++ % 1000 is 0 res.write d sent += d.length assert.ok sent <= (len * chunk.length) return proxy_res.on "end", -> res.end() return return ) proxy_req.on "error", onError proxy_req.end() return ) proxy.listen 9001, ready done = false serversRunning = 0 process.on "exit", -> assert.ok done return
true
# Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. # Produce a very large response. # Proxy to the chargen server. call_chargen = (list) -> if list.length > 0 len = list.shift() common.debug "calling chargen for " + len + " chunks." recved = 0 req = http.request( port: 9001 host: "localhost" path: "/" headers: "x-len": len , (res) -> res.on "data", (d) -> recved += d.length assert.ok recved <= (len * chunk.length) return res.on "end", -> assert.ok recved <= (len * chunk.length) common.debug "end for " + len + " chunks." call_chargen list return return ) req.end() else console.log "End of list. closing servers" proxy.close() chargen.close() done = true return ready = -> return if ++serversRunning < 2 call_chargen [ 100 1000 10000 100000 1000000 ] return common = require("../common") assert = require("assert") util = require("util") fs = require("fs") http = require("http") url = require("url") chunk = "01234567890123456789" chargen = http.createServer((req, res) -> len = parseInt(req.headers["x-len"], 10) assert.ok len > 0 res.writeHead 200, "transfer-encoding": "chunked" i = 0 while i < len common.print "," if i % 1000 is 0 res.write chunk i++ res.end() return ) chargen.listen 9000, ready proxy = http.createServer((req, res) -> onError = (e) -> console.log "proxy client error. sent " + sent throw ereturn len = parseInt(req.headers["x-len"], 10) assert.ok len > 0 sent = 0 proxy_req = http.request( host: "localhost" port: 9000 method: req.method path: req.url headers: req.headers , (proxy_res) -> res.writeHead proxy_res.statusCode, proxy_res.headers count = 0 proxy_res.on "data", (d) -> common.print "." if count++ % 1000 is 0 res.write d sent += d.length assert.ok sent <= (len * chunk.length) return proxy_res.on "end", -> res.end() return return ) proxy_req.on "error", onError proxy_req.end() return ) proxy.listen 9001, ready done = false serversRunning = 0 process.on "exit", -> assert.ok done return
[ { "context": "/www.google.com\",\n \"46\": [{ id: 123 }],\n \"47\": \"foo@bar.com\",\n \"48\": {\n \"country\": \"GB\",\n \"street\": \"1", "end": 1392, "score": 0.9999198913574219, "start": 1381, "tag": "EMAIL", "value": "foo@bar.com" }, { "context": "ut')\n $('.fr_respo...
test/get_value_gm_test.coffee
dobtco/formrenderer-base
79
# This is a "Gold master" test. If you need to update these constants, you can do so # by manually clicking through the kitchen sink form in the Chrome dev console and running: # # copy(JSON.stringify($('[data-formrenderer]').data('form-renderer-instance').getValue())) # # ...which will copy the stringified JSON to your clipboard. You should then manually verify # the output, and if you're satisfied, you can finally update the constant. EXPECTED_BLANK_VALUES = { "35": "", "37": { checked: [] }, "39": { checked: [] }, "3900": { checked: [] }, "3901": { checked: [] }, "41": {}, "42": "", "43": {}, "44": { "am_pm": "AM" }, "45": "", "47": "", "46": [], "48": { "country": "US" }, "49": { "column one": [ "", "" ], "column two": [ "", "" ] }, "51": "", "52": false, "53": [{ "54": "" }] } EXPECTED_PRESENT_VALUES = { "35": "foo", "36": "bar", "37": { checked: ["Choice #1 (yas)"] }, "39": { checked: ["Choice #2"] }, "40": "Choice #2", "41": { "dollars": "12", "cents": "99" }, "42": "123", "43": { "month": "12", "day": "30", "year": "2014" }, "44": { "am_pm": "PM", "hours": "6", "minutes": "01", "seconds": "30" }, "45": "http://www.google.com", "46": [{ id: 123 }], "47": "foo@bar.com", "48": { "country": "GB", "street": "123 main st", "state": null }, "49": { "column one": [ "hey", "" ], "column two": [ "", "nay" ] }, "50": ["40.7700118", "-73.9800453"], "51": "510-123-4567", "52": true, "53": [ { "54":"Large Round Son" } ], "3900": { "checked": [], "other_checked": true, "other_text": "some alternative answer" }, "3901": { "checked": [ "Choice #2" ], "other_checked": true, "other_text": "some alternative answer" } } describe '#getValue', -> before -> $('body').html('<div data-formrenderer />') @fr = new FormRenderer Fixtures.FormRendererOptions.KITCHEN_SINK() it 'renders ok', -> expect(@fr).to.be.ok it 'serializes the blank values', -> expect(JSON.stringify(@fr.getValue())).to.equal(JSON.stringify(EXPECTED_BLANK_VALUES)) it 'serializes present values', -> $('.fr_response_field_text input').val('foo').trigger('input') $('.fr_response_field_paragraph textarea').val('bar').trigger('input') $('.fr_response_field_checkboxes input').first().click().trigger('change') $($('.fr_response_field_radio')[0]).find('input[type=radio]').last().click().trigger('change') $($('.fr_response_field_radio')[1]).find('input[type=radio]').last().click().trigger('change') $($('.fr_response_field_checkboxes')[1]).find('input[type=checkbox]').slice(-2).click().trigger('change') $('.fr_other_option input[type=text]').val("some alternative answer").trigger('input') $('.fr_response_field_dropdown select').val('Choice #2').trigger('change') $('.fr_response_field_price input').first().val('12').trigger('input') $('.fr_response_field_price input').last().val('99').trigger('input') $('.fr_response_field_number input').last().val('123').trigger('input') $('.fr_response_field_date input').eq(0).val('12').trigger('input') $('.fr_response_field_date input').eq(1).val('30').trigger('input') $('.fr_response_field_date input').eq(2).val('2014').trigger('input') $('.fr_response_field_time input').eq(0).val('6').trigger('input') $('.fr_response_field_time input').eq(1).val('01').trigger('input') $('.fr_response_field_time input').eq(2).val('30').trigger('input') $('.fr_response_field_time select').val('PM').trigger('change') $('.fr_response_field_website input').val('http://www.google.com').trigger('input') $('.fr_response_field_email input').val('foo@bar.com').trigger('input') $('.fr_response_field_address input').eq(0).val('123 main st').trigger('input') $('.fr_response_field_address select').val('GB').trigger('change') $('.fr_response_field_table textarea').eq(0).val('hey').trigger('input') $('.fr_response_field_table textarea').eq(3).val('nay').trigger('input') $('.fr_response_field_phone input').val('510-123-4567').trigger('input') $('.fr_response_field_map_marker .fr_map_cover').click() $('.fr_response_field_confirm input').first().click().trigger('change') $('.fr_response_field_group').first().find('[type=text]').val('Large Round Son').trigger('input') # File inlineFileUpload = $('input[type=file]').data('inline-file-upload') inlineFileUpload.options.success(data: { file_id: 123 }) expect(JSON.stringify(@fr.getValue())).to.equal(JSON.stringify(EXPECTED_PRESENT_VALUES))
143861
# This is a "Gold master" test. If you need to update these constants, you can do so # by manually clicking through the kitchen sink form in the Chrome dev console and running: # # copy(JSON.stringify($('[data-formrenderer]').data('form-renderer-instance').getValue())) # # ...which will copy the stringified JSON to your clipboard. You should then manually verify # the output, and if you're satisfied, you can finally update the constant. EXPECTED_BLANK_VALUES = { "35": "", "37": { checked: [] }, "39": { checked: [] }, "3900": { checked: [] }, "3901": { checked: [] }, "41": {}, "42": "", "43": {}, "44": { "am_pm": "AM" }, "45": "", "47": "", "46": [], "48": { "country": "US" }, "49": { "column one": [ "", "" ], "column two": [ "", "" ] }, "51": "", "52": false, "53": [{ "54": "" }] } EXPECTED_PRESENT_VALUES = { "35": "foo", "36": "bar", "37": { checked: ["Choice #1 (yas)"] }, "39": { checked: ["Choice #2"] }, "40": "Choice #2", "41": { "dollars": "12", "cents": "99" }, "42": "123", "43": { "month": "12", "day": "30", "year": "2014" }, "44": { "am_pm": "PM", "hours": "6", "minutes": "01", "seconds": "30" }, "45": "http://www.google.com", "46": [{ id: 123 }], "47": "<EMAIL>", "48": { "country": "GB", "street": "123 main st", "state": null }, "49": { "column one": [ "hey", "" ], "column two": [ "", "nay" ] }, "50": ["40.7700118", "-73.9800453"], "51": "510-123-4567", "52": true, "53": [ { "54":"Large Round Son" } ], "3900": { "checked": [], "other_checked": true, "other_text": "some alternative answer" }, "3901": { "checked": [ "Choice #2" ], "other_checked": true, "other_text": "some alternative answer" } } describe '#getValue', -> before -> $('body').html('<div data-formrenderer />') @fr = new FormRenderer Fixtures.FormRendererOptions.KITCHEN_SINK() it 'renders ok', -> expect(@fr).to.be.ok it 'serializes the blank values', -> expect(JSON.stringify(@fr.getValue())).to.equal(JSON.stringify(EXPECTED_BLANK_VALUES)) it 'serializes present values', -> $('.fr_response_field_text input').val('foo').trigger('input') $('.fr_response_field_paragraph textarea').val('bar').trigger('input') $('.fr_response_field_checkboxes input').first().click().trigger('change') $($('.fr_response_field_radio')[0]).find('input[type=radio]').last().click().trigger('change') $($('.fr_response_field_radio')[1]).find('input[type=radio]').last().click().trigger('change') $($('.fr_response_field_checkboxes')[1]).find('input[type=checkbox]').slice(-2).click().trigger('change') $('.fr_other_option input[type=text]').val("some alternative answer").trigger('input') $('.fr_response_field_dropdown select').val('Choice #2').trigger('change') $('.fr_response_field_price input').first().val('12').trigger('input') $('.fr_response_field_price input').last().val('99').trigger('input') $('.fr_response_field_number input').last().val('123').trigger('input') $('.fr_response_field_date input').eq(0).val('12').trigger('input') $('.fr_response_field_date input').eq(1).val('30').trigger('input') $('.fr_response_field_date input').eq(2).val('2014').trigger('input') $('.fr_response_field_time input').eq(0).val('6').trigger('input') $('.fr_response_field_time input').eq(1).val('01').trigger('input') $('.fr_response_field_time input').eq(2).val('30').trigger('input') $('.fr_response_field_time select').val('PM').trigger('change') $('.fr_response_field_website input').val('http://www.google.com').trigger('input') $('.fr_response_field_email input').val('<EMAIL>').trigger('input') $('.fr_response_field_address input').eq(0).val('123 main st').trigger('input') $('.fr_response_field_address select').val('GB').trigger('change') $('.fr_response_field_table textarea').eq(0).val('hey').trigger('input') $('.fr_response_field_table textarea').eq(3).val('nay').trigger('input') $('.fr_response_field_phone input').val('510-123-4567').trigger('input') $('.fr_response_field_map_marker .fr_map_cover').click() $('.fr_response_field_confirm input').first().click().trigger('change') $('.fr_response_field_group').first().find('[type=text]').val('Large Round Son').trigger('input') # File inlineFileUpload = $('input[type=file]').data('inline-file-upload') inlineFileUpload.options.success(data: { file_id: 123 }) expect(JSON.stringify(@fr.getValue())).to.equal(JSON.stringify(EXPECTED_PRESENT_VALUES))
true
# This is a "Gold master" test. If you need to update these constants, you can do so # by manually clicking through the kitchen sink form in the Chrome dev console and running: # # copy(JSON.stringify($('[data-formrenderer]').data('form-renderer-instance').getValue())) # # ...which will copy the stringified JSON to your clipboard. You should then manually verify # the output, and if you're satisfied, you can finally update the constant. EXPECTED_BLANK_VALUES = { "35": "", "37": { checked: [] }, "39": { checked: [] }, "3900": { checked: [] }, "3901": { checked: [] }, "41": {}, "42": "", "43": {}, "44": { "am_pm": "AM" }, "45": "", "47": "", "46": [], "48": { "country": "US" }, "49": { "column one": [ "", "" ], "column two": [ "", "" ] }, "51": "", "52": false, "53": [{ "54": "" }] } EXPECTED_PRESENT_VALUES = { "35": "foo", "36": "bar", "37": { checked: ["Choice #1 (yas)"] }, "39": { checked: ["Choice #2"] }, "40": "Choice #2", "41": { "dollars": "12", "cents": "99" }, "42": "123", "43": { "month": "12", "day": "30", "year": "2014" }, "44": { "am_pm": "PM", "hours": "6", "minutes": "01", "seconds": "30" }, "45": "http://www.google.com", "46": [{ id: 123 }], "47": "PI:EMAIL:<EMAIL>END_PI", "48": { "country": "GB", "street": "123 main st", "state": null }, "49": { "column one": [ "hey", "" ], "column two": [ "", "nay" ] }, "50": ["40.7700118", "-73.9800453"], "51": "510-123-4567", "52": true, "53": [ { "54":"Large Round Son" } ], "3900": { "checked": [], "other_checked": true, "other_text": "some alternative answer" }, "3901": { "checked": [ "Choice #2" ], "other_checked": true, "other_text": "some alternative answer" } } describe '#getValue', -> before -> $('body').html('<div data-formrenderer />') @fr = new FormRenderer Fixtures.FormRendererOptions.KITCHEN_SINK() it 'renders ok', -> expect(@fr).to.be.ok it 'serializes the blank values', -> expect(JSON.stringify(@fr.getValue())).to.equal(JSON.stringify(EXPECTED_BLANK_VALUES)) it 'serializes present values', -> $('.fr_response_field_text input').val('foo').trigger('input') $('.fr_response_field_paragraph textarea').val('bar').trigger('input') $('.fr_response_field_checkboxes input').first().click().trigger('change') $($('.fr_response_field_radio')[0]).find('input[type=radio]').last().click().trigger('change') $($('.fr_response_field_radio')[1]).find('input[type=radio]').last().click().trigger('change') $($('.fr_response_field_checkboxes')[1]).find('input[type=checkbox]').slice(-2).click().trigger('change') $('.fr_other_option input[type=text]').val("some alternative answer").trigger('input') $('.fr_response_field_dropdown select').val('Choice #2').trigger('change') $('.fr_response_field_price input').first().val('12').trigger('input') $('.fr_response_field_price input').last().val('99').trigger('input') $('.fr_response_field_number input').last().val('123').trigger('input') $('.fr_response_field_date input').eq(0).val('12').trigger('input') $('.fr_response_field_date input').eq(1).val('30').trigger('input') $('.fr_response_field_date input').eq(2).val('2014').trigger('input') $('.fr_response_field_time input').eq(0).val('6').trigger('input') $('.fr_response_field_time input').eq(1).val('01').trigger('input') $('.fr_response_field_time input').eq(2).val('30').trigger('input') $('.fr_response_field_time select').val('PM').trigger('change') $('.fr_response_field_website input').val('http://www.google.com').trigger('input') $('.fr_response_field_email input').val('PI:EMAIL:<EMAIL>END_PI').trigger('input') $('.fr_response_field_address input').eq(0).val('123 main st').trigger('input') $('.fr_response_field_address select').val('GB').trigger('change') $('.fr_response_field_table textarea').eq(0).val('hey').trigger('input') $('.fr_response_field_table textarea').eq(3).val('nay').trigger('input') $('.fr_response_field_phone input').val('510-123-4567').trigger('input') $('.fr_response_field_map_marker .fr_map_cover').click() $('.fr_response_field_confirm input').first().click().trigger('change') $('.fr_response_field_group').first().find('[type=text]').val('Large Round Son').trigger('input') # File inlineFileUpload = $('input[type=file]').data('inline-file-upload') inlineFileUpload.options.success(data: { file_id: 123 }) expect(JSON.stringify(@fr.getValue())).to.equal(JSON.stringify(EXPECTED_PRESENT_VALUES))
[ { "context": " {\"fid\": \"com.example\", \"creds\": {\"username\": \"milo123\", \"password\": \"letmein\"}}\n #\n #\n # #", "end": 3676, "score": 0.999548614025116, "start": 3669, "tag": "USERNAME", "value": "milo123" }, { "context": "e\", \"creds\": {\"username\": \...
application/chrome/content/wesabe/download/Controller.coffee
wesabe/ssu
28
json = require 'lang/json' type = require 'lang/type' func = require 'lang/func' string = require 'lang/string' cookies = require 'util/cookies' Dir = require 'io/Dir' File = require 'io/File' xhr = require 'io/xhr' Job = require 'download/Job' Logger = require 'Logger' inspect = require 'util/inspect' Server = require 'io/http/Server' {EventEmitter} = require 'events2' {tryCatch, tryThrow} = require 'util/try' class Controller constructor: -> @jobs = [] start: (port) -> @windows ||= length: 1 @windows[window.name] = window bindSuccessful = false listener = (request, response) => @dispatch request, response tryCatch 'Controller#start', (log) => @server = new Server port @port = @server.port if not @server? return false @server.post '/_legacy', => action = @server.request.json?.action.replace /\./g, '_' if type.isFunction @[action] logger.debug "Procesing legacy action #{inspect action}" @[action]? @server.request.json.body, (resdata) => @server.deliver resdata else message = "Unrecognized legacy action #{inspect action}" logger.error message throw new Server.NotFoundError message ## POST /eval # # Allows running arbitrary JS/CoffeeScript. Useful for facilitating # building a REPL to introspect/debug at runtime. # # script - a String of code to run # type - a String representing the MIME type of script # (default: text/javascript) # color - a Boolean that, if true, makes the response string use ANSI # color escapes (default: false) # # Examples # # # Request # POST /eval HTTP/1.0 # Content-Type: application/json # # {"script": "(-> 3+4)()", "type": "text/coffeescript"} # # # # Response # HTTP/1.0 200 OK # Content-Type: application/json # # {"result": "7"} # # Returns a REPL-friendly stringified version of the result. @server.post '/eval', => params = @server.request.json script = params.script @scope ||= logger: Logger.loggerForFile('repl'), __filename: 'repl', __dirname: '.' @scope.job = @job if params.type is 'text/coffeescript' script = string.trim(CoffeeScript.compile "(-> #{script})()", bare: on) else script = "(function(){#{script}})()" if /[;\n]/.test script script = "return #{script}" result = func.callWithScope script, @scope, @scope @scope._ = result @server.deliver {result: inspect(result, undefined, undefined, color: params.color)} ## /jobs jobResponse = (job) -> return unless job? id: job.id status: job.status result: job.result data: job.data fid: job.fid completed: job.done cookies: cookies.dump() timestamp: new Date().getTime() version: job.version jobById = => return job for job in @jobs when @server.params.id is job.id ## POST /jobs # # Creates and starts a new sync job. # # id - an id to use to identify this job (optional) # fid - the reverse-dns of the player to use for this job # creds - an Object of credentials to use in this job # options - an Object with customizations to how to run this job # (default: {}) # # Examples # # # Request # POST /jobs HTTP/1.0 # Content-Type: application/json # # {"fid": "com.example", "creds": {"username": "milo123", "password": "letmein"}} # # # # Response # HTTP/1.0 201 Created # Content-Type: application/json # Location: /jobs/1D992147-9078-0001-FFFF-1FFF1FFF1FFF # # Returns a pointer to the newly created job in the form of a Location # header URL. @server.post '/jobs', => params = @server.request.json @jobs.push @job = new Job params.id, params.fid, params.creds, params.options cookies.restore params.cookies if params.cookies @job.start() @server.response.headers['Location'] = "/jobs/#{@job.id}" @server.deliver jobResponse(@job), status: 201 ## GET /jobs # # Lists all previously-run and currently running jobs. # # Examples # # # Request # GET /jobs HTTP/1.0 # # # # Response # HTTP/1.0 200 OK # Content-Type: application/json # # [{"id": "1D992147-9078-0001-FFFF-1FFF1FFF1FFF", "fid": "com.example", ...}] # # Returns relevant data for all jobs started by this instance. @server.get '/jobs', => @server.deliver(@jobs.map jobResponse) ## GET /jobs/:id # # Gets data for a specific job by id. # # Examples # # # Request for a non-existent job id # GET /jobs/1D992147-9078-0001-FFFF-1FFF1FFF1FFF HTTP/1.0 # # # Response # HTTP/1.0 404 Not Found # # # # Request for a real job id # GET /jobs/1D992147-9078-0001-FFFF-1FFF1FFF1FFF HTTP/1.0 # # # Response # HTTP/1.0 200 OK # Content-Type: application/json # # {"id": "1D992147-9078-0001-FFFF-1FFF1FFF1FFF", "fid": "com.example", ...} # # Returns relevant data for the job given by id, or 404 Not Found if no # such job exists. @server.get '/jobs/:id', => @server.deliver(jobResponse jobById()) ## PUT /jobs/:id # # Updates the credentials for this job and resumes it. # # Examples # # # Request for a job that doesn't exist # PUT /jobs/1D992147-9078-0001-FFFF-1FFF1FFF1FFF HTTP/1.0 # Content-Type: application/json # # {"creds": [{"key": "What's your mother's maiden name?", "value": "Smith"}]} # # # Response # HTTP/1.0 404 Not Found # # # # Request for a real job # PUT /jobs/1D992147-9078-0001-FFFF-1FFF1FFF1FFF HTTP/1.0 # Content-Type: application/json # # {"creds": [{"key": "What's your mother's maiden name?", "value": "Smith"}]} # # # Response # HTTP/1.0 200 OK # Content-Type: application/json # # {"id": "1D992147-9078-0001-FFFF-1FFF1FFF1FFF", "fid": "com.example", ...} # # Returns relevant data for the job given by id, or 404 Not Found if no # such job exists. @server.put '/jobs/:id', => params = @server.request.json job = jobById() job?.resume? params.creds @server.deliver(jobResponse job) ## DELETE /jobs/:id # # Stops the job with the given id but does not actually remove it from # the list returned by GET /jobs. # # Examples # # # Request for a job that doesn't exist # DELETE /jobs/1D992147-9078-0001-FFFF-1FFF1FFF1FFF HTTP/1.0 # # # Response # HTTP/1.0 404 Not Found # # # # Request for a real job # DELETE /jobs/1D992147-9078-0001-FFFF-1FFF1FFF1FFF HTTP/1.0 # # # Response # HTTP/1.0 200 OK # Content-Type: application/json # # {"id": "1D992147-9078-0001-FFFF-1FFF1FFF1FFF", "fid": "com.example", ...} # # Returns relevant data for the stopped job or 404 Not Found if no such # job exists. @server.delete '/jobs/:id', => job = jobById() job.fail 504, 'timeout.quit' if job? and job.done is false @server.deliver(jobResponse job) ## /statements statementsDirectory = Dir.profile.child 'statements' readStatement = (id) -> statement = statementsDirectory.child(id) if statement.exists statement.read() else null getStatementList = -> if statementsDirectory.exists {id: file.basename} for file in statementsDirectory.children() else [] ## GET /statements # # Returns a list of all the statements downloaded for any jobs. # # Examples # # # Request # GET /statements HTTP/1.0 # # # # Response # HTTP/1.0 200 OK # Content-Type: application/json # # [{"id": "1D992147-9078-0001-FFFF-1FFF1FFF1FFF"}] # # Returns relevant data for all jobs started by this instance. @server.get '/statements', => @server.deliver(getStatementList()) ## GET /statements/:id # # Gets data for a specific statement by id. # # Examples # # # Request for a non-existent statement id # GET /statements/1D992147-9078-0001-FFFF-1FFF1FFF1FFF HTTP/1.0 # # # Response # HTTP/1.0 404 Not Found # # # # Request for a real statement id # GET /statements/1D992147-9078-0001-FFFF-1FFF1FFF1FFF HTTP/1.0 # Accept: application/ofx # # # Response # HTTP/1.0 200 OK # Content-Type: application/ofx # # OFXHEADER:100 # DATA:OFXSGML # VERSION:102 # SECURITY:NONE # ENCODING:USASCII # ... # # <OFX> # ... # # Returns relevant data for the job given by id, or 404 Not Found if no # such job exists. @server.get '/statements/:id', => @server.deliver(readStatement(@server.params.id), contentType: 'application/ofx') return true window_open: (data, respond) -> index = @windows.length++ name = data?.name or "#{window.name}:#{index}" @windows[name] = window.open window.location.href, name, "chrome,width=600,height=300" waitForPort = => if port = @windows[name].port respond response: status: 'ok' 'window.open': {name, port} else setTimeout waitForPort, 10 waitForPort() window_close: (name, respond) -> w = @windows[name] if w? w.close() delete @windows[name] respond response: status: 'ok' 'window.close': w? window_list: (data, respond) -> respond response: status: 'ok' 'window.list': ({name, port: w.port} for name, w of @windows when name isnt 'length') statement_list: (data, respond) -> statements = Dir.profile.child 'statements' list = [] if statements.exists list = for file in statements.children() file.basename respond response: status: 'ok' 'statement.list': list statement_read: (data, respond) -> unless data respond response: status: 'error' error: "statement id required" return statement = Dir.profile.child('statements').child(data) if statement.exists() respond response: status: 'ok' 'statement.read': statement.read() else respond response: status: 'error' error: "No statement found with id=#{data}" job_stop: (data, respond) -> logger.info 'Got request to stop job, shutting down' # job didn't finish, so it failed @job.fail 504, 'timeout.quit' unless @job.done respond response: status: 'ok' xul_quit: (data, respond) -> setTimeout (-> goQuitApplication()), 1000 respond response: status: 'ok' page_dump: (data, respond) -> try respond response: status: 'ok' 'page.dump': @job.player.page.dump() catch e logger.error 'page.dump: ', e respond response: status: 'error' error: e.toString() module.exports = Controller
60471
json = require 'lang/json' type = require 'lang/type' func = require 'lang/func' string = require 'lang/string' cookies = require 'util/cookies' Dir = require 'io/Dir' File = require 'io/File' xhr = require 'io/xhr' Job = require 'download/Job' Logger = require 'Logger' inspect = require 'util/inspect' Server = require 'io/http/Server' {EventEmitter} = require 'events2' {tryCatch, tryThrow} = require 'util/try' class Controller constructor: -> @jobs = [] start: (port) -> @windows ||= length: 1 @windows[window.name] = window bindSuccessful = false listener = (request, response) => @dispatch request, response tryCatch 'Controller#start', (log) => @server = new Server port @port = @server.port if not @server? return false @server.post '/_legacy', => action = @server.request.json?.action.replace /\./g, '_' if type.isFunction @[action] logger.debug "Procesing legacy action #{inspect action}" @[action]? @server.request.json.body, (resdata) => @server.deliver resdata else message = "Unrecognized legacy action #{inspect action}" logger.error message throw new Server.NotFoundError message ## POST /eval # # Allows running arbitrary JS/CoffeeScript. Useful for facilitating # building a REPL to introspect/debug at runtime. # # script - a String of code to run # type - a String representing the MIME type of script # (default: text/javascript) # color - a Boolean that, if true, makes the response string use ANSI # color escapes (default: false) # # Examples # # # Request # POST /eval HTTP/1.0 # Content-Type: application/json # # {"script": "(-> 3+4)()", "type": "text/coffeescript"} # # # # Response # HTTP/1.0 200 OK # Content-Type: application/json # # {"result": "7"} # # Returns a REPL-friendly stringified version of the result. @server.post '/eval', => params = @server.request.json script = params.script @scope ||= logger: Logger.loggerForFile('repl'), __filename: 'repl', __dirname: '.' @scope.job = @job if params.type is 'text/coffeescript' script = string.trim(CoffeeScript.compile "(-> #{script})()", bare: on) else script = "(function(){#{script}})()" if /[;\n]/.test script script = "return #{script}" result = func.callWithScope script, @scope, @scope @scope._ = result @server.deliver {result: inspect(result, undefined, undefined, color: params.color)} ## /jobs jobResponse = (job) -> return unless job? id: job.id status: job.status result: job.result data: job.data fid: job.fid completed: job.done cookies: cookies.dump() timestamp: new Date().getTime() version: job.version jobById = => return job for job in @jobs when @server.params.id is job.id ## POST /jobs # # Creates and starts a new sync job. # # id - an id to use to identify this job (optional) # fid - the reverse-dns of the player to use for this job # creds - an Object of credentials to use in this job # options - an Object with customizations to how to run this job # (default: {}) # # Examples # # # Request # POST /jobs HTTP/1.0 # Content-Type: application/json # # {"fid": "com.example", "creds": {"username": "milo123", "password": "<PASSWORD>"}} # # # # Response # HTTP/1.0 201 Created # Content-Type: application/json # Location: /jobs/1D992147-9078-0001-FFFF-1FFF1FFF1FFF # # Returns a pointer to the newly created job in the form of a Location # header URL. @server.post '/jobs', => params = @server.request.json @jobs.push @job = new Job params.id, params.fid, params.creds, params.options cookies.restore params.cookies if params.cookies @job.start() @server.response.headers['Location'] = "/jobs/#{@job.id}" @server.deliver jobResponse(@job), status: 201 ## GET /jobs # # Lists all previously-run and currently running jobs. # # Examples # # # Request # GET /jobs HTTP/1.0 # # # # Response # HTTP/1.0 200 OK # Content-Type: application/json # # [{"id": "1D992147-9078-0001-FFFF-1FFF1FFF1FFF", "fid": "com.example", ...}] # # Returns relevant data for all jobs started by this instance. @server.get '/jobs', => @server.deliver(@jobs.map jobResponse) ## GET /jobs/:id # # Gets data for a specific job by id. # # Examples # # # Request for a non-existent job id # GET /jobs/1D992147-9078-0001-FFFF-1FFF1FFF1FFF HTTP/1.0 # # # Response # HTTP/1.0 404 Not Found # # # # Request for a real job id # GET /jobs/1D992147-9078-0001-FFFF-1FFF1FFF1FFF HTTP/1.0 # # # Response # HTTP/1.0 200 OK # Content-Type: application/json # # {"id": "1D992147-9078-0001-FFFF-1FFF1FFF1FFF", "fid": "com.example", ...} # # Returns relevant data for the job given by id, or 404 Not Found if no # such job exists. @server.get '/jobs/:id', => @server.deliver(jobResponse jobById()) ## PUT /jobs/:id # # Updates the credentials for this job and resumes it. # # Examples # # # Request for a job that doesn't exist # PUT /jobs/1D992147-9078-0001-FFFF-1FFF1FFF1FFF HTTP/1.0 # Content-Type: application/json # # {"creds": [{"key": "What's your mother's maiden name?", "value": "<NAME>"}]} # # # Response # HTTP/1.0 404 Not Found # # # # Request for a real job # PUT /jobs/1D992147-9078-0001-FFFF-1FFF1FFF1FFF HTTP/1.0 # Content-Type: application/json # # {"creds": [{"key": "What's your mother's maiden name?", "value": "<NAME>"}]} # # # Response # HTTP/1.0 200 OK # Content-Type: application/json # # {"id": "1D992147-9078-0001-FFFF-1FFF1FFF1FFF", "fid": "com.example", ...} # # Returns relevant data for the job given by id, or 404 Not Found if no # such job exists. @server.put '/jobs/:id', => params = @server.request.json job = jobById() job?.resume? params.creds @server.deliver(jobResponse job) ## DELETE /jobs/:id # # Stops the job with the given id but does not actually remove it from # the list returned by GET /jobs. # # Examples # # # Request for a job that doesn't exist # DELETE /jobs/1D992147-9078-0001-FFFF-1FFF1FFF1FFF HTTP/1.0 # # # Response # HTTP/1.0 404 Not Found # # # # Request for a real job # DELETE /jobs/1D992147-9078-0001-FFFF-1FFF1FFF1FFF HTTP/1.0 # # # Response # HTTP/1.0 200 OK # Content-Type: application/json # # {"id": "1D992147-9078-0001-FFFF-1FFF1FFF1FFF", "fid": "com.example", ...} # # Returns relevant data for the stopped job or 404 Not Found if no such # job exists. @server.delete '/jobs/:id', => job = jobById() job.fail 504, 'timeout.quit' if job? and job.done is false @server.deliver(jobResponse job) ## /statements statementsDirectory = Dir.profile.child 'statements' readStatement = (id) -> statement = statementsDirectory.child(id) if statement.exists statement.read() else null getStatementList = -> if statementsDirectory.exists {id: file.basename} for file in statementsDirectory.children() else [] ## GET /statements # # Returns a list of all the statements downloaded for any jobs. # # Examples # # # Request # GET /statements HTTP/1.0 # # # # Response # HTTP/1.0 200 OK # Content-Type: application/json # # [{"id": "1D992147-9078-0001-FFFF-1FFF1FFF1FFF"}] # # Returns relevant data for all jobs started by this instance. @server.get '/statements', => @server.deliver(getStatementList()) ## GET /statements/:id # # Gets data for a specific statement by id. # # Examples # # # Request for a non-existent statement id # GET /statements/1D992147-9078-0001-FFFF-1FFF1FFF1FFF HTTP/1.0 # # # Response # HTTP/1.0 404 Not Found # # # # Request for a real statement id # GET /statements/1D992147-9078-0001-FFFF-1FFF1FFF1FFF HTTP/1.0 # Accept: application/ofx # # # Response # HTTP/1.0 200 OK # Content-Type: application/ofx # # OFXHEADER:100 # DATA:OFXSGML # VERSION:102 # SECURITY:NONE # ENCODING:USASCII # ... # # <OFX> # ... # # Returns relevant data for the job given by id, or 404 Not Found if no # such job exists. @server.get '/statements/:id', => @server.deliver(readStatement(@server.params.id), contentType: 'application/ofx') return true window_open: (data, respond) -> index = @windows.length++ name = data?.name or "#{window.name}:#{index}" @windows[name] = window.open window.location.href, name, "chrome,width=600,height=300" waitForPort = => if port = @windows[name].port respond response: status: 'ok' 'window.open': {name, port} else setTimeout waitForPort, 10 waitForPort() window_close: (name, respond) -> w = @windows[name] if w? w.close() delete @windows[name] respond response: status: 'ok' 'window.close': w? window_list: (data, respond) -> respond response: status: 'ok' 'window.list': ({name, port: w.port} for name, w of @windows when name isnt 'length') statement_list: (data, respond) -> statements = Dir.profile.child 'statements' list = [] if statements.exists list = for file in statements.children() file.basename respond response: status: 'ok' 'statement.list': list statement_read: (data, respond) -> unless data respond response: status: 'error' error: "statement id required" return statement = Dir.profile.child('statements').child(data) if statement.exists() respond response: status: 'ok' 'statement.read': statement.read() else respond response: status: 'error' error: "No statement found with id=#{data}" job_stop: (data, respond) -> logger.info 'Got request to stop job, shutting down' # job didn't finish, so it failed @job.fail 504, 'timeout.quit' unless @job.done respond response: status: 'ok' xul_quit: (data, respond) -> setTimeout (-> goQuitApplication()), 1000 respond response: status: 'ok' page_dump: (data, respond) -> try respond response: status: 'ok' 'page.dump': @job.player.page.dump() catch e logger.error 'page.dump: ', e respond response: status: 'error' error: e.toString() module.exports = Controller
true
json = require 'lang/json' type = require 'lang/type' func = require 'lang/func' string = require 'lang/string' cookies = require 'util/cookies' Dir = require 'io/Dir' File = require 'io/File' xhr = require 'io/xhr' Job = require 'download/Job' Logger = require 'Logger' inspect = require 'util/inspect' Server = require 'io/http/Server' {EventEmitter} = require 'events2' {tryCatch, tryThrow} = require 'util/try' class Controller constructor: -> @jobs = [] start: (port) -> @windows ||= length: 1 @windows[window.name] = window bindSuccessful = false listener = (request, response) => @dispatch request, response tryCatch 'Controller#start', (log) => @server = new Server port @port = @server.port if not @server? return false @server.post '/_legacy', => action = @server.request.json?.action.replace /\./g, '_' if type.isFunction @[action] logger.debug "Procesing legacy action #{inspect action}" @[action]? @server.request.json.body, (resdata) => @server.deliver resdata else message = "Unrecognized legacy action #{inspect action}" logger.error message throw new Server.NotFoundError message ## POST /eval # # Allows running arbitrary JS/CoffeeScript. Useful for facilitating # building a REPL to introspect/debug at runtime. # # script - a String of code to run # type - a String representing the MIME type of script # (default: text/javascript) # color - a Boolean that, if true, makes the response string use ANSI # color escapes (default: false) # # Examples # # # Request # POST /eval HTTP/1.0 # Content-Type: application/json # # {"script": "(-> 3+4)()", "type": "text/coffeescript"} # # # # Response # HTTP/1.0 200 OK # Content-Type: application/json # # {"result": "7"} # # Returns a REPL-friendly stringified version of the result. @server.post '/eval', => params = @server.request.json script = params.script @scope ||= logger: Logger.loggerForFile('repl'), __filename: 'repl', __dirname: '.' @scope.job = @job if params.type is 'text/coffeescript' script = string.trim(CoffeeScript.compile "(-> #{script})()", bare: on) else script = "(function(){#{script}})()" if /[;\n]/.test script script = "return #{script}" result = func.callWithScope script, @scope, @scope @scope._ = result @server.deliver {result: inspect(result, undefined, undefined, color: params.color)} ## /jobs jobResponse = (job) -> return unless job? id: job.id status: job.status result: job.result data: job.data fid: job.fid completed: job.done cookies: cookies.dump() timestamp: new Date().getTime() version: job.version jobById = => return job for job in @jobs when @server.params.id is job.id ## POST /jobs # # Creates and starts a new sync job. # # id - an id to use to identify this job (optional) # fid - the reverse-dns of the player to use for this job # creds - an Object of credentials to use in this job # options - an Object with customizations to how to run this job # (default: {}) # # Examples # # # Request # POST /jobs HTTP/1.0 # Content-Type: application/json # # {"fid": "com.example", "creds": {"username": "milo123", "password": "PI:PASSWORD:<PASSWORD>END_PI"}} # # # # Response # HTTP/1.0 201 Created # Content-Type: application/json # Location: /jobs/1D992147-9078-0001-FFFF-1FFF1FFF1FFF # # Returns a pointer to the newly created job in the form of a Location # header URL. @server.post '/jobs', => params = @server.request.json @jobs.push @job = new Job params.id, params.fid, params.creds, params.options cookies.restore params.cookies if params.cookies @job.start() @server.response.headers['Location'] = "/jobs/#{@job.id}" @server.deliver jobResponse(@job), status: 201 ## GET /jobs # # Lists all previously-run and currently running jobs. # # Examples # # # Request # GET /jobs HTTP/1.0 # # # # Response # HTTP/1.0 200 OK # Content-Type: application/json # # [{"id": "1D992147-9078-0001-FFFF-1FFF1FFF1FFF", "fid": "com.example", ...}] # # Returns relevant data for all jobs started by this instance. @server.get '/jobs', => @server.deliver(@jobs.map jobResponse) ## GET /jobs/:id # # Gets data for a specific job by id. # # Examples # # # Request for a non-existent job id # GET /jobs/1D992147-9078-0001-FFFF-1FFF1FFF1FFF HTTP/1.0 # # # Response # HTTP/1.0 404 Not Found # # # # Request for a real job id # GET /jobs/1D992147-9078-0001-FFFF-1FFF1FFF1FFF HTTP/1.0 # # # Response # HTTP/1.0 200 OK # Content-Type: application/json # # {"id": "1D992147-9078-0001-FFFF-1FFF1FFF1FFF", "fid": "com.example", ...} # # Returns relevant data for the job given by id, or 404 Not Found if no # such job exists. @server.get '/jobs/:id', => @server.deliver(jobResponse jobById()) ## PUT /jobs/:id # # Updates the credentials for this job and resumes it. # # Examples # # # Request for a job that doesn't exist # PUT /jobs/1D992147-9078-0001-FFFF-1FFF1FFF1FFF HTTP/1.0 # Content-Type: application/json # # {"creds": [{"key": "What's your mother's maiden name?", "value": "PI:NAME:<NAME>END_PI"}]} # # # Response # HTTP/1.0 404 Not Found # # # # Request for a real job # PUT /jobs/1D992147-9078-0001-FFFF-1FFF1FFF1FFF HTTP/1.0 # Content-Type: application/json # # {"creds": [{"key": "What's your mother's maiden name?", "value": "PI:NAME:<NAME>END_PI"}]} # # # Response # HTTP/1.0 200 OK # Content-Type: application/json # # {"id": "1D992147-9078-0001-FFFF-1FFF1FFF1FFF", "fid": "com.example", ...} # # Returns relevant data for the job given by id, or 404 Not Found if no # such job exists. @server.put '/jobs/:id', => params = @server.request.json job = jobById() job?.resume? params.creds @server.deliver(jobResponse job) ## DELETE /jobs/:id # # Stops the job with the given id but does not actually remove it from # the list returned by GET /jobs. # # Examples # # # Request for a job that doesn't exist # DELETE /jobs/1D992147-9078-0001-FFFF-1FFF1FFF1FFF HTTP/1.0 # # # Response # HTTP/1.0 404 Not Found # # # # Request for a real job # DELETE /jobs/1D992147-9078-0001-FFFF-1FFF1FFF1FFF HTTP/1.0 # # # Response # HTTP/1.0 200 OK # Content-Type: application/json # # {"id": "1D992147-9078-0001-FFFF-1FFF1FFF1FFF", "fid": "com.example", ...} # # Returns relevant data for the stopped job or 404 Not Found if no such # job exists. @server.delete '/jobs/:id', => job = jobById() job.fail 504, 'timeout.quit' if job? and job.done is false @server.deliver(jobResponse job) ## /statements statementsDirectory = Dir.profile.child 'statements' readStatement = (id) -> statement = statementsDirectory.child(id) if statement.exists statement.read() else null getStatementList = -> if statementsDirectory.exists {id: file.basename} for file in statementsDirectory.children() else [] ## GET /statements # # Returns a list of all the statements downloaded for any jobs. # # Examples # # # Request # GET /statements HTTP/1.0 # # # # Response # HTTP/1.0 200 OK # Content-Type: application/json # # [{"id": "1D992147-9078-0001-FFFF-1FFF1FFF1FFF"}] # # Returns relevant data for all jobs started by this instance. @server.get '/statements', => @server.deliver(getStatementList()) ## GET /statements/:id # # Gets data for a specific statement by id. # # Examples # # # Request for a non-existent statement id # GET /statements/1D992147-9078-0001-FFFF-1FFF1FFF1FFF HTTP/1.0 # # # Response # HTTP/1.0 404 Not Found # # # # Request for a real statement id # GET /statements/1D992147-9078-0001-FFFF-1FFF1FFF1FFF HTTP/1.0 # Accept: application/ofx # # # Response # HTTP/1.0 200 OK # Content-Type: application/ofx # # OFXHEADER:100 # DATA:OFXSGML # VERSION:102 # SECURITY:NONE # ENCODING:USASCII # ... # # <OFX> # ... # # Returns relevant data for the job given by id, or 404 Not Found if no # such job exists. @server.get '/statements/:id', => @server.deliver(readStatement(@server.params.id), contentType: 'application/ofx') return true window_open: (data, respond) -> index = @windows.length++ name = data?.name or "#{window.name}:#{index}" @windows[name] = window.open window.location.href, name, "chrome,width=600,height=300" waitForPort = => if port = @windows[name].port respond response: status: 'ok' 'window.open': {name, port} else setTimeout waitForPort, 10 waitForPort() window_close: (name, respond) -> w = @windows[name] if w? w.close() delete @windows[name] respond response: status: 'ok' 'window.close': w? window_list: (data, respond) -> respond response: status: 'ok' 'window.list': ({name, port: w.port} for name, w of @windows when name isnt 'length') statement_list: (data, respond) -> statements = Dir.profile.child 'statements' list = [] if statements.exists list = for file in statements.children() file.basename respond response: status: 'ok' 'statement.list': list statement_read: (data, respond) -> unless data respond response: status: 'error' error: "statement id required" return statement = Dir.profile.child('statements').child(data) if statement.exists() respond response: status: 'ok' 'statement.read': statement.read() else respond response: status: 'error' error: "No statement found with id=#{data}" job_stop: (data, respond) -> logger.info 'Got request to stop job, shutting down' # job didn't finish, so it failed @job.fail 504, 'timeout.quit' unless @job.done respond response: status: 'ok' xul_quit: (data, respond) -> setTimeout (-> goQuitApplication()), 1000 respond response: status: 'ok' page_dump: (data, respond) -> try respond response: status: 'ok' 'page.dump': @job.player.page.dump() catch e logger.error 'page.dump: ', e respond response: status: 'error' error: e.toString() module.exports = Controller
[ { "context": "in'\n# something like that, man.\"\n#\n# Author:\n# Brian Shumate <brian@couchbase.com>\n\nmondays = [\n \"http://i.im", "end": 309, "score": 0.99986732006073, "start": 296, "tag": "NAME", "value": "Brian Shumate" }, { "context": "g like that, man.\"\n#\n# Author:\...
files/scripts/caseofmondays.coffee
AAROC/the-boss-role
0
# Description: # Looks like someone has a case of the Mondays # # Dependencies: # None # # Configuration: # None # # Commands: # hubot case of the mondays # # Notes: # "No. No, man. Shit no, man. I believe you'd get your ass kicked sayin' # something like that, man." # # Author: # Brian Shumate <brian@couchbase.com> mondays = [ "http://i.imgur.com/8n4hlQE.jpg" ] module.exports = (robot) -> robot.hear /case of the mondays/i, (msg)-> msg.send msg.random mondays
20733
# Description: # Looks like someone has a case of the Mondays # # Dependencies: # None # # Configuration: # None # # Commands: # hubot case of the mondays # # Notes: # "No. No, man. Shit no, man. I believe you'd get your ass kicked sayin' # something like that, man." # # Author: # <NAME> <<EMAIL>> mondays = [ "http://i.imgur.com/8n4hlQE.jpg" ] module.exports = (robot) -> robot.hear /case of the mondays/i, (msg)-> msg.send msg.random mondays
true
# Description: # Looks like someone has a case of the Mondays # # Dependencies: # None # # Configuration: # None # # Commands: # hubot case of the mondays # # Notes: # "No. No, man. Shit no, man. I believe you'd get your ass kicked sayin' # something like that, man." # # Author: # PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> mondays = [ "http://i.imgur.com/8n4hlQE.jpg" ] module.exports = (robot) -> robot.hear /case of the mondays/i, (msg)-> msg.send msg.random mondays
[ { "context": "de-js-express\n#\n# Nodize CMS\n# https://github.com/hypee/nodize\n#\n# Copyright 2013, Hypee\n# http://hypee.c", "end": 198, "score": 0.9942517280578613, "start": 193, "tag": "USERNAME", "value": "hypee" }, { "context": "ttps://github.com/hypee/nodize\n#\n# Copyright 2...
modules/ionize/libs/express_multiple_views.coffee
nodize/nodizecms
32
# Monkey patching Express to allow using multiple views folder # based on http://stackoverflow.com/questions/11315351/multiple-view-paths-on-node-js-express # # Nodize CMS # https://github.com/hypee/nodize # # Copyright 2013, Hypee # http://hypee.com # # Licensed under the MIT license: # http://www.opensource.org/licenses/MIT # enable_multiple_view_folders = -> # Monkey-patch express to accept multiple paths for looking up views. View = require("../../../node_modules/zappajs/node_modules/express/lib/view") lookup_proxy = View::lookup; View::lookup = (viewName) -> if (@root instanceof Array) for i in [0..@root.length] root = @root[i] or '' # Can be undefined, would break on "path.join" with Node.js >= 0.10 context = {root: root} match = lookup_proxy.call(context, viewName) return match if (match) return null return lookup_proxy.call(this, viewName) enable_multiple_view_folders()
93259
# Monkey patching Express to allow using multiple views folder # based on http://stackoverflow.com/questions/11315351/multiple-view-paths-on-node-js-express # # Nodize CMS # https://github.com/hypee/nodize # # Copyright 2013, <NAME> # http://hypee.com # # Licensed under the MIT license: # http://www.opensource.org/licenses/MIT # enable_multiple_view_folders = -> # Monkey-patch express to accept multiple paths for looking up views. View = require("../../../node_modules/zappajs/node_modules/express/lib/view") lookup_proxy = View::lookup; View::lookup = (viewName) -> if (@root instanceof Array) for i in [0..@root.length] root = @root[i] or '' # Can be undefined, would break on "path.join" with Node.js >= 0.10 context = {root: root} match = lookup_proxy.call(context, viewName) return match if (match) return null return lookup_proxy.call(this, viewName) enable_multiple_view_folders()
true
# Monkey patching Express to allow using multiple views folder # based on http://stackoverflow.com/questions/11315351/multiple-view-paths-on-node-js-express # # Nodize CMS # https://github.com/hypee/nodize # # Copyright 2013, PI:NAME:<NAME>END_PI # http://hypee.com # # Licensed under the MIT license: # http://www.opensource.org/licenses/MIT # enable_multiple_view_folders = -> # Monkey-patch express to accept multiple paths for looking up views. View = require("../../../node_modules/zappajs/node_modules/express/lib/view") lookup_proxy = View::lookup; View::lookup = (viewName) -> if (@root instanceof Array) for i in [0..@root.length] root = @root[i] or '' # Can be undefined, would break on "path.join" with Node.js >= 0.10 context = {root: root} match = lookup_proxy.call(context, viewName) return match if (match) return null return lookup_proxy.call(this, viewName) enable_multiple_view_folders()
[ { "context": " 0.5 }\n ]\n\nclient = new Myna.Client\n apiKey: \"092c90f6-a8f2-11e2-a2b9-7c6d628b25f7\"\n apiRoot: testApiRoot\n experiments: [ expt ]\n", "end": 297, "score": 0.9997674226760864, "start": 261, "tag": "KEY", "value": "092c90f6-a8f2-11e2-a2b9-7c6d628b25f7" } ]
src/test/event-spec.coffee
plyfe/myna-js
2
expt = new Myna.Experiment uuid: "45923780-80ed-47c6-aa46-15e2ae7a0e8c" id: "id" settings: "myna.web.sticky": false variants: [ { id: "variant1", weight: 0.5 } { id: "variant2", weight: 0.5 } ] client = new Myna.Client apiKey: "092c90f6-a8f2-11e2-a2b9-7c6d628b25f7" apiRoot: testApiRoot experiments: [ expt ] recorder = new Myna.Recorder client initialized = (fn) -> return -> expt.off() expt.unstick() recorder.off() recorder.listenTo(expt) recorder.clearQueuedEvents() recorder.semaphore = 0 recorder.waiting = [] calls = [] logCalls = -> for call in calls Myna.log("...", call) expt.on 'beforeView', jasmine.createSpy('beforeView').andCallFake (args...) -> calls.push([ "beforeView", args... ]) logCalls() expt.on 'view', jasmine.createSpy('view').andCallFake (args...) -> calls.push([ "view", args... ]) logCalls() expt.on 'beforeReward', jasmine.createSpy('beforeReward').andCallFake (args...) -> calls.push([ "beforeReward", args... ]) logCalls() expt.on 'reward', jasmine.createSpy('reward').andCallFake (args...) -> calls.push([ "reward", args... ]) logCalls() recorder.on 'beforeSync', jasmine.createSpy('beforeSync').andCallFake (args...) -> calls.push([ "beforeSync", (for events in args then eventSummaries(events))... ]) logCalls() recorder.on 'sync', jasmine.createSpy('sync').andCallFake (args...) -> calls.push([ "sync", (for events in args then eventSummaries(events))... ]) logCalls() fn(calls, logCalls) findCall = (calls, name, index) -> counter = 0 for call in calls when call[0] == name if counter == index return call else counter++ return null indexOfCall = (calls, name) -> for index, call in calls when call[0] == name return index return null describe "events", -> it "should be called in the correct order", initialized (calls, logCalls) -> variant = null rewardCallback = jasmine.createSpy('rewardCallback').andCallFake (args...) -> calls.push([ "rewardCallback", args... ]) logCalls() suggestCallback = jasmine.createSpy('suggestCallback').andCallFake (args...) -> calls.push([ "suggestCallback", args... ]) logCalls() variant = arguments[0] window.setTimeout( (-> expt.reward(0.8, rewardCallback)), 500 ) runs -> Myna.log("BLOCK 1") expt.suggest suggestCallback waitsFor -> rewardCallback.callCount > 0 waits 250 runs -> Myna.log("BLOCK 2") expect(for call in calls then call[0]).toEqual [ "beforeView" "suggestCallback" "view" "beforeSync" "sync" "beforeReward" "beforeSync" "rewardCallback" "reward" "sync" ] expect(findCall(calls, "beforeView", 0)).toEqual([ "beforeView", variant, true ]) expect(findCall(calls, "suggestCallback", 0)).toEqual([ "suggestCallback", variant, true ]) expect(findCall(calls, "view", 0)).toEqual([ "view", variant, true ]) expect(findCall(calls, "beforeSync", 0)).toEqual([ "beforeSync", [[ 'view', variant.id, null ]] ]) expect(findCall(calls, "beforeReward", 0)).toEqual([ "beforeReward", variant, 0.8, true ]) expect(findCall(calls, "reward", 0)).toEqual([ "reward", variant, 0.8, true ]) expect(findCall(calls, "sync", 0)).toEqual([ "sync", [[ 'view', variant.id, null ]], [], [] ]) expect(findCall(calls, "beforeSync", 1)).toEqual([ "beforeSync", [[ 'reward', variant.id, 0.8 ]] ]) expect(findCall(calls, "rewardCallback", 0)).toEqual([ "rewardCallback", variant, 0.8, true ]) expect(findCall(calls, "sync", 1)).toEqual([ "sync", [[ 'reward', variant.id, 0.8 ]], [], [] ]) @removeAllSpies() describe "beforeView event", -> it "should be able to cancel a suggestion", initialized (calls, logCalls) -> variant = null expt.off('beforeView') expt.on 'beforeView', jasmine.createSpy('beforeView').andCallFake (args...) -> calls.push([ "beforeView", args... ]) variant = arguments[0] false rewardCallback = jasmine.createSpy('rewardCallback').andCallFake (args...) -> calls.push([ "rewardCallback", args... ]) logCalls() suggestCallback = jasmine.createSpy('suggestCallback').andCallFake (args...) -> calls.push([ "suggestCallback", args... ]) logCalls() window.setTimeout( (-> expt.reward(0.8, rewardCallback)), 0 ) runs -> expt.suggest suggestCallback waitsFor -> expt.eventHandlers['beforeView'][0].callCount > 0 waits 250 runs -> expect(for call in calls then call[0]).toEqual([ "beforeView" ]) expect(findCall(calls, "beforeView", 0)).toEqual([ "beforeView", variant, true ]) @removeAllSpies() describe "beforeReward event", -> it "should be able to cancel a reward", initialized (calls, logCalls) -> variant = null expt.off('beforeReward') expt.on 'beforeReward', jasmine.createSpy('beforeReward').andCallFake (args...) -> calls.push([ "beforeReward", args... ]) variant = arguments[0] false rewardCallback = jasmine.createSpy('rewardCallback').andCallFake (args...) -> calls.push([ "rewardCallback", args... ]) logCalls() suggestCallback = jasmine.createSpy('suggestCallback').andCallFake (args...) -> calls.push([ "suggestCallback", args... ]) logCalls() window.setTimeout( (-> expt.reward(0.8, rewardCallback)), 500 ) runs -> expt.suggest suggestCallback waitsFor -> expt.eventHandlers['beforeReward'][0].callCount > 0 waits 250 runs -> expect(for call in calls then call[0]).toEqual [ "beforeView" "suggestCallback" "view" "beforeSync" "sync" "beforeReward" ] expect(findCall(calls, "beforeView", 0)).toEqual([ "beforeView", variant, true ]) expect(findCall(calls, "suggestCallback", 0)).toEqual([ "suggestCallback", variant, true ]) expect(findCall(calls, "view", 0)).toEqual([ "view", variant, true ]) expect(findCall(calls, "beforeSync", 0)).toEqual([ "beforeSync", [[ 'view', variant.id, null ]] ]) expect(findCall(calls, "beforeReward", 0)).toEqual([ "beforeReward", variant, 0.8, true ]) expect(findCall(calls, "sync", 0)).toEqual([ "sync", [[ 'view', variant.id, null ]], [], [] ]) @removeAllSpies()
154456
expt = new Myna.Experiment uuid: "45923780-80ed-47c6-aa46-15e2ae7a0e8c" id: "id" settings: "myna.web.sticky": false variants: [ { id: "variant1", weight: 0.5 } { id: "variant2", weight: 0.5 } ] client = new Myna.Client apiKey: "<KEY>" apiRoot: testApiRoot experiments: [ expt ] recorder = new Myna.Recorder client initialized = (fn) -> return -> expt.off() expt.unstick() recorder.off() recorder.listenTo(expt) recorder.clearQueuedEvents() recorder.semaphore = 0 recorder.waiting = [] calls = [] logCalls = -> for call in calls Myna.log("...", call) expt.on 'beforeView', jasmine.createSpy('beforeView').andCallFake (args...) -> calls.push([ "beforeView", args... ]) logCalls() expt.on 'view', jasmine.createSpy('view').andCallFake (args...) -> calls.push([ "view", args... ]) logCalls() expt.on 'beforeReward', jasmine.createSpy('beforeReward').andCallFake (args...) -> calls.push([ "beforeReward", args... ]) logCalls() expt.on 'reward', jasmine.createSpy('reward').andCallFake (args...) -> calls.push([ "reward", args... ]) logCalls() recorder.on 'beforeSync', jasmine.createSpy('beforeSync').andCallFake (args...) -> calls.push([ "beforeSync", (for events in args then eventSummaries(events))... ]) logCalls() recorder.on 'sync', jasmine.createSpy('sync').andCallFake (args...) -> calls.push([ "sync", (for events in args then eventSummaries(events))... ]) logCalls() fn(calls, logCalls) findCall = (calls, name, index) -> counter = 0 for call in calls when call[0] == name if counter == index return call else counter++ return null indexOfCall = (calls, name) -> for index, call in calls when call[0] == name return index return null describe "events", -> it "should be called in the correct order", initialized (calls, logCalls) -> variant = null rewardCallback = jasmine.createSpy('rewardCallback').andCallFake (args...) -> calls.push([ "rewardCallback", args... ]) logCalls() suggestCallback = jasmine.createSpy('suggestCallback').andCallFake (args...) -> calls.push([ "suggestCallback", args... ]) logCalls() variant = arguments[0] window.setTimeout( (-> expt.reward(0.8, rewardCallback)), 500 ) runs -> Myna.log("BLOCK 1") expt.suggest suggestCallback waitsFor -> rewardCallback.callCount > 0 waits 250 runs -> Myna.log("BLOCK 2") expect(for call in calls then call[0]).toEqual [ "beforeView" "suggestCallback" "view" "beforeSync" "sync" "beforeReward" "beforeSync" "rewardCallback" "reward" "sync" ] expect(findCall(calls, "beforeView", 0)).toEqual([ "beforeView", variant, true ]) expect(findCall(calls, "suggestCallback", 0)).toEqual([ "suggestCallback", variant, true ]) expect(findCall(calls, "view", 0)).toEqual([ "view", variant, true ]) expect(findCall(calls, "beforeSync", 0)).toEqual([ "beforeSync", [[ 'view', variant.id, null ]] ]) expect(findCall(calls, "beforeReward", 0)).toEqual([ "beforeReward", variant, 0.8, true ]) expect(findCall(calls, "reward", 0)).toEqual([ "reward", variant, 0.8, true ]) expect(findCall(calls, "sync", 0)).toEqual([ "sync", [[ 'view', variant.id, null ]], [], [] ]) expect(findCall(calls, "beforeSync", 1)).toEqual([ "beforeSync", [[ 'reward', variant.id, 0.8 ]] ]) expect(findCall(calls, "rewardCallback", 0)).toEqual([ "rewardCallback", variant, 0.8, true ]) expect(findCall(calls, "sync", 1)).toEqual([ "sync", [[ 'reward', variant.id, 0.8 ]], [], [] ]) @removeAllSpies() describe "beforeView event", -> it "should be able to cancel a suggestion", initialized (calls, logCalls) -> variant = null expt.off('beforeView') expt.on 'beforeView', jasmine.createSpy('beforeView').andCallFake (args...) -> calls.push([ "beforeView", args... ]) variant = arguments[0] false rewardCallback = jasmine.createSpy('rewardCallback').andCallFake (args...) -> calls.push([ "rewardCallback", args... ]) logCalls() suggestCallback = jasmine.createSpy('suggestCallback').andCallFake (args...) -> calls.push([ "suggestCallback", args... ]) logCalls() window.setTimeout( (-> expt.reward(0.8, rewardCallback)), 0 ) runs -> expt.suggest suggestCallback waitsFor -> expt.eventHandlers['beforeView'][0].callCount > 0 waits 250 runs -> expect(for call in calls then call[0]).toEqual([ "beforeView" ]) expect(findCall(calls, "beforeView", 0)).toEqual([ "beforeView", variant, true ]) @removeAllSpies() describe "beforeReward event", -> it "should be able to cancel a reward", initialized (calls, logCalls) -> variant = null expt.off('beforeReward') expt.on 'beforeReward', jasmine.createSpy('beforeReward').andCallFake (args...) -> calls.push([ "beforeReward", args... ]) variant = arguments[0] false rewardCallback = jasmine.createSpy('rewardCallback').andCallFake (args...) -> calls.push([ "rewardCallback", args... ]) logCalls() suggestCallback = jasmine.createSpy('suggestCallback').andCallFake (args...) -> calls.push([ "suggestCallback", args... ]) logCalls() window.setTimeout( (-> expt.reward(0.8, rewardCallback)), 500 ) runs -> expt.suggest suggestCallback waitsFor -> expt.eventHandlers['beforeReward'][0].callCount > 0 waits 250 runs -> expect(for call in calls then call[0]).toEqual [ "beforeView" "suggestCallback" "view" "beforeSync" "sync" "beforeReward" ] expect(findCall(calls, "beforeView", 0)).toEqual([ "beforeView", variant, true ]) expect(findCall(calls, "suggestCallback", 0)).toEqual([ "suggestCallback", variant, true ]) expect(findCall(calls, "view", 0)).toEqual([ "view", variant, true ]) expect(findCall(calls, "beforeSync", 0)).toEqual([ "beforeSync", [[ 'view', variant.id, null ]] ]) expect(findCall(calls, "beforeReward", 0)).toEqual([ "beforeReward", variant, 0.8, true ]) expect(findCall(calls, "sync", 0)).toEqual([ "sync", [[ 'view', variant.id, null ]], [], [] ]) @removeAllSpies()
true
expt = new Myna.Experiment uuid: "45923780-80ed-47c6-aa46-15e2ae7a0e8c" id: "id" settings: "myna.web.sticky": false variants: [ { id: "variant1", weight: 0.5 } { id: "variant2", weight: 0.5 } ] client = new Myna.Client apiKey: "PI:KEY:<KEY>END_PI" apiRoot: testApiRoot experiments: [ expt ] recorder = new Myna.Recorder client initialized = (fn) -> return -> expt.off() expt.unstick() recorder.off() recorder.listenTo(expt) recorder.clearQueuedEvents() recorder.semaphore = 0 recorder.waiting = [] calls = [] logCalls = -> for call in calls Myna.log("...", call) expt.on 'beforeView', jasmine.createSpy('beforeView').andCallFake (args...) -> calls.push([ "beforeView", args... ]) logCalls() expt.on 'view', jasmine.createSpy('view').andCallFake (args...) -> calls.push([ "view", args... ]) logCalls() expt.on 'beforeReward', jasmine.createSpy('beforeReward').andCallFake (args...) -> calls.push([ "beforeReward", args... ]) logCalls() expt.on 'reward', jasmine.createSpy('reward').andCallFake (args...) -> calls.push([ "reward", args... ]) logCalls() recorder.on 'beforeSync', jasmine.createSpy('beforeSync').andCallFake (args...) -> calls.push([ "beforeSync", (for events in args then eventSummaries(events))... ]) logCalls() recorder.on 'sync', jasmine.createSpy('sync').andCallFake (args...) -> calls.push([ "sync", (for events in args then eventSummaries(events))... ]) logCalls() fn(calls, logCalls) findCall = (calls, name, index) -> counter = 0 for call in calls when call[0] == name if counter == index return call else counter++ return null indexOfCall = (calls, name) -> for index, call in calls when call[0] == name return index return null describe "events", -> it "should be called in the correct order", initialized (calls, logCalls) -> variant = null rewardCallback = jasmine.createSpy('rewardCallback').andCallFake (args...) -> calls.push([ "rewardCallback", args... ]) logCalls() suggestCallback = jasmine.createSpy('suggestCallback').andCallFake (args...) -> calls.push([ "suggestCallback", args... ]) logCalls() variant = arguments[0] window.setTimeout( (-> expt.reward(0.8, rewardCallback)), 500 ) runs -> Myna.log("BLOCK 1") expt.suggest suggestCallback waitsFor -> rewardCallback.callCount > 0 waits 250 runs -> Myna.log("BLOCK 2") expect(for call in calls then call[0]).toEqual [ "beforeView" "suggestCallback" "view" "beforeSync" "sync" "beforeReward" "beforeSync" "rewardCallback" "reward" "sync" ] expect(findCall(calls, "beforeView", 0)).toEqual([ "beforeView", variant, true ]) expect(findCall(calls, "suggestCallback", 0)).toEqual([ "suggestCallback", variant, true ]) expect(findCall(calls, "view", 0)).toEqual([ "view", variant, true ]) expect(findCall(calls, "beforeSync", 0)).toEqual([ "beforeSync", [[ 'view', variant.id, null ]] ]) expect(findCall(calls, "beforeReward", 0)).toEqual([ "beforeReward", variant, 0.8, true ]) expect(findCall(calls, "reward", 0)).toEqual([ "reward", variant, 0.8, true ]) expect(findCall(calls, "sync", 0)).toEqual([ "sync", [[ 'view', variant.id, null ]], [], [] ]) expect(findCall(calls, "beforeSync", 1)).toEqual([ "beforeSync", [[ 'reward', variant.id, 0.8 ]] ]) expect(findCall(calls, "rewardCallback", 0)).toEqual([ "rewardCallback", variant, 0.8, true ]) expect(findCall(calls, "sync", 1)).toEqual([ "sync", [[ 'reward', variant.id, 0.8 ]], [], [] ]) @removeAllSpies() describe "beforeView event", -> it "should be able to cancel a suggestion", initialized (calls, logCalls) -> variant = null expt.off('beforeView') expt.on 'beforeView', jasmine.createSpy('beforeView').andCallFake (args...) -> calls.push([ "beforeView", args... ]) variant = arguments[0] false rewardCallback = jasmine.createSpy('rewardCallback').andCallFake (args...) -> calls.push([ "rewardCallback", args... ]) logCalls() suggestCallback = jasmine.createSpy('suggestCallback').andCallFake (args...) -> calls.push([ "suggestCallback", args... ]) logCalls() window.setTimeout( (-> expt.reward(0.8, rewardCallback)), 0 ) runs -> expt.suggest suggestCallback waitsFor -> expt.eventHandlers['beforeView'][0].callCount > 0 waits 250 runs -> expect(for call in calls then call[0]).toEqual([ "beforeView" ]) expect(findCall(calls, "beforeView", 0)).toEqual([ "beforeView", variant, true ]) @removeAllSpies() describe "beforeReward event", -> it "should be able to cancel a reward", initialized (calls, logCalls) -> variant = null expt.off('beforeReward') expt.on 'beforeReward', jasmine.createSpy('beforeReward').andCallFake (args...) -> calls.push([ "beforeReward", args... ]) variant = arguments[0] false rewardCallback = jasmine.createSpy('rewardCallback').andCallFake (args...) -> calls.push([ "rewardCallback", args... ]) logCalls() suggestCallback = jasmine.createSpy('suggestCallback').andCallFake (args...) -> calls.push([ "suggestCallback", args... ]) logCalls() window.setTimeout( (-> expt.reward(0.8, rewardCallback)), 500 ) runs -> expt.suggest suggestCallback waitsFor -> expt.eventHandlers['beforeReward'][0].callCount > 0 waits 250 runs -> expect(for call in calls then call[0]).toEqual [ "beforeView" "suggestCallback" "view" "beforeSync" "sync" "beforeReward" ] expect(findCall(calls, "beforeView", 0)).toEqual([ "beforeView", variant, true ]) expect(findCall(calls, "suggestCallback", 0)).toEqual([ "suggestCallback", variant, true ]) expect(findCall(calls, "view", 0)).toEqual([ "view", variant, true ]) expect(findCall(calls, "beforeSync", 0)).toEqual([ "beforeSync", [[ 'view', variant.id, null ]] ]) expect(findCall(calls, "beforeReward", 0)).toEqual([ "beforeReward", variant, 0.8, true ]) expect(findCall(calls, "sync", 0)).toEqual([ "sync", [[ 'view', variant.id, null ]], [], [] ]) @removeAllSpies()
[ { "context": "mo, filter) ->\n\t\t\tif filter.type?\n\t\t\t\tfilter_key = \"#{filter.type}\\[\\]\"\n\t\t\t\tmemo[filter_key] = [] unless", "end": 1715, "score": 0.967065155506134, "start": 1712, "tag": "KEY", "value": "\"#{" }, { "context": " ->\n\t\t\tif filter.type?\n\t\t\t\tfilter...
app/assets/javascripts/pophealth.js.coffee
jiangtaojiang/pophealth-booster
0
class @QualityReport constructor: (@measure, @sub_id, @filters) -> @sub_id or= null @filters or= ActiveFilters.all() url: -> base = "/measure/#{@measure}" if @sub_id? then "#{base}/#{@sub_id}" else base fetch: (extraParams, callback) -> params = $.extend({}, @filters, extraParams) $.getJSON this.url(), $.extend({}, @filters, params), (data) -> callback(data) poll: (params, callback) -> ref = this this.fetch params, (response) -> uuids={} $.each response.jobs, (i, job) -> sub_id = '' sub_id = job['sub_id'] if job['sub_id'] uuids[job['measure_id'] + sub_id] = job['uuid'] pollParams = $.extend(params, {jobs: uuids}) callback(response.result, response.complete) if (!response.complete && !response.failed) setTimeout (-> ref.poll(pollParams, callback)), 3000 @Page = { onMeasureSelect: (measure_id) -> onMeasureRemove: (measure_id) -> onFilterChange: (qr, li) -> onReportComplete: (qr) -> onLoad: -> params: {} } @ActiveFilters = { filterTypes: -> _.reduce($(".filterItemList li"), (memo, filter) -> filterType = $(filter).data("filter-type") memo.push(filterType) unless _.include(memo, filterType) || !filterType? memo , []) all: -> ActiveFilters.findFilters(".filterItemList li.checked") providers: -> ActiveFilters.findFilters(".filterItemList li.checked[data-filter-type='provider']") nonProvider: -> ActiveFilters.findFilters(".findFilterList li:not([data-filter-type='provider'])") findFilters: (selector) -> filterElements = _.map $(selector), (el) -> type: $(el).data("filter-type"), value: $(el).data("filter-value") filters = _.reduce filterElements, (memo, filter) -> if filter.type? filter_key = "#{filter.type}\[\]" memo[filter_key] = [] unless memo[filter_key]? memo[filter_key].push(filter.value) return memo , {} return filters } @Render = { fraction: (selector, data) -> selector.find(".numeratorValue").html(data.numerator) selector.find(".denominatorValue").html(data.denominator) percent: (selector, data) -> percent = if (data.denominator == 0 || data.denominator == undefined) then 0 else (data.numerator / data.denominator) * 100 selector.html("#{Math.floor(percent)}%") barChart: (selector, data) -> numerator_width = 0 denominator_width = 0 exclusion_width = 0 if data.patient_count != 0 numerator_width = (data.numerator / data.patient_count) * 100 denominator_width = ((data.denominator - data.numerator) / data.patient_count) * 100 exclusion_width = (data.exclusions / data.patient_count) * 100 selector.children("div.tableBarNumerator").animate(width: "#{numerator_width}%") selector.children("div.tableBarDenominator").animate(width: "#{denominator_width}%") selector.children("div.tableBarExclusion").animate(width: "#{exclusion_width}%") } makeListsExpandable = -> $(".groupList label").click -> $(this).toggleClass("open") $(this).siblings(".expandableList").toggle("blind") makeMeasureListClickable = -> $(".measureItemList ul li").click -> $(this).toggleClass("checked") measure = $(this).attr("data-measure-id") sub_ids = $(this).data("sub-measures").split(",") if sub_ids.length != 0 sub_ids = [null] if $(this).hasClass("checked") Page.onMeasureSelect(measure) $.each sub_ids, (i, sub) -> qr = new QualityReport(measure, sub) params = {} params['npi'] = Page.npi qr.poll(params, Page.onReportComplete) else Page.onMeasureRemove(measure) makeFilterListsClickable = -> $(".filterItemList ul li").click -> $(this).toggleClass("checked") unless $(this).hasClass("disabled") if $(this).hasClass("selectAll") allSelected = $(this).hasClass("checked") $(this).siblings().toggleClass("disabled", allSelected) $(this).siblings().toggleClass("checked", !allSelected) unless $(this).hasClass("providerSelectAll") $(".teamList ul li").click -> $.getScript "#{window.location.pathname}.js?#{$.param(ActiveFilters.all())}", (data, textStatus) -> $(".filterItemList ul li.providerSelectAll").click -> unSelected = $(".filterItemList .providerSelectAll:not(.checked)").length if unSelected > 0 $(".filterItemList ul li[data-filter-type='provider']").toggleClass("checked", true) else if unSelected == 0 $(".filterItemList ul li[data-filter-type='provider']").toggleClass("checked", false) $(".filterItemList ul li").click -> Page.onFilterChange(this) # Load Page $ -> makeMeasureListClickable() makeFilterListsClickable() makeListsExpandable() Page.onLoad();
3853
class @QualityReport constructor: (@measure, @sub_id, @filters) -> @sub_id or= null @filters or= ActiveFilters.all() url: -> base = "/measure/#{@measure}" if @sub_id? then "#{base}/#{@sub_id}" else base fetch: (extraParams, callback) -> params = $.extend({}, @filters, extraParams) $.getJSON this.url(), $.extend({}, @filters, params), (data) -> callback(data) poll: (params, callback) -> ref = this this.fetch params, (response) -> uuids={} $.each response.jobs, (i, job) -> sub_id = '' sub_id = job['sub_id'] if job['sub_id'] uuids[job['measure_id'] + sub_id] = job['uuid'] pollParams = $.extend(params, {jobs: uuids}) callback(response.result, response.complete) if (!response.complete && !response.failed) setTimeout (-> ref.poll(pollParams, callback)), 3000 @Page = { onMeasureSelect: (measure_id) -> onMeasureRemove: (measure_id) -> onFilterChange: (qr, li) -> onReportComplete: (qr) -> onLoad: -> params: {} } @ActiveFilters = { filterTypes: -> _.reduce($(".filterItemList li"), (memo, filter) -> filterType = $(filter).data("filter-type") memo.push(filterType) unless _.include(memo, filterType) || !filterType? memo , []) all: -> ActiveFilters.findFilters(".filterItemList li.checked") providers: -> ActiveFilters.findFilters(".filterItemList li.checked[data-filter-type='provider']") nonProvider: -> ActiveFilters.findFilters(".findFilterList li:not([data-filter-type='provider'])") findFilters: (selector) -> filterElements = _.map $(selector), (el) -> type: $(el).data("filter-type"), value: $(el).data("filter-value") filters = _.reduce filterElements, (memo, filter) -> if filter.type? filter_key = <KEY>filter.<KEY> memo[filter_key] = [] unless memo[filter_key]? memo[filter_key].push(filter.value) return memo , {} return filters } @Render = { fraction: (selector, data) -> selector.find(".numeratorValue").html(data.numerator) selector.find(".denominatorValue").html(data.denominator) percent: (selector, data) -> percent = if (data.denominator == 0 || data.denominator == undefined) then 0 else (data.numerator / data.denominator) * 100 selector.html("#{Math.floor(percent)}%") barChart: (selector, data) -> numerator_width = 0 denominator_width = 0 exclusion_width = 0 if data.patient_count != 0 numerator_width = (data.numerator / data.patient_count) * 100 denominator_width = ((data.denominator - data.numerator) / data.patient_count) * 100 exclusion_width = (data.exclusions / data.patient_count) * 100 selector.children("div.tableBarNumerator").animate(width: "#{numerator_width}%") selector.children("div.tableBarDenominator").animate(width: "#{denominator_width}%") selector.children("div.tableBarExclusion").animate(width: "#{exclusion_width}%") } makeListsExpandable = -> $(".groupList label").click -> $(this).toggleClass("open") $(this).siblings(".expandableList").toggle("blind") makeMeasureListClickable = -> $(".measureItemList ul li").click -> $(this).toggleClass("checked") measure = $(this).attr("data-measure-id") sub_ids = $(this).data("sub-measures").split(",") if sub_ids.length != 0 sub_ids = [null] if $(this).hasClass("checked") Page.onMeasureSelect(measure) $.each sub_ids, (i, sub) -> qr = new QualityReport(measure, sub) params = {} params['npi'] = Page.npi qr.poll(params, Page.onReportComplete) else Page.onMeasureRemove(measure) makeFilterListsClickable = -> $(".filterItemList ul li").click -> $(this).toggleClass("checked") unless $(this).hasClass("disabled") if $(this).hasClass("selectAll") allSelected = $(this).hasClass("checked") $(this).siblings().toggleClass("disabled", allSelected) $(this).siblings().toggleClass("checked", !allSelected) unless $(this).hasClass("providerSelectAll") $(".teamList ul li").click -> $.getScript "#{window.location.pathname}.js?#{$.param(ActiveFilters.all())}", (data, textStatus) -> $(".filterItemList ul li.providerSelectAll").click -> unSelected = $(".filterItemList .providerSelectAll:not(.checked)").length if unSelected > 0 $(".filterItemList ul li[data-filter-type='provider']").toggleClass("checked", true) else if unSelected == 0 $(".filterItemList ul li[data-filter-type='provider']").toggleClass("checked", false) $(".filterItemList ul li").click -> Page.onFilterChange(this) # Load Page $ -> makeMeasureListClickable() makeFilterListsClickable() makeListsExpandable() Page.onLoad();
true
class @QualityReport constructor: (@measure, @sub_id, @filters) -> @sub_id or= null @filters or= ActiveFilters.all() url: -> base = "/measure/#{@measure}" if @sub_id? then "#{base}/#{@sub_id}" else base fetch: (extraParams, callback) -> params = $.extend({}, @filters, extraParams) $.getJSON this.url(), $.extend({}, @filters, params), (data) -> callback(data) poll: (params, callback) -> ref = this this.fetch params, (response) -> uuids={} $.each response.jobs, (i, job) -> sub_id = '' sub_id = job['sub_id'] if job['sub_id'] uuids[job['measure_id'] + sub_id] = job['uuid'] pollParams = $.extend(params, {jobs: uuids}) callback(response.result, response.complete) if (!response.complete && !response.failed) setTimeout (-> ref.poll(pollParams, callback)), 3000 @Page = { onMeasureSelect: (measure_id) -> onMeasureRemove: (measure_id) -> onFilterChange: (qr, li) -> onReportComplete: (qr) -> onLoad: -> params: {} } @ActiveFilters = { filterTypes: -> _.reduce($(".filterItemList li"), (memo, filter) -> filterType = $(filter).data("filter-type") memo.push(filterType) unless _.include(memo, filterType) || !filterType? memo , []) all: -> ActiveFilters.findFilters(".filterItemList li.checked") providers: -> ActiveFilters.findFilters(".filterItemList li.checked[data-filter-type='provider']") nonProvider: -> ActiveFilters.findFilters(".findFilterList li:not([data-filter-type='provider'])") findFilters: (selector) -> filterElements = _.map $(selector), (el) -> type: $(el).data("filter-type"), value: $(el).data("filter-value") filters = _.reduce filterElements, (memo, filter) -> if filter.type? filter_key = PI:KEY:<KEY>END_PIfilter.PI:KEY:<KEY>END_PI memo[filter_key] = [] unless memo[filter_key]? memo[filter_key].push(filter.value) return memo , {} return filters } @Render = { fraction: (selector, data) -> selector.find(".numeratorValue").html(data.numerator) selector.find(".denominatorValue").html(data.denominator) percent: (selector, data) -> percent = if (data.denominator == 0 || data.denominator == undefined) then 0 else (data.numerator / data.denominator) * 100 selector.html("#{Math.floor(percent)}%") barChart: (selector, data) -> numerator_width = 0 denominator_width = 0 exclusion_width = 0 if data.patient_count != 0 numerator_width = (data.numerator / data.patient_count) * 100 denominator_width = ((data.denominator - data.numerator) / data.patient_count) * 100 exclusion_width = (data.exclusions / data.patient_count) * 100 selector.children("div.tableBarNumerator").animate(width: "#{numerator_width}%") selector.children("div.tableBarDenominator").animate(width: "#{denominator_width}%") selector.children("div.tableBarExclusion").animate(width: "#{exclusion_width}%") } makeListsExpandable = -> $(".groupList label").click -> $(this).toggleClass("open") $(this).siblings(".expandableList").toggle("blind") makeMeasureListClickable = -> $(".measureItemList ul li").click -> $(this).toggleClass("checked") measure = $(this).attr("data-measure-id") sub_ids = $(this).data("sub-measures").split(",") if sub_ids.length != 0 sub_ids = [null] if $(this).hasClass("checked") Page.onMeasureSelect(measure) $.each sub_ids, (i, sub) -> qr = new QualityReport(measure, sub) params = {} params['npi'] = Page.npi qr.poll(params, Page.onReportComplete) else Page.onMeasureRemove(measure) makeFilterListsClickable = -> $(".filterItemList ul li").click -> $(this).toggleClass("checked") unless $(this).hasClass("disabled") if $(this).hasClass("selectAll") allSelected = $(this).hasClass("checked") $(this).siblings().toggleClass("disabled", allSelected) $(this).siblings().toggleClass("checked", !allSelected) unless $(this).hasClass("providerSelectAll") $(".teamList ul li").click -> $.getScript "#{window.location.pathname}.js?#{$.param(ActiveFilters.all())}", (data, textStatus) -> $(".filterItemList ul li.providerSelectAll").click -> unSelected = $(".filterItemList .providerSelectAll:not(.checked)").length if unSelected > 0 $(".filterItemList ul li[data-filter-type='provider']").toggleClass("checked", true) else if unSelected == 0 $(".filterItemList ul li[data-filter-type='provider']").toggleClass("checked", false) $(".filterItemList ul li").click -> Page.onFilterChange(this) # Load Page $ -> makeMeasureListClickable() makeFilterListsClickable() makeListsExpandable() Page.onLoad();
[ { "context": "work'\n @artwork.bibliography = \"<p>Literature: Plagens, Peter. &quot;The Sculpture of Peter Alexander.&quot; <e", "end": 437, "score": 0.9600319266319275, "start": 423, "tag": "NAME", "value": "Plagens, Peter" }, { "context": "iterature: Plagens, Peter. &quot;The...
src/mobile/apps/artwork/components/tabs/test/index.coffee
kanaabe/force
1
jade = require 'jade' benv = require 'benv' path = require 'path' fs = require 'fs' { fabricate } = require 'antigravity' { resolve } = require 'path' describe 'Artwork tabs templates', -> before (done) -> benv.setup => benv.expose { $: benv.require 'jquery' } done() after -> benv.teardown() beforeEach (done) -> @artwork = fabricate 'artwork' @artwork.bibliography = "<p>Literature: Plagens, Peter. &quot;The Sculpture of Peter Alexander.&quot; <em>Artforum</em> Oct. 1970: 48-51 for similar example from the same period illustrated.</p>↵" @artwork.provenance = "<p>Provenance: Private Collection, Los Angeles, California (acquired directly from the artist, 1968)</p>↵" benv.render resolve(__dirname, '../templates/index.jade'), { artwork: @artwork sd: ARTWORK: @artwork asset: (->) }, => @accordionFunction = require('../index.coffee') done() describe 'shows tab content when clicked', -> beforeEach -> @accordionFunction() xit 'expands the correct tab', -> $('.js-artwork-tab-link').filter("[data-id=bibliography]").click() $('.artwork-tab').filter("[data-id=bibliography]").css('display').should.equal('block') $('.js-artwork-item').filter("[data-id=bibliography]").hasClass('is-active').should.equal true
44580
jade = require 'jade' benv = require 'benv' path = require 'path' fs = require 'fs' { fabricate } = require 'antigravity' { resolve } = require 'path' describe 'Artwork tabs templates', -> before (done) -> benv.setup => benv.expose { $: benv.require 'jquery' } done() after -> benv.teardown() beforeEach (done) -> @artwork = fabricate 'artwork' @artwork.bibliography = "<p>Literature: <NAME>. &quot;The Sculpture of <NAME>.&quot; <em>Artforum</em> Oct. 1970: 48-51 for similar example from the same period illustrated.</p>↵" @artwork.provenance = "<p>Provenance: Private Collection, Los Angeles, California (acquired directly from the artist, 1968)</p>↵" benv.render resolve(__dirname, '../templates/index.jade'), { artwork: @artwork sd: ARTWORK: @artwork asset: (->) }, => @accordionFunction = require('../index.coffee') done() describe 'shows tab content when clicked', -> beforeEach -> @accordionFunction() xit 'expands the correct tab', -> $('.js-artwork-tab-link').filter("[data-id=bibliography]").click() $('.artwork-tab').filter("[data-id=bibliography]").css('display').should.equal('block') $('.js-artwork-item').filter("[data-id=bibliography]").hasClass('is-active').should.equal true
true
jade = require 'jade' benv = require 'benv' path = require 'path' fs = require 'fs' { fabricate } = require 'antigravity' { resolve } = require 'path' describe 'Artwork tabs templates', -> before (done) -> benv.setup => benv.expose { $: benv.require 'jquery' } done() after -> benv.teardown() beforeEach (done) -> @artwork = fabricate 'artwork' @artwork.bibliography = "<p>Literature: PI:NAME:<NAME>END_PI. &quot;The Sculpture of PI:NAME:<NAME>END_PI.&quot; <em>Artforum</em> Oct. 1970: 48-51 for similar example from the same period illustrated.</p>↵" @artwork.provenance = "<p>Provenance: Private Collection, Los Angeles, California (acquired directly from the artist, 1968)</p>↵" benv.render resolve(__dirname, '../templates/index.jade'), { artwork: @artwork sd: ARTWORK: @artwork asset: (->) }, => @accordionFunction = require('../index.coffee') done() describe 'shows tab content when clicked', -> beforeEach -> @accordionFunction() xit 'expands the correct tab', -> $('.js-artwork-tab-link').filter("[data-id=bibliography]").click() $('.artwork-tab').filter("[data-id=bibliography]").css('display').should.equal('block') $('.js-artwork-item').filter("[data-id=bibliography]").hasClass('is-active').should.equal true
[ { "context": "ectHandler.setObjectValueByPath objs[0], \"name\", \"Jack Black\"\n\t\texpect(objs[0].name).to.be.equal \"Jack Black\"\n", "end": 1791, "score": 0.9998745918273926, "start": 1781, "tag": "NAME", "value": "Jack Black" }, { "context": " \"Jack Black\"\n\t\texpect(objs[0]....
test/modules/objects.spec.coffee
icebob/propertiesjs
21
_ = require("lodash") PSObjectHandler = require "../../src/js/modules/objects.js" testData = require "../test-data" chai = require("chai") sinon = require "sinon" sinonChai = require "sinon-chai" expect = chai.expect chai.use sinonChai describe "Test PJSObjectHandler methods", -> objectHandler = null objs = null beforeEach -> [objs, schema] = testData.clone() objectHandler = new PSObjectHandler objs it "check constructor & setObjs", -> expect(objectHandler).to.be.exist expect(objectHandler.objs).to.be.exist expect(objectHandler.objs).to.be.instanceof(Array) expect(objectHandler.objs).to.be.length 4 objectHandler.setObjects [objs[0], objs[2]] expect(objectHandler.objs).to.be.instanceof(Array) expect(objectHandler.objs).to.be.length 2 it "check getObjectValueByPath", -> expect(objectHandler.getObjectValueByPath objs[0], "name").to.be.equal objs[0].name expect(objectHandler.getObjectValueByPath objs[0], "age").to.be.equal objs[0].age expect(objectHandler.getObjectValueByPath objs[0], "sex").to.be.unDefined expect(objectHandler.getObjectValueByPath objs[0], "body").to.be.equal objs[0].body expect(objectHandler.getObjectValueByPath objs[0], "body.weight").to.be.equal objs[0].body.weight expect(objectHandler.getObjectValueByPath objs[0], "body.weight.size").to.be.unDefined expect(objectHandler.getObjectValueByPath objs[0], "bodies.weight.size").to.be.unDefined expect(objectHandler.getObjectValueByPath objs[0], "").to.be.unDefined expect(objectHandler.getObjectValueByPath objs[0], null).to.be.unDefined expect(objectHandler.getObjectValueByPath objs[0], "skills").to.be.equal objs[0].skills it "check setObjectValueByPath", -> objectHandler.setObjectValueByPath objs[0], "name", "Jack Black" expect(objs[0].name).to.be.equal "Jack Black" objectHandler.setObjectValueByPath objs[0], "age", 44 expect(objs[0].age).to.be.equal 44 objectHandler.setObjectValueByPath objs[0], "body.weight", 95 expect(objs[0].body.weight).to.be.equal 95 objectHandler.setObjectValueByPath objs[0], "body", { weight: 76, height: 198} expect(objs[0].body.weight).to.be.equal 76 expect(objs[0].body.height).to.be.equal 198 objectHandler.setObjectValueByPath objs[0], "bodies.body.weight", 100 expect(objs[0].bodies).to.be.unDefined expect(objs[0].body.weight).to.be.equal 76 objectHandler.setObjectValueByPath objs[0], "skills", ["HTML5", "CSS3"] expect(objs[0].skills).to.be.deep.equal ["HTML5", "CSS3"] it "check getValueFromObjects", -> # With all 4 objects expect(objectHandler.getValueFromObjects "name").to.be.null expect(objectHandler.getValueFromObjects "active").to.be.null expect(objectHandler.getValueFromObjects "retired").to.be.null expect(objectHandler.getValueFromObjects "body.glasses").to.be.null expect(objectHandler.getValueFromObjects "body.height").to.be.null expect(objectHandler.getValueFromObjects "body.foot").to.be.equal 42 expect(objectHandler.getValueFromObjects "skills").to.be.null # ? # With 1 and 3 objects objectHandler.setObjects [objs[0], objs[2]] expect(objectHandler.getValueFromObjects "name").to.be.null expect(objectHandler.getValueFromObjects "active").to.be.true expect(objectHandler.getValueFromObjects "retired").to.be.null expect(objectHandler.getValueFromObjects "body.glasses").to.be.true expect(objectHandler.getValueFromObjects "body.height").to.be.equal 180 expect(objectHandler.getValueFromObjects "body.foot").to.be.equal 42 # With only 1 object objectHandler.setObjects [objs[1]] expect(objectHandler.getValueFromObjects "name").to.be.equal objs[1].name expect(objectHandler.getValueFromObjects "active").to.be.false expect(objectHandler.getValueFromObjects "retired").to.be.false expect(objectHandler.getValueFromObjects "body.glasses").to.be.false expect(objectHandler.getValueFromObjects "body.height").to.be.equal 165 expect(objectHandler.getValueFromObjects "body.foot").to.be.equal 42 # With 2 objects and array property objectHandler.setObjects [objs[0], objs[1]] expect(objectHandler.getValueFromObjects "skills").to.be.deep.equal ["Javascript", "AngularJS"] it "check setValueToObjects with exist propety", -> # With all 3 objects newName = "Steve Douglas" objectHandler.setValueToObjects "name", newName expect(objectHandler.getValueFromObjects "name").to.be.equal newName _.each objectHandler.objs, (obj) -> expect(obj.name).to.be.equal newName objectHandler.setValueToObjects "retired", true expect(objectHandler.getValueFromObjects "retired").to.be.true _.each objectHandler.objs, (obj) -> expect(obj.retired).to.be.true newFoot = 44 objectHandler.setValueToObjects "body.foot", newFoot expect(objectHandler.getValueFromObjects "body.foot").to.be.equal newFoot _.each objectHandler.objs, (obj) -> expect(obj.body.foot).to.be.equal newFoot it "check setValueToObjects with new property", -> # New property test expect(objectHandler.getValueFromObjects "body.head").to.be.null newProp = 12 objectHandler.setValueToObjects "body.head", newProp expect(objectHandler.getValueFromObjects "body.head").to.be.equal newProp _.each objectHandler.objs, (obj) -> expect(obj.body.head).to.be.equal newProp expect(objectHandler.getValueFromObjects "live").to.be.null newProp = true objectHandler.setValueToObjects "live", newProp expect(objectHandler.getValueFromObjects "live").to.be.equal newProp _.each objectHandler.objs, (obj) -> expect(obj.live).to.be.equal newProp it "check hasFunctionInObjects", -> expect(objectHandler.hasFunctionInObjects "onchanged").to.be.false objs[2].onchanged = "Hello" expect(objectHandler.hasFunctionInObjects "onchanged").to.be.false objs[2].onchanged = -> "Jim's value changed" expect(objectHandler.hasFunctionInObjects "onchanged").to.be.true # check null objectHandler.setObjects [] expect(objectHandler.hasFunctionInObjects("onchanged")).to.be.false objectHandler.setObjects undefined expect(objectHandler.hasFunctionInObjects("onchanged")).to.be.false expect(objectHandler.hasFunctionInObjects()).to.be.false it "check callFunctionInObjects", -> # Create spy for callback fncSendMessage = sinon.spy() _.each objs, (obj) -> obj.sendMessage = fncSendMessage objectHandler.callFunctionInObjects "sendMessage" expect(fncSendMessage).to.have.been.callCount 4
221149
_ = require("lodash") PSObjectHandler = require "../../src/js/modules/objects.js" testData = require "../test-data" chai = require("chai") sinon = require "sinon" sinonChai = require "sinon-chai" expect = chai.expect chai.use sinonChai describe "Test PJSObjectHandler methods", -> objectHandler = null objs = null beforeEach -> [objs, schema] = testData.clone() objectHandler = new PSObjectHandler objs it "check constructor & setObjs", -> expect(objectHandler).to.be.exist expect(objectHandler.objs).to.be.exist expect(objectHandler.objs).to.be.instanceof(Array) expect(objectHandler.objs).to.be.length 4 objectHandler.setObjects [objs[0], objs[2]] expect(objectHandler.objs).to.be.instanceof(Array) expect(objectHandler.objs).to.be.length 2 it "check getObjectValueByPath", -> expect(objectHandler.getObjectValueByPath objs[0], "name").to.be.equal objs[0].name expect(objectHandler.getObjectValueByPath objs[0], "age").to.be.equal objs[0].age expect(objectHandler.getObjectValueByPath objs[0], "sex").to.be.unDefined expect(objectHandler.getObjectValueByPath objs[0], "body").to.be.equal objs[0].body expect(objectHandler.getObjectValueByPath objs[0], "body.weight").to.be.equal objs[0].body.weight expect(objectHandler.getObjectValueByPath objs[0], "body.weight.size").to.be.unDefined expect(objectHandler.getObjectValueByPath objs[0], "bodies.weight.size").to.be.unDefined expect(objectHandler.getObjectValueByPath objs[0], "").to.be.unDefined expect(objectHandler.getObjectValueByPath objs[0], null).to.be.unDefined expect(objectHandler.getObjectValueByPath objs[0], "skills").to.be.equal objs[0].skills it "check setObjectValueByPath", -> objectHandler.setObjectValueByPath objs[0], "name", "<NAME>" expect(objs[0].name).to.be.equal "<NAME>" objectHandler.setObjectValueByPath objs[0], "age", 44 expect(objs[0].age).to.be.equal 44 objectHandler.setObjectValueByPath objs[0], "body.weight", 95 expect(objs[0].body.weight).to.be.equal 95 objectHandler.setObjectValueByPath objs[0], "body", { weight: 76, height: 198} expect(objs[0].body.weight).to.be.equal 76 expect(objs[0].body.height).to.be.equal 198 objectHandler.setObjectValueByPath objs[0], "bodies.body.weight", 100 expect(objs[0].bodies).to.be.unDefined expect(objs[0].body.weight).to.be.equal 76 objectHandler.setObjectValueByPath objs[0], "skills", ["HTML5", "CSS3"] expect(objs[0].skills).to.be.deep.equal ["HTML5", "CSS3"] it "check getValueFromObjects", -> # With all 4 objects expect(objectHandler.getValueFromObjects "name").to.be.null expect(objectHandler.getValueFromObjects "active").to.be.null expect(objectHandler.getValueFromObjects "retired").to.be.null expect(objectHandler.getValueFromObjects "body.glasses").to.be.null expect(objectHandler.getValueFromObjects "body.height").to.be.null expect(objectHandler.getValueFromObjects "body.foot").to.be.equal 42 expect(objectHandler.getValueFromObjects "skills").to.be.null # ? # With 1 and 3 objects objectHandler.setObjects [objs[0], objs[2]] expect(objectHandler.getValueFromObjects "name").to.be.null expect(objectHandler.getValueFromObjects "active").to.be.true expect(objectHandler.getValueFromObjects "retired").to.be.null expect(objectHandler.getValueFromObjects "body.glasses").to.be.true expect(objectHandler.getValueFromObjects "body.height").to.be.equal 180 expect(objectHandler.getValueFromObjects "body.foot").to.be.equal 42 # With only 1 object objectHandler.setObjects [objs[1]] expect(objectHandler.getValueFromObjects "name").to.be.equal objs[1].name expect(objectHandler.getValueFromObjects "active").to.be.false expect(objectHandler.getValueFromObjects "retired").to.be.false expect(objectHandler.getValueFromObjects "body.glasses").to.be.false expect(objectHandler.getValueFromObjects "body.height").to.be.equal 165 expect(objectHandler.getValueFromObjects "body.foot").to.be.equal 42 # With 2 objects and array property objectHandler.setObjects [objs[0], objs[1]] expect(objectHandler.getValueFromObjects "skills").to.be.deep.equal ["Javascript", "AngularJS"] it "check setValueToObjects with exist propety", -> # With all 3 objects newName = "<NAME>" objectHandler.setValueToObjects "name", newName expect(objectHandler.getValueFromObjects "name").to.be.equal newName _.each objectHandler.objs, (obj) -> expect(obj.name).to.be.equal newName objectHandler.setValueToObjects "retired", true expect(objectHandler.getValueFromObjects "retired").to.be.true _.each objectHandler.objs, (obj) -> expect(obj.retired).to.be.true newFoot = 44 objectHandler.setValueToObjects "body.foot", newFoot expect(objectHandler.getValueFromObjects "body.foot").to.be.equal newFoot _.each objectHandler.objs, (obj) -> expect(obj.body.foot).to.be.equal newFoot it "check setValueToObjects with new property", -> # New property test expect(objectHandler.getValueFromObjects "body.head").to.be.null newProp = 12 objectHandler.setValueToObjects "body.head", newProp expect(objectHandler.getValueFromObjects "body.head").to.be.equal newProp _.each objectHandler.objs, (obj) -> expect(obj.body.head).to.be.equal newProp expect(objectHandler.getValueFromObjects "live").to.be.null newProp = true objectHandler.setValueToObjects "live", newProp expect(objectHandler.getValueFromObjects "live").to.be.equal newProp _.each objectHandler.objs, (obj) -> expect(obj.live).to.be.equal newProp it "check hasFunctionInObjects", -> expect(objectHandler.hasFunctionInObjects "onchanged").to.be.false objs[2].onchanged = "Hello" expect(objectHandler.hasFunctionInObjects "onchanged").to.be.false objs[2].onchanged = -> "<NAME>'s value changed" expect(objectHandler.hasFunctionInObjects "onchanged").to.be.true # check null objectHandler.setObjects [] expect(objectHandler.hasFunctionInObjects("onchanged")).to.be.false objectHandler.setObjects undefined expect(objectHandler.hasFunctionInObjects("onchanged")).to.be.false expect(objectHandler.hasFunctionInObjects()).to.be.false it "check callFunctionInObjects", -> # Create spy for callback fncSendMessage = sinon.spy() _.each objs, (obj) -> obj.sendMessage = fncSendMessage objectHandler.callFunctionInObjects "sendMessage" expect(fncSendMessage).to.have.been.callCount 4
true
_ = require("lodash") PSObjectHandler = require "../../src/js/modules/objects.js" testData = require "../test-data" chai = require("chai") sinon = require "sinon" sinonChai = require "sinon-chai" expect = chai.expect chai.use sinonChai describe "Test PJSObjectHandler methods", -> objectHandler = null objs = null beforeEach -> [objs, schema] = testData.clone() objectHandler = new PSObjectHandler objs it "check constructor & setObjs", -> expect(objectHandler).to.be.exist expect(objectHandler.objs).to.be.exist expect(objectHandler.objs).to.be.instanceof(Array) expect(objectHandler.objs).to.be.length 4 objectHandler.setObjects [objs[0], objs[2]] expect(objectHandler.objs).to.be.instanceof(Array) expect(objectHandler.objs).to.be.length 2 it "check getObjectValueByPath", -> expect(objectHandler.getObjectValueByPath objs[0], "name").to.be.equal objs[0].name expect(objectHandler.getObjectValueByPath objs[0], "age").to.be.equal objs[0].age expect(objectHandler.getObjectValueByPath objs[0], "sex").to.be.unDefined expect(objectHandler.getObjectValueByPath objs[0], "body").to.be.equal objs[0].body expect(objectHandler.getObjectValueByPath objs[0], "body.weight").to.be.equal objs[0].body.weight expect(objectHandler.getObjectValueByPath objs[0], "body.weight.size").to.be.unDefined expect(objectHandler.getObjectValueByPath objs[0], "bodies.weight.size").to.be.unDefined expect(objectHandler.getObjectValueByPath objs[0], "").to.be.unDefined expect(objectHandler.getObjectValueByPath objs[0], null).to.be.unDefined expect(objectHandler.getObjectValueByPath objs[0], "skills").to.be.equal objs[0].skills it "check setObjectValueByPath", -> objectHandler.setObjectValueByPath objs[0], "name", "PI:NAME:<NAME>END_PI" expect(objs[0].name).to.be.equal "PI:NAME:<NAME>END_PI" objectHandler.setObjectValueByPath objs[0], "age", 44 expect(objs[0].age).to.be.equal 44 objectHandler.setObjectValueByPath objs[0], "body.weight", 95 expect(objs[0].body.weight).to.be.equal 95 objectHandler.setObjectValueByPath objs[0], "body", { weight: 76, height: 198} expect(objs[0].body.weight).to.be.equal 76 expect(objs[0].body.height).to.be.equal 198 objectHandler.setObjectValueByPath objs[0], "bodies.body.weight", 100 expect(objs[0].bodies).to.be.unDefined expect(objs[0].body.weight).to.be.equal 76 objectHandler.setObjectValueByPath objs[0], "skills", ["HTML5", "CSS3"] expect(objs[0].skills).to.be.deep.equal ["HTML5", "CSS3"] it "check getValueFromObjects", -> # With all 4 objects expect(objectHandler.getValueFromObjects "name").to.be.null expect(objectHandler.getValueFromObjects "active").to.be.null expect(objectHandler.getValueFromObjects "retired").to.be.null expect(objectHandler.getValueFromObjects "body.glasses").to.be.null expect(objectHandler.getValueFromObjects "body.height").to.be.null expect(objectHandler.getValueFromObjects "body.foot").to.be.equal 42 expect(objectHandler.getValueFromObjects "skills").to.be.null # ? # With 1 and 3 objects objectHandler.setObjects [objs[0], objs[2]] expect(objectHandler.getValueFromObjects "name").to.be.null expect(objectHandler.getValueFromObjects "active").to.be.true expect(objectHandler.getValueFromObjects "retired").to.be.null expect(objectHandler.getValueFromObjects "body.glasses").to.be.true expect(objectHandler.getValueFromObjects "body.height").to.be.equal 180 expect(objectHandler.getValueFromObjects "body.foot").to.be.equal 42 # With only 1 object objectHandler.setObjects [objs[1]] expect(objectHandler.getValueFromObjects "name").to.be.equal objs[1].name expect(objectHandler.getValueFromObjects "active").to.be.false expect(objectHandler.getValueFromObjects "retired").to.be.false expect(objectHandler.getValueFromObjects "body.glasses").to.be.false expect(objectHandler.getValueFromObjects "body.height").to.be.equal 165 expect(objectHandler.getValueFromObjects "body.foot").to.be.equal 42 # With 2 objects and array property objectHandler.setObjects [objs[0], objs[1]] expect(objectHandler.getValueFromObjects "skills").to.be.deep.equal ["Javascript", "AngularJS"] it "check setValueToObjects with exist propety", -> # With all 3 objects newName = "PI:NAME:<NAME>END_PI" objectHandler.setValueToObjects "name", newName expect(objectHandler.getValueFromObjects "name").to.be.equal newName _.each objectHandler.objs, (obj) -> expect(obj.name).to.be.equal newName objectHandler.setValueToObjects "retired", true expect(objectHandler.getValueFromObjects "retired").to.be.true _.each objectHandler.objs, (obj) -> expect(obj.retired).to.be.true newFoot = 44 objectHandler.setValueToObjects "body.foot", newFoot expect(objectHandler.getValueFromObjects "body.foot").to.be.equal newFoot _.each objectHandler.objs, (obj) -> expect(obj.body.foot).to.be.equal newFoot it "check setValueToObjects with new property", -> # New property test expect(objectHandler.getValueFromObjects "body.head").to.be.null newProp = 12 objectHandler.setValueToObjects "body.head", newProp expect(objectHandler.getValueFromObjects "body.head").to.be.equal newProp _.each objectHandler.objs, (obj) -> expect(obj.body.head).to.be.equal newProp expect(objectHandler.getValueFromObjects "live").to.be.null newProp = true objectHandler.setValueToObjects "live", newProp expect(objectHandler.getValueFromObjects "live").to.be.equal newProp _.each objectHandler.objs, (obj) -> expect(obj.live).to.be.equal newProp it "check hasFunctionInObjects", -> expect(objectHandler.hasFunctionInObjects "onchanged").to.be.false objs[2].onchanged = "Hello" expect(objectHandler.hasFunctionInObjects "onchanged").to.be.false objs[2].onchanged = -> "PI:NAME:<NAME>END_PI's value changed" expect(objectHandler.hasFunctionInObjects "onchanged").to.be.true # check null objectHandler.setObjects [] expect(objectHandler.hasFunctionInObjects("onchanged")).to.be.false objectHandler.setObjects undefined expect(objectHandler.hasFunctionInObjects("onchanged")).to.be.false expect(objectHandler.hasFunctionInObjects()).to.be.false it "check callFunctionInObjects", -> # Create spy for callback fncSendMessage = sinon.spy() _.each objs, (obj) -> obj.sendMessage = fncSendMessage objectHandler.callFunctionInObjects "sendMessage" expect(fncSendMessage).to.have.been.callCount 4
[ { "context": " == 0\n user = @createUser\n nick: \"microstudio\"\n email: \"standalone@microstudio.dev\"\n ", "end": 2054, "score": 0.9989691972732544, "start": 2043, "tag": "USERNAME", "value": "microstudio" }, { "context": "r\n nick: \"microstudio...
server/content/content.coffee
sksdutra/microstudio
0
usage = require "pidusage" User = require __dirname+"/user.js" Project = require __dirname+"/project.js" Tag = require __dirname+"/tag.js" Token = require __dirname+"/token.js" Translator = require __dirname+"/translator.js" Forum = require __dirname+"/../forum/forum.js" Cleaner = require __dirname+"/cleaner.js" class @Content constructor:(@server,@db,@files)-> @users = {} @users_by_email = {} @users_by_nick = {} @tokens = {} @projects = {} @tags = {} @sorted_tags = [] @project_count = 0 @user_count = 0 @guest_count = 0 @load() @hot_projects = [] @top_projects = [] @new_projects = [] @plugin_projects = [] @library_projects = [] @updatePublicProjects() console.info "Content loaded: #{@user_count} users and #{@project_count} projects" @top_interval = setInterval (()=> @sortPublicProjects()),10001 @log_interval = setInterval (()=> @statusLog()),6000 @translator = new Translator @ @forum = new Forum @ @cleaner = new Cleaner @ close:()-> clearInterval @top_interval clearInterval @log_interval @forum.close() @cleaner.stop() if @cleaner? statusLog:()-> usage process.pid,(err,result)=> return if not result? console.info "------------" console.info "#{new Date().toString()}" console.info "cpu: #{Math.round(result.cpu)}%" console.info "memory: #{Math.round(result.memory/1000000)} mb" console.info "users: #{@user_count}" console.info "projects: #{@project_count}" @current_cpu = Math.round(result.cpu) @current_memory = Math.round(result.memory/1000000) @server.stats.max("cpu_max",Math.round(result.cpu)) @server.stats.max("memory_max",@current_memory) load:()-> users = @db.list("users") for record in users @loadUser record if @server.config.standalone if @user_count>1 throw "Error, cannot run standalone if user_count>1" else if @user_count == 0 user = @createUser nick: "microstudio" email: "standalone@microstudio.dev" flags: {validated: true} hash: "---" date_created: Date.now() last_active: Date.now() creation_ip: "127.0.0.1" tokens = @db.list("tokens") for token in tokens @loadToken token projects = @db.list("projects") for record in projects @loadProject record @initLikes() return loadUser:(record)-> data = record.get() user = new User @,record return if user.flags.deleted @users[user.id] = user if user.email? @users_by_email[user.email] = user else @guest_count += 1 @users_by_nick[user.nick] = user @user_count++ user loadProject:(record)-> data = record.get() project = new Project @,record if project.owner? and not project.deleted @projects[project.id] = project @loadTags(project) @project_count++ project loadTags:(project)-> for t in project.tags tag = @tags[t] if not tag? tag = new Tag(t) @tags[t] = tag @sorted_tags.push tag tag.add project return loadToken:(record)-> data = record.get() token = new Token @,record if token.user? @tokens[token.value] = token token initLikes:()-> for key,user of @users for f in user.likes if @projects[f]? @projects[f].likes++ return updatePublicProjects:()-> @hot_projects = [] @top_projects = [] @new_projects = [] @plugin_projects = [] @library_projects = [] for key,project of @projects if project.public and not project.unlisted and project.owner.flags["validated"] and not project.deleted and not project.owner.flags["censored"] @hot_projects.push project @top_projects.push project @new_projects.push project if project.type == "plugin" @plugin_projects.push project if project.type == "library" @library_projects.push project @sortPublicProjects() sortPublicProjects:()-> time = Date.now() @top_projects.sort (a,b)-> b.likes-a.likes @new_projects.sort (a,b)-> b.first_published-a.first_published @sorted_tags.sort (a,b)-> b.uses+b.num_users*10-a.uses-a.num_users*10 @plugin_projects.sort (a,b)-> b.likes-a.likes @library_projects.sort (a,b)-> b.likes-a.likes return if @top_projects.length<5 now = Date.now() maxLikes = Math.max(1,@top_projects[4].likes) fade = (x)-> 1-Math.max(0,Math.min(1,x)) note = (p)-> recent = fade (now-p.first_published)/1000/3600/24/4 rating = p.likes/maxLikes*(.15+2*fade((now-p.first_published)/1000/3600/24/180)) recent+rating @hot_projects.sort (a,b)-> note(b)-note(a) console.info "Sorting public projects took: #{Date.now()-time} ms" setProjectPublic:(project,pub)-> project.set("public",pub) if pub and project.first_published == 0 project.set "first_published",Date.now() if pub and not project.unlisted @hot_projects.push(project) if @hot_projects.indexOf(project) < 0 @top_projects.push(project) if @top_projects.indexOf(project) < 0 @new_projects.push(project) if @new_projects.indexOf(project) < 0 if project.type == "plugin" and @plugin_projects.indexOf(project) < 0 @plugin_projects.push project if project.type == "library" and @library_projects.indexOf(project) < 0 @library_projects.push project #@sortPublicProjects() else index = @hot_projects.indexOf(project) if index>=0 @hot_projects.splice index,1 index = @top_projects.indexOf(project) if index>=0 @top_projects.splice index,1 index = @new_projects.indexOf(project) if index>=0 @new_projects.splice index,1 index = @plugin_projects.indexOf(project) if index>=0 @plugin_projects.splice index,1 index = @library_projects.indexOf(project) if index>=0 @library_projects.splice index,1 setProjectType:(project,type)-> project.set("type",type) if project.public if project.type == "plugin" if @plugin_projects.indexOf(project) < 0 @plugin_projects.push project else index = @plugin_projects.indexOf(project) if index>=0 @plugin_projects.splice index,1 if project.type == "library" if @library_projects.indexOf(project) < 0 @library_projects.push project else index = @library_projects.indexOf(project) if index>=0 @library_projects.splice index,1 projectDeleted:(project)-> @project_count -= 1 index = @hot_projects.indexOf(project) if index>=0 @hot_projects.splice index,1 index = @top_projects.indexOf(project) if index>=0 @top_projects.splice index,1 index = @new_projects.indexOf(project) if index>=0 @new_projects.splice index,1 index = @plugin_projects.indexOf(project) if index>=0 @plugin_projects.splice index,1 index = @library_projects.indexOf(project) if index>=0 @library_projects.splice index,1 addProjectTag:(project,t)-> tag = @tags[t] if not tag? tag = new Tag(t) @tags[t] = tag @sorted_tags.push tag tag.add project removeProjectTag:(project,t)-> tag = @tags[t] if tag? tag.remove project setProjectTags:(project,tags)-> for t in project.tags if tags.indexOf(t)<0 @removeProjectTag(project,t) for t in tags if project.tags.indexOf(t)<0 @addProjectTag(project,t) project.set "tags",tags createUser:(data)-> record = @db.create "users",data @loadUser record createToken:(user)-> value = "" chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" for i in [0..31] by 1 value += chars.charAt(Math.floor(Math.random()*chars.length)) record = @db.create "tokens", value: value user: user.id date_created: Date.now() @loadToken record findUserByNick:(nick)-> @users_by_nick[nick] findUserByEmail:(email)-> @users_by_email[email] changeUserNick:(user,nick)-> delete @users_by_nick[user.nick] user.set "nick",nick @users_by_nick[nick] = user changeUserEmail:(user,email)-> if user.email? delete @users_by_email[user.email] else @guest_count -= 1 user.set "email",email @users_by_email[email] = user userDeleted:(user)-> delete @users_by_nick[user.nick] if user.email? delete @users_by_email[user.email] else @guest_count -= 1 @user_count -= 1 findToken:(token)-> @tokens[token] createProject:(owner,data,callback,empty=false)-> slug = data.slug if owner.findProjectBySlug(slug) count = 2 while owner.findProjectBySlug(slug+count)? count += 1 data.slug = slug+count d = title: data.title slug: data.slug tags: [] likes: [] public: data.public or false date_created: Date.now() last_modified: Date.now() deleted: false owner: owner.id orientation: data.orientation aspect: data.aspect type: data.type language: data.language graphics: data.graphics libs: data.libs tabs: data.tabs plugins: data.plugins libraries: data.libraries description: data.description or "" record = @db.create "projects",d project = @loadProject record if empty callback(project) else if project.language? and DEFAULT_CODE[project.language]? content = DEFAULT_CODE[project.language] else content = DEFAULT_CODE.microscript @files.write "#{owner.id}/#{project.id}/ms/main.ms",content,()=> @files.copyFile "../static/img/defaultappicon.png","#{owner.id}/#{project.id}/sprites/icon.png",()=> callback(project) getConsoleGameList:()-> list = [] for key,p of @projects if p.public and not p.deleted list.push author: p.owner.nick slug: p.slug title: p.title list sendValidationMail:(user)-> return if not user.email? token = user.getValidationToken() translator = @translator.getTranslator(user.language) subject = translator.get("Microstudio e-mail validation") text = translator.get("Thank you for using Microstudio!")+"\n\n" text += translator.get("Click on the link below to validate your e-mail address:")+"\n\n" text += "https://microstudio.dev/v/#{user.id}/#{token}"+"\n\n" @server.mailer.sendMail user.email,subject,text sendPasswordRecoveryMail:(user)-> return if not user.email? token = user.getValidationToken() translator = @translator.getTranslator(user.language) subject = translator.get("Reset your microStudio password") text = translator.get("Click on the link below to choose a new microStudio password:")+"\n\n" text += "https://microstudio.dev/pw/#{user.id}/#{token}"+"\n\n" @server.mailer.sendMail user.email,subject,text checkValidationToken:(user,token)-> token == user.getValidationToken() validateEMailAddress:(user,token)-> console.info "verifying #{token} against #{user.getValidationToken()}" if token? and token.length>0 and @checkValidationToken(user,token) user.resetValidationToken() user.setFlag("validated",true) translator = @translator.getTranslator(user.language) user.notify translator.get "Your e-mail address is now validated" DEFAULT_CODE = python: """ def init(): pass def update(): pass def draw(): pass """ javascript: """ init = function() { } update = function() { } draw = function() { } """ lua: """ init = function() end update = function() end draw = function() end """ microscript: """ init = function() end update = function() end draw = function() end """ module.exports = @Content
67841
usage = require "pidusage" User = require __dirname+"/user.js" Project = require __dirname+"/project.js" Tag = require __dirname+"/tag.js" Token = require __dirname+"/token.js" Translator = require __dirname+"/translator.js" Forum = require __dirname+"/../forum/forum.js" Cleaner = require __dirname+"/cleaner.js" class @Content constructor:(@server,@db,@files)-> @users = {} @users_by_email = {} @users_by_nick = {} @tokens = {} @projects = {} @tags = {} @sorted_tags = [] @project_count = 0 @user_count = 0 @guest_count = 0 @load() @hot_projects = [] @top_projects = [] @new_projects = [] @plugin_projects = [] @library_projects = [] @updatePublicProjects() console.info "Content loaded: #{@user_count} users and #{@project_count} projects" @top_interval = setInterval (()=> @sortPublicProjects()),10001 @log_interval = setInterval (()=> @statusLog()),6000 @translator = new Translator @ @forum = new Forum @ @cleaner = new Cleaner @ close:()-> clearInterval @top_interval clearInterval @log_interval @forum.close() @cleaner.stop() if @cleaner? statusLog:()-> usage process.pid,(err,result)=> return if not result? console.info "------------" console.info "#{new Date().toString()}" console.info "cpu: #{Math.round(result.cpu)}%" console.info "memory: #{Math.round(result.memory/1000000)} mb" console.info "users: #{@user_count}" console.info "projects: #{@project_count}" @current_cpu = Math.round(result.cpu) @current_memory = Math.round(result.memory/1000000) @server.stats.max("cpu_max",Math.round(result.cpu)) @server.stats.max("memory_max",@current_memory) load:()-> users = @db.list("users") for record in users @loadUser record if @server.config.standalone if @user_count>1 throw "Error, cannot run standalone if user_count>1" else if @user_count == 0 user = @createUser nick: "microstudio" email: "<EMAIL>" flags: {validated: true} hash: "---" date_created: Date.now() last_active: Date.now() creation_ip: "127.0.0.1" tokens = @db.list("tokens") for token in tokens @loadToken token projects = @db.list("projects") for record in projects @loadProject record @initLikes() return loadUser:(record)-> data = record.get() user = new User @,record return if user.flags.deleted @users[user.id] = user if user.email? @users_by_email[user.email] = user else @guest_count += 1 @users_by_nick[user.nick] = user @user_count++ user loadProject:(record)-> data = record.get() project = new Project @,record if project.owner? and not project.deleted @projects[project.id] = project @loadTags(project) @project_count++ project loadTags:(project)-> for t in project.tags tag = @tags[t] if not tag? tag = new Tag(t) @tags[t] = tag @sorted_tags.push tag tag.add project return loadToken:(record)-> data = record.get() token = new Token @,record if token.user? @tokens[token.value] = token token initLikes:()-> for key,user of @users for f in user.likes if @projects[f]? @projects[f].likes++ return updatePublicProjects:()-> @hot_projects = [] @top_projects = [] @new_projects = [] @plugin_projects = [] @library_projects = [] for key,project of @projects if project.public and not project.unlisted and project.owner.flags["validated"] and not project.deleted and not project.owner.flags["censored"] @hot_projects.push project @top_projects.push project @new_projects.push project if project.type == "plugin" @plugin_projects.push project if project.type == "library" @library_projects.push project @sortPublicProjects() sortPublicProjects:()-> time = Date.now() @top_projects.sort (a,b)-> b.likes-a.likes @new_projects.sort (a,b)-> b.first_published-a.first_published @sorted_tags.sort (a,b)-> b.uses+b.num_users*10-a.uses-a.num_users*10 @plugin_projects.sort (a,b)-> b.likes-a.likes @library_projects.sort (a,b)-> b.likes-a.likes return if @top_projects.length<5 now = Date.now() maxLikes = Math.max(1,@top_projects[4].likes) fade = (x)-> 1-Math.max(0,Math.min(1,x)) note = (p)-> recent = fade (now-p.first_published)/1000/3600/24/4 rating = p.likes/maxLikes*(.15+2*fade((now-p.first_published)/1000/3600/24/180)) recent+rating @hot_projects.sort (a,b)-> note(b)-note(a) console.info "Sorting public projects took: #{Date.now()-time} ms" setProjectPublic:(project,pub)-> project.set("public",pub) if pub and project.first_published == 0 project.set "first_published",Date.now() if pub and not project.unlisted @hot_projects.push(project) if @hot_projects.indexOf(project) < 0 @top_projects.push(project) if @top_projects.indexOf(project) < 0 @new_projects.push(project) if @new_projects.indexOf(project) < 0 if project.type == "plugin" and @plugin_projects.indexOf(project) < 0 @plugin_projects.push project if project.type == "library" and @library_projects.indexOf(project) < 0 @library_projects.push project #@sortPublicProjects() else index = @hot_projects.indexOf(project) if index>=0 @hot_projects.splice index,1 index = @top_projects.indexOf(project) if index>=0 @top_projects.splice index,1 index = @new_projects.indexOf(project) if index>=0 @new_projects.splice index,1 index = @plugin_projects.indexOf(project) if index>=0 @plugin_projects.splice index,1 index = @library_projects.indexOf(project) if index>=0 @library_projects.splice index,1 setProjectType:(project,type)-> project.set("type",type) if project.public if project.type == "plugin" if @plugin_projects.indexOf(project) < 0 @plugin_projects.push project else index = @plugin_projects.indexOf(project) if index>=0 @plugin_projects.splice index,1 if project.type == "library" if @library_projects.indexOf(project) < 0 @library_projects.push project else index = @library_projects.indexOf(project) if index>=0 @library_projects.splice index,1 projectDeleted:(project)-> @project_count -= 1 index = @hot_projects.indexOf(project) if index>=0 @hot_projects.splice index,1 index = @top_projects.indexOf(project) if index>=0 @top_projects.splice index,1 index = @new_projects.indexOf(project) if index>=0 @new_projects.splice index,1 index = @plugin_projects.indexOf(project) if index>=0 @plugin_projects.splice index,1 index = @library_projects.indexOf(project) if index>=0 @library_projects.splice index,1 addProjectTag:(project,t)-> tag = @tags[t] if not tag? tag = new Tag(t) @tags[t] = tag @sorted_tags.push tag tag.add project removeProjectTag:(project,t)-> tag = @tags[t] if tag? tag.remove project setProjectTags:(project,tags)-> for t in project.tags if tags.indexOf(t)<0 @removeProjectTag(project,t) for t in tags if project.tags.indexOf(t)<0 @addProjectTag(project,t) project.set "tags",tags createUser:(data)-> record = @db.create "users",data @loadUser record createToken:(user)-> value = "" chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrst<KEY>" for i in [0..31] by 1 value += chars.charAt(Math.floor(Math.random()*chars.length)) record = @db.create "tokens", value: value user: user.id date_created: Date.now() @loadToken record findUserByNick:(nick)-> @users_by_nick[nick] findUserByEmail:(email)-> @users_by_email[email] changeUserNick:(user,nick)-> delete @users_by_nick[user.nick] user.set "nick",nick @users_by_nick[nick] = user changeUserEmail:(user,email)-> if user.email? delete @users_by_email[user.email] else @guest_count -= 1 user.set "email",email @users_by_email[email] = user userDeleted:(user)-> delete @users_by_nick[user.nick] if user.email? delete @users_by_email[user.email] else @guest_count -= 1 @user_count -= 1 findToken:(token)-> @tokens[token] createProject:(owner,data,callback,empty=false)-> slug = data.slug if owner.findProjectBySlug(slug) count = 2 while owner.findProjectBySlug(slug+count)? count += 1 data.slug = slug+count d = title: data.title slug: data.slug tags: [] likes: [] public: data.public or false date_created: Date.now() last_modified: Date.now() deleted: false owner: owner.id orientation: data.orientation aspect: data.aspect type: data.type language: data.language graphics: data.graphics libs: data.libs tabs: data.tabs plugins: data.plugins libraries: data.libraries description: data.description or "" record = @db.create "projects",d project = @loadProject record if empty callback(project) else if project.language? and DEFAULT_CODE[project.language]? content = DEFAULT_CODE[project.language] else content = DEFAULT_CODE.microscript @files.write "#{owner.id}/#{project.id}/ms/main.ms",content,()=> @files.copyFile "../static/img/defaultappicon.png","#{owner.id}/#{project.id}/sprites/icon.png",()=> callback(project) getConsoleGameList:()-> list = [] for key,p of @projects if p.public and not p.deleted list.push author: p.owner.nick slug: p.slug title: p.title list sendValidationMail:(user)-> return if not user.email? token = user.getValidationToken() translator = @translator.getTranslator(user.language) subject = translator.get("Microstudio e-mail validation") text = translator.get("Thank you for using Microstudio!")+"\n\n" text += translator.get("Click on the link below to validate your e-mail address:")+"\n\n" text += "https://microstudio.dev/v/#{user.id}/#{token}"+"\n\n" @server.mailer.sendMail user.email,subject,text sendPasswordRecoveryMail:(user)-> return if not user.email? token = user.getValidationToken() translator = @translator.getTranslator(user.language) subject = translator.get("Reset your microStudio password") text = translator.get("Click on the link below to choose a new microStudio password:")+"\n\n" text += "https://microstudio.dev/pw/#{user.id}/#{token}"+"\n\n" @server.mailer.sendMail user.email,subject,text checkValidationToken:(user,token)-> token == user.getValidationToken() validateEMailAddress:(user,token)-> console.info "verifying #{token} against #{user.getValidationToken()}" if token? and token.length>0 and @checkValidationToken(user,token) user.resetValidationToken() user.setFlag("validated",true) translator = @translator.getTranslator(user.language) user.notify translator.get "Your e-mail address is now validated" DEFAULT_CODE = python: """ def init(): pass def update(): pass def draw(): pass """ javascript: """ init = function() { } update = function() { } draw = function() { } """ lua: """ init = function() end update = function() end draw = function() end """ microscript: """ init = function() end update = function() end draw = function() end """ module.exports = @Content
true
usage = require "pidusage" User = require __dirname+"/user.js" Project = require __dirname+"/project.js" Tag = require __dirname+"/tag.js" Token = require __dirname+"/token.js" Translator = require __dirname+"/translator.js" Forum = require __dirname+"/../forum/forum.js" Cleaner = require __dirname+"/cleaner.js" class @Content constructor:(@server,@db,@files)-> @users = {} @users_by_email = {} @users_by_nick = {} @tokens = {} @projects = {} @tags = {} @sorted_tags = [] @project_count = 0 @user_count = 0 @guest_count = 0 @load() @hot_projects = [] @top_projects = [] @new_projects = [] @plugin_projects = [] @library_projects = [] @updatePublicProjects() console.info "Content loaded: #{@user_count} users and #{@project_count} projects" @top_interval = setInterval (()=> @sortPublicProjects()),10001 @log_interval = setInterval (()=> @statusLog()),6000 @translator = new Translator @ @forum = new Forum @ @cleaner = new Cleaner @ close:()-> clearInterval @top_interval clearInterval @log_interval @forum.close() @cleaner.stop() if @cleaner? statusLog:()-> usage process.pid,(err,result)=> return if not result? console.info "------------" console.info "#{new Date().toString()}" console.info "cpu: #{Math.round(result.cpu)}%" console.info "memory: #{Math.round(result.memory/1000000)} mb" console.info "users: #{@user_count}" console.info "projects: #{@project_count}" @current_cpu = Math.round(result.cpu) @current_memory = Math.round(result.memory/1000000) @server.stats.max("cpu_max",Math.round(result.cpu)) @server.stats.max("memory_max",@current_memory) load:()-> users = @db.list("users") for record in users @loadUser record if @server.config.standalone if @user_count>1 throw "Error, cannot run standalone if user_count>1" else if @user_count == 0 user = @createUser nick: "microstudio" email: "PI:EMAIL:<EMAIL>END_PI" flags: {validated: true} hash: "---" date_created: Date.now() last_active: Date.now() creation_ip: "127.0.0.1" tokens = @db.list("tokens") for token in tokens @loadToken token projects = @db.list("projects") for record in projects @loadProject record @initLikes() return loadUser:(record)-> data = record.get() user = new User @,record return if user.flags.deleted @users[user.id] = user if user.email? @users_by_email[user.email] = user else @guest_count += 1 @users_by_nick[user.nick] = user @user_count++ user loadProject:(record)-> data = record.get() project = new Project @,record if project.owner? and not project.deleted @projects[project.id] = project @loadTags(project) @project_count++ project loadTags:(project)-> for t in project.tags tag = @tags[t] if not tag? tag = new Tag(t) @tags[t] = tag @sorted_tags.push tag tag.add project return loadToken:(record)-> data = record.get() token = new Token @,record if token.user? @tokens[token.value] = token token initLikes:()-> for key,user of @users for f in user.likes if @projects[f]? @projects[f].likes++ return updatePublicProjects:()-> @hot_projects = [] @top_projects = [] @new_projects = [] @plugin_projects = [] @library_projects = [] for key,project of @projects if project.public and not project.unlisted and project.owner.flags["validated"] and not project.deleted and not project.owner.flags["censored"] @hot_projects.push project @top_projects.push project @new_projects.push project if project.type == "plugin" @plugin_projects.push project if project.type == "library" @library_projects.push project @sortPublicProjects() sortPublicProjects:()-> time = Date.now() @top_projects.sort (a,b)-> b.likes-a.likes @new_projects.sort (a,b)-> b.first_published-a.first_published @sorted_tags.sort (a,b)-> b.uses+b.num_users*10-a.uses-a.num_users*10 @plugin_projects.sort (a,b)-> b.likes-a.likes @library_projects.sort (a,b)-> b.likes-a.likes return if @top_projects.length<5 now = Date.now() maxLikes = Math.max(1,@top_projects[4].likes) fade = (x)-> 1-Math.max(0,Math.min(1,x)) note = (p)-> recent = fade (now-p.first_published)/1000/3600/24/4 rating = p.likes/maxLikes*(.15+2*fade((now-p.first_published)/1000/3600/24/180)) recent+rating @hot_projects.sort (a,b)-> note(b)-note(a) console.info "Sorting public projects took: #{Date.now()-time} ms" setProjectPublic:(project,pub)-> project.set("public",pub) if pub and project.first_published == 0 project.set "first_published",Date.now() if pub and not project.unlisted @hot_projects.push(project) if @hot_projects.indexOf(project) < 0 @top_projects.push(project) if @top_projects.indexOf(project) < 0 @new_projects.push(project) if @new_projects.indexOf(project) < 0 if project.type == "plugin" and @plugin_projects.indexOf(project) < 0 @plugin_projects.push project if project.type == "library" and @library_projects.indexOf(project) < 0 @library_projects.push project #@sortPublicProjects() else index = @hot_projects.indexOf(project) if index>=0 @hot_projects.splice index,1 index = @top_projects.indexOf(project) if index>=0 @top_projects.splice index,1 index = @new_projects.indexOf(project) if index>=0 @new_projects.splice index,1 index = @plugin_projects.indexOf(project) if index>=0 @plugin_projects.splice index,1 index = @library_projects.indexOf(project) if index>=0 @library_projects.splice index,1 setProjectType:(project,type)-> project.set("type",type) if project.public if project.type == "plugin" if @plugin_projects.indexOf(project) < 0 @plugin_projects.push project else index = @plugin_projects.indexOf(project) if index>=0 @plugin_projects.splice index,1 if project.type == "library" if @library_projects.indexOf(project) < 0 @library_projects.push project else index = @library_projects.indexOf(project) if index>=0 @library_projects.splice index,1 projectDeleted:(project)-> @project_count -= 1 index = @hot_projects.indexOf(project) if index>=0 @hot_projects.splice index,1 index = @top_projects.indexOf(project) if index>=0 @top_projects.splice index,1 index = @new_projects.indexOf(project) if index>=0 @new_projects.splice index,1 index = @plugin_projects.indexOf(project) if index>=0 @plugin_projects.splice index,1 index = @library_projects.indexOf(project) if index>=0 @library_projects.splice index,1 addProjectTag:(project,t)-> tag = @tags[t] if not tag? tag = new Tag(t) @tags[t] = tag @sorted_tags.push tag tag.add project removeProjectTag:(project,t)-> tag = @tags[t] if tag? tag.remove project setProjectTags:(project,tags)-> for t in project.tags if tags.indexOf(t)<0 @removeProjectTag(project,t) for t in tags if project.tags.indexOf(t)<0 @addProjectTag(project,t) project.set "tags",tags createUser:(data)-> record = @db.create "users",data @loadUser record createToken:(user)-> value = "" chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstPI:KEY:<KEY>END_PI" for i in [0..31] by 1 value += chars.charAt(Math.floor(Math.random()*chars.length)) record = @db.create "tokens", value: value user: user.id date_created: Date.now() @loadToken record findUserByNick:(nick)-> @users_by_nick[nick] findUserByEmail:(email)-> @users_by_email[email] changeUserNick:(user,nick)-> delete @users_by_nick[user.nick] user.set "nick",nick @users_by_nick[nick] = user changeUserEmail:(user,email)-> if user.email? delete @users_by_email[user.email] else @guest_count -= 1 user.set "email",email @users_by_email[email] = user userDeleted:(user)-> delete @users_by_nick[user.nick] if user.email? delete @users_by_email[user.email] else @guest_count -= 1 @user_count -= 1 findToken:(token)-> @tokens[token] createProject:(owner,data,callback,empty=false)-> slug = data.slug if owner.findProjectBySlug(slug) count = 2 while owner.findProjectBySlug(slug+count)? count += 1 data.slug = slug+count d = title: data.title slug: data.slug tags: [] likes: [] public: data.public or false date_created: Date.now() last_modified: Date.now() deleted: false owner: owner.id orientation: data.orientation aspect: data.aspect type: data.type language: data.language graphics: data.graphics libs: data.libs tabs: data.tabs plugins: data.plugins libraries: data.libraries description: data.description or "" record = @db.create "projects",d project = @loadProject record if empty callback(project) else if project.language? and DEFAULT_CODE[project.language]? content = DEFAULT_CODE[project.language] else content = DEFAULT_CODE.microscript @files.write "#{owner.id}/#{project.id}/ms/main.ms",content,()=> @files.copyFile "../static/img/defaultappicon.png","#{owner.id}/#{project.id}/sprites/icon.png",()=> callback(project) getConsoleGameList:()-> list = [] for key,p of @projects if p.public and not p.deleted list.push author: p.owner.nick slug: p.slug title: p.title list sendValidationMail:(user)-> return if not user.email? token = user.getValidationToken() translator = @translator.getTranslator(user.language) subject = translator.get("Microstudio e-mail validation") text = translator.get("Thank you for using Microstudio!")+"\n\n" text += translator.get("Click on the link below to validate your e-mail address:")+"\n\n" text += "https://microstudio.dev/v/#{user.id}/#{token}"+"\n\n" @server.mailer.sendMail user.email,subject,text sendPasswordRecoveryMail:(user)-> return if not user.email? token = user.getValidationToken() translator = @translator.getTranslator(user.language) subject = translator.get("Reset your microStudio password") text = translator.get("Click on the link below to choose a new microStudio password:")+"\n\n" text += "https://microstudio.dev/pw/#{user.id}/#{token}"+"\n\n" @server.mailer.sendMail user.email,subject,text checkValidationToken:(user,token)-> token == user.getValidationToken() validateEMailAddress:(user,token)-> console.info "verifying #{token} against #{user.getValidationToken()}" if token? and token.length>0 and @checkValidationToken(user,token) user.resetValidationToken() user.setFlag("validated",true) translator = @translator.getTranslator(user.language) user.notify translator.get "Your e-mail address is now validated" DEFAULT_CODE = python: """ def init(): pass def update(): pass def draw(): pass """ javascript: """ init = function() { } update = function() { } draw = function() { } """ lua: """ init = function() end update = function() end draw = function() end """ microscript: """ init = function() end update = function() end draw = function() end """ module.exports = @Content
[ { "context": "dy.Inputs.Static\n model: model\n key: @id\n formatter: this\n\n # Create an input th", "end": 730, "score": 0.9537540674209595, "start": 727, "tag": "KEY", "value": "@id" } ]
app/vendor/kalnoy/cruddy/resources/assets/coffee/fields/base.coffee
EH7AN/lawyers
0
class Cruddy.Fields.Base extends Cruddy.Attribute viewConstructor: Cruddy.Fields.InputView # Create a view that will represent this field in field list createView: (model, forceDisable = no, parent) -> new @viewConstructor { model: model, field: this, forceDisable: forceDisable }, parent # Create an input that is used by default view createInput: (model, inputId, forceDisable = no) -> input = @createEditableInput model, inputId if not forceDisable and @isEditable(model) input or @createStaticInput(model) # Create an input that will display a static value without possibility to edit createStaticInput: (model) -> new Cruddy.Inputs.Static model: model key: @id formatter: this # Create an input that is used when field is editable createEditableInput: (model, inputId) -> null # Create filter input that createFilterInput: (model) -> null # Get a label for filter input getFilterLabel: -> @attributes.label # Format value as static text format: (value) -> value or NOT_AVAILABLE # Get field's label getLabel: -> @attributes.label # Get whether the field is editable for specified model isEditable: (model) -> model.canBeSaved() and @attributes.disabled isnt yes and @attributes.disabled isnt model.action() # Get whether field is required isRequired: (model) -> @attributes.required is yes or @attributes.required == model.action() # Get whether the field is unique isUnique: -> @attributes.unique hasChangedSinceSync: (model) -> not @valuesEqual model.get(@id), model.getOriginal(@id) valuesEqual: (a, b) -> a is b isCopyable: -> not @isUnique() copyAttribute: (model, copy) -> model.get @id parse: (model, value) -> value prepareAttribute: (value) -> value prepareFilterData: (value) -> @prepareAttribute value parseFilterData: (value) -> value
1063
class Cruddy.Fields.Base extends Cruddy.Attribute viewConstructor: Cruddy.Fields.InputView # Create a view that will represent this field in field list createView: (model, forceDisable = no, parent) -> new @viewConstructor { model: model, field: this, forceDisable: forceDisable }, parent # Create an input that is used by default view createInput: (model, inputId, forceDisable = no) -> input = @createEditableInput model, inputId if not forceDisable and @isEditable(model) input or @createStaticInput(model) # Create an input that will display a static value without possibility to edit createStaticInput: (model) -> new Cruddy.Inputs.Static model: model key: <KEY> formatter: this # Create an input that is used when field is editable createEditableInput: (model, inputId) -> null # Create filter input that createFilterInput: (model) -> null # Get a label for filter input getFilterLabel: -> @attributes.label # Format value as static text format: (value) -> value or NOT_AVAILABLE # Get field's label getLabel: -> @attributes.label # Get whether the field is editable for specified model isEditable: (model) -> model.canBeSaved() and @attributes.disabled isnt yes and @attributes.disabled isnt model.action() # Get whether field is required isRequired: (model) -> @attributes.required is yes or @attributes.required == model.action() # Get whether the field is unique isUnique: -> @attributes.unique hasChangedSinceSync: (model) -> not @valuesEqual model.get(@id), model.getOriginal(@id) valuesEqual: (a, b) -> a is b isCopyable: -> not @isUnique() copyAttribute: (model, copy) -> model.get @id parse: (model, value) -> value prepareAttribute: (value) -> value prepareFilterData: (value) -> @prepareAttribute value parseFilterData: (value) -> value
true
class Cruddy.Fields.Base extends Cruddy.Attribute viewConstructor: Cruddy.Fields.InputView # Create a view that will represent this field in field list createView: (model, forceDisable = no, parent) -> new @viewConstructor { model: model, field: this, forceDisable: forceDisable }, parent # Create an input that is used by default view createInput: (model, inputId, forceDisable = no) -> input = @createEditableInput model, inputId if not forceDisable and @isEditable(model) input or @createStaticInput(model) # Create an input that will display a static value without possibility to edit createStaticInput: (model) -> new Cruddy.Inputs.Static model: model key: PI:KEY:<KEY>END_PI formatter: this # Create an input that is used when field is editable createEditableInput: (model, inputId) -> null # Create filter input that createFilterInput: (model) -> null # Get a label for filter input getFilterLabel: -> @attributes.label # Format value as static text format: (value) -> value or NOT_AVAILABLE # Get field's label getLabel: -> @attributes.label # Get whether the field is editable for specified model isEditable: (model) -> model.canBeSaved() and @attributes.disabled isnt yes and @attributes.disabled isnt model.action() # Get whether field is required isRequired: (model) -> @attributes.required is yes or @attributes.required == model.action() # Get whether the field is unique isUnique: -> @attributes.unique hasChangedSinceSync: (model) -> not @valuesEqual model.get(@id), model.getOriginal(@id) valuesEqual: (a, b) -> a is b isCopyable: -> not @isUnique() copyAttribute: (model, copy) -> model.get @id parse: (model, value) -> value prepareAttribute: (value) -> value prepareFilterData: (value) -> @prepareAttribute value parseFilterData: (value) -> value
[ { "context": "/api/public/v1.0/lists/movies/opening.json?apikey=k5xhfmsbbapb8pjj5bpfwvh4&limit=3\"\n dataType: \"jsonp\"\n success: print", "end": 1126, "score": 0.9993665218353271, "start": 1102, "tag": "KEY", "value": "k5xhfmsbbapb8pjj5bpfwvh4" }, { "context": "i/public/v1.0/...
coffee/main.coffee
mattwhitesides/LateTitleCard
0
# send off the query printJsonOpening = (data) -> movies = data.movies $.each movies, (index, movie) -> $("#jsonHolderOpening tbody").append "<tr class='child'><td><img src=\"" + movie.posters.thumbnail + "\" /></td>" + "<td><h4>" + movie.title + "</h4></td><td>" + movie.release_dates.theater + "</td></tr>" return return printJsonTop = (data) -> movies = data.movies $.each movies, (index, movie) -> $("#jsonHolderTop tbody").append "<tr class='child'><td><img src=\"" + movie.posters.thumbnail + "\" /></td>" + "<td><h4>" + movie.title + "</h4></td><td>" + movie.release_dates.theater + "</td></tr>" return return printJsonUpcomming = (data) -> movies = data.movies.slice(0,3) $.each movies, (index, movie) -> $("#jsonHolderUpcomming tbody").append "<tr class='child'><td><img src=\"" + movie.posters.thumbnail + "\" /></td>" + "<td><h4>" + movie.title + "</h4></td><td>" + movie.release_dates.theater + "</td></tr>" return return $(document).ready -> $.ajax url: "http://api.rottentomatoes.com/api/public/v1.0/lists/movies/opening.json?apikey=k5xhfmsbbapb8pjj5bpfwvh4&limit=3" dataType: "jsonp" success: printJsonOpening $.ajax url: "http://api.rottentomatoes.com/api/public/v1.0/lists/movies/box_office.json?apikey=k5xhfmsbbapb8pjj5bpfwvh4&limit=3" dataType: "jsonp" success: printJsonTop $.ajax url: "http://api.rottentomatoes.com/api/public/v1.0/lists/movies/upcoming.json?apikey=k5xhfmsbbapb8pjj5bpfwvh4&limit=3" dataType: "jsonp" success: printJsonUpcomming return # detect touch # background fix # fix vertical when not overflow #call fullscreenFix() if .fullscreen content changes fullscreenFix = -> h = $("body").height() # set .fullscreen height $(".content-b").each (i) -> $(this).closest(".fullscreen").addClass "not-overflow" if $(this).innerHeight() <= h return return # resize background images backgroundResize = -> windowH = $(window).height() $(".background").each (i) -> path = $(this) # variables contW = path.width() contH = path.height() imgW = path.attr("data-img-width") imgH = path.attr("data-img-height") ratio = imgW / imgH # overflowing difference diff = parseFloat(path.attr("data-diff")) diff = (if diff then diff else 0) # remaining height to have fullscreen image only on parallax remainingH = 0 if path.hasClass("parallax") and not $("html").hasClass("touch") maxH = (if contH > windowH then contH else windowH) remainingH = windowH - contH # set img values depending on cont imgH = contH + remainingH + diff imgW = imgH * ratio # fix when too large if contW > imgW imgW = contW imgH = imgW / ratio # path.data "resized-imgW", imgW path.data "resized-imgH", imgH path.css "background-size", imgW + "px " + imgH + "px" return return # set parallax background-position parallaxPosition = (e) -> heightWindow = $(window).height() topWindow = $(window).scrollTop() bottomWindow = topWindow + heightWindow currentWindow = (topWindow + bottomWindow) / 2 $(".parallax").each (i) -> path = $(this) height = path.height() top = path.offset().top bottom = top + height # only when in range if bottomWindow > top and topWindow < bottom imgW = path.data("resized-imgW") imgH = path.data("resized-imgH") # min when image touch top of window min = 0 # max when image touch bottom of window max = -imgH + heightWindow # overflow changes parallax overflowH = (if height < heightWindow then imgH - height else imgH - heightWindow) # fix height on overflow top = top - overflowH bottom = bottom + overflowH # value with linear interpolation value = min + (max - min) * (currentWindow - top) / (bottom - top) # set background-position orizontalPosition = path.attr("data-oriz-pos") orizontalPosition = (if orizontalPosition then orizontalPosition else "50%") $(this).css "background-position", orizontalPosition + " " + value + "px" return return document.documentElement.className = document.documentElement.className + " touch" if "ontouchstart" of window $(".parallax").css "background-attachment", "fixed" unless $("html").hasClass("touch") $(window).resize fullscreenFix fullscreenFix() $(window).resize backgroundResize $(window).focus backgroundResize backgroundResize() unless $("html").hasClass("touch") $(window).resize parallaxPosition #$(window).focus(parallaxPosition); $(window).scroll parallaxPosition parallaxPosition()
87270
# send off the query printJsonOpening = (data) -> movies = data.movies $.each movies, (index, movie) -> $("#jsonHolderOpening tbody").append "<tr class='child'><td><img src=\"" + movie.posters.thumbnail + "\" /></td>" + "<td><h4>" + movie.title + "</h4></td><td>" + movie.release_dates.theater + "</td></tr>" return return printJsonTop = (data) -> movies = data.movies $.each movies, (index, movie) -> $("#jsonHolderTop tbody").append "<tr class='child'><td><img src=\"" + movie.posters.thumbnail + "\" /></td>" + "<td><h4>" + movie.title + "</h4></td><td>" + movie.release_dates.theater + "</td></tr>" return return printJsonUpcomming = (data) -> movies = data.movies.slice(0,3) $.each movies, (index, movie) -> $("#jsonHolderUpcomming tbody").append "<tr class='child'><td><img src=\"" + movie.posters.thumbnail + "\" /></td>" + "<td><h4>" + movie.title + "</h4></td><td>" + movie.release_dates.theater + "</td></tr>" return return $(document).ready -> $.ajax url: "http://api.rottentomatoes.com/api/public/v1.0/lists/movies/opening.json?apikey=<KEY>&limit=3" dataType: "jsonp" success: printJsonOpening $.ajax url: "http://api.rottentomatoes.com/api/public/v1.0/lists/movies/box_office.json?apikey=<KEY>&limit=3" dataType: "jsonp" success: printJsonTop $.ajax url: "http://api.rottentomatoes.com/api/public/v1.0/lists/movies/upcoming.json?apikey=<KEY>jj5bpfwvh4&limit=3" dataType: "jsonp" success: printJsonUpcomming return # detect touch # background fix # fix vertical when not overflow #call fullscreenFix() if .fullscreen content changes fullscreenFix = -> h = $("body").height() # set .fullscreen height $(".content-b").each (i) -> $(this).closest(".fullscreen").addClass "not-overflow" if $(this).innerHeight() <= h return return # resize background images backgroundResize = -> windowH = $(window).height() $(".background").each (i) -> path = $(this) # variables contW = path.width() contH = path.height() imgW = path.attr("data-img-width") imgH = path.attr("data-img-height") ratio = imgW / imgH # overflowing difference diff = parseFloat(path.attr("data-diff")) diff = (if diff then diff else 0) # remaining height to have fullscreen image only on parallax remainingH = 0 if path.hasClass("parallax") and not $("html").hasClass("touch") maxH = (if contH > windowH then contH else windowH) remainingH = windowH - contH # set img values depending on cont imgH = contH + remainingH + diff imgW = imgH * ratio # fix when too large if contW > imgW imgW = contW imgH = imgW / ratio # path.data "resized-imgW", imgW path.data "resized-imgH", imgH path.css "background-size", imgW + "px " + imgH + "px" return return # set parallax background-position parallaxPosition = (e) -> heightWindow = $(window).height() topWindow = $(window).scrollTop() bottomWindow = topWindow + heightWindow currentWindow = (topWindow + bottomWindow) / 2 $(".parallax").each (i) -> path = $(this) height = path.height() top = path.offset().top bottom = top + height # only when in range if bottomWindow > top and topWindow < bottom imgW = path.data("resized-imgW") imgH = path.data("resized-imgH") # min when image touch top of window min = 0 # max when image touch bottom of window max = -imgH + heightWindow # overflow changes parallax overflowH = (if height < heightWindow then imgH - height else imgH - heightWindow) # fix height on overflow top = top - overflowH bottom = bottom + overflowH # value with linear interpolation value = min + (max - min) * (currentWindow - top) / (bottom - top) # set background-position orizontalPosition = path.attr("data-oriz-pos") orizontalPosition = (if orizontalPosition then orizontalPosition else "50%") $(this).css "background-position", orizontalPosition + " " + value + "px" return return document.documentElement.className = document.documentElement.className + " touch" if "ontouchstart" of window $(".parallax").css "background-attachment", "fixed" unless $("html").hasClass("touch") $(window).resize fullscreenFix fullscreenFix() $(window).resize backgroundResize $(window).focus backgroundResize backgroundResize() unless $("html").hasClass("touch") $(window).resize parallaxPosition #$(window).focus(parallaxPosition); $(window).scroll parallaxPosition parallaxPosition()
true
# send off the query printJsonOpening = (data) -> movies = data.movies $.each movies, (index, movie) -> $("#jsonHolderOpening tbody").append "<tr class='child'><td><img src=\"" + movie.posters.thumbnail + "\" /></td>" + "<td><h4>" + movie.title + "</h4></td><td>" + movie.release_dates.theater + "</td></tr>" return return printJsonTop = (data) -> movies = data.movies $.each movies, (index, movie) -> $("#jsonHolderTop tbody").append "<tr class='child'><td><img src=\"" + movie.posters.thumbnail + "\" /></td>" + "<td><h4>" + movie.title + "</h4></td><td>" + movie.release_dates.theater + "</td></tr>" return return printJsonUpcomming = (data) -> movies = data.movies.slice(0,3) $.each movies, (index, movie) -> $("#jsonHolderUpcomming tbody").append "<tr class='child'><td><img src=\"" + movie.posters.thumbnail + "\" /></td>" + "<td><h4>" + movie.title + "</h4></td><td>" + movie.release_dates.theater + "</td></tr>" return return $(document).ready -> $.ajax url: "http://api.rottentomatoes.com/api/public/v1.0/lists/movies/opening.json?apikey=PI:KEY:<KEY>END_PI&limit=3" dataType: "jsonp" success: printJsonOpening $.ajax url: "http://api.rottentomatoes.com/api/public/v1.0/lists/movies/box_office.json?apikey=PI:KEY:<KEY>END_PI&limit=3" dataType: "jsonp" success: printJsonTop $.ajax url: "http://api.rottentomatoes.com/api/public/v1.0/lists/movies/upcoming.json?apikey=PI:KEY:<KEY>END_PIjj5bpfwvh4&limit=3" dataType: "jsonp" success: printJsonUpcomming return # detect touch # background fix # fix vertical when not overflow #call fullscreenFix() if .fullscreen content changes fullscreenFix = -> h = $("body").height() # set .fullscreen height $(".content-b").each (i) -> $(this).closest(".fullscreen").addClass "not-overflow" if $(this).innerHeight() <= h return return # resize background images backgroundResize = -> windowH = $(window).height() $(".background").each (i) -> path = $(this) # variables contW = path.width() contH = path.height() imgW = path.attr("data-img-width") imgH = path.attr("data-img-height") ratio = imgW / imgH # overflowing difference diff = parseFloat(path.attr("data-diff")) diff = (if diff then diff else 0) # remaining height to have fullscreen image only on parallax remainingH = 0 if path.hasClass("parallax") and not $("html").hasClass("touch") maxH = (if contH > windowH then contH else windowH) remainingH = windowH - contH # set img values depending on cont imgH = contH + remainingH + diff imgW = imgH * ratio # fix when too large if contW > imgW imgW = contW imgH = imgW / ratio # path.data "resized-imgW", imgW path.data "resized-imgH", imgH path.css "background-size", imgW + "px " + imgH + "px" return return # set parallax background-position parallaxPosition = (e) -> heightWindow = $(window).height() topWindow = $(window).scrollTop() bottomWindow = topWindow + heightWindow currentWindow = (topWindow + bottomWindow) / 2 $(".parallax").each (i) -> path = $(this) height = path.height() top = path.offset().top bottom = top + height # only when in range if bottomWindow > top and topWindow < bottom imgW = path.data("resized-imgW") imgH = path.data("resized-imgH") # min when image touch top of window min = 0 # max when image touch bottom of window max = -imgH + heightWindow # overflow changes parallax overflowH = (if height < heightWindow then imgH - height else imgH - heightWindow) # fix height on overflow top = top - overflowH bottom = bottom + overflowH # value with linear interpolation value = min + (max - min) * (currentWindow - top) / (bottom - top) # set background-position orizontalPosition = path.attr("data-oriz-pos") orizontalPosition = (if orizontalPosition then orizontalPosition else "50%") $(this).css "background-position", orizontalPosition + " " + value + "px" return return document.documentElement.className = document.documentElement.className + " touch" if "ontouchstart" of window $(".parallax").css "background-attachment", "fixed" unless $("html").hasClass("touch") $(window).resize fullscreenFix fullscreenFix() $(window).resize backgroundResize $(window).focus backgroundResize backgroundResize() unless $("html").hasClass("touch") $(window).resize parallaxPosition #$(window).focus(parallaxPosition); $(window).scroll parallaxPosition parallaxPosition()
[ { "context": "common.assertPilotIs(test, '#empire-builder', 3, 'Soontir Fel')\n common.assertUpgradeInSlot(test, '#empire-b", "end": 5192, "score": 0.8114113807678223, "start": 5181, "tag": "NAME", "value": "Soontir Fel" } ]
tests/test_translation_es.coffee
CrazyVulcan/xwing
100
common = require './common' common.setup() casper.test.begin "Spanish translations: Rebel", (test) -> common.waitForStartup('#rebel-builder') common.selectLanguage('Español') common.createList('#rebel-builder', [ { ship: 'Ala-X' pilot: "Piloto Novato" upgrades: [ "Torpedos de Protones" "Droide Astromecánico R2" "Escudos Mejorados" ] } { ship: 'Ala-X' pilot: "Luke Skywalker" upgrades: [ "Puntería" null "R2-D2" null ] } { ship: 'YT-1300' pilot: "Chewbacca" upgrades: [ "Atraer su fuego" "Misiles de Asalto" "Agente del Servicio de Inteligencia" "Especialista en Reconocimiento" "Halcón Milenario" "Motor Mejorado" ] } { ship: 'Ala-A' pilot: 'Piloto de Pruebas' upgrades: [ 'Reequipado en Chardaan' ] } ]) common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex(3, 3)}", 'Luke Skywalker') common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex(3, 4)}", 'Luke Skywalker') common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex(3, 3)}", 'R2-D2 (Tripulante)') common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex(3, 4)}", 'R2-D2 (Tripulante)') common.assertTotalPoints(test, '#rebel-builder', 137) common.selectLanguage('English') common.assertShipTypeIs(test, '#rebel-builder', 1, 'X-Wing') common.assertPilotIs(test, '#rebel-builder', 1, 'Rookie Pilot') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 1, 'Proton Torpedoes') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 2, 'R2 Astromech') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 3, 'Shield Upgrade') common.assertShipTypeIs(test, '#rebel-builder', 2, 'X-Wing') common.assertPilotIs(test, '#rebel-builder', 2, 'Luke Skywalker') common.assertUpgradeInSlot(test, '#rebel-builder', 2, 1, 'Marksmanship') common.assertNoUpgradeInSlot(test, '#rebel-builder', 2, 2) common.assertUpgradeInSlot(test, '#rebel-builder', 2, 3, 'R2-D2') common.assertNoUpgradeInSlot(test, '#rebel-builder', 2, 4) common.assertShipTypeIs(test, '#rebel-builder', 3, 'YT-1300') common.assertPilotIs(test, '#rebel-builder', 3, 'Chewbacca') common.assertUpgradeInSlot(test, '#rebel-builder', 3, 1, 'Draw Their Fire') common.assertUpgradeInSlot(test, '#rebel-builder', 3, 2, 'Assault Missiles') common.assertUpgradeInSlot(test, '#rebel-builder', 3, 3, 'Intelligence Agent') common.assertUpgradeInSlot(test, '#rebel-builder', 3, 4, 'Recon Specialist') common.assertUpgradeInSlot(test, '#rebel-builder', 3, 5, 'Millennium Falcon') common.assertUpgradeInSlot(test, '#rebel-builder', 3, 6, 'Engine Upgrade') common.assertShipTypeIs(test, '#rebel-builder', 4, 'A-Wing') common.assertPilotIs(test, '#rebel-builder', 4, 'Prototype Pilot') common.assertUpgradeInSlot(test, '#rebel-builder', 4, 1, 'Chardaan Refit') common.assertNoUpgradeInSlot(test, '#rebel-builder', 4, 2) common.assertNoUpgradeInSlot(test, '#rebel-builder', 4, 3) common.assertTotalPoints(test, '#rebel-builder', 137) common.removeShip('#rebel-builder', 1) common.removeShip('#rebel-builder', 1) common.removeShip('#rebel-builder', 1) .run -> test.done() casper.test.begin "Spanish translations: Imperial", (test) -> common.waitForStartup('#rebel-builder') common.openEmpireBuilder() common.selectLanguage('Español') common.createList('#empire-builder', [ { ship: 'Interceptor TIE' pilot: "Piloto del escuadrón Alfa" upgrades: [ null "Dispositivo de Sigilo" ] } { ship: 'Caza TIE' pilot: "Piloto de la academia" upgrades: [ null ] } { ship: 'Interceptor TIE' pilot: "Soontir Fel" upgrades: [ null "TIE de la Guardia Real" "Blindaje mejorado" "Escudos Mejorados" ] } ]) common.assertTotalPoints(test, '#empire-builder', 67) common.selectLanguage('English') common.assertShipTypeIs(test, '#empire-builder', 1, 'TIE Interceptor') common.assertPilotIs(test, '#empire-builder', 1, 'Alpha Squadron Pilot') common.assertUpgradeInSlot(test, '#empire-builder', 1, 2, 'Stealth Device') common.assertShipTypeIs(test, '#empire-builder', 2, 'TIE Fighter') common.assertPilotIs(test, '#empire-builder', 2, 'Academy Pilot') common.assertShipTypeIs(test, '#empire-builder', 3, 'TIE Interceptor') common.assertPilotIs(test, '#empire-builder', 3, 'Soontir Fel') common.assertUpgradeInSlot(test, '#empire-builder', 3, 2, 'Royal Guard TIE') common.assertUpgradeInSlot(test, '#empire-builder', 3, 3, 'Hull Upgrade') common.assertUpgradeInSlot(test, '#empire-builder', 3, 4, 'Shield Upgrade') common.assertTotalPoints(test, '#empire-builder', 67) common.removeShip('#empire-builder', 1) common.removeShip('#empire-builder', 1) common.removeShip('#empire-builder', 1) .run -> test.done()
188031
common = require './common' common.setup() casper.test.begin "Spanish translations: Rebel", (test) -> common.waitForStartup('#rebel-builder') common.selectLanguage('Español') common.createList('#rebel-builder', [ { ship: 'Ala-X' pilot: "Piloto Novato" upgrades: [ "Torpedos de Protones" "Droide Astromecánico R2" "Escudos Mejorados" ] } { ship: 'Ala-X' pilot: "Luke Skywalker" upgrades: [ "Puntería" null "R2-D2" null ] } { ship: 'YT-1300' pilot: "Chewbacca" upgrades: [ "Atraer su fuego" "Misiles de Asalto" "Agente del Servicio de Inteligencia" "Especialista en Reconocimiento" "Halcón Milenario" "Motor Mejorado" ] } { ship: 'Ala-A' pilot: 'Piloto de Pruebas' upgrades: [ 'Reequipado en Chardaan' ] } ]) common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex(3, 3)}", 'Luke Skywalker') common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex(3, 4)}", 'Luke Skywalker') common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex(3, 3)}", 'R2-D2 (Tripulante)') common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex(3, 4)}", 'R2-D2 (Tripulante)') common.assertTotalPoints(test, '#rebel-builder', 137) common.selectLanguage('English') common.assertShipTypeIs(test, '#rebel-builder', 1, 'X-Wing') common.assertPilotIs(test, '#rebel-builder', 1, 'Rookie Pilot') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 1, 'Proton Torpedoes') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 2, 'R2 Astromech') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 3, 'Shield Upgrade') common.assertShipTypeIs(test, '#rebel-builder', 2, 'X-Wing') common.assertPilotIs(test, '#rebel-builder', 2, 'Luke Skywalker') common.assertUpgradeInSlot(test, '#rebel-builder', 2, 1, 'Marksmanship') common.assertNoUpgradeInSlot(test, '#rebel-builder', 2, 2) common.assertUpgradeInSlot(test, '#rebel-builder', 2, 3, 'R2-D2') common.assertNoUpgradeInSlot(test, '#rebel-builder', 2, 4) common.assertShipTypeIs(test, '#rebel-builder', 3, 'YT-1300') common.assertPilotIs(test, '#rebel-builder', 3, 'Chewbacca') common.assertUpgradeInSlot(test, '#rebel-builder', 3, 1, 'Draw Their Fire') common.assertUpgradeInSlot(test, '#rebel-builder', 3, 2, 'Assault Missiles') common.assertUpgradeInSlot(test, '#rebel-builder', 3, 3, 'Intelligence Agent') common.assertUpgradeInSlot(test, '#rebel-builder', 3, 4, 'Recon Specialist') common.assertUpgradeInSlot(test, '#rebel-builder', 3, 5, 'Millennium Falcon') common.assertUpgradeInSlot(test, '#rebel-builder', 3, 6, 'Engine Upgrade') common.assertShipTypeIs(test, '#rebel-builder', 4, 'A-Wing') common.assertPilotIs(test, '#rebel-builder', 4, 'Prototype Pilot') common.assertUpgradeInSlot(test, '#rebel-builder', 4, 1, 'Chardaan Refit') common.assertNoUpgradeInSlot(test, '#rebel-builder', 4, 2) common.assertNoUpgradeInSlot(test, '#rebel-builder', 4, 3) common.assertTotalPoints(test, '#rebel-builder', 137) common.removeShip('#rebel-builder', 1) common.removeShip('#rebel-builder', 1) common.removeShip('#rebel-builder', 1) .run -> test.done() casper.test.begin "Spanish translations: Imperial", (test) -> common.waitForStartup('#rebel-builder') common.openEmpireBuilder() common.selectLanguage('Español') common.createList('#empire-builder', [ { ship: 'Interceptor TIE' pilot: "Piloto del escuadrón Alfa" upgrades: [ null "Dispositivo de Sigilo" ] } { ship: 'Caza TIE' pilot: "Piloto de la academia" upgrades: [ null ] } { ship: 'Interceptor TIE' pilot: "Soontir Fel" upgrades: [ null "TIE de la Guardia Real" "Blindaje mejorado" "Escudos Mejorados" ] } ]) common.assertTotalPoints(test, '#empire-builder', 67) common.selectLanguage('English') common.assertShipTypeIs(test, '#empire-builder', 1, 'TIE Interceptor') common.assertPilotIs(test, '#empire-builder', 1, 'Alpha Squadron Pilot') common.assertUpgradeInSlot(test, '#empire-builder', 1, 2, 'Stealth Device') common.assertShipTypeIs(test, '#empire-builder', 2, 'TIE Fighter') common.assertPilotIs(test, '#empire-builder', 2, 'Academy Pilot') common.assertShipTypeIs(test, '#empire-builder', 3, 'TIE Interceptor') common.assertPilotIs(test, '#empire-builder', 3, '<NAME>') common.assertUpgradeInSlot(test, '#empire-builder', 3, 2, 'Royal Guard TIE') common.assertUpgradeInSlot(test, '#empire-builder', 3, 3, 'Hull Upgrade') common.assertUpgradeInSlot(test, '#empire-builder', 3, 4, 'Shield Upgrade') common.assertTotalPoints(test, '#empire-builder', 67) common.removeShip('#empire-builder', 1) common.removeShip('#empire-builder', 1) common.removeShip('#empire-builder', 1) .run -> test.done()
true
common = require './common' common.setup() casper.test.begin "Spanish translations: Rebel", (test) -> common.waitForStartup('#rebel-builder') common.selectLanguage('Español') common.createList('#rebel-builder', [ { ship: 'Ala-X' pilot: "Piloto Novato" upgrades: [ "Torpedos de Protones" "Droide Astromecánico R2" "Escudos Mejorados" ] } { ship: 'Ala-X' pilot: "Luke Skywalker" upgrades: [ "Puntería" null "R2-D2" null ] } { ship: 'YT-1300' pilot: "Chewbacca" upgrades: [ "Atraer su fuego" "Misiles de Asalto" "Agente del Servicio de Inteligencia" "Especialista en Reconocimiento" "Halcón Milenario" "Motor Mejorado" ] } { ship: 'Ala-A' pilot: 'Piloto de Pruebas' upgrades: [ 'Reequipado en Chardaan' ] } ]) common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex(3, 3)}", 'Luke Skywalker') common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex(3, 4)}", 'Luke Skywalker') common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex(3, 3)}", 'R2-D2 (Tripulante)') common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex(3, 4)}", 'R2-D2 (Tripulante)') common.assertTotalPoints(test, '#rebel-builder', 137) common.selectLanguage('English') common.assertShipTypeIs(test, '#rebel-builder', 1, 'X-Wing') common.assertPilotIs(test, '#rebel-builder', 1, 'Rookie Pilot') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 1, 'Proton Torpedoes') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 2, 'R2 Astromech') common.assertUpgradeInSlot(test, '#rebel-builder', 1, 3, 'Shield Upgrade') common.assertShipTypeIs(test, '#rebel-builder', 2, 'X-Wing') common.assertPilotIs(test, '#rebel-builder', 2, 'Luke Skywalker') common.assertUpgradeInSlot(test, '#rebel-builder', 2, 1, 'Marksmanship') common.assertNoUpgradeInSlot(test, '#rebel-builder', 2, 2) common.assertUpgradeInSlot(test, '#rebel-builder', 2, 3, 'R2-D2') common.assertNoUpgradeInSlot(test, '#rebel-builder', 2, 4) common.assertShipTypeIs(test, '#rebel-builder', 3, 'YT-1300') common.assertPilotIs(test, '#rebel-builder', 3, 'Chewbacca') common.assertUpgradeInSlot(test, '#rebel-builder', 3, 1, 'Draw Their Fire') common.assertUpgradeInSlot(test, '#rebel-builder', 3, 2, 'Assault Missiles') common.assertUpgradeInSlot(test, '#rebel-builder', 3, 3, 'Intelligence Agent') common.assertUpgradeInSlot(test, '#rebel-builder', 3, 4, 'Recon Specialist') common.assertUpgradeInSlot(test, '#rebel-builder', 3, 5, 'Millennium Falcon') common.assertUpgradeInSlot(test, '#rebel-builder', 3, 6, 'Engine Upgrade') common.assertShipTypeIs(test, '#rebel-builder', 4, 'A-Wing') common.assertPilotIs(test, '#rebel-builder', 4, 'Prototype Pilot') common.assertUpgradeInSlot(test, '#rebel-builder', 4, 1, 'Chardaan Refit') common.assertNoUpgradeInSlot(test, '#rebel-builder', 4, 2) common.assertNoUpgradeInSlot(test, '#rebel-builder', 4, 3) common.assertTotalPoints(test, '#rebel-builder', 137) common.removeShip('#rebel-builder', 1) common.removeShip('#rebel-builder', 1) common.removeShip('#rebel-builder', 1) .run -> test.done() casper.test.begin "Spanish translations: Imperial", (test) -> common.waitForStartup('#rebel-builder') common.openEmpireBuilder() common.selectLanguage('Español') common.createList('#empire-builder', [ { ship: 'Interceptor TIE' pilot: "Piloto del escuadrón Alfa" upgrades: [ null "Dispositivo de Sigilo" ] } { ship: 'Caza TIE' pilot: "Piloto de la academia" upgrades: [ null ] } { ship: 'Interceptor TIE' pilot: "Soontir Fel" upgrades: [ null "TIE de la Guardia Real" "Blindaje mejorado" "Escudos Mejorados" ] } ]) common.assertTotalPoints(test, '#empire-builder', 67) common.selectLanguage('English') common.assertShipTypeIs(test, '#empire-builder', 1, 'TIE Interceptor') common.assertPilotIs(test, '#empire-builder', 1, 'Alpha Squadron Pilot') common.assertUpgradeInSlot(test, '#empire-builder', 1, 2, 'Stealth Device') common.assertShipTypeIs(test, '#empire-builder', 2, 'TIE Fighter') common.assertPilotIs(test, '#empire-builder', 2, 'Academy Pilot') common.assertShipTypeIs(test, '#empire-builder', 3, 'TIE Interceptor') common.assertPilotIs(test, '#empire-builder', 3, 'PI:NAME:<NAME>END_PI') common.assertUpgradeInSlot(test, '#empire-builder', 3, 2, 'Royal Guard TIE') common.assertUpgradeInSlot(test, '#empire-builder', 3, 3, 'Hull Upgrade') common.assertUpgradeInSlot(test, '#empire-builder', 3, 4, 'Shield Upgrade') common.assertTotalPoints(test, '#empire-builder', 67) common.removeShip('#empire-builder', 1) common.removeShip('#empire-builder', 1) common.removeShip('#empire-builder', 1) .run -> test.done()
[ { "context": "ethernet]\n\t\t\t\t\tType = ethernet\n\t\t\t\t\tNameservers = 8.8.8.8,8.8.4.4\n\t\t\t\t'''\n\n\t\tdescribe 'given wifiSsid is an", "end": 606, "score": 0.9996732473373413, "start": 599, "tag": "IP_ADDRESS", "value": "8.8.8.8" }, { "context": "]\n\t\t\t\t\tType = etherne...
tests/settings.spec.coffee
balena-io/resin-network-conf
2
chai = require('chai') expect = chai.expect settings = require('../lib/settings') describe 'Settings:', -> describe '.main', -> it 'should be a string', -> expect(settings.main).to.be.a('string') it 'should not be empty', -> expect(settings.main).to.not.have.length(0) describe '.getHomeSettings()', -> describe 'given no wifiSsid', -> beforeEach -> @options = {} it 'should only return ethernet related settings', -> config = settings.getHomeSettings(@options) expect(config).to.equal ''' [service_home_ethernet] Type = ethernet Nameservers = 8.8.8.8,8.8.4.4 ''' describe 'given wifiSsid is an empty string', -> beforeEach -> @options = wifiSsid: '' it 'should only return ethernet related settings', -> config = settings.getHomeSettings(@options) expect(config).to.equal ''' [service_home_ethernet] Type = ethernet Nameservers = 8.8.8.8,8.8.4.4 ''' describe 'given wifiSsid is a string only containing spaces', -> beforeEach -> @options = wifiSsid: ' ' it 'should only return ethernet related settings', -> config = settings.getHomeSettings(@options) expect(config).to.equal ''' [service_home_ethernet] Type = ethernet Nameservers = 8.8.8.8,8.8.4.4 ''' describe 'given a wifiSsid and a wifiKey', -> beforeEach -> @options = wifiSsid: 'foo' wifiKey: 'bar' it 'should configure wifi with a passphrase', -> config = settings.getHomeSettings(@options) expect(config).to.equal ''' [service_home_ethernet] Type = ethernet Nameservers = 8.8.8.8,8.8.4.4 [service_home_wifi] Type = wifi Name = foo Passphrase = bar Nameservers = 8.8.8.8,8.8.4.4 ''' describe 'given a wifiSsid but no wifiKey', -> beforeEach -> @options = wifiSsid: 'foo' it 'should configure wifi without a passphrase', -> config = settings.getHomeSettings(@options) expect(config).to.equal ''' [service_home_ethernet] Type = ethernet Nameservers = 8.8.8.8,8.8.4.4 [service_home_wifi] Type = wifi Name = foo Nameservers = 8.8.8.8,8.8.4.4 '''
3170
chai = require('chai') expect = chai.expect settings = require('../lib/settings') describe 'Settings:', -> describe '.main', -> it 'should be a string', -> expect(settings.main).to.be.a('string') it 'should not be empty', -> expect(settings.main).to.not.have.length(0) describe '.getHomeSettings()', -> describe 'given no wifiSsid', -> beforeEach -> @options = {} it 'should only return ethernet related settings', -> config = settings.getHomeSettings(@options) expect(config).to.equal ''' [service_home_ethernet] Type = ethernet Nameservers = 8.8.8.8,8.8.4.4 ''' describe 'given wifiSsid is an empty string', -> beforeEach -> @options = wifiSsid: '' it 'should only return ethernet related settings', -> config = settings.getHomeSettings(@options) expect(config).to.equal ''' [service_home_ethernet] Type = ethernet Nameservers = 8.8.8.8,8.8.4.4 ''' describe 'given wifiSsid is a string only containing spaces', -> beforeEach -> @options = wifiSsid: ' ' it 'should only return ethernet related settings', -> config = settings.getHomeSettings(@options) expect(config).to.equal ''' [service_home_ethernet] Type = ethernet Nameservers = 8.8.8.8,8.8.4.4 ''' describe 'given a wifiSsid and a wifiKey', -> beforeEach -> @options = wifiSsid: 'foo' wifiKey: 'bar' it 'should configure wifi with a passphrase', -> config = settings.getHomeSettings(@options) expect(config).to.equal ''' [service_home_ethernet] Type = ethernet Nameservers = 8.8.8.8,8.8.4.4 [service_home_wifi] Type = wifi Name = foo Passphrase = <PASSWORD> Nameservers = 8.8.8.8,8.8.4.4 ''' describe 'given a wifiSsid but no wifiKey', -> beforeEach -> @options = wifiSsid: 'foo' it 'should configure wifi without a passphrase', -> config = settings.getHomeSettings(@options) expect(config).to.equal ''' [service_home_ethernet] Type = ethernet Nameservers = 8.8.8.8,8.8.4.4 [service_home_wifi] Type = wifi Name = foo Nameservers = 8.8.8.8,8.8.4.4 '''
true
chai = require('chai') expect = chai.expect settings = require('../lib/settings') describe 'Settings:', -> describe '.main', -> it 'should be a string', -> expect(settings.main).to.be.a('string') it 'should not be empty', -> expect(settings.main).to.not.have.length(0) describe '.getHomeSettings()', -> describe 'given no wifiSsid', -> beforeEach -> @options = {} it 'should only return ethernet related settings', -> config = settings.getHomeSettings(@options) expect(config).to.equal ''' [service_home_ethernet] Type = ethernet Nameservers = 8.8.8.8,8.8.4.4 ''' describe 'given wifiSsid is an empty string', -> beforeEach -> @options = wifiSsid: '' it 'should only return ethernet related settings', -> config = settings.getHomeSettings(@options) expect(config).to.equal ''' [service_home_ethernet] Type = ethernet Nameservers = 8.8.8.8,8.8.4.4 ''' describe 'given wifiSsid is a string only containing spaces', -> beforeEach -> @options = wifiSsid: ' ' it 'should only return ethernet related settings', -> config = settings.getHomeSettings(@options) expect(config).to.equal ''' [service_home_ethernet] Type = ethernet Nameservers = 8.8.8.8,8.8.4.4 ''' describe 'given a wifiSsid and a wifiKey', -> beforeEach -> @options = wifiSsid: 'foo' wifiKey: 'bar' it 'should configure wifi with a passphrase', -> config = settings.getHomeSettings(@options) expect(config).to.equal ''' [service_home_ethernet] Type = ethernet Nameservers = 8.8.8.8,8.8.4.4 [service_home_wifi] Type = wifi Name = foo Passphrase = PI:PASSWORD:<PASSWORD>END_PI Nameservers = 8.8.8.8,8.8.4.4 ''' describe 'given a wifiSsid but no wifiKey', -> beforeEach -> @options = wifiSsid: 'foo' it 'should configure wifi without a passphrase', -> config = settings.getHomeSettings(@options) expect(config).to.equal ''' [service_home_ethernet] Type = ethernet Nameservers = 8.8.8.8,8.8.4.4 [service_home_wifi] Type = wifi Name = foo Nameservers = 8.8.8.8,8.8.4.4 '''
[ { "context": "###\n# lib/bootstrap.coffee\n#\n# © 2014 Dan Nichols\n# See LICENSE for more details\n#\n# This module bo", "end": 49, "score": 0.9996711015701294, "start": 38, "tag": "NAME", "value": "Dan Nichols" } ]
lib/bootstrap.coffee
dlnichols/h_media
0
### # lib/bootstrap.coffee # # © 2014 Dan Nichols # See LICENSE for more details # # This module bootstraps our mongo connection ### 'use strict' # External libs mongoose = require 'mongoose' debug = require('debug') 'hMedia:bootstrap' module.exports = exports = (env) -> # Print connected message mongoose.connection.on 'open', -> debug 'Connected to mongo.' # Handle errors mongoose.connection.on 'error', (err) -> debug 'Unable to connect to mongo: ' + err unless mongoose.connection.readyState > 0 debug 'Connecting to mongo: ' + env.mongo.uri mongoose.connect env.mongo.uri, env.mongo.options else debug 'Mongoose already connected.'
93868
### # lib/bootstrap.coffee # # © 2014 <NAME> # See LICENSE for more details # # This module bootstraps our mongo connection ### 'use strict' # External libs mongoose = require 'mongoose' debug = require('debug') 'hMedia:bootstrap' module.exports = exports = (env) -> # Print connected message mongoose.connection.on 'open', -> debug 'Connected to mongo.' # Handle errors mongoose.connection.on 'error', (err) -> debug 'Unable to connect to mongo: ' + err unless mongoose.connection.readyState > 0 debug 'Connecting to mongo: ' + env.mongo.uri mongoose.connect env.mongo.uri, env.mongo.options else debug 'Mongoose already connected.'
true
### # lib/bootstrap.coffee # # © 2014 PI:NAME:<NAME>END_PI # See LICENSE for more details # # This module bootstraps our mongo connection ### 'use strict' # External libs mongoose = require 'mongoose' debug = require('debug') 'hMedia:bootstrap' module.exports = exports = (env) -> # Print connected message mongoose.connection.on 'open', -> debug 'Connected to mongo.' # Handle errors mongoose.connection.on 'error', (err) -> debug 'Unable to connect to mongo: ' + err unless mongoose.connection.readyState > 0 debug 'Connecting to mongo: ' + env.mongo.uri mongoose.connect env.mongo.uri, env.mongo.options else debug 'Mongoose already connected.'
[ { "context": " spark = new Dog('Spark')\n fido = new Dog('Fido')\n fido.bark = spark.bark\n\n ok fido.bar", "end": 1998, "score": 0.8855751752853394, "start": 1994, "tag": "NAME", "value": "Fido" }, { "context": "bare: yes) for directive in directives\n\n test 'ja...
test/classes.coffee
slang800/TypedCoffeeScript
94
suite 'Classes', -> suite 'Class Definition', -> test "Overriding the static property new doesn't clobber Function::new", -> class OneClass @new: 'new' function: 'function' constructor: (name) -> @name = name class TwoClass extends OneClass delete TwoClass.new Function.prototype.new = -> new this arguments... ok (TwoClass.new('three')).name is 'three' ok (new OneClass).function is 'function' ok OneClass.new is 'new' delete Function.prototype.new test.skip 'basic classes, again, but in the manual prototype style', -> Base = -> Base::func = (string) -> 'zero/' + string Base::['func-func'] = (string) -> "dynamic-#{string}" FirstChild = -> SecondChild = -> ThirdChild = -> @array = [1, 2, 3] this ThirdChild extends SecondChild extends FirstChild extends Base FirstChild::func = (string) -> super('one/') + string SecondChild::func = (string) -> super('two/') + string ThirdChild::func = (string) -> super('three/') + string result = (new ThirdChild).func 'four' ok result is 'zero/one/two/three/four' ok (new ThirdChild)['func-func']('thing') is 'dynamic-thing' test 'static assignment via colon', -> nonce = {} class A then @b: nonce eq nonce, A.b test 'classes with JS-keyword properties', -> class Class class: 'class' name: -> @class instance = new Class ok instance.class is 'class' ok instance.name() is 'class' test 'nothing classes', -> c = class ok c instanceof Function test 'instance-bound methods and statically-bound methods', -> class Dog constructor: (name) -> @name = name bark: => "#{@name} woofs!" @static = => new this('Dog') spark = new Dog('Spark') fido = new Dog('Fido') fido.bark = spark.bark ok fido.bark() is 'Spark woofs!' obj = {func: Dog.static} ok obj.func().name is 'Dog' test 'anonymous classes', -> obj = klass: class method: -> 'value' instance = new obj.klass ok instance.method() is 'value' test 'Implicit objects as static properties', -> class Static @static = one: 1 two: 2 ok Static.static.one is 1 ok Static.static.two is 2 test.skip 'classes with static-level implicit objects', -> class A @static = one: 1 two: 2 class B @static = one: 1, two: 2 eq A.static.one, 1 eq A.static.two, undefined eq (new A).two, 2 eq B.static.one, 1 eq B.static.two, 2 eq (new B).two, undefined test 'external constructors', -> counter = 0 classMaker = -> inner = ++counter -> @value = inner class One constructor: classMaker() class Two constructor: classMaker() eq (new One).value, 1 eq (new Two).value, 2 eq (new One).value, 1 eq (new Two).value, 2 test.skip 'exectuable class bodies', -> class A if true b: 'b' else c: 'c' a = new A eq a.b, 'b' eq a.c, undefined test 'mild metaprogramming', -> class Base @attr = (name) -> this::[name] = (val) -> if arguments.length > 0 this["_#{name}"] = val else this["_#{name}"] class Robot extends Base @attr 'power' @attr 'speed' robby = new Robot ok robby.power() is undefined robby.power 11 robby.speed Infinity eq robby.power(), 11 eq robby.speed(), Infinity test 'namespaced classes do not reserve their function name in outside scope', -> one = {} two = {} class one.Klass @label = "one" class two.Klass @label = "two" eq typeof Klass, 'undefined' eq one.Klass.label, 'one' eq two.Klass.label, 'two' test 'nested classes', -> class Outer constructor: -> @label = 'outer' class @Inner constructor: -> @label = 'inner' eq (new Outer).label, 'outer' eq (new Outer.Inner).label, 'inner' test 'variables in constructor bodies are correctly scoped', -> class A x = 1 constructor: -> x = 10 y = 20 y = 2 captured: -> {x, y} a = new A eq a.captured().x, 10 eq a.captured().y, 2 test 'Issue #924: Static methods in nested classes', -> class A @B = class @c = -> 5 eq A.B.c(), 5 test 'jashkenas/coffee-script#1182: a subclass should be able to set its constructor to an external function', -> ctor = -> @val = 1 class A class B extends A constructor: ctor eq (new B).val, 1 test 'jashkenas/coffee-script#1182: external constructors continued', -> ctor = -> class A class B extends A method: -> constructor: ctor ok B::method test 'jashkenas/coffee-script#1182: execution order needs to be considered as well', -> counter = 0 makeFn = (n) -> eq n, ++counter; -> class B extends (makeFn 1) @B = makeFn 2 constructor: makeFn 3 test 'jashkenas/coffee-script#1182: external constructors with bound functions', -> fn = -> {one: 1} this class B class A constructor: fn method: => this instanceof A ok (new A).method.call(new B) test 'jashkenas/coffee-script#1372: bound class methods with reserved names', -> class C delete: => ok C::delete test 'jashkenas/coffee-script#1464: bound class methods should keep context', -> nonce = {} class C constructor: (id) -> @id = id @boundStatic = => new this(nonce) eq nonce, C.boundStatic().id test 'jashkenas/coffee-script#1009: classes with reserved words as determined names', -> fn = -> eq 'function', typeof (class @for) ok not /\seval\s?\(/.test (class @eval).toString() ok not /\sarguments\s\(/.test (class @arguments).toString() fn.call {} test 'jashkenas/coffee-script#1842: Regression with bound functions within bound class methods', -> class Store @bound = => do => eq this, Store Store.bound() # And a fancier case: class Store eq this, Store @bound = => do => eq this, Store @unbound = -> eq this, Store instance: => ok this instanceof Store Store.bound() Store.unbound() (new Store).instance() test 'jashkenas/coffee-script#1813: Passing class definitions as expressions', -> ident = (x) -> x result = ident class A then x = 1 eq result, A result = ident class B extends A x = 1 eq result, B test 'jashkenas/coffee-script#1966: external constructors should produce their return value', -> ctor = -> {} class A then constructor: ctor ok (new A) not instanceof A test.skip "jashkenas/coffee-script#1534: class then 'use strict'", -> # [14.1 Directive Prologues and the Use Strict Directive](http://es5.github.com/#x14.1) nonce = {} error = 'do -> ok this' strictTest = "do ->'use strict';#{error}" return unless (try CoffeeScript.run strictTest, bare: yes catch e then nonce) is nonce throws -> CoffeeScript.run "class then 'use strict';#{error}", bare: yes doesNotThrow -> CoffeeScript.run "class then #{error}", bare: yes doesNotThrow -> CoffeeScript.run "class then #{error};'use strict'", bare: yes # comments are ignored in the Directive Prologue comments = [""" class ### comment ### 'use strict' #{error}""", """ class ### comment 1 ### ### comment 2 ### 'use strict' #{error}""", """ class ### comment 1 ### ### comment 2 ### 'use strict' #{error} ### comment 3 ###""" ] throws (-> CoffeeScript.run comment, bare: yes) for comment in comments # [ES5 §14.1](http://es5.github.com/#x14.1) allows for other directives directives = [""" class 'directive 1' 'use strict' #{error}""", """ class 'use strict' 'directive 2' #{error}""", """ class ### comment 1 ### 'directive 1' 'use strict' #{error}""", """ class ### comment 1 ### 'directive 1' ### comment 2 ### 'use strict' #{error}""" ] throws (-> CoffeeScript.run directive, bare: yes) for directive in directives test 'jashkenas/coffee-script#2052: classes should work in strict mode', -> do -> 'use strict' class A suite 'Class Instantiation', -> test '"@" referring to the current instance, and not being coerced into a call', -> class ClassName amI: -> this instanceof ClassName obj = new ClassName ok obj.amI() test 'a bound function in a bound function', -> class Mini num: 10 generate: => for i in [0, 0, 0] => @num m = new Mini eq (func() for func in m.generate()).join(' '), '10 10 10' test 'contructor called with varargs', -> class Connection constructor: (one, two, three) -> [@one, @two, @three] = [one, two, three] out: -> "#{@one}-#{@two}-#{@three}" list = [3, 2, 1] conn = new Connection list... ok conn instanceof Connection ok conn.out() is '3-2-1' test 'classes wrapped in decorators', -> func = (klass) -> klass::prop = 'value' klass func class Test prop2: 'value2' ok (new Test).prop is 'value' ok (new Test).prop2 is 'value2' test 'ensure that constructors invoked with splats return a new object', -> args = [1, 2, 3] Type = (@args) -> type = new Type args ok type and type instanceof Type ok type.args and type.args instanceof Array ok v is args[i] for v, i in type.args Type1 = (@a, @b, @c) -> type1 = new Type1 args... ok type1 instanceof Type1 eq type1.constructor, Type1 ok type1.a is args[0] and type1.b is args[1] and type1.c is args[2] # Ensure that constructors invoked with splats cache the function. called = 0 get = -> if called++ then false else class Type new get() args... test '`new` shouldn\'t add extra parens', -> ok new Date().constructor is Date # TODO: this test belongs with the operator tests test '`new` works against bare function', -> eq Date, new -> eq this, new => this Date suite 'Inheritance and Super', -> test 'classes with a four-level inheritance chain', -> class Base func: (string) -> "zero/#{string}" @static: (string) -> "static/#{string}" class FirstChild extends Base func: (string) -> super('one/') + string SecondChild = class extends FirstChild func: (string) -> super('two/') + string thirdCtor = -> @array = [1, 2, 3] class ThirdChild extends SecondChild constructor: -> thirdCtor.call this # Gratuitous comment for testing. func: (string) -> super('three/') + string result = (new ThirdChild).func 'four' ok result is 'zero/one/two/three/four' ok Base.static('word') is 'static/word' FirstChild::func = (string) -> super('one/').length + string result = (new ThirdChild).func 'four' # eq result, '9two/three/four' # can't pass super('one/').length + string # ok (new ThirdChild).array.join(' ') is '1 2 3' test 'constructors with inheritance and super', -> identity = (f) -> f class TopClass constructor: (arg) -> @prop = 'top-' + arg class SuperClass extends TopClass constructor: (arg) -> identity super 'super-' + arg class SubClass extends SuperClass constructor: -> identity super 'sub' ok (new SubClass).prop is 'top-super-sub' test "super with plain ol' functions as the original constructors", -> TopClass = -> TopClass::func = (arg) -> 'top-' + arg SuperClass = -> SuperClass extends TopClass SuperClass::func = (arg) -> super 'super-' + arg SubClass = -> SubClass extends SuperClass SubClass::func = -> super 'sub' eq (new SubClass).func(), 'top-super-sub' test 'super() calls in constructors of classes that are defined as object properties', -> class Hive constructor: (name) -> @name = name class Hive.Bee extends Hive constructor: (name) -> super maya = new Hive.Bee 'Maya' ok maya.name is 'Maya' test 'calling super and passing along all arguments', -> class Parent method: (args...) -> @args = args class Child extends Parent method: -> super c = new Child c.method 1, 2, 3, 4 ok c.args.join(' ') is '1 2 3 4' test.skip '`class extends this`', -> # Currently syntax error. # # class A # func: -> 'A' # # B = null # makeClass = -> # B = class extends this # func: -> super + ' B' # # makeClass.call A # # eq (new B()).func(), 'A B' test 'jashkenas/coffee-script#1313: misplaced __extends', -> nonce = {} class A class B extends A prop: nonce constructor: -> eq nonce, B::prop test.skip 'jashkenas/coffee-script#1380: `super` with reserved names', -> # Currently syntax error. # class C # do: -> super # ok C::do # # class B # 0: -> super # ok B::[0] test 'jashkenas/coffee-script#1482: classes can extend expressions', -> id = (x) -> x nonce = {} class A then nonce: nonce class B extends id A eq nonce, (new B).nonce test 'jashkenas/coffee-script#1598: super works for static methods too', -> class Parent method: -> 'NO' @method: -> 'yes' class Child extends Parent @method: -> 'pass? ' + super eq Child.method(), 'pass? yes' test 'jashkenas/coffee-script#1876: Class @A extends A', -> class A class @A extends A ok (new @A) instanceof A test 'jashkenas/coffee-script#1980: regression with an inherited class with static function members', -> class A class B extends A @static = => 'value' eq B.static(), 'value' test 'bound function literals as constructors should be treated as unbound', -> nonce = {} class A constructor: => @nonce = nonce a = new A ok a instanceof A eq nonce, a.nonce test 'super function', -> class Super func: (@a = 1) -> @a class Sub extends Super func: -> super eq @a, 1 super 3 eq @a, 3 a = super v = 2 * super 3 eq v, 6 a = new Sub a.func() test '#199: implicit object as static class member', -> nonceA = {} nonceB = {} class A @prop: a: nonceA b: nonceB eq nonceA, A.prop.a eq nonceB, A.prop.b test '#205: implicit objects should not consume following prototype assignments', -> class A a: b: 0 c: 1 ok 'a' of A.prototype ok 'b' of A::a ok 'b' not of A.prototype ok 'c' of A.prototype test '#201: subclasses without explicit constructors inherit parent constructors', -> i = 0 class A constructor: -> i++ class B extends A eq 0, i a = new A ok a instanceof A eq 1, i b = new B eq 2, i ok b instanceof B ok b instanceof A
6807
suite 'Classes', -> suite 'Class Definition', -> test "Overriding the static property new doesn't clobber Function::new", -> class OneClass @new: 'new' function: 'function' constructor: (name) -> @name = name class TwoClass extends OneClass delete TwoClass.new Function.prototype.new = -> new this arguments... ok (TwoClass.new('three')).name is 'three' ok (new OneClass).function is 'function' ok OneClass.new is 'new' delete Function.prototype.new test.skip 'basic classes, again, but in the manual prototype style', -> Base = -> Base::func = (string) -> 'zero/' + string Base::['func-func'] = (string) -> "dynamic-#{string}" FirstChild = -> SecondChild = -> ThirdChild = -> @array = [1, 2, 3] this ThirdChild extends SecondChild extends FirstChild extends Base FirstChild::func = (string) -> super('one/') + string SecondChild::func = (string) -> super('two/') + string ThirdChild::func = (string) -> super('three/') + string result = (new ThirdChild).func 'four' ok result is 'zero/one/two/three/four' ok (new ThirdChild)['func-func']('thing') is 'dynamic-thing' test 'static assignment via colon', -> nonce = {} class A then @b: nonce eq nonce, A.b test 'classes with JS-keyword properties', -> class Class class: 'class' name: -> @class instance = new Class ok instance.class is 'class' ok instance.name() is 'class' test 'nothing classes', -> c = class ok c instanceof Function test 'instance-bound methods and statically-bound methods', -> class Dog constructor: (name) -> @name = name bark: => "#{@name} woofs!" @static = => new this('Dog') spark = new Dog('Spark') fido = new Dog('<NAME>') fido.bark = spark.bark ok fido.bark() is 'Spark woofs!' obj = {func: Dog.static} ok obj.func().name is 'Dog' test 'anonymous classes', -> obj = klass: class method: -> 'value' instance = new obj.klass ok instance.method() is 'value' test 'Implicit objects as static properties', -> class Static @static = one: 1 two: 2 ok Static.static.one is 1 ok Static.static.two is 2 test.skip 'classes with static-level implicit objects', -> class A @static = one: 1 two: 2 class B @static = one: 1, two: 2 eq A.static.one, 1 eq A.static.two, undefined eq (new A).two, 2 eq B.static.one, 1 eq B.static.two, 2 eq (new B).two, undefined test 'external constructors', -> counter = 0 classMaker = -> inner = ++counter -> @value = inner class One constructor: classMaker() class Two constructor: classMaker() eq (new One).value, 1 eq (new Two).value, 2 eq (new One).value, 1 eq (new Two).value, 2 test.skip 'exectuable class bodies', -> class A if true b: 'b' else c: 'c' a = new A eq a.b, 'b' eq a.c, undefined test 'mild metaprogramming', -> class Base @attr = (name) -> this::[name] = (val) -> if arguments.length > 0 this["_#{name}"] = val else this["_#{name}"] class Robot extends Base @attr 'power' @attr 'speed' robby = new Robot ok robby.power() is undefined robby.power 11 robby.speed Infinity eq robby.power(), 11 eq robby.speed(), Infinity test 'namespaced classes do not reserve their function name in outside scope', -> one = {} two = {} class one.Klass @label = "one" class two.Klass @label = "two" eq typeof Klass, 'undefined' eq one.Klass.label, 'one' eq two.Klass.label, 'two' test 'nested classes', -> class Outer constructor: -> @label = 'outer' class @Inner constructor: -> @label = 'inner' eq (new Outer).label, 'outer' eq (new Outer.Inner).label, 'inner' test 'variables in constructor bodies are correctly scoped', -> class A x = 1 constructor: -> x = 10 y = 20 y = 2 captured: -> {x, y} a = new A eq a.captured().x, 10 eq a.captured().y, 2 test 'Issue #924: Static methods in nested classes', -> class A @B = class @c = -> 5 eq A.B.c(), 5 test 'jashkenas/coffee-script#1182: a subclass should be able to set its constructor to an external function', -> ctor = -> @val = 1 class A class B extends A constructor: ctor eq (new B).val, 1 test 'jashkenas/coffee-script#1182: external constructors continued', -> ctor = -> class A class B extends A method: -> constructor: ctor ok B::method test 'jashkenas/coffee-script#1182: execution order needs to be considered as well', -> counter = 0 makeFn = (n) -> eq n, ++counter; -> class B extends (makeFn 1) @B = makeFn 2 constructor: makeFn 3 test 'jashkenas/coffee-script#1182: external constructors with bound functions', -> fn = -> {one: 1} this class B class A constructor: fn method: => this instanceof A ok (new A).method.call(new B) test 'jashkenas/coffee-script#1372: bound class methods with reserved names', -> class C delete: => ok C::delete test 'jashkenas/coffee-script#1464: bound class methods should keep context', -> nonce = {} class C constructor: (id) -> @id = id @boundStatic = => new this(nonce) eq nonce, C.boundStatic().id test 'jashkenas/coffee-script#1009: classes with reserved words as determined names', -> fn = -> eq 'function', typeof (class @for) ok not /\seval\s?\(/.test (class @eval).toString() ok not /\sarguments\s\(/.test (class @arguments).toString() fn.call {} test 'jashkenas/coffee-script#1842: Regression with bound functions within bound class methods', -> class Store @bound = => do => eq this, Store Store.bound() # And a fancier case: class Store eq this, Store @bound = => do => eq this, Store @unbound = -> eq this, Store instance: => ok this instanceof Store Store.bound() Store.unbound() (new Store).instance() test 'jashkenas/coffee-script#1813: Passing class definitions as expressions', -> ident = (x) -> x result = ident class A then x = 1 eq result, A result = ident class B extends A x = 1 eq result, B test 'jashkenas/coffee-script#1966: external constructors should produce their return value', -> ctor = -> {} class A then constructor: ctor ok (new A) not instanceof A test.skip "jashkenas/coffee-script#1534: class then 'use strict'", -> # [14.1 Directive Prologues and the Use Strict Directive](http://es5.github.com/#x14.1) nonce = {} error = 'do -> ok this' strictTest = "do ->'use strict';#{error}" return unless (try CoffeeScript.run strictTest, bare: yes catch e then nonce) is nonce throws -> CoffeeScript.run "class then 'use strict';#{error}", bare: yes doesNotThrow -> CoffeeScript.run "class then #{error}", bare: yes doesNotThrow -> CoffeeScript.run "class then #{error};'use strict'", bare: yes # comments are ignored in the Directive Prologue comments = [""" class ### comment ### 'use strict' #{error}""", """ class ### comment 1 ### ### comment 2 ### 'use strict' #{error}""", """ class ### comment 1 ### ### comment 2 ### 'use strict' #{error} ### comment 3 ###""" ] throws (-> CoffeeScript.run comment, bare: yes) for comment in comments # [ES5 §14.1](http://es5.github.com/#x14.1) allows for other directives directives = [""" class 'directive 1' 'use strict' #{error}""", """ class 'use strict' 'directive 2' #{error}""", """ class ### comment 1 ### 'directive 1' 'use strict' #{error}""", """ class ### comment 1 ### 'directive 1' ### comment 2 ### 'use strict' #{error}""" ] throws (-> CoffeeScript.run directive, bare: yes) for directive in directives test 'jashkenas/coffee-script#2052: classes should work in strict mode', -> do -> 'use strict' class A suite 'Class Instantiation', -> test '"@" referring to the current instance, and not being coerced into a call', -> class ClassName amI: -> this instanceof ClassName obj = new ClassName ok obj.amI() test 'a bound function in a bound function', -> class Mini num: 10 generate: => for i in [0, 0, 0] => @num m = new Mini eq (func() for func in m.generate()).join(' '), '10 10 10' test 'contructor called with varargs', -> class Connection constructor: (one, two, three) -> [@one, @two, @three] = [one, two, three] out: -> "#{@one}-#{@two}-#{@three}" list = [3, 2, 1] conn = new Connection list... ok conn instanceof Connection ok conn.out() is '3-2-1' test 'classes wrapped in decorators', -> func = (klass) -> klass::prop = 'value' klass func class Test prop2: 'value2' ok (new Test).prop is 'value' ok (new Test).prop2 is 'value2' test 'ensure that constructors invoked with splats return a new object', -> args = [1, 2, 3] Type = (@args) -> type = new Type args ok type and type instanceof Type ok type.args and type.args instanceof Array ok v is args[i] for v, i in type.args Type1 = (@a, @b, @c) -> type1 = new Type1 args... ok type1 instanceof Type1 eq type1.constructor, Type1 ok type1.a is args[0] and type1.b is args[1] and type1.c is args[2] # Ensure that constructors invoked with splats cache the function. called = 0 get = -> if called++ then false else class Type new get() args... test '`new` shouldn\'t add extra parens', -> ok new Date().constructor is Date # TODO: this test belongs with the operator tests test '`new` works against bare function', -> eq Date, new -> eq this, new => this Date suite 'Inheritance and Super', -> test 'classes with a four-level inheritance chain', -> class Base func: (string) -> "zero/#{string}" @static: (string) -> "static/#{string}" class FirstChild extends Base func: (string) -> super('one/') + string SecondChild = class extends FirstChild func: (string) -> super('two/') + string thirdCtor = -> @array = [1, 2, 3] class ThirdChild extends SecondChild constructor: -> thirdCtor.call this # Gratuitous comment for testing. func: (string) -> super('three/') + string result = (new ThirdChild).func 'four' ok result is 'zero/one/two/three/four' ok Base.static('word') is 'static/word' FirstChild::func = (string) -> super('one/').length + string result = (new ThirdChild).func 'four' # eq result, '9two/three/four' # can't pass super('one/').length + string # ok (new ThirdChild).array.join(' ') is '1 2 3' test 'constructors with inheritance and super', -> identity = (f) -> f class TopClass constructor: (arg) -> @prop = 'top-' + arg class SuperClass extends TopClass constructor: (arg) -> identity super 'super-' + arg class SubClass extends SuperClass constructor: -> identity super 'sub' ok (new SubClass).prop is 'top-super-sub' test "super with plain ol' functions as the original constructors", -> TopClass = -> TopClass::func = (arg) -> 'top-' + arg SuperClass = -> SuperClass extends TopClass SuperClass::func = (arg) -> super 'super-' + arg SubClass = -> SubClass extends SuperClass SubClass::func = -> super 'sub' eq (new SubClass).func(), 'top-super-sub' test 'super() calls in constructors of classes that are defined as object properties', -> class Hive constructor: (name) -> @name = name class Hive.Bee extends Hive constructor: (name) -> super maya = new Hive.Bee 'Maya' ok maya.name is 'Maya' test 'calling super and passing along all arguments', -> class Parent method: (args...) -> @args = args class Child extends Parent method: -> super c = new Child c.method 1, 2, 3, 4 ok c.args.join(' ') is '1 2 3 4' test.skip '`class extends this`', -> # Currently syntax error. # # class A # func: -> 'A' # # B = null # makeClass = -> # B = class extends this # func: -> super + ' B' # # makeClass.call A # # eq (new B()).func(), 'A B' test 'jashkenas/coffee-script#1313: misplaced __extends', -> nonce = {} class A class B extends A prop: nonce constructor: -> eq nonce, B::prop test.skip 'jashkenas/coffee-script#1380: `super` with reserved names', -> # Currently syntax error. # class C # do: -> super # ok C::do # # class B # 0: -> super # ok B::[0] test 'jashkenas/coffee-script#1482: classes can extend expressions', -> id = (x) -> x nonce = {} class A then nonce: nonce class B extends id A eq nonce, (new B).nonce test 'jashkenas/coffee-script#1598: super works for static methods too', -> class Parent method: -> 'NO' @method: -> 'yes' class Child extends Parent @method: -> 'pass? ' + super eq Child.method(), 'pass? yes' test 'jashkenas/coffee-script#1876: Class @A extends A', -> class A class @A extends A ok (new @A) instanceof A test 'jashkenas/coffee-script#1980: regression with an inherited class with static function members', -> class A class B extends A @static = => 'value' eq B.static(), 'value' test 'bound function literals as constructors should be treated as unbound', -> nonce = {} class A constructor: => @nonce = nonce a = new A ok a instanceof A eq nonce, a.nonce test 'super function', -> class Super func: (@a = 1) -> @a class Sub extends Super func: -> super eq @a, 1 super 3 eq @a, 3 a = super v = 2 * super 3 eq v, 6 a = new Sub a.func() test '#199: implicit object as static class member', -> nonceA = {} nonceB = {} class A @prop: a: nonceA b: nonceB eq nonceA, A.prop.a eq nonceB, A.prop.b test '#205: implicit objects should not consume following prototype assignments', -> class A a: b: 0 c: 1 ok 'a' of A.prototype ok 'b' of A::a ok 'b' not of A.prototype ok 'c' of A.prototype test '#201: subclasses without explicit constructors inherit parent constructors', -> i = 0 class A constructor: -> i++ class B extends A eq 0, i a = new A ok a instanceof A eq 1, i b = new B eq 2, i ok b instanceof B ok b instanceof A
true
suite 'Classes', -> suite 'Class Definition', -> test "Overriding the static property new doesn't clobber Function::new", -> class OneClass @new: 'new' function: 'function' constructor: (name) -> @name = name class TwoClass extends OneClass delete TwoClass.new Function.prototype.new = -> new this arguments... ok (TwoClass.new('three')).name is 'three' ok (new OneClass).function is 'function' ok OneClass.new is 'new' delete Function.prototype.new test.skip 'basic classes, again, but in the manual prototype style', -> Base = -> Base::func = (string) -> 'zero/' + string Base::['func-func'] = (string) -> "dynamic-#{string}" FirstChild = -> SecondChild = -> ThirdChild = -> @array = [1, 2, 3] this ThirdChild extends SecondChild extends FirstChild extends Base FirstChild::func = (string) -> super('one/') + string SecondChild::func = (string) -> super('two/') + string ThirdChild::func = (string) -> super('three/') + string result = (new ThirdChild).func 'four' ok result is 'zero/one/two/three/four' ok (new ThirdChild)['func-func']('thing') is 'dynamic-thing' test 'static assignment via colon', -> nonce = {} class A then @b: nonce eq nonce, A.b test 'classes with JS-keyword properties', -> class Class class: 'class' name: -> @class instance = new Class ok instance.class is 'class' ok instance.name() is 'class' test 'nothing classes', -> c = class ok c instanceof Function test 'instance-bound methods and statically-bound methods', -> class Dog constructor: (name) -> @name = name bark: => "#{@name} woofs!" @static = => new this('Dog') spark = new Dog('Spark') fido = new Dog('PI:NAME:<NAME>END_PI') fido.bark = spark.bark ok fido.bark() is 'Spark woofs!' obj = {func: Dog.static} ok obj.func().name is 'Dog' test 'anonymous classes', -> obj = klass: class method: -> 'value' instance = new obj.klass ok instance.method() is 'value' test 'Implicit objects as static properties', -> class Static @static = one: 1 two: 2 ok Static.static.one is 1 ok Static.static.two is 2 test.skip 'classes with static-level implicit objects', -> class A @static = one: 1 two: 2 class B @static = one: 1, two: 2 eq A.static.one, 1 eq A.static.two, undefined eq (new A).two, 2 eq B.static.one, 1 eq B.static.two, 2 eq (new B).two, undefined test 'external constructors', -> counter = 0 classMaker = -> inner = ++counter -> @value = inner class One constructor: classMaker() class Two constructor: classMaker() eq (new One).value, 1 eq (new Two).value, 2 eq (new One).value, 1 eq (new Two).value, 2 test.skip 'exectuable class bodies', -> class A if true b: 'b' else c: 'c' a = new A eq a.b, 'b' eq a.c, undefined test 'mild metaprogramming', -> class Base @attr = (name) -> this::[name] = (val) -> if arguments.length > 0 this["_#{name}"] = val else this["_#{name}"] class Robot extends Base @attr 'power' @attr 'speed' robby = new Robot ok robby.power() is undefined robby.power 11 robby.speed Infinity eq robby.power(), 11 eq robby.speed(), Infinity test 'namespaced classes do not reserve their function name in outside scope', -> one = {} two = {} class one.Klass @label = "one" class two.Klass @label = "two" eq typeof Klass, 'undefined' eq one.Klass.label, 'one' eq two.Klass.label, 'two' test 'nested classes', -> class Outer constructor: -> @label = 'outer' class @Inner constructor: -> @label = 'inner' eq (new Outer).label, 'outer' eq (new Outer.Inner).label, 'inner' test 'variables in constructor bodies are correctly scoped', -> class A x = 1 constructor: -> x = 10 y = 20 y = 2 captured: -> {x, y} a = new A eq a.captured().x, 10 eq a.captured().y, 2 test 'Issue #924: Static methods in nested classes', -> class A @B = class @c = -> 5 eq A.B.c(), 5 test 'jashkenas/coffee-script#1182: a subclass should be able to set its constructor to an external function', -> ctor = -> @val = 1 class A class B extends A constructor: ctor eq (new B).val, 1 test 'jashkenas/coffee-script#1182: external constructors continued', -> ctor = -> class A class B extends A method: -> constructor: ctor ok B::method test 'jashkenas/coffee-script#1182: execution order needs to be considered as well', -> counter = 0 makeFn = (n) -> eq n, ++counter; -> class B extends (makeFn 1) @B = makeFn 2 constructor: makeFn 3 test 'jashkenas/coffee-script#1182: external constructors with bound functions', -> fn = -> {one: 1} this class B class A constructor: fn method: => this instanceof A ok (new A).method.call(new B) test 'jashkenas/coffee-script#1372: bound class methods with reserved names', -> class C delete: => ok C::delete test 'jashkenas/coffee-script#1464: bound class methods should keep context', -> nonce = {} class C constructor: (id) -> @id = id @boundStatic = => new this(nonce) eq nonce, C.boundStatic().id test 'jashkenas/coffee-script#1009: classes with reserved words as determined names', -> fn = -> eq 'function', typeof (class @for) ok not /\seval\s?\(/.test (class @eval).toString() ok not /\sarguments\s\(/.test (class @arguments).toString() fn.call {} test 'jashkenas/coffee-script#1842: Regression with bound functions within bound class methods', -> class Store @bound = => do => eq this, Store Store.bound() # And a fancier case: class Store eq this, Store @bound = => do => eq this, Store @unbound = -> eq this, Store instance: => ok this instanceof Store Store.bound() Store.unbound() (new Store).instance() test 'jashkenas/coffee-script#1813: Passing class definitions as expressions', -> ident = (x) -> x result = ident class A then x = 1 eq result, A result = ident class B extends A x = 1 eq result, B test 'jashkenas/coffee-script#1966: external constructors should produce their return value', -> ctor = -> {} class A then constructor: ctor ok (new A) not instanceof A test.skip "jashkenas/coffee-script#1534: class then 'use strict'", -> # [14.1 Directive Prologues and the Use Strict Directive](http://es5.github.com/#x14.1) nonce = {} error = 'do -> ok this' strictTest = "do ->'use strict';#{error}" return unless (try CoffeeScript.run strictTest, bare: yes catch e then nonce) is nonce throws -> CoffeeScript.run "class then 'use strict';#{error}", bare: yes doesNotThrow -> CoffeeScript.run "class then #{error}", bare: yes doesNotThrow -> CoffeeScript.run "class then #{error};'use strict'", bare: yes # comments are ignored in the Directive Prologue comments = [""" class ### comment ### 'use strict' #{error}""", """ class ### comment 1 ### ### comment 2 ### 'use strict' #{error}""", """ class ### comment 1 ### ### comment 2 ### 'use strict' #{error} ### comment 3 ###""" ] throws (-> CoffeeScript.run comment, bare: yes) for comment in comments # [ES5 §14.1](http://es5.github.com/#x14.1) allows for other directives directives = [""" class 'directive 1' 'use strict' #{error}""", """ class 'use strict' 'directive 2' #{error}""", """ class ### comment 1 ### 'directive 1' 'use strict' #{error}""", """ class ### comment 1 ### 'directive 1' ### comment 2 ### 'use strict' #{error}""" ] throws (-> CoffeeScript.run directive, bare: yes) for directive in directives test 'jashkenas/coffee-script#2052: classes should work in strict mode', -> do -> 'use strict' class A suite 'Class Instantiation', -> test '"@" referring to the current instance, and not being coerced into a call', -> class ClassName amI: -> this instanceof ClassName obj = new ClassName ok obj.amI() test 'a bound function in a bound function', -> class Mini num: 10 generate: => for i in [0, 0, 0] => @num m = new Mini eq (func() for func in m.generate()).join(' '), '10 10 10' test 'contructor called with varargs', -> class Connection constructor: (one, two, three) -> [@one, @two, @three] = [one, two, three] out: -> "#{@one}-#{@two}-#{@three}" list = [3, 2, 1] conn = new Connection list... ok conn instanceof Connection ok conn.out() is '3-2-1' test 'classes wrapped in decorators', -> func = (klass) -> klass::prop = 'value' klass func class Test prop2: 'value2' ok (new Test).prop is 'value' ok (new Test).prop2 is 'value2' test 'ensure that constructors invoked with splats return a new object', -> args = [1, 2, 3] Type = (@args) -> type = new Type args ok type and type instanceof Type ok type.args and type.args instanceof Array ok v is args[i] for v, i in type.args Type1 = (@a, @b, @c) -> type1 = new Type1 args... ok type1 instanceof Type1 eq type1.constructor, Type1 ok type1.a is args[0] and type1.b is args[1] and type1.c is args[2] # Ensure that constructors invoked with splats cache the function. called = 0 get = -> if called++ then false else class Type new get() args... test '`new` shouldn\'t add extra parens', -> ok new Date().constructor is Date # TODO: this test belongs with the operator tests test '`new` works against bare function', -> eq Date, new -> eq this, new => this Date suite 'Inheritance and Super', -> test 'classes with a four-level inheritance chain', -> class Base func: (string) -> "zero/#{string}" @static: (string) -> "static/#{string}" class FirstChild extends Base func: (string) -> super('one/') + string SecondChild = class extends FirstChild func: (string) -> super('two/') + string thirdCtor = -> @array = [1, 2, 3] class ThirdChild extends SecondChild constructor: -> thirdCtor.call this # Gratuitous comment for testing. func: (string) -> super('three/') + string result = (new ThirdChild).func 'four' ok result is 'zero/one/two/three/four' ok Base.static('word') is 'static/word' FirstChild::func = (string) -> super('one/').length + string result = (new ThirdChild).func 'four' # eq result, '9two/three/four' # can't pass super('one/').length + string # ok (new ThirdChild).array.join(' ') is '1 2 3' test 'constructors with inheritance and super', -> identity = (f) -> f class TopClass constructor: (arg) -> @prop = 'top-' + arg class SuperClass extends TopClass constructor: (arg) -> identity super 'super-' + arg class SubClass extends SuperClass constructor: -> identity super 'sub' ok (new SubClass).prop is 'top-super-sub' test "super with plain ol' functions as the original constructors", -> TopClass = -> TopClass::func = (arg) -> 'top-' + arg SuperClass = -> SuperClass extends TopClass SuperClass::func = (arg) -> super 'super-' + arg SubClass = -> SubClass extends SuperClass SubClass::func = -> super 'sub' eq (new SubClass).func(), 'top-super-sub' test 'super() calls in constructors of classes that are defined as object properties', -> class Hive constructor: (name) -> @name = name class Hive.Bee extends Hive constructor: (name) -> super maya = new Hive.Bee 'Maya' ok maya.name is 'Maya' test 'calling super and passing along all arguments', -> class Parent method: (args...) -> @args = args class Child extends Parent method: -> super c = new Child c.method 1, 2, 3, 4 ok c.args.join(' ') is '1 2 3 4' test.skip '`class extends this`', -> # Currently syntax error. # # class A # func: -> 'A' # # B = null # makeClass = -> # B = class extends this # func: -> super + ' B' # # makeClass.call A # # eq (new B()).func(), 'A B' test 'jashkenas/coffee-script#1313: misplaced __extends', -> nonce = {} class A class B extends A prop: nonce constructor: -> eq nonce, B::prop test.skip 'jashkenas/coffee-script#1380: `super` with reserved names', -> # Currently syntax error. # class C # do: -> super # ok C::do # # class B # 0: -> super # ok B::[0] test 'jashkenas/coffee-script#1482: classes can extend expressions', -> id = (x) -> x nonce = {} class A then nonce: nonce class B extends id A eq nonce, (new B).nonce test 'jashkenas/coffee-script#1598: super works for static methods too', -> class Parent method: -> 'NO' @method: -> 'yes' class Child extends Parent @method: -> 'pass? ' + super eq Child.method(), 'pass? yes' test 'jashkenas/coffee-script#1876: Class @A extends A', -> class A class @A extends A ok (new @A) instanceof A test 'jashkenas/coffee-script#1980: regression with an inherited class with static function members', -> class A class B extends A @static = => 'value' eq B.static(), 'value' test 'bound function literals as constructors should be treated as unbound', -> nonce = {} class A constructor: => @nonce = nonce a = new A ok a instanceof A eq nonce, a.nonce test 'super function', -> class Super func: (@a = 1) -> @a class Sub extends Super func: -> super eq @a, 1 super 3 eq @a, 3 a = super v = 2 * super 3 eq v, 6 a = new Sub a.func() test '#199: implicit object as static class member', -> nonceA = {} nonceB = {} class A @prop: a: nonceA b: nonceB eq nonceA, A.prop.a eq nonceB, A.prop.b test '#205: implicit objects should not consume following prototype assignments', -> class A a: b: 0 c: 1 ok 'a' of A.prototype ok 'b' of A::a ok 'b' not of A.prototype ok 'c' of A.prototype test '#201: subclasses without explicit constructors inherit parent constructors', -> i = 0 class A constructor: -> i++ class B extends A eq 0, i a = new A ok a instanceof A eq 1, i b = new B eq 2, i ok b instanceof B ok b instanceof A
[ { "context": " uuid.v4()\n data[idName] = idValue\n\n key = \"#{table}:id:#{idValue}\"\n self.client.hmset key, data, (err) ->\n r", "end": 4545, "score": 0.9976446628570557, "start": 4521, "tag": "KEY", "value": "\"#{table}:id:#{idValue}\"" }, { "context": "[\"id\"]\...
src/redis_adapter.coffee
jwhitehorn/redium
1
redis = require 'redis' uuid = require 'node-uuid' async = require 'async' crc = require 'crc' fs = require 'fs' path = require 'path' _ = require 'underscore' indexTypes = require './index_types' commands = {} indexOptions = {} class RedisAdapter constructor: (config, connection, opts) -> @client = redis.createClient(config.port, config.host, {}) @customTypes = {} @blank = -> return isSql: false @index: (model, property, indexType) -> modelOptions = indexOptions[model] modelOptions = {} unless modelOptions? modelOptions[property] = indexType indexOptions[model] = modelOptions #Establishes your database connection. connect: (callback) -> self = this rootPath = path.dirname(fs.realpathSync(__filename)) async.series [ (next) -> return next() if commands.keysFor? filename = path.join rootPath, "./keys_for.lua" fs.readFile filename, 'utf8', (err, lua) -> return callback?(err) if err? self.client.script 'load', lua, (err, sha) -> commands.keysFor = sha next(err) (next) -> return next() if commands.mhgetAll? filename = path.join rootPath, "./mhgetall.lua" fs.readFile filename, 'utf8', (err, lua) -> return callback?(err) if err? self.client.script 'load', lua, (err, sha) -> commands.mhgetAll = sha next(err) (next) -> return next() if commands.createIndex? filename = path.join rootPath, "./create_index.lua" fs.readFile filename, 'utf8', (err, lua) -> return callback?(err) if err? self.client.script 'load', lua, (err, sha) -> commands.createIndex = sha next(err) (next) -> return next() if commands.updateIndex? filename = path.join rootPath, "./update_index.lua" fs.readFile filename, 'utf8', (err, lua) -> return callback?(err) if err? self.client.script 'load', lua, (err, sha) -> commands.updateIndex = sha next(err) (next) -> return next() if commands.delete? filename = path.join rootPath, "./delete.lua" fs.readFile filename, 'utf8', (err, lua) -> return callback?(err) if err? self.client.script 'load', lua, (err, sha) -> commands.delete = sha next(err) ], (err) -> alreadyConfiguredLua = true callback(err) if callback? #Tests whether your connection is still alive. ping: (callback) -> callback() if callback? #Closes your database connection. close: (callback) -> @client.quit() if @client? callback() if callback? #Maps an object property to the correlated value to use for the database. propertyToValue: (value, property) -> typeHandler = @customTypes[property.type] if typeHandler and "propertyToValue" of typeHandler return typeHandler.propertyToValue(value) if property["type"] == "number" or property["type"] == "date" return null if isNaN value return value #Maps a database value to the property value to use for the mapped object. valueToProperty: (value, property) -> if property["type"] == "number" v = parseFloat value if isNaN(v) v = null return v if property["type"] == "boolean" return value == 'true' || value == '1' || value == 1 || value == true if property["type"] == "text" if value == 'null' return null if property["type"] == "date" return null unless value? v = new Date Date.parse value if isNaN(v) v = null return v typeHandler = @customTypes[property.type] if typeHandler and "valueToProperty" of typeHandler return typeHandler.valueToProperty(value) return value on: (event, callback) -> return this #@client.on event, callback find: (fields, table, conditions, opts, callback) -> return unless callback? self = this self.keysFor table, conditions, opts, (err, keys) -> return callback(err) if err? self.mgetKeys keys, (err, results) -> return callback(err) if err? self.recheckConditionals results, conditions, callback insert: (table, data, id_prop, callback) -> self = this idName = id_prop[0]["name"] idValue = data[idName] unless idValue? idValue = uuid.v4() data[idName] = idValue key = "#{table}:id:#{idValue}" self.client.hmset key, data, (err) -> return callback(err) if err? and callback? props = Object.keys(data) args = [commands.createIndex, 0, props.length] for prop in props value = data[prop] score = self.score value storage = self.storageFor table, prop, value args.push "#{table}:#{prop}" args.push storage args.push score args.push key self.client.evalsha args, (err) -> callback(err, idName: idValue) if callback? update: (table, changes, conditions, callback) -> self = this callback = self.blank unless callback? id = conditions["id"] props = Object.keys changes key = "#{table}:id:#{id}" args = [commands.updateIndex, 0, props.length] for prop in props value = changes[prop] score = self.score value storage = self.storageFor table, prop, value args.push "#{table}:#{prop}" args.push prop args.push storage args.push score args.push value args.push key self.client.evalsha args, (err) -> callback err remove: (table, conditions, callback) -> self = this callback = self.blank unless callback? self.keysFor table, conditions, {}, (err, keys) -> return callback(err) if err? async.eachSeries keys, (key, next) -> args = [commands.delete, 0, table, key] self.client.evalsha args, next , callback count: (table, conditions, opts, callback) -> callback(null, []) unless callback? self = this self.keysFor table, conditions, opts, (err, keys) -> return callback(err) if err? callback(err, [c:keys.length]) clear: (table, callback) -> self = this @client.keys "#{table}:*", (err, keys) -> return callback(err) if callback? and (err? or keys == null or keys.length == 0) self.client.del keys, (err) -> callback(err) if callback? eagerQuery: (association, opts, ids, callback) -> callback() if callback? score: (value) -> if typeof value == "string" score = parseInt crc.crc32(value), 16 return score unless value? and isNaN(value) ==false return "-inf" if typeof value == "number" return value if value instanceof Date return value.getTime() if typeof value == "boolean" return 1 if value == true return 0 if value == false return 0 storageFor: (model, prop, value) -> modelOptions = indexOptions[model] if modelOptions? return modelOptions[prop] if modelOptions[prop]? if typeof value == "boolean" return indexTypes.discrete return indexTypes.series mgetKeys: (keys, callback) -> self = this args = [commands.mhgetAll, 0, keys.length].concat keys self.client.evalsha args, (err, rawResults) -> results = [] if rawResults? for rawResult in rawResults obj = {} i = 0 while i isnt rawResult.length obj[rawResult[i]] = rawResult[i+1] i += 2 results.push obj callback err, results scoreRange: (model, prop, conditions, callback) -> value = null self = this comparator = "eq" if conditions[prop].sql_comparator? comparator = conditions[prop].sql_comparator() value = conditions[prop]["val"] else value = conditions[prop] storage = self.storageFor model, prop, value lowerScore = "-inf" upperScore = "+inf" if comparator == "ne" err = new Error "Unsupported operator" err.code = 4001 return callback err else if comparator == "lt" upperScore = self.score(value) - 1 else if comparator == "lte" upperScore = self.score value else if comparator == "gt" lowerScore = self.score(value) + 1 else if comparator == "gte" lowerScore = self.score value else if comparator == "between" lowerScore = self.score(conditions[prop]["from"]) upperScore = self.score(conditions[prop]["to"]) else if value.length? and typeof value is 'object' scores = [] for v in value scores.push self.score v return callback null, storage, scores, null lowerScore = self.score value upperScore = lowerScore callback null, storage, lowerScore, upperScore keysFor: (table, conditions, opts, callback) -> limit = opts.limit if typeof opts.limit == "number" offset = opts.offset if typeof opts.offset == "number" self = this if conditions == null or Object.keys(conditions).length == 0 self.performZRangeByScore "#{table}:id", "-inf", "inf", limit, offset, (err, keys) -> callback err, keys else if conditions["id"]? idValue = conditions["id"] callback null, ["#{table}:id:#{idValue}"] else async.map Object.keys(conditions), (prop, next) -> #first, let's convert node-orm's conditions from a hash, to an array with redis scores self.scoreRange table, prop, conditions, (err, storage, lowerScore, upperScore) -> return next(err) if err? if storage == indexTypes.discrete op = "set" else if lowerScore.length? and typeof lowerScore is 'object' op = "in" lowerScore = lowerScore.join ',' else op = "between" next err, ["#{table}:#{prop}", op, lowerScore, upperScore] , (err, conditions) -> return callback(err) if err? #now that we have an array we can pass to redis, let's call our Lua function queryId = uuid.v4() offset = 0 unless offset? limit = 999999 unless limit? args = [commands.keysFor, 0, queryId, limit, offset, conditions.length].concat _.flatten(conditions) self.client.evalsha args, (err, keys) -> if keys == "ERROR" err = new Error "Query too large" err.code = 4000 return callback err callback err, keys performZRangeByScore: (key, min, max, limit, offset, callback) -> args = [key, min, max] if limit? or offset? args.push "LIMIT" args.push offset if offset? args.push 0 unless offset? args.push limit if limit? args.push callback @client.zrangebyscore.apply @client, args recheckConditionals: (results, conditions, callback) -> self = this results = [] unless results? async.filter results, (result, next) -> keep = true return next(false) unless result? for prop in Object.keys(conditions) value = null if conditions[prop].sql_comparator? value = conditions[prop]["val"] else value = conditions[prop] if typeof value == "string" if result[prop] != value keep = false break next keep , (results) -> callback null, results module.exports = RedisAdapter
2971
redis = require 'redis' uuid = require 'node-uuid' async = require 'async' crc = require 'crc' fs = require 'fs' path = require 'path' _ = require 'underscore' indexTypes = require './index_types' commands = {} indexOptions = {} class RedisAdapter constructor: (config, connection, opts) -> @client = redis.createClient(config.port, config.host, {}) @customTypes = {} @blank = -> return isSql: false @index: (model, property, indexType) -> modelOptions = indexOptions[model] modelOptions = {} unless modelOptions? modelOptions[property] = indexType indexOptions[model] = modelOptions #Establishes your database connection. connect: (callback) -> self = this rootPath = path.dirname(fs.realpathSync(__filename)) async.series [ (next) -> return next() if commands.keysFor? filename = path.join rootPath, "./keys_for.lua" fs.readFile filename, 'utf8', (err, lua) -> return callback?(err) if err? self.client.script 'load', lua, (err, sha) -> commands.keysFor = sha next(err) (next) -> return next() if commands.mhgetAll? filename = path.join rootPath, "./mhgetall.lua" fs.readFile filename, 'utf8', (err, lua) -> return callback?(err) if err? self.client.script 'load', lua, (err, sha) -> commands.mhgetAll = sha next(err) (next) -> return next() if commands.createIndex? filename = path.join rootPath, "./create_index.lua" fs.readFile filename, 'utf8', (err, lua) -> return callback?(err) if err? self.client.script 'load', lua, (err, sha) -> commands.createIndex = sha next(err) (next) -> return next() if commands.updateIndex? filename = path.join rootPath, "./update_index.lua" fs.readFile filename, 'utf8', (err, lua) -> return callback?(err) if err? self.client.script 'load', lua, (err, sha) -> commands.updateIndex = sha next(err) (next) -> return next() if commands.delete? filename = path.join rootPath, "./delete.lua" fs.readFile filename, 'utf8', (err, lua) -> return callback?(err) if err? self.client.script 'load', lua, (err, sha) -> commands.delete = sha next(err) ], (err) -> alreadyConfiguredLua = true callback(err) if callback? #Tests whether your connection is still alive. ping: (callback) -> callback() if callback? #Closes your database connection. close: (callback) -> @client.quit() if @client? callback() if callback? #Maps an object property to the correlated value to use for the database. propertyToValue: (value, property) -> typeHandler = @customTypes[property.type] if typeHandler and "propertyToValue" of typeHandler return typeHandler.propertyToValue(value) if property["type"] == "number" or property["type"] == "date" return null if isNaN value return value #Maps a database value to the property value to use for the mapped object. valueToProperty: (value, property) -> if property["type"] == "number" v = parseFloat value if isNaN(v) v = null return v if property["type"] == "boolean" return value == 'true' || value == '1' || value == 1 || value == true if property["type"] == "text" if value == 'null' return null if property["type"] == "date" return null unless value? v = new Date Date.parse value if isNaN(v) v = null return v typeHandler = @customTypes[property.type] if typeHandler and "valueToProperty" of typeHandler return typeHandler.valueToProperty(value) return value on: (event, callback) -> return this #@client.on event, callback find: (fields, table, conditions, opts, callback) -> return unless callback? self = this self.keysFor table, conditions, opts, (err, keys) -> return callback(err) if err? self.mgetKeys keys, (err, results) -> return callback(err) if err? self.recheckConditionals results, conditions, callback insert: (table, data, id_prop, callback) -> self = this idName = id_prop[0]["name"] idValue = data[idName] unless idValue? idValue = uuid.v4() data[idName] = idValue key = <KEY> self.client.hmset key, data, (err) -> return callback(err) if err? and callback? props = Object.keys(data) args = [commands.createIndex, 0, props.length] for prop in props value = data[prop] score = self.score value storage = self.storageFor table, prop, value args.push "#{table}:#{prop}" args.push storage args.push score args.push key self.client.evalsha args, (err) -> callback(err, idName: idValue) if callback? update: (table, changes, conditions, callback) -> self = this callback = self.blank unless callback? id = conditions["id"] props = Object.keys changes key = <KEY>id<KEY>}" args = [commands.updateIndex, 0, props.length] for prop in props value = changes[prop] score = self.score value storage = self.storageFor table, prop, value args.push "#{table}:#{prop}" args.push prop args.push storage args.push score args.push value args.push key self.client.evalsha args, (err) -> callback err remove: (table, conditions, callback) -> self = this callback = self.blank unless callback? self.keysFor table, conditions, {}, (err, keys) -> return callback(err) if err? async.eachSeries keys, (key, next) -> args = [commands.delete, 0, table, key] self.client.evalsha args, next , callback count: (table, conditions, opts, callback) -> callback(null, []) unless callback? self = this self.keysFor table, conditions, opts, (err, keys) -> return callback(err) if err? callback(err, [c:keys.length]) clear: (table, callback) -> self = this @client.keys "#{table}:*", (err, keys) -> return callback(err) if callback? and (err? or keys == null or keys.length == 0) self.client.del keys, (err) -> callback(err) if callback? eagerQuery: (association, opts, ids, callback) -> callback() if callback? score: (value) -> if typeof value == "string" score = parseInt crc.crc32(value), 16 return score unless value? and isNaN(value) ==false return "-inf" if typeof value == "number" return value if value instanceof Date return value.getTime() if typeof value == "boolean" return 1 if value == true return 0 if value == false return 0 storageFor: (model, prop, value) -> modelOptions = indexOptions[model] if modelOptions? return modelOptions[prop] if modelOptions[prop]? if typeof value == "boolean" return indexTypes.discrete return indexTypes.series mgetKeys: (keys, callback) -> self = this args = [commands.mhgetAll, 0, keys.length].concat keys self.client.evalsha args, (err, rawResults) -> results = [] if rawResults? for rawResult in rawResults obj = {} i = 0 while i isnt rawResult.length obj[rawResult[i]] = rawResult[i+1] i += 2 results.push obj callback err, results scoreRange: (model, prop, conditions, callback) -> value = null self = this comparator = "eq" if conditions[prop].sql_comparator? comparator = conditions[prop].sql_comparator() value = conditions[prop]["val"] else value = conditions[prop] storage = self.storageFor model, prop, value lowerScore = "-inf" upperScore = "+inf" if comparator == "ne" err = new Error "Unsupported operator" err.code = 4001 return callback err else if comparator == "lt" upperScore = self.score(value) - 1 else if comparator == "lte" upperScore = self.score value else if comparator == "gt" lowerScore = self.score(value) + 1 else if comparator == "gte" lowerScore = self.score value else if comparator == "between" lowerScore = self.score(conditions[prop]["from"]) upperScore = self.score(conditions[prop]["to"]) else if value.length? and typeof value is 'object' scores = [] for v in value scores.push self.score v return callback null, storage, scores, null lowerScore = self.score value upperScore = lowerScore callback null, storage, lowerScore, upperScore keysFor: (table, conditions, opts, callback) -> limit = opts.limit if typeof opts.limit == "number" offset = opts.offset if typeof opts.offset == "number" self = this if conditions == null or Object.keys(conditions).length == 0 self.performZRangeByScore "#{table}:id", "-inf", "inf", limit, offset, (err, keys) -> callback err, keys else if conditions["id"]? idValue = conditions["id"] callback null, ["#{table}:id:#{idValue}"] else async.map Object.keys(conditions), (prop, next) -> #first, let's convert node-orm's conditions from a hash, to an array with redis scores self.scoreRange table, prop, conditions, (err, storage, lowerScore, upperScore) -> return next(err) if err? if storage == indexTypes.discrete op = "set" else if lowerScore.length? and typeof lowerScore is 'object' op = "in" lowerScore = lowerScore.join ',' else op = "between" next err, ["#{table}:#{prop}", op, lowerScore, upperScore] , (err, conditions) -> return callback(err) if err? #now that we have an array we can pass to redis, let's call our Lua function queryId = uuid.v4() offset = 0 unless offset? limit = 999999 unless limit? args = [commands.keysFor, 0, queryId, limit, offset, conditions.length].concat _.flatten(conditions) self.client.evalsha args, (err, keys) -> if keys == "ERROR" err = new Error "Query too large" err.code = 4000 return callback err callback err, keys performZRangeByScore: (key, min, max, limit, offset, callback) -> args = [key, min, max] if limit? or offset? args.push "LIMIT" args.push offset if offset? args.push 0 unless offset? args.push limit if limit? args.push callback @client.zrangebyscore.apply @client, args recheckConditionals: (results, conditions, callback) -> self = this results = [] unless results? async.filter results, (result, next) -> keep = true return next(false) unless result? for prop in Object.keys(conditions) value = null if conditions[prop].sql_comparator? value = conditions[prop]["val"] else value = conditions[prop] if typeof value == "string" if result[prop] != value keep = false break next keep , (results) -> callback null, results module.exports = RedisAdapter
true
redis = require 'redis' uuid = require 'node-uuid' async = require 'async' crc = require 'crc' fs = require 'fs' path = require 'path' _ = require 'underscore' indexTypes = require './index_types' commands = {} indexOptions = {} class RedisAdapter constructor: (config, connection, opts) -> @client = redis.createClient(config.port, config.host, {}) @customTypes = {} @blank = -> return isSql: false @index: (model, property, indexType) -> modelOptions = indexOptions[model] modelOptions = {} unless modelOptions? modelOptions[property] = indexType indexOptions[model] = modelOptions #Establishes your database connection. connect: (callback) -> self = this rootPath = path.dirname(fs.realpathSync(__filename)) async.series [ (next) -> return next() if commands.keysFor? filename = path.join rootPath, "./keys_for.lua" fs.readFile filename, 'utf8', (err, lua) -> return callback?(err) if err? self.client.script 'load', lua, (err, sha) -> commands.keysFor = sha next(err) (next) -> return next() if commands.mhgetAll? filename = path.join rootPath, "./mhgetall.lua" fs.readFile filename, 'utf8', (err, lua) -> return callback?(err) if err? self.client.script 'load', lua, (err, sha) -> commands.mhgetAll = sha next(err) (next) -> return next() if commands.createIndex? filename = path.join rootPath, "./create_index.lua" fs.readFile filename, 'utf8', (err, lua) -> return callback?(err) if err? self.client.script 'load', lua, (err, sha) -> commands.createIndex = sha next(err) (next) -> return next() if commands.updateIndex? filename = path.join rootPath, "./update_index.lua" fs.readFile filename, 'utf8', (err, lua) -> return callback?(err) if err? self.client.script 'load', lua, (err, sha) -> commands.updateIndex = sha next(err) (next) -> return next() if commands.delete? filename = path.join rootPath, "./delete.lua" fs.readFile filename, 'utf8', (err, lua) -> return callback?(err) if err? self.client.script 'load', lua, (err, sha) -> commands.delete = sha next(err) ], (err) -> alreadyConfiguredLua = true callback(err) if callback? #Tests whether your connection is still alive. ping: (callback) -> callback() if callback? #Closes your database connection. close: (callback) -> @client.quit() if @client? callback() if callback? #Maps an object property to the correlated value to use for the database. propertyToValue: (value, property) -> typeHandler = @customTypes[property.type] if typeHandler and "propertyToValue" of typeHandler return typeHandler.propertyToValue(value) if property["type"] == "number" or property["type"] == "date" return null if isNaN value return value #Maps a database value to the property value to use for the mapped object. valueToProperty: (value, property) -> if property["type"] == "number" v = parseFloat value if isNaN(v) v = null return v if property["type"] == "boolean" return value == 'true' || value == '1' || value == 1 || value == true if property["type"] == "text" if value == 'null' return null if property["type"] == "date" return null unless value? v = new Date Date.parse value if isNaN(v) v = null return v typeHandler = @customTypes[property.type] if typeHandler and "valueToProperty" of typeHandler return typeHandler.valueToProperty(value) return value on: (event, callback) -> return this #@client.on event, callback find: (fields, table, conditions, opts, callback) -> return unless callback? self = this self.keysFor table, conditions, opts, (err, keys) -> return callback(err) if err? self.mgetKeys keys, (err, results) -> return callback(err) if err? self.recheckConditionals results, conditions, callback insert: (table, data, id_prop, callback) -> self = this idName = id_prop[0]["name"] idValue = data[idName] unless idValue? idValue = uuid.v4() data[idName] = idValue key = PI:KEY:<KEY>END_PI self.client.hmset key, data, (err) -> return callback(err) if err? and callback? props = Object.keys(data) args = [commands.createIndex, 0, props.length] for prop in props value = data[prop] score = self.score value storage = self.storageFor table, prop, value args.push "#{table}:#{prop}" args.push storage args.push score args.push key self.client.evalsha args, (err) -> callback(err, idName: idValue) if callback? update: (table, changes, conditions, callback) -> self = this callback = self.blank unless callback? id = conditions["id"] props = Object.keys changes key = PI:KEY:<KEY>END_PIidPI:KEY:<KEY>END_PI}" args = [commands.updateIndex, 0, props.length] for prop in props value = changes[prop] score = self.score value storage = self.storageFor table, prop, value args.push "#{table}:#{prop}" args.push prop args.push storage args.push score args.push value args.push key self.client.evalsha args, (err) -> callback err remove: (table, conditions, callback) -> self = this callback = self.blank unless callback? self.keysFor table, conditions, {}, (err, keys) -> return callback(err) if err? async.eachSeries keys, (key, next) -> args = [commands.delete, 0, table, key] self.client.evalsha args, next , callback count: (table, conditions, opts, callback) -> callback(null, []) unless callback? self = this self.keysFor table, conditions, opts, (err, keys) -> return callback(err) if err? callback(err, [c:keys.length]) clear: (table, callback) -> self = this @client.keys "#{table}:*", (err, keys) -> return callback(err) if callback? and (err? or keys == null or keys.length == 0) self.client.del keys, (err) -> callback(err) if callback? eagerQuery: (association, opts, ids, callback) -> callback() if callback? score: (value) -> if typeof value == "string" score = parseInt crc.crc32(value), 16 return score unless value? and isNaN(value) ==false return "-inf" if typeof value == "number" return value if value instanceof Date return value.getTime() if typeof value == "boolean" return 1 if value == true return 0 if value == false return 0 storageFor: (model, prop, value) -> modelOptions = indexOptions[model] if modelOptions? return modelOptions[prop] if modelOptions[prop]? if typeof value == "boolean" return indexTypes.discrete return indexTypes.series mgetKeys: (keys, callback) -> self = this args = [commands.mhgetAll, 0, keys.length].concat keys self.client.evalsha args, (err, rawResults) -> results = [] if rawResults? for rawResult in rawResults obj = {} i = 0 while i isnt rawResult.length obj[rawResult[i]] = rawResult[i+1] i += 2 results.push obj callback err, results scoreRange: (model, prop, conditions, callback) -> value = null self = this comparator = "eq" if conditions[prop].sql_comparator? comparator = conditions[prop].sql_comparator() value = conditions[prop]["val"] else value = conditions[prop] storage = self.storageFor model, prop, value lowerScore = "-inf" upperScore = "+inf" if comparator == "ne" err = new Error "Unsupported operator" err.code = 4001 return callback err else if comparator == "lt" upperScore = self.score(value) - 1 else if comparator == "lte" upperScore = self.score value else if comparator == "gt" lowerScore = self.score(value) + 1 else if comparator == "gte" lowerScore = self.score value else if comparator == "between" lowerScore = self.score(conditions[prop]["from"]) upperScore = self.score(conditions[prop]["to"]) else if value.length? and typeof value is 'object' scores = [] for v in value scores.push self.score v return callback null, storage, scores, null lowerScore = self.score value upperScore = lowerScore callback null, storage, lowerScore, upperScore keysFor: (table, conditions, opts, callback) -> limit = opts.limit if typeof opts.limit == "number" offset = opts.offset if typeof opts.offset == "number" self = this if conditions == null or Object.keys(conditions).length == 0 self.performZRangeByScore "#{table}:id", "-inf", "inf", limit, offset, (err, keys) -> callback err, keys else if conditions["id"]? idValue = conditions["id"] callback null, ["#{table}:id:#{idValue}"] else async.map Object.keys(conditions), (prop, next) -> #first, let's convert node-orm's conditions from a hash, to an array with redis scores self.scoreRange table, prop, conditions, (err, storage, lowerScore, upperScore) -> return next(err) if err? if storage == indexTypes.discrete op = "set" else if lowerScore.length? and typeof lowerScore is 'object' op = "in" lowerScore = lowerScore.join ',' else op = "between" next err, ["#{table}:#{prop}", op, lowerScore, upperScore] , (err, conditions) -> return callback(err) if err? #now that we have an array we can pass to redis, let's call our Lua function queryId = uuid.v4() offset = 0 unless offset? limit = 999999 unless limit? args = [commands.keysFor, 0, queryId, limit, offset, conditions.length].concat _.flatten(conditions) self.client.evalsha args, (err, keys) -> if keys == "ERROR" err = new Error "Query too large" err.code = 4000 return callback err callback err, keys performZRangeByScore: (key, min, max, limit, offset, callback) -> args = [key, min, max] if limit? or offset? args.push "LIMIT" args.push offset if offset? args.push 0 unless offset? args.push limit if limit? args.push callback @client.zrangebyscore.apply @client, args recheckConditionals: (results, conditions, callback) -> self = this results = [] unless results? async.filter results, (result, next) -> keep = true return next(false) unless result? for prop in Object.keys(conditions) value = null if conditions[prop].sql_comparator? value = conditions[prop]["val"] else value = conditions[prop] if typeof value == "string" if result[prop] != value keep = false break next keep , (results) -> callback null, results module.exports = RedisAdapter
[ { "context": "data.id, 'bob'\n assert.equal data.name, 'bob'\n assert.equal data.age, 35\n\n 'getS", "end": 3098, "score": 0.9973537921905518, "start": 3095, "tag": "NAME", "value": "bob" }, { "context": "data.id, 'bob'\n assert.equal data.name, 'bob'\...
node_modules/resources/persistence/vendor/jugglingdb/lib/nosqlite/test/database-test.coffee
manecz/storytail
0
vows = require 'vows' assert = require 'assert' fs = require 'fs' path = require 'path' nosqlite = require '../src/nosqlite' connection = new(nosqlite.Connection) path.resolve(__dirname, 'fixtures') vows .describe('database') .addBatch 'Database "test"': topic: () -> connection.database 'test' 'should have "dir"': (db) -> assert.equal db.dir, path.resolve(__dirname, 'fixtures/test') 'should have "name"': (db) -> assert.equal db.name, 'test' 'exists()': topic: (db) -> db.exists @callback 'should be successful': (exists) -> assert.isTrue exists 'existsSync()': topic: (db) -> db.existsSync() 'should be successful': (exists) -> assert.isTrue exists 'create()': topic: (db) -> db 'should throw error': (db) -> assert.throws db.create() .addBatch 'Database "dummy"': topic: () -> connection.database 'dummy' 'should have "dir"': (db) -> assert.equal db.dir, path.resolve(__dirname, 'fixtures/dummy') 'should have "name"': (db) -> assert.equal db.name, 'dummy' 'exists()': topic: (db) -> db.exists @callback 'should be successful': (exists) -> assert.isFalse exists 'existsSync()': topic: (db) -> db.existsSync() 'should be successful': (exists) -> assert.isFalse exists .addBatch 'Database "dummy"': topic: () -> connection.database 'dummy' 'create()': topic: (db) -> db.create @callback 'should be successful': (ex) -> assert.isUndefined ex assert.isTrue path.existsSync(path.resolve(__dirname, 'fixtures/dummy')) .addBatch 'Database "dummy"': topic: () -> connection.database 'dummy' 'destroy()': topic: (db) -> db.destroy @callback 'should be successful': (ex) -> assert.isUndefined ex assert.isFalse path.existsSync(path.resolve(__dirname, 'fixtures/dummy')) .addBatch 'Database "dummy"': topic: () -> connection.database 'dummy' 'createSync()': topic: (db) -> db 'should be successful': (db) -> assert.isUndefined db.createSync() assert.isTrue path.existsSync(path.resolve(__dirname, 'fixtures/dummy')) .addBatch 'Database "dummy"': topic: () -> connection.database 'dummy' 'destroySync()': topic: (db) -> db 'should be successful': (db) -> assert.isUndefined db.destroySync() assert.isFalse path.existsSync(path.resolve(__dirname, 'fixtures/dummy')) .addBatch 'Database "test"': topic: () -> connection.database 'test' 'get()': topic: (db) -> db.get 'bob', @callback 'should be successful': (err, data) -> assert.isNull err assert.equal data.id, 'bob' assert.equal data.name, 'bob' assert.equal data.age, 35 'getSync()': topic: (db) -> db.getSync 'bob' 'should be successful': (data) -> assert.equal data.id, 'bob' assert.equal data.name, 'bob' assert.equal data.age, 35 'get() non-existing': topic: (db) -> db.get 'tim', @callback 'should throw error': (err, data) -> assert.isUndefined data assert.equal err.code, 'ENOENT' 'getSync() non-existing': topic: (db) -> db 'should throw error': (db) -> assert.throws -> db.getSync 'tim' .addBatch 'Database "test"': topic: () -> connection.database 'test' 'post()': topic: (db) -> db.post id: 'tim' name: 'tim' age: 31 , @callback 'should be successful': (err) -> assert.isUndefined err .addBatch 'Database "test"': topic: () -> connection.database 'test' 'post() should save': topic: (db) -> db.getSync 'tim' 'successfully': (data) -> assert.equal data.id, 'tim' assert.equal data.name, 'tim' assert.equal data.age, 31 .addBatch 'Database "test"': topic: () -> connection.database 'test' 'delete()': topic: (db) -> db.delete 'tim', @callback 'should be successful': (err) -> assert.isUndefined err .addBatch 'Database "test"': topic: () -> connection.database 'test' 'delete() should remove': topic: (db) -> db.get 'tim', @callback 'successfully': (err, data) -> assert.isUndefined data assert.equal err.code, 'ENOENT' .addBatch 'Database "test"': topic: () -> connection.database 'test' 'postSync()': topic: (db) -> db 'should be successful': (db) -> assert.doesNotThrow -> db.postSync id: 'tim' name: 'tim' age: 31 .addBatch 'Database "test"': topic: () -> connection.database 'test' 'postSync() should save': topic: (db) -> db.getSync 'tim' 'successfully': (data) -> assert.equal data.id, 'tim' assert.equal data.name, 'tim' assert.equal data.age, 31 .addBatch 'Database "test"': topic: () -> connection.database 'test' 'deleteSync()': topic: (db) -> db 'should be successful': (db) -> assert.doesNotThrow -> db.deleteSync 'tim' .addBatch 'Database "test"': topic: () -> connection.database 'test' 'deleteSync() should remove': topic: (db) -> db.get 'tim', @callback 'successfully': (err, data) -> assert.isUndefined data assert.equal err.code, 'ENOENT' .addBatch 'Database "test"': topic: () -> connection.database 'test' # 'delete() non-existing': # topic: (db) -> # db.delete 'tim', @callback # 'should throw error': (err) -> # assert.equal err.code, 'ENOENT' .addBatch 'Database "test"': topic: () -> connection.database 'test' 'deleteSync() non-existing': topic: (db) -> db 'should throw error': (db) -> assert.throws -> db.deleteSync 'tim' .addBatch 'Database "test"': topic: () -> connection.database 'test' 'all()': topic: (db) -> db.all @callback 'should be successful': (docs) -> assert.equal docs.length, 1 assert.equal docs[0].id, 'bob' assert.equal docs[0].name, 'bob' assert.equal docs[0].age, 35 'allSync()': topic: (db) -> db.allSync() 'should be successful': (docs) -> assert.equal docs.length, 1 assert.equal docs[0].id, 'bob' assert.equal docs[0].name, 'bob' assert.equal docs[0].age, 35 .addBatch 'Database "test"': topic: () -> connection.database 'test' 'find()': topic: (db) -> db.find age: 35, @callback 'should be successful': (docs) -> assert.equal docs.length, 1 assert.equal docs[0].id, 'bob' assert.equal docs[0].name, 'bob' assert.equal docs[0].age, 35 'findSync()': topic: (db) -> db.findSync age: 35 'should be successful': (docs) -> assert.equal docs.length, 1 assert.equal docs[0].id, 'bob' assert.equal docs[0].name, 'bob' assert.equal docs[0].age, 35 'find() empty': topic: (db) -> db.find age: 31, @callback 'should be successful': (docs) -> assert.equal docs.length, 0 'findSync() empty': topic: (db) -> db.findSync age: 31 'should be successful': (docs) -> assert.equal docs.length, 0 .addBatch 'Database "test"': topic: () -> connection.database 'test' 'put()': topic: (db) -> db.put 'bob', age: 31, @callback 'should be successful': (err) -> assert.isUndefined err .addBatch 'Database "test"': topic: () -> connection.database 'test' 'should be saved': topic: (db) -> db.getSync 'bob' 'successfully': (data) -> assert.equal data.age, 31 .addBatch 'Database "test"': topic: () -> connection.database 'test' 'putSync()': topic: (db) -> db 'should be successful': (db) -> assert.doesNotThrow -> db.putSync 'bob', age: 35 .addBatch 'Database "test"': topic: () -> connection.database 'test' 'should be saved': topic: (db) -> db.getSync 'bob' 'successfully': (data) -> assert.equal data.age, 35 .export(module)
179548
vows = require 'vows' assert = require 'assert' fs = require 'fs' path = require 'path' nosqlite = require '../src/nosqlite' connection = new(nosqlite.Connection) path.resolve(__dirname, 'fixtures') vows .describe('database') .addBatch 'Database "test"': topic: () -> connection.database 'test' 'should have "dir"': (db) -> assert.equal db.dir, path.resolve(__dirname, 'fixtures/test') 'should have "name"': (db) -> assert.equal db.name, 'test' 'exists()': topic: (db) -> db.exists @callback 'should be successful': (exists) -> assert.isTrue exists 'existsSync()': topic: (db) -> db.existsSync() 'should be successful': (exists) -> assert.isTrue exists 'create()': topic: (db) -> db 'should throw error': (db) -> assert.throws db.create() .addBatch 'Database "dummy"': topic: () -> connection.database 'dummy' 'should have "dir"': (db) -> assert.equal db.dir, path.resolve(__dirname, 'fixtures/dummy') 'should have "name"': (db) -> assert.equal db.name, 'dummy' 'exists()': topic: (db) -> db.exists @callback 'should be successful': (exists) -> assert.isFalse exists 'existsSync()': topic: (db) -> db.existsSync() 'should be successful': (exists) -> assert.isFalse exists .addBatch 'Database "dummy"': topic: () -> connection.database 'dummy' 'create()': topic: (db) -> db.create @callback 'should be successful': (ex) -> assert.isUndefined ex assert.isTrue path.existsSync(path.resolve(__dirname, 'fixtures/dummy')) .addBatch 'Database "dummy"': topic: () -> connection.database 'dummy' 'destroy()': topic: (db) -> db.destroy @callback 'should be successful': (ex) -> assert.isUndefined ex assert.isFalse path.existsSync(path.resolve(__dirname, 'fixtures/dummy')) .addBatch 'Database "dummy"': topic: () -> connection.database 'dummy' 'createSync()': topic: (db) -> db 'should be successful': (db) -> assert.isUndefined db.createSync() assert.isTrue path.existsSync(path.resolve(__dirname, 'fixtures/dummy')) .addBatch 'Database "dummy"': topic: () -> connection.database 'dummy' 'destroySync()': topic: (db) -> db 'should be successful': (db) -> assert.isUndefined db.destroySync() assert.isFalse path.existsSync(path.resolve(__dirname, 'fixtures/dummy')) .addBatch 'Database "test"': topic: () -> connection.database 'test' 'get()': topic: (db) -> db.get 'bob', @callback 'should be successful': (err, data) -> assert.isNull err assert.equal data.id, 'bob' assert.equal data.name, '<NAME>' assert.equal data.age, 35 'getSync()': topic: (db) -> db.getSync 'bob' 'should be successful': (data) -> assert.equal data.id, 'bob' assert.equal data.name, '<NAME>' assert.equal data.age, 35 'get() non-existing': topic: (db) -> db.get 'tim', @callback 'should throw error': (err, data) -> assert.isUndefined data assert.equal err.code, 'ENOENT' 'getSync() non-existing': topic: (db) -> db 'should throw error': (db) -> assert.throws -> db.getSync 'tim' .addBatch 'Database "test"': topic: () -> connection.database 'test' 'post()': topic: (db) -> db.post id: 'tim' name: '<NAME>' age: 31 , @callback 'should be successful': (err) -> assert.isUndefined err .addBatch 'Database "test"': topic: () -> connection.database 'test' 'post() should save': topic: (db) -> db.getSync 'tim' 'successfully': (data) -> assert.equal data.id, '<NAME>' assert.equal data.name, '<NAME>' assert.equal data.age, 31 .addBatch 'Database "test"': topic: () -> connection.database 'test' 'delete()': topic: (db) -> db.delete 'tim', @callback 'should be successful': (err) -> assert.isUndefined err .addBatch 'Database "test"': topic: () -> connection.database 'test' 'delete() should remove': topic: (db) -> db.get 'tim', @callback 'successfully': (err, data) -> assert.isUndefined data assert.equal err.code, 'ENOENT' .addBatch 'Database "test"': topic: () -> connection.database 'test' 'postSync()': topic: (db) -> db 'should be successful': (db) -> assert.doesNotThrow -> db.postSync id: '<NAME>' name: '<NAME>' age: 31 .addBatch 'Database "test"': topic: () -> connection.database 'test' 'postSync() should save': topic: (db) -> db.getSync 'tim' 'successfully': (data) -> assert.equal data.id, '<NAME>' assert.equal data.name, '<NAME>' assert.equal data.age, 31 .addBatch 'Database "test"': topic: () -> connection.database 'test' 'deleteSync()': topic: (db) -> db 'should be successful': (db) -> assert.doesNotThrow -> db.deleteSync 'tim' .addBatch 'Database "test"': topic: () -> connection.database 'test' 'deleteSync() should remove': topic: (db) -> db.get 'tim', @callback 'successfully': (err, data) -> assert.isUndefined data assert.equal err.code, 'ENOENT' .addBatch 'Database "test"': topic: () -> connection.database 'test' # 'delete() non-existing': # topic: (db) -> # db.delete 'tim', @callback # 'should throw error': (err) -> # assert.equal err.code, 'ENOENT' .addBatch 'Database "test"': topic: () -> connection.database 'test' 'deleteSync() non-existing': topic: (db) -> db 'should throw error': (db) -> assert.throws -> db.deleteSync 'tim' .addBatch 'Database "test"': topic: () -> connection.database 'test' 'all()': topic: (db) -> db.all @callback 'should be successful': (docs) -> assert.equal docs.length, 1 assert.equal docs[0].id, 'bob' assert.equal docs[0].name, '<NAME>' assert.equal docs[0].age, 35 'allSync()': topic: (db) -> db.allSync() 'should be successful': (docs) -> assert.equal docs.length, 1 assert.equal docs[0].id, 'bob' assert.equal docs[0].name, '<NAME>' assert.equal docs[0].age, 35 .addBatch 'Database "test"': topic: () -> connection.database 'test' 'find()': topic: (db) -> db.find age: 35, @callback 'should be successful': (docs) -> assert.equal docs.length, 1 assert.equal docs[0].id, 'bob' assert.equal docs[0].name, '<NAME>' assert.equal docs[0].age, 35 'findSync()': topic: (db) -> db.findSync age: 35 'should be successful': (docs) -> assert.equal docs.length, 1 assert.equal docs[0].id, 'bob' assert.equal docs[0].name, '<NAME>' assert.equal docs[0].age, 35 'find() empty': topic: (db) -> db.find age: 31, @callback 'should be successful': (docs) -> assert.equal docs.length, 0 'findSync() empty': topic: (db) -> db.findSync age: 31 'should be successful': (docs) -> assert.equal docs.length, 0 .addBatch 'Database "test"': topic: () -> connection.database 'test' 'put()': topic: (db) -> db.put 'bob', age: 31, @callback 'should be successful': (err) -> assert.isUndefined err .addBatch 'Database "test"': topic: () -> connection.database 'test' 'should be saved': topic: (db) -> db.getSync 'bob' 'successfully': (data) -> assert.equal data.age, 31 .addBatch 'Database "test"': topic: () -> connection.database 'test' 'putSync()': topic: (db) -> db 'should be successful': (db) -> assert.doesNotThrow -> db.putSync 'bob', age: 35 .addBatch 'Database "test"': topic: () -> connection.database 'test' 'should be saved': topic: (db) -> db.getSync 'bob' 'successfully': (data) -> assert.equal data.age, 35 .export(module)
true
vows = require 'vows' assert = require 'assert' fs = require 'fs' path = require 'path' nosqlite = require '../src/nosqlite' connection = new(nosqlite.Connection) path.resolve(__dirname, 'fixtures') vows .describe('database') .addBatch 'Database "test"': topic: () -> connection.database 'test' 'should have "dir"': (db) -> assert.equal db.dir, path.resolve(__dirname, 'fixtures/test') 'should have "name"': (db) -> assert.equal db.name, 'test' 'exists()': topic: (db) -> db.exists @callback 'should be successful': (exists) -> assert.isTrue exists 'existsSync()': topic: (db) -> db.existsSync() 'should be successful': (exists) -> assert.isTrue exists 'create()': topic: (db) -> db 'should throw error': (db) -> assert.throws db.create() .addBatch 'Database "dummy"': topic: () -> connection.database 'dummy' 'should have "dir"': (db) -> assert.equal db.dir, path.resolve(__dirname, 'fixtures/dummy') 'should have "name"': (db) -> assert.equal db.name, 'dummy' 'exists()': topic: (db) -> db.exists @callback 'should be successful': (exists) -> assert.isFalse exists 'existsSync()': topic: (db) -> db.existsSync() 'should be successful': (exists) -> assert.isFalse exists .addBatch 'Database "dummy"': topic: () -> connection.database 'dummy' 'create()': topic: (db) -> db.create @callback 'should be successful': (ex) -> assert.isUndefined ex assert.isTrue path.existsSync(path.resolve(__dirname, 'fixtures/dummy')) .addBatch 'Database "dummy"': topic: () -> connection.database 'dummy' 'destroy()': topic: (db) -> db.destroy @callback 'should be successful': (ex) -> assert.isUndefined ex assert.isFalse path.existsSync(path.resolve(__dirname, 'fixtures/dummy')) .addBatch 'Database "dummy"': topic: () -> connection.database 'dummy' 'createSync()': topic: (db) -> db 'should be successful': (db) -> assert.isUndefined db.createSync() assert.isTrue path.existsSync(path.resolve(__dirname, 'fixtures/dummy')) .addBatch 'Database "dummy"': topic: () -> connection.database 'dummy' 'destroySync()': topic: (db) -> db 'should be successful': (db) -> assert.isUndefined db.destroySync() assert.isFalse path.existsSync(path.resolve(__dirname, 'fixtures/dummy')) .addBatch 'Database "test"': topic: () -> connection.database 'test' 'get()': topic: (db) -> db.get 'bob', @callback 'should be successful': (err, data) -> assert.isNull err assert.equal data.id, 'bob' assert.equal data.name, 'PI:NAME:<NAME>END_PI' assert.equal data.age, 35 'getSync()': topic: (db) -> db.getSync 'bob' 'should be successful': (data) -> assert.equal data.id, 'bob' assert.equal data.name, 'PI:NAME:<NAME>END_PI' assert.equal data.age, 35 'get() non-existing': topic: (db) -> db.get 'tim', @callback 'should throw error': (err, data) -> assert.isUndefined data assert.equal err.code, 'ENOENT' 'getSync() non-existing': topic: (db) -> db 'should throw error': (db) -> assert.throws -> db.getSync 'tim' .addBatch 'Database "test"': topic: () -> connection.database 'test' 'post()': topic: (db) -> db.post id: 'tim' name: 'PI:NAME:<NAME>END_PI' age: 31 , @callback 'should be successful': (err) -> assert.isUndefined err .addBatch 'Database "test"': topic: () -> connection.database 'test' 'post() should save': topic: (db) -> db.getSync 'tim' 'successfully': (data) -> assert.equal data.id, 'PI:NAME:<NAME>END_PI' assert.equal data.name, 'PI:NAME:<NAME>END_PI' assert.equal data.age, 31 .addBatch 'Database "test"': topic: () -> connection.database 'test' 'delete()': topic: (db) -> db.delete 'tim', @callback 'should be successful': (err) -> assert.isUndefined err .addBatch 'Database "test"': topic: () -> connection.database 'test' 'delete() should remove': topic: (db) -> db.get 'tim', @callback 'successfully': (err, data) -> assert.isUndefined data assert.equal err.code, 'ENOENT' .addBatch 'Database "test"': topic: () -> connection.database 'test' 'postSync()': topic: (db) -> db 'should be successful': (db) -> assert.doesNotThrow -> db.postSync id: 'PI:NAME:<NAME>END_PI' name: 'PI:NAME:<NAME>END_PI' age: 31 .addBatch 'Database "test"': topic: () -> connection.database 'test' 'postSync() should save': topic: (db) -> db.getSync 'tim' 'successfully': (data) -> assert.equal data.id, 'PI:NAME:<NAME>END_PI' assert.equal data.name, 'PI:NAME:<NAME>END_PI' assert.equal data.age, 31 .addBatch 'Database "test"': topic: () -> connection.database 'test' 'deleteSync()': topic: (db) -> db 'should be successful': (db) -> assert.doesNotThrow -> db.deleteSync 'tim' .addBatch 'Database "test"': topic: () -> connection.database 'test' 'deleteSync() should remove': topic: (db) -> db.get 'tim', @callback 'successfully': (err, data) -> assert.isUndefined data assert.equal err.code, 'ENOENT' .addBatch 'Database "test"': topic: () -> connection.database 'test' # 'delete() non-existing': # topic: (db) -> # db.delete 'tim', @callback # 'should throw error': (err) -> # assert.equal err.code, 'ENOENT' .addBatch 'Database "test"': topic: () -> connection.database 'test' 'deleteSync() non-existing': topic: (db) -> db 'should throw error': (db) -> assert.throws -> db.deleteSync 'tim' .addBatch 'Database "test"': topic: () -> connection.database 'test' 'all()': topic: (db) -> db.all @callback 'should be successful': (docs) -> assert.equal docs.length, 1 assert.equal docs[0].id, 'bob' assert.equal docs[0].name, 'PI:NAME:<NAME>END_PI' assert.equal docs[0].age, 35 'allSync()': topic: (db) -> db.allSync() 'should be successful': (docs) -> assert.equal docs.length, 1 assert.equal docs[0].id, 'bob' assert.equal docs[0].name, 'PI:NAME:<NAME>END_PI' assert.equal docs[0].age, 35 .addBatch 'Database "test"': topic: () -> connection.database 'test' 'find()': topic: (db) -> db.find age: 35, @callback 'should be successful': (docs) -> assert.equal docs.length, 1 assert.equal docs[0].id, 'bob' assert.equal docs[0].name, 'PI:NAME:<NAME>END_PI' assert.equal docs[0].age, 35 'findSync()': topic: (db) -> db.findSync age: 35 'should be successful': (docs) -> assert.equal docs.length, 1 assert.equal docs[0].id, 'bob' assert.equal docs[0].name, 'PI:NAME:<NAME>END_PI' assert.equal docs[0].age, 35 'find() empty': topic: (db) -> db.find age: 31, @callback 'should be successful': (docs) -> assert.equal docs.length, 0 'findSync() empty': topic: (db) -> db.findSync age: 31 'should be successful': (docs) -> assert.equal docs.length, 0 .addBatch 'Database "test"': topic: () -> connection.database 'test' 'put()': topic: (db) -> db.put 'bob', age: 31, @callback 'should be successful': (err) -> assert.isUndefined err .addBatch 'Database "test"': topic: () -> connection.database 'test' 'should be saved': topic: (db) -> db.getSync 'bob' 'successfully': (data) -> assert.equal data.age, 31 .addBatch 'Database "test"': topic: () -> connection.database 'test' 'putSync()': topic: (db) -> db 'should be successful': (db) -> assert.doesNotThrow -> db.putSync 'bob', age: 35 .addBatch 'Database "test"': topic: () -> connection.database 'test' 'should be saved': topic: (db) -> db.getSync 'bob' 'successfully': (data) -> assert.equal data.age, 35 .export(module)
[ { "context": "brous ->\n model = @model.sync.create { key: '123', name: 'apple' }\n model.name = 'orange'\n\n ", "end": 2368, "score": 0.9990875124931335, "start": 2365, "tag": "KEY", "value": "123" }, { "context": "ibrous ->\n model = @model.sync.create name: 'Apple'...
test/normal_schema/put/put_one.coffee
goodeggs/resource-schema
3
fibrous = require 'fibrous' mongoose = require 'mongoose' expect = require('chai').expect mongoose = require 'mongoose' sinon = require 'sinon' {suite, given} = require '../../support/helpers' ResourceSchema = require '../../..' suite 'PUT one', ({withModel, withServer}) -> given 'updating model values', -> withModel (mongoose) -> mongoose.Schema name: String beforeEach -> schema = { '_id', 'name' } @resource = new ResourceSchema @model, schema withServer (app) -> app.put '/res/:_id', @resource.put('_id'), @resource.send app beforeEach fibrous -> model = @model.sync.create name: 'orange' model.name = 'apple' @response = @request.sync.put "/res/#{model._id}", json: {name: 'apple'} it 'returns the saved resources', fibrous -> expect(@response.statusCode).to.equal 200 expect(@response.body.name).to.equal 'apple' expect(@response.body._id).to.be.ok it 'saves the updated model to the DB', fibrous -> modelsFound = @model.sync.find() expect(modelsFound.length).to.equal 1 expect(modelsFound[0].name).to.equal 'apple' given 'updating falsy values', -> withModel (mongoose) -> mongoose.Schema active: Boolean beforeEach -> schema = { '_id', 'active' } @resource = new ResourceSchema @model, schema withServer (app) -> app.put '/res/:_id', @resource.put('_id'), @resource.send app it 'updates the falsy value', fibrous -> model = @model.sync.create { active: true } model.active = false response = @request.sync.put "/res/#{model._id}", json: {active: false} expect(response.statusCode).to.equal 200 expect(response.body.active).to.equal false expect(response.body._id).to.be.ok modelsFound = @model.sync.find() expect(modelsFound.length).to.equal 1 expect(modelsFound[0].active).to.equal false given 'putting to a custom key (not _id)', -> withModel (mongoose) -> mongoose.Schema key: type: String name: String beforeEach -> schema = { 'key', 'name' } @resource = new ResourceSchema @model, schema withServer (app) -> app.put '/res/:key', @resource.put('key'), @resource.send app it 'updates the resource', fibrous -> model = @model.sync.create { key: '123', name: 'apple' } model.name = 'orange' response = @request.sync.put "/res/#{model.key}", json: model expect(response.statusCode).to.equal 200 expect(response.body.name).to.equal 'orange' modelsFound = @model.sync.find() expect(modelsFound.length).to.equal 1 expect(modelsFound[0].name).to.equal 'orange' @model.sync.remove() given 'putting to uncreated resource (upserting)', -> withModel (mongoose) -> mongoose.Schema name: String beforeEach -> schema = { '_id', 'name' } @resource = new ResourceSchema @model, schema withServer (app) -> app.put '/res/:_id', @resource.put('_id'), @resource.send app it 'upserts the resource', fibrous -> newId = new mongoose.Types.ObjectId() response = @request.sync.put "/res/#{newId}", json: {name: 'apple'} expect(response.statusCode).to.equal 200 expect(response.body.name).to.equal 'apple' expect(response.body._id).to.equal newId.toString() modelsFound = @model.sync.find() expect(modelsFound.length).to.equal 1 expect(modelsFound[0].name).to.equal 'apple' given 'PUT resource with set field', -> withModel (mongoose) -> mongoose.Schema name: String beforeEach -> schema = { '_id' 'name': field: 'name' set: (resource) -> resource.name.toLowerCase() } @resource = new ResourceSchema @model, schema withServer (app) -> app.put '/res/:_id', @resource.put('_id'), @resource.send app it 'applies the setter', fibrous -> model = @model.sync.create name: 'Apple' response = @request.sync.put "/res/#{model._id}", json: model expect(response.statusCode).to.equal 200 expect(response.body.name).to.equal 'apple' expect(response.body._id).to.be.ok modelsFound = @model.sync.find() expect(modelsFound.length).to.equal 1 expect(modelsFound[0].name).to.equal 'apple' given 'PUT resource with optional fields', -> withModel (mongoose) -> mongoose.Schema name: String age: Number beforeEach -> schema = { '_id' 'name' 'age': optional: true field: 'age' 'score': optional: true get: -> 95 } @resource = new ResourceSchema @model, schema withServer (app) -> app.put '/res/:_id', @resource.put('_id'), @resource.send app it 'returns the optional field if it is included in the request body', fibrous -> model = @model.sync.create name: 'bob' age: 10 response = @request.sync.put "/res/#{model._id}", json: name: 'joe' age: 10 score: 95 expect(response.statusCode).to.equal 200 expect(response.body.name).to.equal 'joe' expect(response.body.score).to.equal 95 expect(response.body.age).to.equal 10 it 'does not return the optional field if it is not included in the request body', fibrous -> model = @model.sync.create name: 'bob' age: 10 response = @request.sync.put "/res/#{model._id}", json: {name: 'joe'} expect(response.statusCode).to.equal 200 expect(response.body.name).to.equal 'joe' expect(response.body.score).to.be.undefined expect(response.body.age).to.be.undefined given 'default on mongoose model', -> withModel (mongoose) -> mongoose.Schema name: {type: String, default: 'foo'} withServer (app) -> @resource = new ResourceSchema @model, {'_id', 'name'} app.put '/bar/:_id', @resource.put('_id'), @resource.send it 'uses the mongoose schema defaults', fibrous -> _id = new mongoose.Types.ObjectId() response = @request.sync.put "/bar/#{_id}", json: {} expect(response.body).to.have.property '_id' expect(response.body).to.have.property 'name', 'foo' given 'save hooks on mongoose model', -> saveSpy = sinon.spy() withModel (mongoose) -> schema = mongoose.Schema name: String schema.pre 'save', (next) -> saveSpy() next() withServer (app) -> @resource = new ResourceSchema @model, {'_id', 'name'} app.put '/fruit/:_id', @resource.put('_id'), @resource.send beforeEach fibrous -> @apple = @model.sync.create name: 'apple' saveSpy.reset() it 'calls the save hook', fibrous -> @request.sync.put "/fruit/#{@apple._id}", json: {name: 'orange'} expect(saveSpy.callCount).to.equal 1 given 'schema with nested requires', -> saveSpy = sinon.spy() withModel (mongoose) -> mongoose.Schema name: String siblings: [ name: String age: type: Number, required: true ] withServer (app) -> @resource = new ResourceSchema @model, {'_id', 'name', 'siblings'} app.put '/person/:_id', @resource.put('_id'), @resource.send beforeEach fibrous -> @michael = @model.sync.create name: 'Michael', siblings: [ {name: 'Matthew', age: 33}, {name: 'Jon', age: 38} ] it 'allows you to remove and update items in the array', fibrous -> response = @request.sync.put "/person/#{@michael._id}", json: {siblings: [{name: 'Jon', age:39, _id: @michael.siblings[1]._id}]} expect(response.statusCode).to.equal 200 given 'mongoose model field with default is already set, and resource does not contain the field', -> withModel (mongoose) -> mongoose.Schema name: String # mongoose arrays default to an empty array siblings: [ name: String age: type: Number, required: true ] withServer (app) -> # resource does not contain the array... @resource = new ResourceSchema @model, {'_id', 'name'} app.put '/person/:_id', @resource.put('_id'), @resource.send beforeEach fibrous -> @michael = @model.sync.create name: 'Michael', siblings: [ {name: 'Matthew', age: 33}, {name: 'Jon', age: 38} ] it 'does not overwrite the model value with the default value', fibrous -> response = @request.sync.put "/person/#{@michael._id}", json: name: 'Max' expect(response.statusCode).to.equal 200 model = @model.sync.findById @michael._id # the array still has both items (it was not overwritten with an empty array) expect(model.siblings).to.have.length 2
202913
fibrous = require 'fibrous' mongoose = require 'mongoose' expect = require('chai').expect mongoose = require 'mongoose' sinon = require 'sinon' {suite, given} = require '../../support/helpers' ResourceSchema = require '../../..' suite 'PUT one', ({withModel, withServer}) -> given 'updating model values', -> withModel (mongoose) -> mongoose.Schema name: String beforeEach -> schema = { '_id', 'name' } @resource = new ResourceSchema @model, schema withServer (app) -> app.put '/res/:_id', @resource.put('_id'), @resource.send app beforeEach fibrous -> model = @model.sync.create name: 'orange' model.name = 'apple' @response = @request.sync.put "/res/#{model._id}", json: {name: 'apple'} it 'returns the saved resources', fibrous -> expect(@response.statusCode).to.equal 200 expect(@response.body.name).to.equal 'apple' expect(@response.body._id).to.be.ok it 'saves the updated model to the DB', fibrous -> modelsFound = @model.sync.find() expect(modelsFound.length).to.equal 1 expect(modelsFound[0].name).to.equal 'apple' given 'updating falsy values', -> withModel (mongoose) -> mongoose.Schema active: Boolean beforeEach -> schema = { '_id', 'active' } @resource = new ResourceSchema @model, schema withServer (app) -> app.put '/res/:_id', @resource.put('_id'), @resource.send app it 'updates the falsy value', fibrous -> model = @model.sync.create { active: true } model.active = false response = @request.sync.put "/res/#{model._id}", json: {active: false} expect(response.statusCode).to.equal 200 expect(response.body.active).to.equal false expect(response.body._id).to.be.ok modelsFound = @model.sync.find() expect(modelsFound.length).to.equal 1 expect(modelsFound[0].active).to.equal false given 'putting to a custom key (not _id)', -> withModel (mongoose) -> mongoose.Schema key: type: String name: String beforeEach -> schema = { 'key', 'name' } @resource = new ResourceSchema @model, schema withServer (app) -> app.put '/res/:key', @resource.put('key'), @resource.send app it 'updates the resource', fibrous -> model = @model.sync.create { key: '<KEY>', name: 'apple' } model.name = 'orange' response = @request.sync.put "/res/#{model.key}", json: model expect(response.statusCode).to.equal 200 expect(response.body.name).to.equal 'orange' modelsFound = @model.sync.find() expect(modelsFound.length).to.equal 1 expect(modelsFound[0].name).to.equal 'orange' @model.sync.remove() given 'putting to uncreated resource (upserting)', -> withModel (mongoose) -> mongoose.Schema name: String beforeEach -> schema = { '_id', 'name' } @resource = new ResourceSchema @model, schema withServer (app) -> app.put '/res/:_id', @resource.put('_id'), @resource.send app it 'upserts the resource', fibrous -> newId = new mongoose.Types.ObjectId() response = @request.sync.put "/res/#{newId}", json: {name: 'apple'} expect(response.statusCode).to.equal 200 expect(response.body.name).to.equal 'apple' expect(response.body._id).to.equal newId.toString() modelsFound = @model.sync.find() expect(modelsFound.length).to.equal 1 expect(modelsFound[0].name).to.equal 'apple' given 'PUT resource with set field', -> withModel (mongoose) -> mongoose.Schema name: String beforeEach -> schema = { '_id' 'name': field: 'name' set: (resource) -> resource.name.toLowerCase() } @resource = new ResourceSchema @model, schema withServer (app) -> app.put '/res/:_id', @resource.put('_id'), @resource.send app it 'applies the setter', fibrous -> model = @model.sync.create name: '<NAME>' response = @request.sync.put "/res/#{model._id}", json: model expect(response.statusCode).to.equal 200 expect(response.body.name).to.equal 'apple' expect(response.body._id).to.be.ok modelsFound = @model.sync.find() expect(modelsFound.length).to.equal 1 expect(modelsFound[0].name).to.equal 'apple' given 'PUT resource with optional fields', -> withModel (mongoose) -> mongoose.Schema name: String age: Number beforeEach -> schema = { '_id' 'name' 'age': optional: true field: 'age' 'score': optional: true get: -> 95 } @resource = new ResourceSchema @model, schema withServer (app) -> app.put '/res/:_id', @resource.put('_id'), @resource.send app it 'returns the optional field if it is included in the request body', fibrous -> model = @model.sync.create name: '<NAME>' age: 10 response = @request.sync.put "/res/#{model._id}", json: name: '<NAME>' age: 10 score: 95 expect(response.statusCode).to.equal 200 expect(response.body.name).to.equal 'jo<NAME>' expect(response.body.score).to.equal 95 expect(response.body.age).to.equal 10 it 'does not return the optional field if it is not included in the request body', fibrous -> model = @model.sync.create name: '<NAME>' age: 10 response = @request.sync.put "/res/#{model._id}", json: {name: '<NAME>'} expect(response.statusCode).to.equal 200 expect(response.body.name).to.equal 'jo<NAME>' expect(response.body.score).to.be.undefined expect(response.body.age).to.be.undefined given 'default on mongoose model', -> withModel (mongoose) -> mongoose.Schema name: {type: String, default: 'foo'} withServer (app) -> @resource = new ResourceSchema @model, {'_id', 'name'} app.put '/bar/:_id', @resource.put('_id'), @resource.send it 'uses the mongoose schema defaults', fibrous -> _id = new mongoose.Types.ObjectId() response = @request.sync.put "/bar/#{_id}", json: {} expect(response.body).to.have.property '_id' expect(response.body).to.have.property 'name', 'foo' given 'save hooks on mongoose model', -> saveSpy = sinon.spy() withModel (mongoose) -> schema = mongoose.Schema name: String schema.pre 'save', (next) -> saveSpy() next() withServer (app) -> @resource = new ResourceSchema @model, {'_id', 'name'} app.put '/fruit/:_id', @resource.put('_id'), @resource.send beforeEach fibrous -> @apple = @model.sync.create name: 'apple' saveSpy.reset() it 'calls the save hook', fibrous -> @request.sync.put "/fruit/#{@apple._id}", json: {name: 'orange'} expect(saveSpy.callCount).to.equal 1 given 'schema with nested requires', -> saveSpy = sinon.spy() withModel (mongoose) -> mongoose.Schema name: String siblings: [ name: String age: type: Number, required: true ] withServer (app) -> @resource = new ResourceSchema @model, {'_id', 'name', 'siblings'} app.put '/person/:_id', @resource.put('_id'), @resource.send beforeEach fibrous -> @michael = @model.sync.create name: '<NAME>', siblings: [ {name: '<NAME>', age: 33}, {name: '<NAME>', age: 38} ] it 'allows you to remove and update items in the array', fibrous -> response = @request.sync.put "/person/#{@michael._id}", json: {siblings: [{name: '<NAME>', age:39, _id: @michael.siblings[1]._id}]} expect(response.statusCode).to.equal 200 given 'mongoose model field with default is already set, and resource does not contain the field', -> withModel (mongoose) -> mongoose.Schema name: String # mongoose arrays default to an empty array siblings: [ name: String age: type: Number, required: true ] withServer (app) -> # resource does not contain the array... @resource = new ResourceSchema @model, {'_id', 'name'} app.put '/person/:_id', @resource.put('_id'), @resource.send beforeEach fibrous -> @michael = @model.sync.create name: '<NAME>', siblings: [ {name: '<NAME>', age: 33}, {name: '<NAME>', age: 38} ] it 'does not overwrite the model value with the default value', fibrous -> response = @request.sync.put "/person/#{@michael._id}", json: name: '<NAME>' expect(response.statusCode).to.equal 200 model = @model.sync.findById @michael._id # the array still has both items (it was not overwritten with an empty array) expect(model.siblings).to.have.length 2
true
fibrous = require 'fibrous' mongoose = require 'mongoose' expect = require('chai').expect mongoose = require 'mongoose' sinon = require 'sinon' {suite, given} = require '../../support/helpers' ResourceSchema = require '../../..' suite 'PUT one', ({withModel, withServer}) -> given 'updating model values', -> withModel (mongoose) -> mongoose.Schema name: String beforeEach -> schema = { '_id', 'name' } @resource = new ResourceSchema @model, schema withServer (app) -> app.put '/res/:_id', @resource.put('_id'), @resource.send app beforeEach fibrous -> model = @model.sync.create name: 'orange' model.name = 'apple' @response = @request.sync.put "/res/#{model._id}", json: {name: 'apple'} it 'returns the saved resources', fibrous -> expect(@response.statusCode).to.equal 200 expect(@response.body.name).to.equal 'apple' expect(@response.body._id).to.be.ok it 'saves the updated model to the DB', fibrous -> modelsFound = @model.sync.find() expect(modelsFound.length).to.equal 1 expect(modelsFound[0].name).to.equal 'apple' given 'updating falsy values', -> withModel (mongoose) -> mongoose.Schema active: Boolean beforeEach -> schema = { '_id', 'active' } @resource = new ResourceSchema @model, schema withServer (app) -> app.put '/res/:_id', @resource.put('_id'), @resource.send app it 'updates the falsy value', fibrous -> model = @model.sync.create { active: true } model.active = false response = @request.sync.put "/res/#{model._id}", json: {active: false} expect(response.statusCode).to.equal 200 expect(response.body.active).to.equal false expect(response.body._id).to.be.ok modelsFound = @model.sync.find() expect(modelsFound.length).to.equal 1 expect(modelsFound[0].active).to.equal false given 'putting to a custom key (not _id)', -> withModel (mongoose) -> mongoose.Schema key: type: String name: String beforeEach -> schema = { 'key', 'name' } @resource = new ResourceSchema @model, schema withServer (app) -> app.put '/res/:key', @resource.put('key'), @resource.send app it 'updates the resource', fibrous -> model = @model.sync.create { key: 'PI:KEY:<KEY>END_PI', name: 'apple' } model.name = 'orange' response = @request.sync.put "/res/#{model.key}", json: model expect(response.statusCode).to.equal 200 expect(response.body.name).to.equal 'orange' modelsFound = @model.sync.find() expect(modelsFound.length).to.equal 1 expect(modelsFound[0].name).to.equal 'orange' @model.sync.remove() given 'putting to uncreated resource (upserting)', -> withModel (mongoose) -> mongoose.Schema name: String beforeEach -> schema = { '_id', 'name' } @resource = new ResourceSchema @model, schema withServer (app) -> app.put '/res/:_id', @resource.put('_id'), @resource.send app it 'upserts the resource', fibrous -> newId = new mongoose.Types.ObjectId() response = @request.sync.put "/res/#{newId}", json: {name: 'apple'} expect(response.statusCode).to.equal 200 expect(response.body.name).to.equal 'apple' expect(response.body._id).to.equal newId.toString() modelsFound = @model.sync.find() expect(modelsFound.length).to.equal 1 expect(modelsFound[0].name).to.equal 'apple' given 'PUT resource with set field', -> withModel (mongoose) -> mongoose.Schema name: String beforeEach -> schema = { '_id' 'name': field: 'name' set: (resource) -> resource.name.toLowerCase() } @resource = new ResourceSchema @model, schema withServer (app) -> app.put '/res/:_id', @resource.put('_id'), @resource.send app it 'applies the setter', fibrous -> model = @model.sync.create name: 'PI:NAME:<NAME>END_PI' response = @request.sync.put "/res/#{model._id}", json: model expect(response.statusCode).to.equal 200 expect(response.body.name).to.equal 'apple' expect(response.body._id).to.be.ok modelsFound = @model.sync.find() expect(modelsFound.length).to.equal 1 expect(modelsFound[0].name).to.equal 'apple' given 'PUT resource with optional fields', -> withModel (mongoose) -> mongoose.Schema name: String age: Number beforeEach -> schema = { '_id' 'name' 'age': optional: true field: 'age' 'score': optional: true get: -> 95 } @resource = new ResourceSchema @model, schema withServer (app) -> app.put '/res/:_id', @resource.put('_id'), @resource.send app it 'returns the optional field if it is included in the request body', fibrous -> model = @model.sync.create name: 'PI:NAME:<NAME>END_PI' age: 10 response = @request.sync.put "/res/#{model._id}", json: name: 'PI:NAME:<NAME>END_PI' age: 10 score: 95 expect(response.statusCode).to.equal 200 expect(response.body.name).to.equal 'joPI:NAME:<NAME>END_PI' expect(response.body.score).to.equal 95 expect(response.body.age).to.equal 10 it 'does not return the optional field if it is not included in the request body', fibrous -> model = @model.sync.create name: 'PI:NAME:<NAME>END_PI' age: 10 response = @request.sync.put "/res/#{model._id}", json: {name: 'PI:NAME:<NAME>END_PI'} expect(response.statusCode).to.equal 200 expect(response.body.name).to.equal 'joPI:NAME:<NAME>END_PI' expect(response.body.score).to.be.undefined expect(response.body.age).to.be.undefined given 'default on mongoose model', -> withModel (mongoose) -> mongoose.Schema name: {type: String, default: 'foo'} withServer (app) -> @resource = new ResourceSchema @model, {'_id', 'name'} app.put '/bar/:_id', @resource.put('_id'), @resource.send it 'uses the mongoose schema defaults', fibrous -> _id = new mongoose.Types.ObjectId() response = @request.sync.put "/bar/#{_id}", json: {} expect(response.body).to.have.property '_id' expect(response.body).to.have.property 'name', 'foo' given 'save hooks on mongoose model', -> saveSpy = sinon.spy() withModel (mongoose) -> schema = mongoose.Schema name: String schema.pre 'save', (next) -> saveSpy() next() withServer (app) -> @resource = new ResourceSchema @model, {'_id', 'name'} app.put '/fruit/:_id', @resource.put('_id'), @resource.send beforeEach fibrous -> @apple = @model.sync.create name: 'apple' saveSpy.reset() it 'calls the save hook', fibrous -> @request.sync.put "/fruit/#{@apple._id}", json: {name: 'orange'} expect(saveSpy.callCount).to.equal 1 given 'schema with nested requires', -> saveSpy = sinon.spy() withModel (mongoose) -> mongoose.Schema name: String siblings: [ name: String age: type: Number, required: true ] withServer (app) -> @resource = new ResourceSchema @model, {'_id', 'name', 'siblings'} app.put '/person/:_id', @resource.put('_id'), @resource.send beforeEach fibrous -> @michael = @model.sync.create name: 'PI:NAME:<NAME>END_PI', siblings: [ {name: 'PI:NAME:<NAME>END_PI', age: 33}, {name: 'PI:NAME:<NAME>END_PI', age: 38} ] it 'allows you to remove and update items in the array', fibrous -> response = @request.sync.put "/person/#{@michael._id}", json: {siblings: [{name: 'PI:NAME:<NAME>END_PI', age:39, _id: @michael.siblings[1]._id}]} expect(response.statusCode).to.equal 200 given 'mongoose model field with default is already set, and resource does not contain the field', -> withModel (mongoose) -> mongoose.Schema name: String # mongoose arrays default to an empty array siblings: [ name: String age: type: Number, required: true ] withServer (app) -> # resource does not contain the array... @resource = new ResourceSchema @model, {'_id', 'name'} app.put '/person/:_id', @resource.put('_id'), @resource.send beforeEach fibrous -> @michael = @model.sync.create name: 'PI:NAME:<NAME>END_PI', siblings: [ {name: 'PI:NAME:<NAME>END_PI', age: 33}, {name: 'PI:NAME:<NAME>END_PI', age: 38} ] it 'does not overwrite the model value with the default value', fibrous -> response = @request.sync.put "/person/#{@michael._id}", json: name: 'PI:NAME:<NAME>END_PI' expect(response.statusCode).to.equal 200 model = @model.sync.findById @michael._id # the array still has both items (it was not overwritten with an empty array) expect(model.siblings).to.have.length 2
[ { "context": "###\n* User: Liad Magen\n* Date: 11/02/13\n* Time: 17:15\n*\n* Knownode files", "end": 22, "score": 0.9998739957809448, "start": 12, "tag": "NAME", "value": "Liad Magen" }, { "context": ",\n\t\t\ttitle: params.title,\n\t\t\tmeta:\n\t\t\t\tuploaderId: @user.id,\n\t\t\t\t...
modules/knownodeFiles._coffee
CyberCRI/KnowNodes
5
### * User: Liad Magen * Date: 11/02/13 * Time: 17:15 * * Knownode files module. for saving / retriving the file articles for knownode from MongoDB * ##### userModule = require('./user') mongoose = require('mongoose') postSchema = require('../DB/PostSchema') config = require('../config/DB.conf') DBModule = require './DBModule' module.exports = class KnownodeFiles extends DBModule constructor: (user) -> super user @currentModule = 'module/KnownodeFiles' initDB: (callback) -> @logger.logDebug @currentModule, 'initDB' opts = server: auto_reconnect: false, user: config.getDBDetails('mongoDB').user, pass: config.getDBDetails('mongoDB').pass dbURL = config.getDBURL('mongoDB').url mongoose.connect dbURL, opts db = mongoose.connection db.on 'error', (err) -> @logger.logError @currentModule, err try mongoose.disconnect() #mongoose.connection.close() callback err catch error @logger.logError @currentModule, error callback error db.once 'open', () -> console.log 'db is open' Post = db.model 'Post', postSchema console.log 'sending Post' callback null, Post saveFile: (files, params, _) => @logger.logDebug @currentModule, 'saveFile' Post = @initDB _ @logger.logDebug @currentModule, 'post initialized' post = new Post fileURL: params.url, fileName: files.uploadedFile.name, abstract: params.bodyText, title: params.title, meta: uploaderId: @user.id, uploaderEmail: @user.email, size: files.uploadedFile.size opts = content_type: files.uploadedFile.type #filepost = post.save _ post.addFile files.uploadedFile, opts, _ mongoose.disconnect() #mongoose.connection.close() post getFile: (id, _) => @logger.logDebug @currentModule, "getFile #{id}" Post = @initDB _ post = new Post() post.getFile id, _ sendFileToStreamHandler: (response, id)-> @logger.logDebug @currentModule, "sendFileToStreamHandler #{id}" @getFile id, (err, store)-> if err? response.json error: err else response.writeHead 200, 'Content-Type': store.contentType, 'Content-Length': store.length, 'Content-disposition': 'attachment; filename=' + store.filename fileStream = store.stream(false) fileStream.pipe response, end:false fileStream.on "end", () -> #fileStream.end() mongoose.connection.close() deleteFile: (id, _) => @logger.logDebug @currentModule, "deleteFile #{id}" Post = @initDB _ post = new Post() post.deleteFile id, _ mongoose.connection.close()
36934
### * User: <NAME> * Date: 11/02/13 * Time: 17:15 * * Knownode files module. for saving / retriving the file articles for knownode from MongoDB * ##### userModule = require('./user') mongoose = require('mongoose') postSchema = require('../DB/PostSchema') config = require('../config/DB.conf') DBModule = require './DBModule' module.exports = class KnownodeFiles extends DBModule constructor: (user) -> super user @currentModule = 'module/KnownodeFiles' initDB: (callback) -> @logger.logDebug @currentModule, 'initDB' opts = server: auto_reconnect: false, user: config.getDBDetails('mongoDB').user, pass: config.getDBDetails('mongoDB').pass dbURL = config.getDBURL('mongoDB').url mongoose.connect dbURL, opts db = mongoose.connection db.on 'error', (err) -> @logger.logError @currentModule, err try mongoose.disconnect() #mongoose.connection.close() callback err catch error @logger.logError @currentModule, error callback error db.once 'open', () -> console.log 'db is open' Post = db.model 'Post', postSchema console.log 'sending Post' callback null, Post saveFile: (files, params, _) => @logger.logDebug @currentModule, 'saveFile' Post = @initDB _ @logger.logDebug @currentModule, 'post initialized' post = new Post fileURL: params.url, fileName: files.uploadedFile.name, abstract: params.bodyText, title: params.title, meta: uploaderId: @user.id, uploaderEmail: @user.email, size: files.uploadedFile.size opts = content_type: files.uploadedFile.type #filepost = post.save _ post.addFile files.uploadedFile, opts, _ mongoose.disconnect() #mongoose.connection.close() post getFile: (id, _) => @logger.logDebug @currentModule, "getFile #{id}" Post = @initDB _ post = new Post() post.getFile id, _ sendFileToStreamHandler: (response, id)-> @logger.logDebug @currentModule, "sendFileToStreamHandler #{id}" @getFile id, (err, store)-> if err? response.json error: err else response.writeHead 200, 'Content-Type': store.contentType, 'Content-Length': store.length, 'Content-disposition': 'attachment; filename=' + store.filename fileStream = store.stream(false) fileStream.pipe response, end:false fileStream.on "end", () -> #fileStream.end() mongoose.connection.close() deleteFile: (id, _) => @logger.logDebug @currentModule, "deleteFile #{id}" Post = @initDB _ post = new Post() post.deleteFile id, _ mongoose.connection.close()
true
### * User: PI:NAME:<NAME>END_PI * Date: 11/02/13 * Time: 17:15 * * Knownode files module. for saving / retriving the file articles for knownode from MongoDB * ##### userModule = require('./user') mongoose = require('mongoose') postSchema = require('../DB/PostSchema') config = require('../config/DB.conf') DBModule = require './DBModule' module.exports = class KnownodeFiles extends DBModule constructor: (user) -> super user @currentModule = 'module/KnownodeFiles' initDB: (callback) -> @logger.logDebug @currentModule, 'initDB' opts = server: auto_reconnect: false, user: config.getDBDetails('mongoDB').user, pass: config.getDBDetails('mongoDB').pass dbURL = config.getDBURL('mongoDB').url mongoose.connect dbURL, opts db = mongoose.connection db.on 'error', (err) -> @logger.logError @currentModule, err try mongoose.disconnect() #mongoose.connection.close() callback err catch error @logger.logError @currentModule, error callback error db.once 'open', () -> console.log 'db is open' Post = db.model 'Post', postSchema console.log 'sending Post' callback null, Post saveFile: (files, params, _) => @logger.logDebug @currentModule, 'saveFile' Post = @initDB _ @logger.logDebug @currentModule, 'post initialized' post = new Post fileURL: params.url, fileName: files.uploadedFile.name, abstract: params.bodyText, title: params.title, meta: uploaderId: @user.id, uploaderEmail: @user.email, size: files.uploadedFile.size opts = content_type: files.uploadedFile.type #filepost = post.save _ post.addFile files.uploadedFile, opts, _ mongoose.disconnect() #mongoose.connection.close() post getFile: (id, _) => @logger.logDebug @currentModule, "getFile #{id}" Post = @initDB _ post = new Post() post.getFile id, _ sendFileToStreamHandler: (response, id)-> @logger.logDebug @currentModule, "sendFileToStreamHandler #{id}" @getFile id, (err, store)-> if err? response.json error: err else response.writeHead 200, 'Content-Type': store.contentType, 'Content-Length': store.length, 'Content-disposition': 'attachment; filename=' + store.filename fileStream = store.stream(false) fileStream.pipe response, end:false fileStream.on "end", () -> #fileStream.end() mongoose.connection.close() deleteFile: (id, _) => @logger.logDebug @currentModule, "deleteFile #{id}" Post = @initDB _ post = new Post() post.deleteFile id, _ mongoose.connection.close()
[ { "context": "000\n# mioID = 'aaaa'\n# mioPass = 'bbb'\n# client_id = 'ccc'\n# redirect_u", "end": 468, "score": 0.9884516000747681, "start": 465, "tag": "PASSWORD", "value": "bbb" }, { "context": " mioID = 'aaaa'\n mioPass = 'bbb...
test/index.mocha.coffee
KamataRyo/node-miopon
2
expect = require('chai').expect nock = require 'nock' _ = require 'underscore' main = '../' + require('../package.json').main miopon = require main oAuth = miopon.oAuth Coupon = miopon.Coupon utility = miopon.utility alsoTestWebCases = false describeWebCases = if alsoTestWebCases then describe else describe.skip # describe 'test of nock', -> # it 'test of test', (done)-> # this.timeout 50000 # mioID = 'aaaa' # mioPass = 'bbb' # client_id = 'ccc' # redirect_uri = 'ddd' # scope = nock miopon.endpoints.oAuth # oAuth { # mioID # mioPass # client_id # redirect_uri # success: -> # console.log 'success' # done() # failure: -> # console.log 'failure' # done() # } # # return describe 'The `oAuth` function', -> it '`oAuth` exists', -> expect(oAuth).is.a 'function' describeWebCases 'oAuth fails wihout mioID, mioPass, client_id or redirect_uri:', -> mioID = 'aaaa' mioPass = 'bbb' client_id = 'ccc' redirect_uri = 'ddd' args = [ {} {mioID}, {mioPass}, {client_id}, {redirect_uri} {mioID, mioPass}, {mioID, client_id}, {mioID, redirect_uri} {mioPass, client_id}, {mioPass, redirect_uri} {client_id, redirect_uri} {mioID, mioPass, client_id} {mioID, mioPass, redirect_uri} {mioID, client_id, redirect_uri} {mioPass, client_id, redirect_uri} ] _.each args, (arg) -> it arg.toString(), (done) -> arg.failure = -> done() arg.success = -> expect(false).to.be.true done() oAuth arg it 'oAuth even failes with a nonsense set of arguments', (done) -> this.timeout 50000 oAuth { mioID mioPass client_id redirect_uri success: -> expect(false).to.be.true done() failure: -> done() } describe 'The `Coupon` constructor, \n', -> it 'should exist.', -> expect(Coupon).to.be.a.instanceof Function describe 'Test for the instance of `Coupon`. \n', -> coupon = null before -> coupon = new Coupon() # 後方互換のため残す。v2よりoAuthはCouponコンンストラクタ関数から分離した it 'the instance coupon should have a method `oAuth`', -> expect(coupon.oAuth).is.a 'function' # 互換チェック it '`coupon.oAuth` referes miopon.oAuth', -> expect(coupon.oAuth).to.equal miopon.oAuth it 'the instance coupon should have a method `inform`', -> expect(coupon.inform).is.a 'function' it 'the instance coupon should have a method `turn`', -> expect(coupon.turn).is.a 'function' # 後方互換のため残す。v2よりoAuthはCouponコンンストラクタ関数からprivateメンバへ移動 it 'the instance coupon should have a string property `api.urls.oAuth`', -> expect(coupon.urls.oAuth).to.be.an 'string' # 後方互換のため残す。v2よりoAuthはCouponコンンストラクタ関数からprivateメンバへ移動 it 'the instance coupon should have a string property `api.urls.coupon`', -> expect(coupon.urls.coupon).to.be.an 'string' describeWebCases 'inform fails wihout access_token or client_id:', -> access_token = 'aaaa' client_id = 'bbb' args = [ {} {access_token} {client_id} ] _.each args, (arg) -> it arg.toString(), (done) -> arg.failure = -> done() arg.success = -> expect(false).to.be.true done() coupon.inform arg it 'inform even fails with nonsense access_token and client_id.', (done) -> this.timeout 20000 coupon.inform { client_id access_token failure: -> done() success: -> expect(false).to.be.true done() } describeWebCases 'turn fails wihout access_token, client_id or query:', -> access_token = 'aaaa' client_id = 'bbb' query = {query:''} args = [ {} {access_token} {client_id} {access_token, client_id} {client_id, query} {query, access_token} ] _.each args, (arg) -> it arg.toString(), (done) -> arg.failure = -> done() arg.success = -> expect(false).to.be.true done() coupon.turn arg it 'turn even fails with nonsense access_token, client_id and query.', (done) -> this.timeout 20000 coupon.turn { client_id access_token query failure: -> done() success: -> expect(false).to.be.true done() } describe 'The module `utility`, \n', -> it 'should exist.', -> expect(utility).to.be.a.instanceof Object describe 'Test for the each member of `utility`. \n', -> describe '`arraify`', -> it 'the utility has a method `arraify`', -> expect(utility.arraify).is.a 'function' describe 'test of the utility method `arraify` cases: ', -> it 'undefined', -> result = utility.arraify undefined correctAnswer = [] expect(result).to.eql correctAnswer it 'string.', -> result = utility.arraify '1234567890' correctAnswer = ['1234567890'] expect(result).to.eql correctAnswer it 'number.', -> result = utility.arraify 1234567890 correctAnswer = ['1234567890'] expect(result).to.eql correctAnswer it 'string with hyphen to be ignored.', -> result = utility.arraify '1-23-4567-89-0' correctAnswer = ['1234567890'] expect(result).to.eql correctAnswer it 'string with brackets to be ignored.', -> result = utility.arraify '1(2)3{45}67[890]' correctAnswer = ['1234567890'] expect(result).to.eql correctAnswer it 'string with alphabets to be ignored.', -> result = utility.arraify '1a2b3c4d5e6f7g8h9i0' correctAnswer = ['1234567890'] expect(result).to.eql correctAnswer it 'non-number', -> result = utility.arraify 'aaa' correctAnswer = [] expect(result).to.eql correctAnswer it 'non-number and number', -> result = utility.arraify ['','1234567890','^&(*&&^())'] correctAnswer = ['1234567890'] expect(result).to.eql correctAnswer it 'non-numbers', -> result = utility.arraify ['','aaa','^&(*&&^())'] correctAnswer = [] expect(result).to.eql correctAnswer it 'array case', -> args = [ '1234567890' 1234567890 '1-23-4567-89-0' '1(2)3{45}67[890]' '1a2b3c4d5e6f7g8h9i0' ] result = utility.arraify args correctAnswer = ('1234567890' for n in args) expect(result).to.eql correctAnswer describe '`orderCouponUse`', -> it 'the utility has a method `orderCouponUse`', -> expect(utility.orderCouponUse).is.a 'function' describe 'test of the utility method `orderCouponUse` cases: ', -> _.each ['on', 1, 'abc', true], (arg) -> it '`orderCouponUse` works well in positive cases("on" or something evaluated as true)', -> result = utility.orderCouponUse arg expect(result).to.true _.each ['off', 0, '', false], (arg) -> it '`orderCouponUse` works well in negative cases("off" or something evaluated as false)', -> result = utility.orderCouponUse arg expect(result).to.false describe '`querify`', -> it 'the utility has a method `querify`', -> expect(utility.querify).is.a 'function' describe 'test of the utility method `querify` cases: ', -> describe 'case of information object: ', -> it '`querify` works well', -> result = utility.querify { information: require '../test/cases/querify-before.json' } correct =require '../test/cases/querify-after.json' expect(result).to.eql correct it '`querify` works well with filter', -> result = utility.querify { information: require '../test/cases/querify-before.json' filter: ['2345678901','4567890123'] } correct =require '../test/cases/querify-after_filtered.json' expect(result).to.eql correct it '`querify` works well with coupon order1', -> result = utility.querify { information: require '../test/cases/querify-before.json' couponUse: true } correct =require '../test/cases/querify-after_ordered1.json' expect(result).to.eql correct it '`querify` works well with coupon order2', -> result = utility.querify { information: require '../test/cases/querify-before.json' couponUse: 'off' } correct =require '../test/cases/querify-after_ordered2.json' expect(result).to.eql correct it '`querify` works well with broken input', -> result = utility.querify { information: require '../test/cases/querify-before_broken.json' } correct =require '../test/cases/querify-after_broken.json' expect(result).to.eql correct describe '`generateQuery`', -> it 'the utility has a method `generateQuery`', -> expect(utility.generateQuery).is.a 'function' describe 'behaviors:', -> it 'works with no codes', -> turnStates = [] exact = couponInfo: [] expect(utility.generateQuery {turnStates}).to.eql exact describe 'works with unformatted codes will be eliminated:', -> turnStatesCases = [ null, undefined,'dummycode', 1, false, true, {}, [] [null], [undefined],['dummycode'], [1], [false], [true], {}, [] ] exact = couponInfo: [] _.each turnStatesCases, (turnStateCase) -> it "#{turnStateCase}", -> expect(utility.generateQuery {turnStates:turnStateCase}).to.eql exact it 'works with single code', -> turnStates = [ { 'hdoWWWWWWWW':true } ] exact = couponInfo: [ { hdoInfo: [ {hdoServiceCode: 'hdoWWWWWWWW', couponUse: true } ] } ] expect(utility.generateQuery {turnStates}).to.eql exact it 'works with single code and "on" statement', -> turnStates = [ { 'hdoWWWWWWWW':'on' } ] exact = couponInfo: [ { hdoInfo: [ {hdoServiceCode: 'hdoWWWWWWWW', couponUse: true } ] } ] expect(utility.generateQuery {turnStates}).to.eql exact it 'works with single code and "off" statement', -> turnStates = [ { 'hdoWWWWWWWW':'off' } ] exact = couponInfo: [ { hdoInfo: [ {hdoServiceCode: 'hdoWWWWWWWW', couponUse: false } ] } ] expect(utility.generateQuery {turnStates}).to.eql exact it 'works with several code', -> turnStates = [ { 'hdoWWWWWWWW':true 'hdoYYYYYYYY':false 'hdoZZZZZZZZ':true } ] exact = couponInfo: [ { hdoInfo: [ {hdoServiceCode: 'hdoWWWWWWWW', couponUse: true } {hdoServiceCode: 'hdoYYYYYYYY', couponUse: false } {hdoServiceCode: 'hdoZZZZZZZZ', couponUse: true } ] } ] expect(utility.generateQuery {turnStates}).to.eql exact it 'works with several coupon', -> turnStates = [ { 'hdoWWWWWWWW':false }, { 'hdoXXXXXXXX':true } ] exact = couponInfo: [ { hdoInfo: [ {hdoServiceCode: 'hdoWWWWWWWW', couponUse: false } ] }, { hdoInfo: [ {hdoServiceCode: 'hdoXXXXXXXX', couponUse: true } ] } ] expect(utility.generateQuery {turnStates}).to.eql exact it 'works with complex object', -> turnStates = [ { 'hdoWWWWWWWW':true }, { 'hdoXXXXXXXX':false 'hdoYYYYYYYY':true }, { 'hdoZZZZZZZZ':false 'hdoVVVVVVVV':true 'hdoUUUUUUUU':false } ] exact = couponInfo: [ { hdoInfo: [ {hdoServiceCode: 'hdoWWWWWWWW', couponUse: true } ] }, { hdoInfo: [ {hdoServiceCode: 'hdoXXXXXXXX', couponUse: false } {hdoServiceCode: 'hdoYYYYYYYY', couponUse: true } ] }, { hdoInfo: [ {hdoServiceCode: 'hdoZZZZZZZZ', couponUse: false } {hdoServiceCode: 'hdoVVVVVVVV', couponUse: true } {hdoServiceCode: 'hdoUUUUUUUU', couponUse: false } ] } ] expect(utility.generateQuery {turnStates}).to.eql exact describe '`callback`', -> it 'the utility has a method `callback`', -> expect(utility.callback).is.a 'function' it '`callback` call the 1st argument if function', -> func = (arg) -> arg + arg actual = utility.callback func, 'aaaa' expect(actual is 'aaaaaaaa').to.be.true it '`callback` also works asynchronously', (done) -> utility.callback setTimeout, done, 20 it '`callback` do nothing with the 1st argument if non-function', -> actual = utility.callback 'aaa', 'bbb' expect(actual).to.be.false
64801
expect = require('chai').expect nock = require 'nock' _ = require 'underscore' main = '../' + require('../package.json').main miopon = require main oAuth = miopon.oAuth Coupon = miopon.Coupon utility = miopon.utility alsoTestWebCases = false describeWebCases = if alsoTestWebCases then describe else describe.skip # describe 'test of nock', -> # it 'test of test', (done)-> # this.timeout 50000 # mioID = 'aaaa' # mioPass = '<PASSWORD>' # client_id = 'ccc' # redirect_uri = 'ddd' # scope = nock miopon.endpoints.oAuth # oAuth { # mioID # mioPass # client_id # redirect_uri # success: -> # console.log 'success' # done() # failure: -> # console.log 'failure' # done() # } # # return describe 'The `oAuth` function', -> it '`oAuth` exists', -> expect(oAuth).is.a 'function' describeWebCases 'oAuth fails wihout mioID, mioPass, client_id or redirect_uri:', -> mioID = 'aaaa' mioPass = '<PASSWORD>' client_id = 'ccc' redirect_uri = 'ddd' args = [ {} {mioID}, {mioPass}, {client_id}, {redirect_uri} {mioID, mioPass}, {mioID, client_id}, {mioID, redirect_uri} {mioPass, client_id}, {mioPass, redirect_uri} {client_id, redirect_uri} {mioID, mioPass, client_id} {mioID, mioPass, redirect_uri} {mioID, client_id, redirect_uri} {mioPass, client_id, redirect_uri} ] _.each args, (arg) -> it arg.toString(), (done) -> arg.failure = -> done() arg.success = -> expect(false).to.be.true done() oAuth arg it 'oAuth even failes with a nonsense set of arguments', (done) -> this.timeout 50000 oAuth { mioID mioPass client_id redirect_uri success: -> expect(false).to.be.true done() failure: -> done() } describe 'The `Coupon` constructor, \n', -> it 'should exist.', -> expect(Coupon).to.be.a.instanceof Function describe 'Test for the instance of `Coupon`. \n', -> coupon = null before -> coupon = new Coupon() # 後方互換のため残す。v2よりoAuthはCouponコンンストラクタ関数から分離した it 'the instance coupon should have a method `oAuth`', -> expect(coupon.oAuth).is.a 'function' # 互換チェック it '`coupon.oAuth` referes miopon.oAuth', -> expect(coupon.oAuth).to.equal miopon.oAuth it 'the instance coupon should have a method `inform`', -> expect(coupon.inform).is.a 'function' it 'the instance coupon should have a method `turn`', -> expect(coupon.turn).is.a 'function' # 後方互換のため残す。v2よりoAuthはCouponコンンストラクタ関数からprivateメンバへ移動 it 'the instance coupon should have a string property `api.urls.oAuth`', -> expect(coupon.urls.oAuth).to.be.an 'string' # 後方互換のため残す。v2よりoAuthはCouponコンンストラクタ関数からprivateメンバへ移動 it 'the instance coupon should have a string property `api.urls.coupon`', -> expect(coupon.urls.coupon).to.be.an 'string' describeWebCases 'inform fails wihout access_token or client_id:', -> access_token = '<KEY>' client_id = 'bbb' args = [ {} {access_token} {client_id} ] _.each args, (arg) -> it arg.toString(), (done) -> arg.failure = -> done() arg.success = -> expect(false).to.be.true done() coupon.inform arg it 'inform even fails with nonsense access_token and client_id.', (done) -> this.timeout 20000 coupon.inform { client_id access_token failure: -> done() success: -> expect(false).to.be.true done() } describeWebCases 'turn fails wihout access_token, client_id or query:', -> access_token = '<KEY>' client_id = 'bbb' query = {query:''} args = [ {} {access_token} {client_id} {access_token, client_id} {client_id, query} {query, access_token} ] _.each args, (arg) -> it arg.toString(), (done) -> arg.failure = -> done() arg.success = -> expect(false).to.be.true done() coupon.turn arg it 'turn even fails with nonsense access_token, client_id and query.', (done) -> this.timeout 20000 coupon.turn { client_id access_token query failure: -> done() success: -> expect(false).to.be.true done() } describe 'The module `utility`, \n', -> it 'should exist.', -> expect(utility).to.be.a.instanceof Object describe 'Test for the each member of `utility`. \n', -> describe '`arraify`', -> it 'the utility has a method `arraify`', -> expect(utility.arraify).is.a 'function' describe 'test of the utility method `arraify` cases: ', -> it 'undefined', -> result = utility.arraify undefined correctAnswer = [] expect(result).to.eql correctAnswer it 'string.', -> result = utility.arraify '1234567890' correctAnswer = ['1234567890'] expect(result).to.eql correctAnswer it 'number.', -> result = utility.arraify 1234567890 correctAnswer = ['1234567890'] expect(result).to.eql correctAnswer it 'string with hyphen to be ignored.', -> result = utility.arraify '1-23-4567-89-0' correctAnswer = ['1234567890'] expect(result).to.eql correctAnswer it 'string with brackets to be ignored.', -> result = utility.arraify '1(2)3{45}67[890]' correctAnswer = ['1234567890'] expect(result).to.eql correctAnswer it 'string with alphabets to be ignored.', -> result = utility.arraify '1a2b3c4d5e6f7g8h9i0' correctAnswer = ['1234567890'] expect(result).to.eql correctAnswer it 'non-number', -> result = utility.arraify 'aaa' correctAnswer = [] expect(result).to.eql correctAnswer it 'non-number and number', -> result = utility.arraify ['','1234567890','^&(*&&^())'] correctAnswer = ['1234567890'] expect(result).to.eql correctAnswer it 'non-numbers', -> result = utility.arraify ['','aaa','^&(*&&^())'] correctAnswer = [] expect(result).to.eql correctAnswer it 'array case', -> args = [ '1234567890' 1234567890 '1-23-4567-89-0' '1(2)3{45}67[890]' '1a2b3c4d5e6f7g8h9i0' ] result = utility.arraify args correctAnswer = ('1234567890' for n in args) expect(result).to.eql correctAnswer describe '`orderCouponUse`', -> it 'the utility has a method `orderCouponUse`', -> expect(utility.orderCouponUse).is.a 'function' describe 'test of the utility method `orderCouponUse` cases: ', -> _.each ['on', 1, 'abc', true], (arg) -> it '`orderCouponUse` works well in positive cases("on" or something evaluated as true)', -> result = utility.orderCouponUse arg expect(result).to.true _.each ['off', 0, '', false], (arg) -> it '`orderCouponUse` works well in negative cases("off" or something evaluated as false)', -> result = utility.orderCouponUse arg expect(result).to.false describe '`querify`', -> it 'the utility has a method `querify`', -> expect(utility.querify).is.a 'function' describe 'test of the utility method `querify` cases: ', -> describe 'case of information object: ', -> it '`querify` works well', -> result = utility.querify { information: require '../test/cases/querify-before.json' } correct =require '../test/cases/querify-after.json' expect(result).to.eql correct it '`querify` works well with filter', -> result = utility.querify { information: require '../test/cases/querify-before.json' filter: ['2345678901','4567890123'] } correct =require '../test/cases/querify-after_filtered.json' expect(result).to.eql correct it '`querify` works well with coupon order1', -> result = utility.querify { information: require '../test/cases/querify-before.json' couponUse: true } correct =require '../test/cases/querify-after_ordered1.json' expect(result).to.eql correct it '`querify` works well with coupon order2', -> result = utility.querify { information: require '../test/cases/querify-before.json' couponUse: 'off' } correct =require '../test/cases/querify-after_ordered2.json' expect(result).to.eql correct it '`querify` works well with broken input', -> result = utility.querify { information: require '../test/cases/querify-before_broken.json' } correct =require '../test/cases/querify-after_broken.json' expect(result).to.eql correct describe '`generateQuery`', -> it 'the utility has a method `generateQuery`', -> expect(utility.generateQuery).is.a 'function' describe 'behaviors:', -> it 'works with no codes', -> turnStates = [] exact = couponInfo: [] expect(utility.generateQuery {turnStates}).to.eql exact describe 'works with unformatted codes will be eliminated:', -> turnStatesCases = [ null, undefined,'dummycode', 1, false, true, {}, [] [null], [undefined],['dummycode'], [1], [false], [true], {}, [] ] exact = couponInfo: [] _.each turnStatesCases, (turnStateCase) -> it "#{turnStateCase}", -> expect(utility.generateQuery {turnStates:turnStateCase}).to.eql exact it 'works with single code', -> turnStates = [ { 'hdoWWWWWWWW':true } ] exact = couponInfo: [ { hdoInfo: [ {hdoServiceCode: 'hdoWWWWWWWW', couponUse: true } ] } ] expect(utility.generateQuery {turnStates}).to.eql exact it 'works with single code and "on" statement', -> turnStates = [ { 'hdoWWWWWWWW':'on' } ] exact = couponInfo: [ { hdoInfo: [ {hdoServiceCode: 'hdoWWWWWWWW', couponUse: true } ] } ] expect(utility.generateQuery {turnStates}).to.eql exact it 'works with single code and "off" statement', -> turnStates = [ { 'hdoWWWWWWWW':'off' } ] exact = couponInfo: [ { hdoInfo: [ {hdoServiceCode: 'hdoWWWWWWWW', couponUse: false } ] } ] expect(utility.generateQuery {turnStates}).to.eql exact it 'works with several code', -> turnStates = [ { 'hdoWWWWWWWW':true 'hdoYYYYYYYY':false 'hdoZZZZZZZZ':true } ] exact = couponInfo: [ { hdoInfo: [ {hdoServiceCode: 'hdoWWWWWWWW', couponUse: true } {hdoServiceCode: 'hdoYYYYYYYY', couponUse: false } {hdoServiceCode: 'hdoZZZZZZZZ', couponUse: true } ] } ] expect(utility.generateQuery {turnStates}).to.eql exact it 'works with several coupon', -> turnStates = [ { 'hdoWWWWWWWW':false }, { 'hdoXXXXXXXX':true } ] exact = couponInfo: [ { hdoInfo: [ {hdoServiceCode: 'hdoWWWWWWWW', couponUse: false } ] }, { hdoInfo: [ {hdoServiceCode: 'hdoXXXXXXXX', couponUse: true } ] } ] expect(utility.generateQuery {turnStates}).to.eql exact it 'works with complex object', -> turnStates = [ { 'hdoWWWWWWWW':true }, { 'hdoXXXXXXXX':false 'hdoYYYYYYYY':true }, { 'hdoZZZZZZZZ':false 'hdoVVVVVVVV':true 'hdoUUUUUUUU':false } ] exact = couponInfo: [ { hdoInfo: [ {hdoServiceCode: 'hdoWWWWWWWW', couponUse: true } ] }, { hdoInfo: [ {hdoServiceCode: 'hdoXXXXXXXX', couponUse: false } {hdoServiceCode: 'hdoYYYYYYYY', couponUse: true } ] }, { hdoInfo: [ {hdoServiceCode: 'hdoZZZZZZZZ', couponUse: false } {hdoServiceCode: 'hdoVVVVVVVV', couponUse: true } {hdoServiceCode: 'hdoUUUUUUUU', couponUse: false } ] } ] expect(utility.generateQuery {turnStates}).to.eql exact describe '`callback`', -> it 'the utility has a method `callback`', -> expect(utility.callback).is.a 'function' it '`callback` call the 1st argument if function', -> func = (arg) -> arg + arg actual = utility.callback func, 'aaaa' expect(actual is 'aaaaaaaa').to.be.true it '`callback` also works asynchronously', (done) -> utility.callback setTimeout, done, 20 it '`callback` do nothing with the 1st argument if non-function', -> actual = utility.callback 'aaa', 'bbb' expect(actual).to.be.false
true
expect = require('chai').expect nock = require 'nock' _ = require 'underscore' main = '../' + require('../package.json').main miopon = require main oAuth = miopon.oAuth Coupon = miopon.Coupon utility = miopon.utility alsoTestWebCases = false describeWebCases = if alsoTestWebCases then describe else describe.skip # describe 'test of nock', -> # it 'test of test', (done)-> # this.timeout 50000 # mioID = 'aaaa' # mioPass = 'PI:PASSWORD:<PASSWORD>END_PI' # client_id = 'ccc' # redirect_uri = 'ddd' # scope = nock miopon.endpoints.oAuth # oAuth { # mioID # mioPass # client_id # redirect_uri # success: -> # console.log 'success' # done() # failure: -> # console.log 'failure' # done() # } # # return describe 'The `oAuth` function', -> it '`oAuth` exists', -> expect(oAuth).is.a 'function' describeWebCases 'oAuth fails wihout mioID, mioPass, client_id or redirect_uri:', -> mioID = 'aaaa' mioPass = 'PI:PASSWORD:<PASSWORD>END_PI' client_id = 'ccc' redirect_uri = 'ddd' args = [ {} {mioID}, {mioPass}, {client_id}, {redirect_uri} {mioID, mioPass}, {mioID, client_id}, {mioID, redirect_uri} {mioPass, client_id}, {mioPass, redirect_uri} {client_id, redirect_uri} {mioID, mioPass, client_id} {mioID, mioPass, redirect_uri} {mioID, client_id, redirect_uri} {mioPass, client_id, redirect_uri} ] _.each args, (arg) -> it arg.toString(), (done) -> arg.failure = -> done() arg.success = -> expect(false).to.be.true done() oAuth arg it 'oAuth even failes with a nonsense set of arguments', (done) -> this.timeout 50000 oAuth { mioID mioPass client_id redirect_uri success: -> expect(false).to.be.true done() failure: -> done() } describe 'The `Coupon` constructor, \n', -> it 'should exist.', -> expect(Coupon).to.be.a.instanceof Function describe 'Test for the instance of `Coupon`. \n', -> coupon = null before -> coupon = new Coupon() # 後方互換のため残す。v2よりoAuthはCouponコンンストラクタ関数から分離した it 'the instance coupon should have a method `oAuth`', -> expect(coupon.oAuth).is.a 'function' # 互換チェック it '`coupon.oAuth` referes miopon.oAuth', -> expect(coupon.oAuth).to.equal miopon.oAuth it 'the instance coupon should have a method `inform`', -> expect(coupon.inform).is.a 'function' it 'the instance coupon should have a method `turn`', -> expect(coupon.turn).is.a 'function' # 後方互換のため残す。v2よりoAuthはCouponコンンストラクタ関数からprivateメンバへ移動 it 'the instance coupon should have a string property `api.urls.oAuth`', -> expect(coupon.urls.oAuth).to.be.an 'string' # 後方互換のため残す。v2よりoAuthはCouponコンンストラクタ関数からprivateメンバへ移動 it 'the instance coupon should have a string property `api.urls.coupon`', -> expect(coupon.urls.coupon).to.be.an 'string' describeWebCases 'inform fails wihout access_token or client_id:', -> access_token = 'PI:KEY:<KEY>END_PI' client_id = 'bbb' args = [ {} {access_token} {client_id} ] _.each args, (arg) -> it arg.toString(), (done) -> arg.failure = -> done() arg.success = -> expect(false).to.be.true done() coupon.inform arg it 'inform even fails with nonsense access_token and client_id.', (done) -> this.timeout 20000 coupon.inform { client_id access_token failure: -> done() success: -> expect(false).to.be.true done() } describeWebCases 'turn fails wihout access_token, client_id or query:', -> access_token = 'PI:KEY:<KEY>END_PI' client_id = 'bbb' query = {query:''} args = [ {} {access_token} {client_id} {access_token, client_id} {client_id, query} {query, access_token} ] _.each args, (arg) -> it arg.toString(), (done) -> arg.failure = -> done() arg.success = -> expect(false).to.be.true done() coupon.turn arg it 'turn even fails with nonsense access_token, client_id and query.', (done) -> this.timeout 20000 coupon.turn { client_id access_token query failure: -> done() success: -> expect(false).to.be.true done() } describe 'The module `utility`, \n', -> it 'should exist.', -> expect(utility).to.be.a.instanceof Object describe 'Test for the each member of `utility`. \n', -> describe '`arraify`', -> it 'the utility has a method `arraify`', -> expect(utility.arraify).is.a 'function' describe 'test of the utility method `arraify` cases: ', -> it 'undefined', -> result = utility.arraify undefined correctAnswer = [] expect(result).to.eql correctAnswer it 'string.', -> result = utility.arraify '1234567890' correctAnswer = ['1234567890'] expect(result).to.eql correctAnswer it 'number.', -> result = utility.arraify 1234567890 correctAnswer = ['1234567890'] expect(result).to.eql correctAnswer it 'string with hyphen to be ignored.', -> result = utility.arraify '1-23-4567-89-0' correctAnswer = ['1234567890'] expect(result).to.eql correctAnswer it 'string with brackets to be ignored.', -> result = utility.arraify '1(2)3{45}67[890]' correctAnswer = ['1234567890'] expect(result).to.eql correctAnswer it 'string with alphabets to be ignored.', -> result = utility.arraify '1a2b3c4d5e6f7g8h9i0' correctAnswer = ['1234567890'] expect(result).to.eql correctAnswer it 'non-number', -> result = utility.arraify 'aaa' correctAnswer = [] expect(result).to.eql correctAnswer it 'non-number and number', -> result = utility.arraify ['','1234567890','^&(*&&^())'] correctAnswer = ['1234567890'] expect(result).to.eql correctAnswer it 'non-numbers', -> result = utility.arraify ['','aaa','^&(*&&^())'] correctAnswer = [] expect(result).to.eql correctAnswer it 'array case', -> args = [ '1234567890' 1234567890 '1-23-4567-89-0' '1(2)3{45}67[890]' '1a2b3c4d5e6f7g8h9i0' ] result = utility.arraify args correctAnswer = ('1234567890' for n in args) expect(result).to.eql correctAnswer describe '`orderCouponUse`', -> it 'the utility has a method `orderCouponUse`', -> expect(utility.orderCouponUse).is.a 'function' describe 'test of the utility method `orderCouponUse` cases: ', -> _.each ['on', 1, 'abc', true], (arg) -> it '`orderCouponUse` works well in positive cases("on" or something evaluated as true)', -> result = utility.orderCouponUse arg expect(result).to.true _.each ['off', 0, '', false], (arg) -> it '`orderCouponUse` works well in negative cases("off" or something evaluated as false)', -> result = utility.orderCouponUse arg expect(result).to.false describe '`querify`', -> it 'the utility has a method `querify`', -> expect(utility.querify).is.a 'function' describe 'test of the utility method `querify` cases: ', -> describe 'case of information object: ', -> it '`querify` works well', -> result = utility.querify { information: require '../test/cases/querify-before.json' } correct =require '../test/cases/querify-after.json' expect(result).to.eql correct it '`querify` works well with filter', -> result = utility.querify { information: require '../test/cases/querify-before.json' filter: ['2345678901','4567890123'] } correct =require '../test/cases/querify-after_filtered.json' expect(result).to.eql correct it '`querify` works well with coupon order1', -> result = utility.querify { information: require '../test/cases/querify-before.json' couponUse: true } correct =require '../test/cases/querify-after_ordered1.json' expect(result).to.eql correct it '`querify` works well with coupon order2', -> result = utility.querify { information: require '../test/cases/querify-before.json' couponUse: 'off' } correct =require '../test/cases/querify-after_ordered2.json' expect(result).to.eql correct it '`querify` works well with broken input', -> result = utility.querify { information: require '../test/cases/querify-before_broken.json' } correct =require '../test/cases/querify-after_broken.json' expect(result).to.eql correct describe '`generateQuery`', -> it 'the utility has a method `generateQuery`', -> expect(utility.generateQuery).is.a 'function' describe 'behaviors:', -> it 'works with no codes', -> turnStates = [] exact = couponInfo: [] expect(utility.generateQuery {turnStates}).to.eql exact describe 'works with unformatted codes will be eliminated:', -> turnStatesCases = [ null, undefined,'dummycode', 1, false, true, {}, [] [null], [undefined],['dummycode'], [1], [false], [true], {}, [] ] exact = couponInfo: [] _.each turnStatesCases, (turnStateCase) -> it "#{turnStateCase}", -> expect(utility.generateQuery {turnStates:turnStateCase}).to.eql exact it 'works with single code', -> turnStates = [ { 'hdoWWWWWWWW':true } ] exact = couponInfo: [ { hdoInfo: [ {hdoServiceCode: 'hdoWWWWWWWW', couponUse: true } ] } ] expect(utility.generateQuery {turnStates}).to.eql exact it 'works with single code and "on" statement', -> turnStates = [ { 'hdoWWWWWWWW':'on' } ] exact = couponInfo: [ { hdoInfo: [ {hdoServiceCode: 'hdoWWWWWWWW', couponUse: true } ] } ] expect(utility.generateQuery {turnStates}).to.eql exact it 'works with single code and "off" statement', -> turnStates = [ { 'hdoWWWWWWWW':'off' } ] exact = couponInfo: [ { hdoInfo: [ {hdoServiceCode: 'hdoWWWWWWWW', couponUse: false } ] } ] expect(utility.generateQuery {turnStates}).to.eql exact it 'works with several code', -> turnStates = [ { 'hdoWWWWWWWW':true 'hdoYYYYYYYY':false 'hdoZZZZZZZZ':true } ] exact = couponInfo: [ { hdoInfo: [ {hdoServiceCode: 'hdoWWWWWWWW', couponUse: true } {hdoServiceCode: 'hdoYYYYYYYY', couponUse: false } {hdoServiceCode: 'hdoZZZZZZZZ', couponUse: true } ] } ] expect(utility.generateQuery {turnStates}).to.eql exact it 'works with several coupon', -> turnStates = [ { 'hdoWWWWWWWW':false }, { 'hdoXXXXXXXX':true } ] exact = couponInfo: [ { hdoInfo: [ {hdoServiceCode: 'hdoWWWWWWWW', couponUse: false } ] }, { hdoInfo: [ {hdoServiceCode: 'hdoXXXXXXXX', couponUse: true } ] } ] expect(utility.generateQuery {turnStates}).to.eql exact it 'works with complex object', -> turnStates = [ { 'hdoWWWWWWWW':true }, { 'hdoXXXXXXXX':false 'hdoYYYYYYYY':true }, { 'hdoZZZZZZZZ':false 'hdoVVVVVVVV':true 'hdoUUUUUUUU':false } ] exact = couponInfo: [ { hdoInfo: [ {hdoServiceCode: 'hdoWWWWWWWW', couponUse: true } ] }, { hdoInfo: [ {hdoServiceCode: 'hdoXXXXXXXX', couponUse: false } {hdoServiceCode: 'hdoYYYYYYYY', couponUse: true } ] }, { hdoInfo: [ {hdoServiceCode: 'hdoZZZZZZZZ', couponUse: false } {hdoServiceCode: 'hdoVVVVVVVV', couponUse: true } {hdoServiceCode: 'hdoUUUUUUUU', couponUse: false } ] } ] expect(utility.generateQuery {turnStates}).to.eql exact describe '`callback`', -> it 'the utility has a method `callback`', -> expect(utility.callback).is.a 'function' it '`callback` call the 1st argument if function', -> func = (arg) -> arg + arg actual = utility.callback func, 'aaaa' expect(actual is 'aaaaaaaa').to.be.true it '`callback` also works asynchronously', (done) -> utility.callback setTimeout, done, 20 it '`callback` do nothing with the 1st argument if non-function', -> actual = utility.callback 'aaa', 'bbb' expect(actual).to.be.false
[ { "context": "e: process.env.HUBOT_XMPP_USERNAME\n password: process.env.HUBOT_XMPP_PASSWORD\n rooms: process.env.HU", "end": 183, "score": 0.7930471897125244, "start": 172, "tag": "PASSWORD", "value": "process.env" }, { "context": "v.HUBOT_XMPP_USERNAME\n password:...
src/hubot/xmpp.coffee
russelldb/hubot
1
Robot = require '../robot' Xmpp = require 'node-xmpp' class XmppBot extends Robot run: -> options = username: process.env.HUBOT_XMPP_USERNAME password: process.env.HUBOT_XMPP_PASSWORD rooms: process.env.HUBOT_XMPP_ROOMS.split(',') keepaliveInterval: 30000 # ms interval to send whitespace to xmpp server console.log options @client = new Xmpp.Client jid: options.username password: options.password @client.on 'error', @.error @client.on 'online', @.online @client.on 'stanza', @.read @options = options error: (error) => console.error error online: => console.log 'Hubot XMPP client online' @client.send new Xmpp.Element('presence', type: 'available' ) .c('show').t('chat') # join each room # http://xmpp.org/extensions/xep-0045.html for XMPP chat standard for room in @options.rooms @client.send(new Xmpp.Element('presence', to: "#{room}/#{@name}" ) .c('x', xmlns: 'http://jabber.org/protocol/muc' ) .c('history', seconds: 1 )) # prevent the server from confusing us with old messages # and it seems that servers don't reliably support maxchars # or zero values # send raw whitespace for keepalive setInterval => @client.send ' ' , @options.keepaliveInterval read: (stanza) => if stanza.attrs.type is 'error' console.error '[xmpp error]' + stanza return switch stanza.name when 'message' @readMessage stanza when 'presence' @readPresence stanza readMessage: (stanza) => # ignore non-messages return if stanza.attrs.type not in ['groupchat', 'direct', 'chat'] # ignore our own messages return if @options.username in stanza.attrs.from # ignore messages from the server. on Openfire, this includes "This room is not anonymous" return if stanza.attrs.from in @options.rooms # ignore empty bodies (i.e., topic changes -- maybe watch these someday) body = stanza.getChild 'body' return unless body message = body.getText() [room, from] = stanza.attrs.from.split '/' # note that 'from' isn't a full JID, just the local user part user = @userForId from user.room = room user.type = stanza.attrs.type @receive new Robot.TextMessage user, message readPresence: (stanza) => jid = new Xmpp.JID(stanza.attrs.from) bareJid = jid.bare().toString() # xmpp doesn't add types for standard available mesages # note that upon joining a room, server will send available # presences for all members # http://xmpp.org/rfcs/rfc3921.html#rfc.section.2.2.1 stanza.attrs.type ?= 'available' switch stanza.attrs.type when 'subscribe' console.log "#{stanza.attrs.from} subscribed to us" @client.send new Xmpp.Element('presence', from: stanza.attrs.to to: stanza.attrs.from id: stanza.attrs.id type: 'subscribed' ) when 'probe' @client.send new Xmpp.Element('presence', from: stanza.attrs.to to: stanza.attrs.from id: stanza.attrs.id ) when 'available' if bareJid not in @options.rooms from = stanza.attrs.from else # room presence is stupid, and optional for some anonymous rooms # http://xmpp.org/extensions/xep-0045.html#enter-nonanon from = stanza.getChild('x', 'http://jabber.org/protocol/muc#user')?.getChild('item')?.attrs?.jid return if not from? # for now, user IDs and user names are the same. we don't # use full JIDs as user ID, since we don't get them in # standard groupchat messages jid = new Xmpp.JID(from) userId = userName = jid.user console.log "Availability received for #{userId}" user = @userForId userId, name: userName user.jid = jid.toString() send: (user, strings...) -> for str in strings console.log "Sending to #{user.room}: #{str}" to = if user.type in ['direct', 'chat'] then "#{user.room}/#{user.id}" else user.room message = new Xmpp.Element('message', from: @options.username to: to type: user.type ). c('body').t(str) @client.send message reply: (user, strings...) -> for str in strings @send user, "#{user.name}: #{str}" topic: (user, strings...) -> string = strings.join "\n" message = new Xmpp.Element('message', from: @options.username, to: user.room type: user.type ). c('subject').t(string) @client.send message module.exports = XmppBot
199134
Robot = require '../robot' Xmpp = require 'node-xmpp' class XmppBot extends Robot run: -> options = username: process.env.HUBOT_XMPP_USERNAME password: <PASSWORD>.<PASSWORD>_XMPP_PASSWORD rooms: process.env.HUBOT_XMPP_ROOMS.split(',') keepaliveInterval: 30000 # ms interval to send whitespace to xmpp server console.log options @client = new Xmpp.Client jid: options.username password: <PASSWORD> @client.on 'error', @.error @client.on 'online', @.online @client.on 'stanza', @.read @options = options error: (error) => console.error error online: => console.log 'Hubot XMPP client online' @client.send new Xmpp.Element('presence', type: 'available' ) .c('show').t('chat') # join each room # http://xmpp.org/extensions/xep-0045.html for XMPP chat standard for room in @options.rooms @client.send(new Xmpp.Element('presence', to: "#{room}/#{@name}" ) .c('x', xmlns: 'http://jabber.org/protocol/muc' ) .c('history', seconds: 1 )) # prevent the server from confusing us with old messages # and it seems that servers don't reliably support maxchars # or zero values # send raw whitespace for keepalive setInterval => @client.send ' ' , @options.keepaliveInterval read: (stanza) => if stanza.attrs.type is 'error' console.error '[xmpp error]' + stanza return switch stanza.name when 'message' @readMessage stanza when 'presence' @readPresence stanza readMessage: (stanza) => # ignore non-messages return if stanza.attrs.type not in ['groupchat', 'direct', 'chat'] # ignore our own messages return if @options.username in stanza.attrs.from # ignore messages from the server. on Openfire, this includes "This room is not anonymous" return if stanza.attrs.from in @options.rooms # ignore empty bodies (i.e., topic changes -- maybe watch these someday) body = stanza.getChild 'body' return unless body message = body.getText() [room, from] = stanza.attrs.from.split '/' # note that 'from' isn't a full JID, just the local user part user = @userForId from user.room = room user.type = stanza.attrs.type @receive new Robot.TextMessage user, message readPresence: (stanza) => jid = new Xmpp.JID(stanza.attrs.from) bareJid = jid.bare().toString() # xmpp doesn't add types for standard available mesages # note that upon joining a room, server will send available # presences for all members # http://xmpp.org/rfcs/rfc3921.html#rfc.section.2.2.1 stanza.attrs.type ?= 'available' switch stanza.attrs.type when 'subscribe' console.log "#{stanza.attrs.from} subscribed to us" @client.send new Xmpp.Element('presence', from: stanza.attrs.to to: stanza.attrs.from id: stanza.attrs.id type: 'subscribed' ) when 'probe' @client.send new Xmpp.Element('presence', from: stanza.attrs.to to: stanza.attrs.from id: stanza.attrs.id ) when 'available' if bareJid not in @options.rooms from = stanza.attrs.from else # room presence is stupid, and optional for some anonymous rooms # http://xmpp.org/extensions/xep-0045.html#enter-nonanon from = stanza.getChild('x', 'http://jabber.org/protocol/muc#user')?.getChild('item')?.attrs?.jid return if not from? # for now, user IDs and user names are the same. we don't # use full JIDs as user ID, since we don't get them in # standard groupchat messages jid = new Xmpp.JID(from) userId = userName = jid.user console.log "Availability received for #{userId}" user = @userForId userId, name: userName user.jid = jid.toString() send: (user, strings...) -> for str in strings console.log "Sending to #{user.room}: #{str}" to = if user.type in ['direct', 'chat'] then "#{user.room}/#{user.id}" else user.room message = new Xmpp.Element('message', from: @options.username to: to type: user.type ). c('body').t(str) @client.send message reply: (user, strings...) -> for str in strings @send user, "#{user.name}: #{str}" topic: (user, strings...) -> string = strings.join "\n" message = new Xmpp.Element('message', from: @options.username, to: user.room type: user.type ). c('subject').t(string) @client.send message module.exports = XmppBot
true
Robot = require '../robot' Xmpp = require 'node-xmpp' class XmppBot extends Robot run: -> options = username: process.env.HUBOT_XMPP_USERNAME password: PI:PASSWORD:<PASSWORD>END_PI.PI:PASSWORD:<PASSWORD>END_PI_XMPP_PASSWORD rooms: process.env.HUBOT_XMPP_ROOMS.split(',') keepaliveInterval: 30000 # ms interval to send whitespace to xmpp server console.log options @client = new Xmpp.Client jid: options.username password: PI:PASSWORD:<PASSWORD>END_PI @client.on 'error', @.error @client.on 'online', @.online @client.on 'stanza', @.read @options = options error: (error) => console.error error online: => console.log 'Hubot XMPP client online' @client.send new Xmpp.Element('presence', type: 'available' ) .c('show').t('chat') # join each room # http://xmpp.org/extensions/xep-0045.html for XMPP chat standard for room in @options.rooms @client.send(new Xmpp.Element('presence', to: "#{room}/#{@name}" ) .c('x', xmlns: 'http://jabber.org/protocol/muc' ) .c('history', seconds: 1 )) # prevent the server from confusing us with old messages # and it seems that servers don't reliably support maxchars # or zero values # send raw whitespace for keepalive setInterval => @client.send ' ' , @options.keepaliveInterval read: (stanza) => if stanza.attrs.type is 'error' console.error '[xmpp error]' + stanza return switch stanza.name when 'message' @readMessage stanza when 'presence' @readPresence stanza readMessage: (stanza) => # ignore non-messages return if stanza.attrs.type not in ['groupchat', 'direct', 'chat'] # ignore our own messages return if @options.username in stanza.attrs.from # ignore messages from the server. on Openfire, this includes "This room is not anonymous" return if stanza.attrs.from in @options.rooms # ignore empty bodies (i.e., topic changes -- maybe watch these someday) body = stanza.getChild 'body' return unless body message = body.getText() [room, from] = stanza.attrs.from.split '/' # note that 'from' isn't a full JID, just the local user part user = @userForId from user.room = room user.type = stanza.attrs.type @receive new Robot.TextMessage user, message readPresence: (stanza) => jid = new Xmpp.JID(stanza.attrs.from) bareJid = jid.bare().toString() # xmpp doesn't add types for standard available mesages # note that upon joining a room, server will send available # presences for all members # http://xmpp.org/rfcs/rfc3921.html#rfc.section.2.2.1 stanza.attrs.type ?= 'available' switch stanza.attrs.type when 'subscribe' console.log "#{stanza.attrs.from} subscribed to us" @client.send new Xmpp.Element('presence', from: stanza.attrs.to to: stanza.attrs.from id: stanza.attrs.id type: 'subscribed' ) when 'probe' @client.send new Xmpp.Element('presence', from: stanza.attrs.to to: stanza.attrs.from id: stanza.attrs.id ) when 'available' if bareJid not in @options.rooms from = stanza.attrs.from else # room presence is stupid, and optional for some anonymous rooms # http://xmpp.org/extensions/xep-0045.html#enter-nonanon from = stanza.getChild('x', 'http://jabber.org/protocol/muc#user')?.getChild('item')?.attrs?.jid return if not from? # for now, user IDs and user names are the same. we don't # use full JIDs as user ID, since we don't get them in # standard groupchat messages jid = new Xmpp.JID(from) userId = userName = jid.user console.log "Availability received for #{userId}" user = @userForId userId, name: userName user.jid = jid.toString() send: (user, strings...) -> for str in strings console.log "Sending to #{user.room}: #{str}" to = if user.type in ['direct', 'chat'] then "#{user.room}/#{user.id}" else user.room message = new Xmpp.Element('message', from: @options.username to: to type: user.type ). c('body').t(str) @client.send message reply: (user, strings...) -> for str in strings @send user, "#{user.name}: #{str}" topic: (user, strings...) -> string = strings.join "\n" message = new Xmpp.Element('message', from: @options.username, to: user.room type: user.type ). c('subject').t(string) @client.send message module.exports = XmppBot
[ { "context": "\n\n###*\n * Gets some JSON from some url.\n * @author MindfulMinun\n * @param {String} url - The URL to get the data ", "end": 152, "score": 0.9558537602424622, "start": 140, "tag": "USERNAME", "value": "MindfulMinun" }, { "context": "#*\n * Posts some JSON data to som...
src/main.coffee
MindfulMinun/xyz
0
###* * The xyz object * @global ### xyz = new Object require './math' require './time' ###* * Gets some JSON from some url. * @author MindfulMinun * @param {String} url - The URL to get the data from. * @returns {Promise<Response>} * @example * xyz.getJSON('https://jsonplaceholder.typicode.com/todos/1') * .then(console.log); * // { * // "userId": 1, * // "id": 1, * // "title": "delectus aut autem", * // "completed": false * // } * @since Aug 30, 2018 - 0.1.0 * @version 0.1.0 ### xyz.getJSON = (url) -> new Promise (resolve, reject) -> r = new XMLHttpRequest r.open 'GET', url, yes r.onload = -> if 200 <= @status < 400 # Success! resolve JSON.parse @response else # Server reached, returned error reject @response r.send() ###* * Posts some JSON data to some url. * @author MindfulMinun * @param {String} url - The URL to post the data to. * @param {Object} data - The data to post. * @returns {undefined} * @since Aug 30, 2018 - 0.1.0 * @example * xyz.postJSON('https://jsonplaceholder.typicode.com/posts', { * "title": "My example JSON" * }); * @version 0.1.0 ### xyz.postJSON = (url, data) -> r = new XMLHttpRequest r.open 'POST', url, yes r.setRequestHeader 'Content-Type', 'application/json; charset=UTF-8' r.send data return ###* * Gets some data from some url. * @author MindfulMinun * @param {String} url - The URL to get the data from. * @returns {Promise<Response>} * @since Aug 30, 2018 - 0.1.0 * @version 0.1.0 ### xyz.get = (url) -> new Promise (resolve, reject) -> r = new XMLHttpRequest r.open 'GET', url, yes r.onload = -> if 200 <= @status < 400 # Success! resolve @response else # Server reached, returned error reject @response r.send() ###* * Posts some data to some url. * @author MindfulMinun * @param {String} url - The URL to post the data to. * @param {String} data - The data to post. * @returns {undefined} * @since Aug 30, 2018 - 0.1.0 * @version 0.1.0 ### xyz.post = (url, data) -> r = new XMLHttpRequest r.open 'POST', url, yes r.setRequestHeader 'Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8' r.send data return ###* * Calls a function for each element of the array, then returns that array. * @author MindfulMinun * @param {Array} arr - The array to loop over * @returns {Array} The array that was looped over * @since Aug 22, 2018 - 0.1.0 * @example * xyz.tap([1, 2, 3, 4, 5], function (el, i, arr) { * console.log(el); * }); * @version 0.1.0 ### xyz.tap = (arr, fn) -> for el, i in arr fn(el, i, arr) arr ###* * Chooses a random element from an array. * @author MindfulMinun * @param {Array} arr - The array to choose from * @returns {*} An array element * @private * @example * xyz._chooseArray([1, 2, 3, 4, 5]) // -> A random element * @since Aug 28, 2018 - 0.1.0 * @version 0.1.0 ### xyz._chooseArray = (arr) -> arr[Math.floor Math.random() * arr.length] ###* * Retrieves an element from an array given its index. * @author MindfulMinun * @param {Array} arr - The array retrieve from * @param {Number} i - The index of the element to retrieve. If negative, the nth element from the end is returned. * @returns {*} The nth element from the array. * @example * var arr = [0, 1, 2, 3, 4, 5] * xyz.nth(arr, 0) // -> 0 * xyz.nth(arr, 4) // -> 4 * xyz.nth(arr, -0) // -> 5 * xyz.nth(arr, -4) // -> 1 * @since Aug 28, 2018 - 0.1.0 * @version 0.1.0 ### xyz.nth = (arr, i) -> _isPositiveZero = (zero) -> 1 / zero is Infinity pos = i neg = (arr.length - 1) + i if i isnt 0 arr[if Math.sign(i) is 1 then pos else neg] else arr[if _isPositiveZero(i) then pos else neg] ###* * Parses a string of HTML. * @author MindfulMinun * @param {String} html - The HTML to parse * @returns {HTMLElement[]} - An array of HTML elements. * @example * xyz.parseHTML(` * <h1>My header</h1> * <p>My paragraph</p> * `) // -> [h1, p] * @since Aug 23, 2018 - 0.1.0 * @version 0.1.0 ### xyz.parseHTML = (html) -> tmp = document.implementation.createHTMLDocument() tmp.body.innerHTML = html Array.from tmp.body.children ###* * Escapes an unsafe string for use in HTML / XML * @author MindfulMinun * @param {String} unsafe - The unsafe string to escape * @returns {String} The escaped string * @example * xyz.escapeHTML('<my unsafe="string">') * // -> '&lt;my unsafe=&quot;string&quot;&gt;' * @since Aug 24, 2018 - 0.1.0 * @version 0.1.0 ### xyz.escapeHTML = (unsafe) -> _escapeMap = { '&': '&amp;' '<': '&lt;' '>': '&gt;' '"': '&quot;' "'": '&#39;' } unsafe.replace(/[&<>"']/g, (m) -> _escapeMap[m]) ###* * Returns a random number between `min` and `max`, optionally floating. * @author MindfulMinun * @param {Number} [min] - The lower bound to generate numbers from. Defaults to 0. * @param {Number} [max] - The upper bound to generate numbers from. * @param {Boolean} [float] - Whether to return a floating-point number or an integer. Defaults to false. * @returns {Number} The randomly generated number. * @example * xyz.random() // -> random float between 0 and 1 * xyz.random(8) // -> random int between 0 and 8 * xyz.random(8, true) // -> random float between 0 and 8 * xyz.random(4, 8) // -> random int between 4 and 8 * xyz.random(4, 8, true) // -> random float between 4 and 8 * @since Aug 23, 2018 - 0.1.0 * @version 0.1.0 ### xyz.random = (min, max, float) -> a = arguments switch a.length when 0 then return Math.random() # xd shhh when 1 if typeof a[0] is "number" [min, max, float] = [0, a[0], no] else throw Error "Expected argument `max` to be a finite number." when 2 switch typeof a[1] when "number" then [min, max, float] = [a[0], a[1], no] when "boolean" then [min, max, float] = [0, a[0], a[1]] else throw Error "Expected last argument to be either a boolean or a number." when 3 then [min, max, float] = [min, max, float] else throw Error "Expected at most 3 arguments, instead saw #{a.length}" #! Type checking if not Number.isFinite(min) throw Error "Expected argument `min` to be a finite number." if not Number.isFinite(max) throw Error "Expected argument `max` to be a finite number." if typeof float isnt "boolean" throw Error "Expected argument `float` to be a boolean." if min >= max throw Error "Expected argument `min` (#{min}) to be less than `max` (#{max})" # [min, max, float] if float # Return floating-point number Math.random() * (max - min) + min else # Return integer [min, max] = [Math.floor(min), Math.ceil(max)] Math.floor(Math.random() * (max - min)) + min ###* * Determine if a and b are equivalent. * @author MindfulMinun * @param {*} a - The object to compare to `b` * @param {*} b - The object to compare to `a` * @returns {Boolean} Whether `a` and `b` are the same value * @example * xyz.is(NaN, 0 / 0) // -> true * xyz.is(0, 0) // -> true * xyz.is(-0, 0) // -> false * @since Aug 28, 2018 - 0.1.0 * @version 0.1.0 ### xyz.is = (a, b) -> # Modeled after Object.is Same-value algorithm if a is b (a isnt 0) or ((1 / a) is (1 / b)) else # ¿NaN is NaN? (a isnt a) and (b isnt b) ###* * Determine the type of an object. * @author MindfulMinun * @param {*} obj - The object with an unknown type. * @returns {String} The object's type. * @example * var set = new Set * , map = new Map * , arr = new Array; * xyz.type(set) // -> "set" * xyz.type(map) // -> "map" * xyz.type(arr) // -> "array" * @since Aug 28, 2018 - 0.1.0 * @version 0.1.0 ### xyz.type = (obj) -> Object::toString.call(obj).replace(/^\[object (.+)\]$/, '$1').toLowerCase() ###* * Writes properties from `sources` to `target` if they don’t exist. * @author MindfulMinun * @param {Object} target - The target to assign properties to. This object will be mutated. * @param {...Object} sources - The sources to assign properties from. * @returns {Object} The mutated target * @example * xyz.defaults({ * key: "value" * }, { * key: "default value", * foo: "bar" * }) * // -> { key: 'value', foo: 'bar' } * @since Aug 30, 2018 - 0.1.0 * @version 0.1.0 ### xyz.defaults = (target, ...sources) -> if not target? throw Error "Argument `target` must be an object." target = Object(target) for source, i in sources if source? for key, value of source if (not Object::hasOwnProperty.call(target, key)) target[key] = source[key] target ### *** Exports *** ### if this is window? window.xyz = xyz else module.exports = xyz
161879
###* * The xyz object * @global ### xyz = new Object require './math' require './time' ###* * Gets some JSON from some url. * @author MindfulMinun * @param {String} url - The URL to get the data from. * @returns {Promise<Response>} * @example * xyz.getJSON('https://jsonplaceholder.typicode.com/todos/1') * .then(console.log); * // { * // "userId": 1, * // "id": 1, * // "title": "delectus aut autem", * // "completed": false * // } * @since Aug 30, 2018 - 0.1.0 * @version 0.1.0 ### xyz.getJSON = (url) -> new Promise (resolve, reject) -> r = new XMLHttpRequest r.open 'GET', url, yes r.onload = -> if 200 <= @status < 400 # Success! resolve JSON.parse @response else # Server reached, returned error reject @response r.send() ###* * Posts some JSON data to some url. * @author MindfulMinun * @param {String} url - The URL to post the data to. * @param {Object} data - The data to post. * @returns {undefined} * @since Aug 30, 2018 - 0.1.0 * @example * xyz.postJSON('https://jsonplaceholder.typicode.com/posts', { * "title": "My example JSON" * }); * @version 0.1.0 ### xyz.postJSON = (url, data) -> r = new XMLHttpRequest r.open 'POST', url, yes r.setRequestHeader 'Content-Type', 'application/json; charset=UTF-8' r.send data return ###* * Gets some data from some url. * @author MindfulMinun * @param {String} url - The URL to get the data from. * @returns {Promise<Response>} * @since Aug 30, 2018 - 0.1.0 * @version 0.1.0 ### xyz.get = (url) -> new Promise (resolve, reject) -> r = new XMLHttpRequest r.open 'GET', url, yes r.onload = -> if 200 <= @status < 400 # Success! resolve @response else # Server reached, returned error reject @response r.send() ###* * Posts some data to some url. * @author MindfulMinun * @param {String} url - The URL to post the data to. * @param {String} data - The data to post. * @returns {undefined} * @since Aug 30, 2018 - 0.1.0 * @version 0.1.0 ### xyz.post = (url, data) -> r = new XMLHttpRequest r.open 'POST', url, yes r.setRequestHeader 'Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8' r.send data return ###* * Calls a function for each element of the array, then returns that array. * @author MindfulMinun * @param {Array} arr - The array to loop over * @returns {Array} The array that was looped over * @since Aug 22, 2018 - 0.1.0 * @example * xyz.tap([1, 2, 3, 4, 5], function (el, i, arr) { * console.log(el); * }); * @version 0.1.0 ### xyz.tap = (arr, fn) -> for el, i in arr fn(el, i, arr) arr ###* * Chooses a random element from an array. * @author MindfulMinun * @param {Array} arr - The array to choose from * @returns {*} An array element * @private * @example * xyz._chooseArray([1, 2, 3, 4, 5]) // -> A random element * @since Aug 28, 2018 - 0.1.0 * @version 0.1.0 ### xyz._chooseArray = (arr) -> arr[Math.floor Math.random() * arr.length] ###* * Retrieves an element from an array given its index. * @author MindfulMinun * @param {Array} arr - The array retrieve from * @param {Number} i - The index of the element to retrieve. If negative, the nth element from the end is returned. * @returns {*} The nth element from the array. * @example * var arr = [0, 1, 2, 3, 4, 5] * xyz.nth(arr, 0) // -> 0 * xyz.nth(arr, 4) // -> 4 * xyz.nth(arr, -0) // -> 5 * xyz.nth(arr, -4) // -> 1 * @since Aug 28, 2018 - 0.1.0 * @version 0.1.0 ### xyz.nth = (arr, i) -> _isPositiveZero = (zero) -> 1 / zero is Infinity pos = i neg = (arr.length - 1) + i if i isnt 0 arr[if Math.sign(i) is 1 then pos else neg] else arr[if _isPositiveZero(i) then pos else neg] ###* * Parses a string of HTML. * @author MindfulMinun * @param {String} html - The HTML to parse * @returns {HTMLElement[]} - An array of HTML elements. * @example * xyz.parseHTML(` * <h1>My header</h1> * <p>My paragraph</p> * `) // -> [h1, p] * @since Aug 23, 2018 - 0.1.0 * @version 0.1.0 ### xyz.parseHTML = (html) -> tmp = document.implementation.createHTMLDocument() tmp.body.innerHTML = html Array.from tmp.body.children ###* * Escapes an unsafe string for use in HTML / XML * @author MindfulMinun * @param {String} unsafe - The unsafe string to escape * @returns {String} The escaped string * @example * xyz.escapeHTML('<my unsafe="string">') * // -> '&lt;my unsafe=&quot;string&quot;&gt;' * @since Aug 24, 2018 - 0.1.0 * @version 0.1.0 ### xyz.escapeHTML = (unsafe) -> _escapeMap = { '&': '&amp;' '<': '&lt;' '>': '&gt;' '"': '&quot;' "'": '&#39;' } unsafe.replace(/[&<>"']/g, (m) -> _escapeMap[m]) ###* * Returns a random number between `min` and `max`, optionally floating. * @author MindfulMinun * @param {Number} [min] - The lower bound to generate numbers from. Defaults to 0. * @param {Number} [max] - The upper bound to generate numbers from. * @param {Boolean} [float] - Whether to return a floating-point number or an integer. Defaults to false. * @returns {Number} The randomly generated number. * @example * xyz.random() // -> random float between 0 and 1 * xyz.random(8) // -> random int between 0 and 8 * xyz.random(8, true) // -> random float between 0 and 8 * xyz.random(4, 8) // -> random int between 4 and 8 * xyz.random(4, 8, true) // -> random float between 4 and 8 * @since Aug 23, 2018 - 0.1.0 * @version 0.1.0 ### xyz.random = (min, max, float) -> a = arguments switch a.length when 0 then return Math.random() # xd shhh when 1 if typeof a[0] is "number" [min, max, float] = [0, a[0], no] else throw Error "Expected argument `max` to be a finite number." when 2 switch typeof a[1] when "number" then [min, max, float] = [a[0], a[1], no] when "boolean" then [min, max, float] = [0, a[0], a[1]] else throw Error "Expected last argument to be either a boolean or a number." when 3 then [min, max, float] = [min, max, float] else throw Error "Expected at most 3 arguments, instead saw #{a.length}" #! Type checking if not Number.isFinite(min) throw Error "Expected argument `min` to be a finite number." if not Number.isFinite(max) throw Error "Expected argument `max` to be a finite number." if typeof float isnt "boolean" throw Error "Expected argument `float` to be a boolean." if min >= max throw Error "Expected argument `min` (#{min}) to be less than `max` (#{max})" # [min, max, float] if float # Return floating-point number Math.random() * (max - min) + min else # Return integer [min, max] = [Math.floor(min), Math.ceil(max)] Math.floor(Math.random() * (max - min)) + min ###* * Determine if a and b are equivalent. * @author <NAME> * @param {*} a - The object to compare to `b` * @param {*} b - The object to compare to `a` * @returns {Boolean} Whether `a` and `b` are the same value * @example * xyz.is(NaN, 0 / 0) // -> true * xyz.is(0, 0) // -> true * xyz.is(-0, 0) // -> false * @since Aug 28, 2018 - 0.1.0 * @version 0.1.0 ### xyz.is = (a, b) -> # Modeled after Object.is Same-value algorithm if a is b (a isnt 0) or ((1 / a) is (1 / b)) else # ¿NaN is NaN? (a isnt a) and (b isnt b) ###* * Determine the type of an object. * @author MindfulMinun * @param {*} obj - The object with an unknown type. * @returns {String} The object's type. * @example * var set = new Set * , map = new Map * , arr = new Array; * xyz.type(set) // -> "set" * xyz.type(map) // -> "map" * xyz.type(arr) // -> "array" * @since Aug 28, 2018 - 0.1.0 * @version 0.1.0 ### xyz.type = (obj) -> Object::toString.call(obj).replace(/^\[object (.+)\]$/, '$1').toLowerCase() ###* * Writes properties from `sources` to `target` if they don’t exist. * @author MindfulMinun * @param {Object} target - The target to assign properties to. This object will be mutated. * @param {...Object} sources - The sources to assign properties from. * @returns {Object} The mutated target * @example * xyz.defaults({ * key: "value" * }, { * key: "default value", * foo: "bar" * }) * // -> { key: 'value', foo: 'bar' } * @since Aug 30, 2018 - 0.1.0 * @version 0.1.0 ### xyz.defaults = (target, ...sources) -> if not target? throw Error "Argument `target` must be an object." target = Object(target) for source, i in sources if source? for key, value of source if (not Object::hasOwnProperty.call(target, key)) target[key] = source[key] target ### *** Exports *** ### if this is window? window.xyz = xyz else module.exports = xyz
true
###* * The xyz object * @global ### xyz = new Object require './math' require './time' ###* * Gets some JSON from some url. * @author MindfulMinun * @param {String} url - The URL to get the data from. * @returns {Promise<Response>} * @example * xyz.getJSON('https://jsonplaceholder.typicode.com/todos/1') * .then(console.log); * // { * // "userId": 1, * // "id": 1, * // "title": "delectus aut autem", * // "completed": false * // } * @since Aug 30, 2018 - 0.1.0 * @version 0.1.0 ### xyz.getJSON = (url) -> new Promise (resolve, reject) -> r = new XMLHttpRequest r.open 'GET', url, yes r.onload = -> if 200 <= @status < 400 # Success! resolve JSON.parse @response else # Server reached, returned error reject @response r.send() ###* * Posts some JSON data to some url. * @author MindfulMinun * @param {String} url - The URL to post the data to. * @param {Object} data - The data to post. * @returns {undefined} * @since Aug 30, 2018 - 0.1.0 * @example * xyz.postJSON('https://jsonplaceholder.typicode.com/posts', { * "title": "My example JSON" * }); * @version 0.1.0 ### xyz.postJSON = (url, data) -> r = new XMLHttpRequest r.open 'POST', url, yes r.setRequestHeader 'Content-Type', 'application/json; charset=UTF-8' r.send data return ###* * Gets some data from some url. * @author MindfulMinun * @param {String} url - The URL to get the data from. * @returns {Promise<Response>} * @since Aug 30, 2018 - 0.1.0 * @version 0.1.0 ### xyz.get = (url) -> new Promise (resolve, reject) -> r = new XMLHttpRequest r.open 'GET', url, yes r.onload = -> if 200 <= @status < 400 # Success! resolve @response else # Server reached, returned error reject @response r.send() ###* * Posts some data to some url. * @author MindfulMinun * @param {String} url - The URL to post the data to. * @param {String} data - The data to post. * @returns {undefined} * @since Aug 30, 2018 - 0.1.0 * @version 0.1.0 ### xyz.post = (url, data) -> r = new XMLHttpRequest r.open 'POST', url, yes r.setRequestHeader 'Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8' r.send data return ###* * Calls a function for each element of the array, then returns that array. * @author MindfulMinun * @param {Array} arr - The array to loop over * @returns {Array} The array that was looped over * @since Aug 22, 2018 - 0.1.0 * @example * xyz.tap([1, 2, 3, 4, 5], function (el, i, arr) { * console.log(el); * }); * @version 0.1.0 ### xyz.tap = (arr, fn) -> for el, i in arr fn(el, i, arr) arr ###* * Chooses a random element from an array. * @author MindfulMinun * @param {Array} arr - The array to choose from * @returns {*} An array element * @private * @example * xyz._chooseArray([1, 2, 3, 4, 5]) // -> A random element * @since Aug 28, 2018 - 0.1.0 * @version 0.1.0 ### xyz._chooseArray = (arr) -> arr[Math.floor Math.random() * arr.length] ###* * Retrieves an element from an array given its index. * @author MindfulMinun * @param {Array} arr - The array retrieve from * @param {Number} i - The index of the element to retrieve. If negative, the nth element from the end is returned. * @returns {*} The nth element from the array. * @example * var arr = [0, 1, 2, 3, 4, 5] * xyz.nth(arr, 0) // -> 0 * xyz.nth(arr, 4) // -> 4 * xyz.nth(arr, -0) // -> 5 * xyz.nth(arr, -4) // -> 1 * @since Aug 28, 2018 - 0.1.0 * @version 0.1.0 ### xyz.nth = (arr, i) -> _isPositiveZero = (zero) -> 1 / zero is Infinity pos = i neg = (arr.length - 1) + i if i isnt 0 arr[if Math.sign(i) is 1 then pos else neg] else arr[if _isPositiveZero(i) then pos else neg] ###* * Parses a string of HTML. * @author MindfulMinun * @param {String} html - The HTML to parse * @returns {HTMLElement[]} - An array of HTML elements. * @example * xyz.parseHTML(` * <h1>My header</h1> * <p>My paragraph</p> * `) // -> [h1, p] * @since Aug 23, 2018 - 0.1.0 * @version 0.1.0 ### xyz.parseHTML = (html) -> tmp = document.implementation.createHTMLDocument() tmp.body.innerHTML = html Array.from tmp.body.children ###* * Escapes an unsafe string for use in HTML / XML * @author MindfulMinun * @param {String} unsafe - The unsafe string to escape * @returns {String} The escaped string * @example * xyz.escapeHTML('<my unsafe="string">') * // -> '&lt;my unsafe=&quot;string&quot;&gt;' * @since Aug 24, 2018 - 0.1.0 * @version 0.1.0 ### xyz.escapeHTML = (unsafe) -> _escapeMap = { '&': '&amp;' '<': '&lt;' '>': '&gt;' '"': '&quot;' "'": '&#39;' } unsafe.replace(/[&<>"']/g, (m) -> _escapeMap[m]) ###* * Returns a random number between `min` and `max`, optionally floating. * @author MindfulMinun * @param {Number} [min] - The lower bound to generate numbers from. Defaults to 0. * @param {Number} [max] - The upper bound to generate numbers from. * @param {Boolean} [float] - Whether to return a floating-point number or an integer. Defaults to false. * @returns {Number} The randomly generated number. * @example * xyz.random() // -> random float between 0 and 1 * xyz.random(8) // -> random int between 0 and 8 * xyz.random(8, true) // -> random float between 0 and 8 * xyz.random(4, 8) // -> random int between 4 and 8 * xyz.random(4, 8, true) // -> random float between 4 and 8 * @since Aug 23, 2018 - 0.1.0 * @version 0.1.0 ### xyz.random = (min, max, float) -> a = arguments switch a.length when 0 then return Math.random() # xd shhh when 1 if typeof a[0] is "number" [min, max, float] = [0, a[0], no] else throw Error "Expected argument `max` to be a finite number." when 2 switch typeof a[1] when "number" then [min, max, float] = [a[0], a[1], no] when "boolean" then [min, max, float] = [0, a[0], a[1]] else throw Error "Expected last argument to be either a boolean or a number." when 3 then [min, max, float] = [min, max, float] else throw Error "Expected at most 3 arguments, instead saw #{a.length}" #! Type checking if not Number.isFinite(min) throw Error "Expected argument `min` to be a finite number." if not Number.isFinite(max) throw Error "Expected argument `max` to be a finite number." if typeof float isnt "boolean" throw Error "Expected argument `float` to be a boolean." if min >= max throw Error "Expected argument `min` (#{min}) to be less than `max` (#{max})" # [min, max, float] if float # Return floating-point number Math.random() * (max - min) + min else # Return integer [min, max] = [Math.floor(min), Math.ceil(max)] Math.floor(Math.random() * (max - min)) + min ###* * Determine if a and b are equivalent. * @author PI:NAME:<NAME>END_PI * @param {*} a - The object to compare to `b` * @param {*} b - The object to compare to `a` * @returns {Boolean} Whether `a` and `b` are the same value * @example * xyz.is(NaN, 0 / 0) // -> true * xyz.is(0, 0) // -> true * xyz.is(-0, 0) // -> false * @since Aug 28, 2018 - 0.1.0 * @version 0.1.0 ### xyz.is = (a, b) -> # Modeled after Object.is Same-value algorithm if a is b (a isnt 0) or ((1 / a) is (1 / b)) else # ¿NaN is NaN? (a isnt a) and (b isnt b) ###* * Determine the type of an object. * @author MindfulMinun * @param {*} obj - The object with an unknown type. * @returns {String} The object's type. * @example * var set = new Set * , map = new Map * , arr = new Array; * xyz.type(set) // -> "set" * xyz.type(map) // -> "map" * xyz.type(arr) // -> "array" * @since Aug 28, 2018 - 0.1.0 * @version 0.1.0 ### xyz.type = (obj) -> Object::toString.call(obj).replace(/^\[object (.+)\]$/, '$1').toLowerCase() ###* * Writes properties from `sources` to `target` if they don’t exist. * @author MindfulMinun * @param {Object} target - The target to assign properties to. This object will be mutated. * @param {...Object} sources - The sources to assign properties from. * @returns {Object} The mutated target * @example * xyz.defaults({ * key: "value" * }, { * key: "default value", * foo: "bar" * }) * // -> { key: 'value', foo: 'bar' } * @since Aug 30, 2018 - 0.1.0 * @version 0.1.0 ### xyz.defaults = (target, ...sources) -> if not target? throw Error "Argument `target` must be an object." target = Object(target) for source, i in sources if source? for key, value of source if (not Object::hasOwnProperty.call(target, key)) target[key] = source[key] target ### *** Exports *** ### if this is window? window.xyz = xyz else module.exports = xyz
[ { "context": "l\n\t\tconstructor: ->\n\t\t\tsuper\n\t\t\tDropbox.appKey = \"2nvimyu9eugsqm9\"\n\t\t\t@set \"files\", new Batman.Set\n\t\t\t@set \"pageLoa", "end": 765, "score": 0.9996479749679565, "start": 750, "tag": "KEY", "value": "2nvimyu9eugsqm9" } ]
page.coffee
GotEmB/SaveToDropB
2
require.config paths: jquery: "//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min" batman: "batmanjs/batman" bootstrap: "//netdna.bootstrapcdn.com/bootstrap/3.0.0-wip/js/bootstrap.min" dropbox: "//dropbox.com/static/api/1/dropins" shim: batman: deps: ["jquery"], exports: "Batman" bootstrap: deps: ["jquery"] dropbox: exports: "Dropbox" waitSeconds: 30 appContext = undefined define "Batman", ["batman"], (Batman) -> Batman.DOM.readers.batmantarget = Batman.DOM.readers.target and delete Batman.DOM.readers.target and Batman require ["jquery", "Batman", "dropbox", "bootstrap"], ($, Batman, Dropbox) -> class File extends Batman.Model class AppContext extends Batman.Model constructor: -> super Dropbox.appKey = "2nvimyu9eugsqm9" @set "files", new Batman.Set @set "pageLoaded", false addFile: -> thisFile = new File url: @get("newFileUrl"), css: "width: 0%;" @set "newFileUrl", "" Dropbox.save files: [url: thisFile.get "url"] success: => thisFile.set "uploadSuccess", true progress: (progress) => @get("files").add thisFile unless @get("files").has thisFile thisFile.set "css", "width: #{progress * 100}%;" cancel: => @get("files").remove thisFile if @get("files").has thisFile error: (err) => console.error err thisFile.set "uploadFailure", true class SavetoDropB extends Batman.App @appContext: appContext = new AppContext SavetoDropB.run() $ -> appContext.set "pageLoaded", true
105843
require.config paths: jquery: "//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min" batman: "batmanjs/batman" bootstrap: "//netdna.bootstrapcdn.com/bootstrap/3.0.0-wip/js/bootstrap.min" dropbox: "//dropbox.com/static/api/1/dropins" shim: batman: deps: ["jquery"], exports: "Batman" bootstrap: deps: ["jquery"] dropbox: exports: "Dropbox" waitSeconds: 30 appContext = undefined define "Batman", ["batman"], (Batman) -> Batman.DOM.readers.batmantarget = Batman.DOM.readers.target and delete Batman.DOM.readers.target and Batman require ["jquery", "Batman", "dropbox", "bootstrap"], ($, Batman, Dropbox) -> class File extends Batman.Model class AppContext extends Batman.Model constructor: -> super Dropbox.appKey = "<KEY>" @set "files", new Batman.Set @set "pageLoaded", false addFile: -> thisFile = new File url: @get("newFileUrl"), css: "width: 0%;" @set "newFileUrl", "" Dropbox.save files: [url: thisFile.get "url"] success: => thisFile.set "uploadSuccess", true progress: (progress) => @get("files").add thisFile unless @get("files").has thisFile thisFile.set "css", "width: #{progress * 100}%;" cancel: => @get("files").remove thisFile if @get("files").has thisFile error: (err) => console.error err thisFile.set "uploadFailure", true class SavetoDropB extends Batman.App @appContext: appContext = new AppContext SavetoDropB.run() $ -> appContext.set "pageLoaded", true
true
require.config paths: jquery: "//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min" batman: "batmanjs/batman" bootstrap: "//netdna.bootstrapcdn.com/bootstrap/3.0.0-wip/js/bootstrap.min" dropbox: "//dropbox.com/static/api/1/dropins" shim: batman: deps: ["jquery"], exports: "Batman" bootstrap: deps: ["jquery"] dropbox: exports: "Dropbox" waitSeconds: 30 appContext = undefined define "Batman", ["batman"], (Batman) -> Batman.DOM.readers.batmantarget = Batman.DOM.readers.target and delete Batman.DOM.readers.target and Batman require ["jquery", "Batman", "dropbox", "bootstrap"], ($, Batman, Dropbox) -> class File extends Batman.Model class AppContext extends Batman.Model constructor: -> super Dropbox.appKey = "PI:KEY:<KEY>END_PI" @set "files", new Batman.Set @set "pageLoaded", false addFile: -> thisFile = new File url: @get("newFileUrl"), css: "width: 0%;" @set "newFileUrl", "" Dropbox.save files: [url: thisFile.get "url"] success: => thisFile.set "uploadSuccess", true progress: (progress) => @get("files").add thisFile unless @get("files").has thisFile thisFile.set "css", "width: #{progress * 100}%;" cancel: => @get("files").remove thisFile if @get("files").has thisFile error: (err) => console.error err thisFile.set "uploadFailure", true class SavetoDropB extends Batman.App @appContext: appContext = new AppContext SavetoDropB.run() $ -> appContext.set "pageLoaded", true
[ { "context": "ric imageless spinner class\n#\n# Copyright (C) 2012 Nikolay Nemshilov\n#\nclass Spinner extends Element\n include: Option", "end": 76, "score": 0.9998815059661865, "start": 59, "tag": "NAME", "value": "Nikolay Nemshilov" } ]
ui/core/src/spinner.coffee
lovely-io/lovely.io-stl
2
# # Generic imageless spinner class # # Copyright (C) 2012 Nikolay Nemshilov # class Spinner extends Element include: Options extend: Options: size: 5 # lines size type: 'circular' # spinner type, use 'flat' if you want a flat line of bars rotate: true # if you want the spinner to be rotated with CSS3 when possible speed: 300 # animation speed # # Default constructor # # NOTE: this constructor can take additional `size` option # to set how many pieces it should has # # @param {Object} html-options # @return {Spinner} self # constructor: (options)-> @$super('div', @setOptions(options)) @addClass('lui-spinner') @build() # # Builds the spinner's internals # # @return {Spinner} this # build: -> @_.innerHTML = '<div class="lui-spinner-current"></div>'; i=1 while i < @options.size @_.innerHTML += '<div></div>'; i++ # rotating lines for a circular spinner if css_transform && @options.type is 'circular' @addClass('lui-spinner-circular') @find('div').forEach (div, i)=> div._.style.width = (100 / @options.size) + '%' div._.style[css_transform] = 'rotate('+Math.round(360/@options.size*i)+'deg) translate(0,-80%) skew(0deg, 20deg)' # kicking in CSS3 rotation if needed if css_transform && css_animation && @options.type is 'circular' && @options.rotate @_.style[css_animation+"Duration"] = @options.speed * 4 + 'ms' @addClass('lui-spinner-rotate') # fallback spinning in JavaScript for flat spinners if !css_transform or !css_animation or @options.type isnt 'circular' or !@options.rotate window.setInterval => dot = @first('.lui-spinner-current') (dot.nextSibling() || @first()).radioClass('lui-spinner-current') , @options.speed return @
206614
# # Generic imageless spinner class # # Copyright (C) 2012 <NAME> # class Spinner extends Element include: Options extend: Options: size: 5 # lines size type: 'circular' # spinner type, use 'flat' if you want a flat line of bars rotate: true # if you want the spinner to be rotated with CSS3 when possible speed: 300 # animation speed # # Default constructor # # NOTE: this constructor can take additional `size` option # to set how many pieces it should has # # @param {Object} html-options # @return {Spinner} self # constructor: (options)-> @$super('div', @setOptions(options)) @addClass('lui-spinner') @build() # # Builds the spinner's internals # # @return {Spinner} this # build: -> @_.innerHTML = '<div class="lui-spinner-current"></div>'; i=1 while i < @options.size @_.innerHTML += '<div></div>'; i++ # rotating lines for a circular spinner if css_transform && @options.type is 'circular' @addClass('lui-spinner-circular') @find('div').forEach (div, i)=> div._.style.width = (100 / @options.size) + '%' div._.style[css_transform] = 'rotate('+Math.round(360/@options.size*i)+'deg) translate(0,-80%) skew(0deg, 20deg)' # kicking in CSS3 rotation if needed if css_transform && css_animation && @options.type is 'circular' && @options.rotate @_.style[css_animation+"Duration"] = @options.speed * 4 + 'ms' @addClass('lui-spinner-rotate') # fallback spinning in JavaScript for flat spinners if !css_transform or !css_animation or @options.type isnt 'circular' or !@options.rotate window.setInterval => dot = @first('.lui-spinner-current') (dot.nextSibling() || @first()).radioClass('lui-spinner-current') , @options.speed return @
true
# # Generic imageless spinner class # # Copyright (C) 2012 PI:NAME:<NAME>END_PI # class Spinner extends Element include: Options extend: Options: size: 5 # lines size type: 'circular' # spinner type, use 'flat' if you want a flat line of bars rotate: true # if you want the spinner to be rotated with CSS3 when possible speed: 300 # animation speed # # Default constructor # # NOTE: this constructor can take additional `size` option # to set how many pieces it should has # # @param {Object} html-options # @return {Spinner} self # constructor: (options)-> @$super('div', @setOptions(options)) @addClass('lui-spinner') @build() # # Builds the spinner's internals # # @return {Spinner} this # build: -> @_.innerHTML = '<div class="lui-spinner-current"></div>'; i=1 while i < @options.size @_.innerHTML += '<div></div>'; i++ # rotating lines for a circular spinner if css_transform && @options.type is 'circular' @addClass('lui-spinner-circular') @find('div').forEach (div, i)=> div._.style.width = (100 / @options.size) + '%' div._.style[css_transform] = 'rotate('+Math.round(360/@options.size*i)+'deg) translate(0,-80%) skew(0deg, 20deg)' # kicking in CSS3 rotation if needed if css_transform && css_animation && @options.type is 'circular' && @options.rotate @_.style[css_animation+"Duration"] = @options.speed * 4 + 'ms' @addClass('lui-spinner-rotate') # fallback spinning in JavaScript for flat spinners if !css_transform or !css_animation or @options.type isnt 'circular' or !@options.rotate window.setInterval => dot = @first('.lui-spinner-current') (dot.nextSibling() || @first()).radioClass('lui-spinner-current') , @options.speed return @
[ { "context": "els\n\n Factory.define 'user', User, {\n email: 'foo@bar.com'\n }\n", "end": 113, "score": 0.9999240636825562, "start": 102, "tag": "EMAIL", "value": "foo@bar.com" } ]
sample/domain/mongoose/fixtures/data.coffee
TorchlightSoftware/axiom-mongoose
0
module.exports = (Factory) -> {User} = Factory.models Factory.define 'user', User, { email: 'foo@bar.com' }
42370
module.exports = (Factory) -> {User} = Factory.models Factory.define 'user', User, { email: '<EMAIL>' }
true
module.exports = (Factory) -> {User} = Factory.models Factory.define 'user', User, { email: 'PI:EMAIL:<EMAIL>END_PI' }
[ { "context": "unes\",checked: false,horarios:[]}\n\t\t{id:3,nombre:\"Martes\",checked: false,horarios:[]}\n\t\t{id:4,nombre:\"Mi", "end": 259, "score": 0.7033618092536926, "start": 255, "tag": "NAME", "value": "Mart" } ]
assets/js/controllers/horarios.coffee
WCLab/horarios-de-restaurantes
0
app = angular.module 'yapp' app.controller "HorarioController", ["$scope","$rootScope", ($scope,$rootScope) -> $rootScope.dias = [ {id:1,nombre:"Domingo",checked: false,horarios:[]} {id:2,nombre:"Lunes",checked: false,horarios:[]} {id:3,nombre:"Martes",checked: false,horarios:[]} {id:4,nombre:"Miercoles",checked: false,horarios:[]} {id:5,nombre:"Jueves",checked: false,horarios:[]} {id:6,nombre:"Viernes",checked: false,horarios:[]} {id:7,nombre:"Sábado",checked: false,horarios:[]} ] $scope.add = (id) -> $rootScope.dias[id].horarios.push({apertura:'',cierre:''}) # $scope.save = -> # console.log JSON.stringify $scope.dias ]
121221
app = angular.module 'yapp' app.controller "HorarioController", ["$scope","$rootScope", ($scope,$rootScope) -> $rootScope.dias = [ {id:1,nombre:"Domingo",checked: false,horarios:[]} {id:2,nombre:"Lunes",checked: false,horarios:[]} {id:3,nombre:"<NAME>es",checked: false,horarios:[]} {id:4,nombre:"Miercoles",checked: false,horarios:[]} {id:5,nombre:"Jueves",checked: false,horarios:[]} {id:6,nombre:"Viernes",checked: false,horarios:[]} {id:7,nombre:"Sábado",checked: false,horarios:[]} ] $scope.add = (id) -> $rootScope.dias[id].horarios.push({apertura:'',cierre:''}) # $scope.save = -> # console.log JSON.stringify $scope.dias ]
true
app = angular.module 'yapp' app.controller "HorarioController", ["$scope","$rootScope", ($scope,$rootScope) -> $rootScope.dias = [ {id:1,nombre:"Domingo",checked: false,horarios:[]} {id:2,nombre:"Lunes",checked: false,horarios:[]} {id:3,nombre:"PI:NAME:<NAME>END_PIes",checked: false,horarios:[]} {id:4,nombre:"Miercoles",checked: false,horarios:[]} {id:5,nombre:"Jueves",checked: false,horarios:[]} {id:6,nombre:"Viernes",checked: false,horarios:[]} {id:7,nombre:"Sábado",checked: false,horarios:[]} ] $scope.add = (id) -> $rootScope.dias[id].horarios.push({apertura:'',cierre:''}) # $scope.save = -> # console.log JSON.stringify $scope.dias ]
[ { "context": "getFullYear()}-#{1+dt.getMonth()}\"\n key1: \"win\"\n key2: \"contest_num\"\n filter: \"off", "end": 367, "score": 0.9964054822921753, "start": 364, "tag": "KEY", "value": "win" }, { "context": "t.getMonth()}\"\n key1: \"win\"\n key2: ...
views/js/result_ranking.coffee
pjmtdw/kagetra
2
define (require,exports,module) -> $rc = require("result_common") ResultRankingRouter = Backbone.Router.extend routes: "" : "start" "show/:params" : "show" start: -> dt = new Date() params = $.param({ start: "#{dt.getFullYear()-1}-#{1+dt.getMonth()}" end: "#{dt.getFullYear()}-#{1+dt.getMonth()}" key1: "win" key2: "contest_num" filter: "official" }) @navigate("show/#{params}",{trigger:true,replace:true}) show: (params) -> if not window.result_ranking_view? window.result_ranking_view = new ResultRankingView() obj = _.deparam(params) window.result_ranking_view.search(obj) $("#ranking-form").fillForm(obj) ResultRankingView = Backbone.View.extend template: _.template_braces($("#templ-ranking").html()) template_result: _.template_braces($("#templ-ranking-result").html()) events: "submit #ranking-form" : "do_search" "change #ranking-form select" : -> $("#ranking-form").submit() "click .goto-year" : "goto_year" initialize: -> @render() render: -> @$el.html(@template()) @$el.appendTo("#result-ranking") render_result: (data:data) -> $("#ranking-result").html(@template_result(data:data)) do_search: _.wrap_submit -> obj = $("#ranking-form").serializeObj() window.result_ranking_router.navigate("show/#{$.param(obj)}",{trigger:true}) goto_year: (ev)-> year = $(ev.currentTarget).data("year") [f,t] = if year == "all" then ["",""] else ["#{year}-1","#{year}-12"] $("#ranking-form input[name='start']").val(f) $("#ranking-form input[name='end']").val(t) $("#ranking-form").submit() # TDOO: is this the correct way to close dropdown ? $("[data-dropdown='year-list']").click() search: (obj)-> that = this $.ajax("api/result_ranking/search",{ data: JSON.stringify(obj), contentType: "application/json", type: "POST" }).done((data)->that.render_result(data:data)) init: -> $rc.init() window.result_ranking_router = new ResultRankingRouter() Backbone.history.start()
84133
define (require,exports,module) -> $rc = require("result_common") ResultRankingRouter = Backbone.Router.extend routes: "" : "start" "show/:params" : "show" start: -> dt = new Date() params = $.param({ start: "#{dt.getFullYear()-1}-#{1+dt.getMonth()}" end: "#{dt.getFullYear()}-#{1+dt.getMonth()}" key1: "<KEY>" key2: "<KEY>" filter: "official" }) @navigate("show/#{params}",{trigger:true,replace:true}) show: (params) -> if not window.result_ranking_view? window.result_ranking_view = new ResultRankingView() obj = _.deparam(params) window.result_ranking_view.search(obj) $("#ranking-form").fillForm(obj) ResultRankingView = Backbone.View.extend template: _.template_braces($("#templ-ranking").html()) template_result: _.template_braces($("#templ-ranking-result").html()) events: "submit #ranking-form" : "do_search" "change #ranking-form select" : -> $("#ranking-form").submit() "click .goto-year" : "goto_year" initialize: -> @render() render: -> @$el.html(@template()) @$el.appendTo("#result-ranking") render_result: (data:data) -> $("#ranking-result").html(@template_result(data:data)) do_search: _.wrap_submit -> obj = $("#ranking-form").serializeObj() window.result_ranking_router.navigate("show/#{$.param(obj)}",{trigger:true}) goto_year: (ev)-> year = $(ev.currentTarget).data("year") [f,t] = if year == "all" then ["",""] else ["#{year}-1","#{year}-12"] $("#ranking-form input[name='start']").val(f) $("#ranking-form input[name='end']").val(t) $("#ranking-form").submit() # TDOO: is this the correct way to close dropdown ? $("[data-dropdown='year-list']").click() search: (obj)-> that = this $.ajax("api/result_ranking/search",{ data: JSON.stringify(obj), contentType: "application/json", type: "POST" }).done((data)->that.render_result(data:data)) init: -> $rc.init() window.result_ranking_router = new ResultRankingRouter() Backbone.history.start()
true
define (require,exports,module) -> $rc = require("result_common") ResultRankingRouter = Backbone.Router.extend routes: "" : "start" "show/:params" : "show" start: -> dt = new Date() params = $.param({ start: "#{dt.getFullYear()-1}-#{1+dt.getMonth()}" end: "#{dt.getFullYear()}-#{1+dt.getMonth()}" key1: "PI:KEY:<KEY>END_PI" key2: "PI:KEY:<KEY>END_PI" filter: "official" }) @navigate("show/#{params}",{trigger:true,replace:true}) show: (params) -> if not window.result_ranking_view? window.result_ranking_view = new ResultRankingView() obj = _.deparam(params) window.result_ranking_view.search(obj) $("#ranking-form").fillForm(obj) ResultRankingView = Backbone.View.extend template: _.template_braces($("#templ-ranking").html()) template_result: _.template_braces($("#templ-ranking-result").html()) events: "submit #ranking-form" : "do_search" "change #ranking-form select" : -> $("#ranking-form").submit() "click .goto-year" : "goto_year" initialize: -> @render() render: -> @$el.html(@template()) @$el.appendTo("#result-ranking") render_result: (data:data) -> $("#ranking-result").html(@template_result(data:data)) do_search: _.wrap_submit -> obj = $("#ranking-form").serializeObj() window.result_ranking_router.navigate("show/#{$.param(obj)}",{trigger:true}) goto_year: (ev)-> year = $(ev.currentTarget).data("year") [f,t] = if year == "all" then ["",""] else ["#{year}-1","#{year}-12"] $("#ranking-form input[name='start']").val(f) $("#ranking-form input[name='end']").val(t) $("#ranking-form").submit() # TDOO: is this the correct way to close dropdown ? $("[data-dropdown='year-list']").click() search: (obj)-> that = this $.ajax("api/result_ranking/search",{ data: JSON.stringify(obj), contentType: "application/json", type: "POST" }).done((data)->that.render_result(data:data)) init: -> $rc.init() window.result_ranking_router = new ResultRankingRouter() Backbone.history.start()
[ { "context": "ody:\n username: data.username\n password: data.password\n\n authenticate = passport.authenticate 'local', ", "end": 495, "score": 0.9993002414703369, "start": 482, "tag": "PASSWORD", "value": "data.password" } ]
coffeescript/models/user.coffee
purple-circle/chat
0
Q = require('q') api = require('../models/api') passport = require('passport') mongoose = require('mongoose') LocalStrategy = require('passport-local').Strategy Users = mongoose.model 'users' passport.use new LocalStrategy(Users.authenticate()) user = {} rejectPromise = -> deferred = Q.defer() deferred.reject() deferred.promise user.login = (data) -> deferred = Q.defer() # Fucking stupid passport.js req = body: username: data.username password: data.password authenticate = passport.authenticate 'local', (err, user, info) -> if err deferred.reject err else if info deferred.reject info else deferred.resolve user authenticate(req) deferred.promise user.create_default_picture_album = (userid) -> data = user_id: userid title: 'Default album' default: true user.create_picture_album(data) user.check_username = (username) -> api.createQueue('api.check_username', username) user.create = (data) -> deferred = Q.defer() api .createQueue('api.createUser', data) .then (result) -> user .create_default_picture_album(result._id) .then -> deferred.resolve(result) , deferred.reject deferred.promise user.edit = (id, data) -> api.createQueue('api.edit_user', {id, data}) user.localSignup = (data) -> deferred = Q.defer() api .createQueue('api.localSignupUser', data) .then (result) -> user .create_default_picture_album(result._id) .then -> deferred.resolve(result) , deferred.reject deferred.promise user.getUser = (id) -> api.createQueue('api.getUser', {_id: id}) user.savePicture = (id, data) -> user .getUser(id) .then (profile) -> if not profile return rejectPromise() api.createQueue('api.saveProfilePicture', {id, data}) user.getPictures = (id) -> api.createQueue('api.getProfilePictures', id) user.create_picture_album = (data) -> if not data.user_id return rejectPromise() api.createQueue('api.create_profile_picture_album', data) user.get_profile_picture_albums = (id) -> api.createQueue('api.get_profile_picture_albums', id) user.get_profile_picture = (user_id, picture_id) -> api.createQueue('api.get_profile_picture', {user_id, picture_id}) user.set_profile_picture = (user_id, picture_id) -> deferred = Q.defer() user .get_profile_picture(user_id, picture_id) .then (picture) -> data = picture_url: "/uploads/#{picture.filename}" user .edit(user_id, data) .then deferred.resolve, deferred.reject , deferred.reject deferred.promise user.set_cover_picture = (user_id, picture_id) -> deferred = Q.defer() user .get_profile_picture(user_id, picture_id) .then (picture) -> data = cover_url: "/uploads/#{picture.filename}" user .edit(user_id, data) .then deferred.resolve, deferred.reject , deferred.reject deferred.promise module.exports = user
63986
Q = require('q') api = require('../models/api') passport = require('passport') mongoose = require('mongoose') LocalStrategy = require('passport-local').Strategy Users = mongoose.model 'users' passport.use new LocalStrategy(Users.authenticate()) user = {} rejectPromise = -> deferred = Q.defer() deferred.reject() deferred.promise user.login = (data) -> deferred = Q.defer() # Fucking stupid passport.js req = body: username: data.username password: <PASSWORD> authenticate = passport.authenticate 'local', (err, user, info) -> if err deferred.reject err else if info deferred.reject info else deferred.resolve user authenticate(req) deferred.promise user.create_default_picture_album = (userid) -> data = user_id: userid title: 'Default album' default: true user.create_picture_album(data) user.check_username = (username) -> api.createQueue('api.check_username', username) user.create = (data) -> deferred = Q.defer() api .createQueue('api.createUser', data) .then (result) -> user .create_default_picture_album(result._id) .then -> deferred.resolve(result) , deferred.reject deferred.promise user.edit = (id, data) -> api.createQueue('api.edit_user', {id, data}) user.localSignup = (data) -> deferred = Q.defer() api .createQueue('api.localSignupUser', data) .then (result) -> user .create_default_picture_album(result._id) .then -> deferred.resolve(result) , deferred.reject deferred.promise user.getUser = (id) -> api.createQueue('api.getUser', {_id: id}) user.savePicture = (id, data) -> user .getUser(id) .then (profile) -> if not profile return rejectPromise() api.createQueue('api.saveProfilePicture', {id, data}) user.getPictures = (id) -> api.createQueue('api.getProfilePictures', id) user.create_picture_album = (data) -> if not data.user_id return rejectPromise() api.createQueue('api.create_profile_picture_album', data) user.get_profile_picture_albums = (id) -> api.createQueue('api.get_profile_picture_albums', id) user.get_profile_picture = (user_id, picture_id) -> api.createQueue('api.get_profile_picture', {user_id, picture_id}) user.set_profile_picture = (user_id, picture_id) -> deferred = Q.defer() user .get_profile_picture(user_id, picture_id) .then (picture) -> data = picture_url: "/uploads/#{picture.filename}" user .edit(user_id, data) .then deferred.resolve, deferred.reject , deferred.reject deferred.promise user.set_cover_picture = (user_id, picture_id) -> deferred = Q.defer() user .get_profile_picture(user_id, picture_id) .then (picture) -> data = cover_url: "/uploads/#{picture.filename}" user .edit(user_id, data) .then deferred.resolve, deferred.reject , deferred.reject deferred.promise module.exports = user
true
Q = require('q') api = require('../models/api') passport = require('passport') mongoose = require('mongoose') LocalStrategy = require('passport-local').Strategy Users = mongoose.model 'users' passport.use new LocalStrategy(Users.authenticate()) user = {} rejectPromise = -> deferred = Q.defer() deferred.reject() deferred.promise user.login = (data) -> deferred = Q.defer() # Fucking stupid passport.js req = body: username: data.username password: PI:PASSWORD:<PASSWORD>END_PI authenticate = passport.authenticate 'local', (err, user, info) -> if err deferred.reject err else if info deferred.reject info else deferred.resolve user authenticate(req) deferred.promise user.create_default_picture_album = (userid) -> data = user_id: userid title: 'Default album' default: true user.create_picture_album(data) user.check_username = (username) -> api.createQueue('api.check_username', username) user.create = (data) -> deferred = Q.defer() api .createQueue('api.createUser', data) .then (result) -> user .create_default_picture_album(result._id) .then -> deferred.resolve(result) , deferred.reject deferred.promise user.edit = (id, data) -> api.createQueue('api.edit_user', {id, data}) user.localSignup = (data) -> deferred = Q.defer() api .createQueue('api.localSignupUser', data) .then (result) -> user .create_default_picture_album(result._id) .then -> deferred.resolve(result) , deferred.reject deferred.promise user.getUser = (id) -> api.createQueue('api.getUser', {_id: id}) user.savePicture = (id, data) -> user .getUser(id) .then (profile) -> if not profile return rejectPromise() api.createQueue('api.saveProfilePicture', {id, data}) user.getPictures = (id) -> api.createQueue('api.getProfilePictures', id) user.create_picture_album = (data) -> if not data.user_id return rejectPromise() api.createQueue('api.create_profile_picture_album', data) user.get_profile_picture_albums = (id) -> api.createQueue('api.get_profile_picture_albums', id) user.get_profile_picture = (user_id, picture_id) -> api.createQueue('api.get_profile_picture', {user_id, picture_id}) user.set_profile_picture = (user_id, picture_id) -> deferred = Q.defer() user .get_profile_picture(user_id, picture_id) .then (picture) -> data = picture_url: "/uploads/#{picture.filename}" user .edit(user_id, data) .then deferred.resolve, deferred.reject , deferred.reject deferred.promise user.set_cover_picture = (user_id, picture_id) -> deferred = Q.defer() user .get_profile_picture(user_id, picture_id) .then (picture) -> data = cover_url: "/uploads/#{picture.filename}" user .edit(user_id, data) .then deferred.resolve, deferred.reject , deferred.reject deferred.promise module.exports = user