code
stringlengths
2
1.05M
repo_name
stringlengths
5
114
path
stringlengths
4
991
language
stringclasses
1 value
license
stringclasses
15 values
size
int32
2
1.05M
var NAVTREEINDEX3 = { "d4/db5/array_8hpp.html":[3,0,1,11], "d4/db5/array_8hpp.html#a0048463a9200ce90a34092d719fe9922":[3,0,1,11,1], "d4/db5/array_8hpp.html#a311d0610601290b2bb98f1808fc56d24":[3,0,1,11,3], "d4/db5/array_8hpp.html#a44c20174c4360e3d4ec9373839c493e2":[3,0,1,11,2], "d4/db5/array_8hpp.html#a66c2e9bfacf2a266d988285089c50705":[3,0,1,11,5], "d4/db5/array_8hpp.html#ae74917955a3fa69cd29c43493f75fef3":[3,0,1,11,4], "d4/de8/classstd_1_1basic__string.html":[2,0,0,16], "d4/de8/classstd_1_1basic__string.html#a048145b966ec41fbaa4714140308167a":[2,0,0,16,28], "d4/de8/classstd_1_1basic__string.html#a11da29d044d50af12ad86730e077c349":[2,0,0,16,37], "d4/de8/classstd_1_1basic__string.html#a155d2fa939e5c2c45b68db675a5fa86a":[2,0,0,16,6], "d4/de8/classstd_1_1basic__string.html#a19700f17170ad1f72867c379b2d0d75e":[2,0,0,16,44], "d4/de8/classstd_1_1basic__string.html#a1f4ccdd026fe166b90dd52cb7be634c9":[2,0,0,16,8], "d4/de8/classstd_1_1basic__string.html#a26f9a2e19f6933f947bee0132e3aae81":[2,0,0,16,27], "d4/de8/classstd_1_1basic__string.html#a366ac2380d95d352498c88278a7a9d8b":[2,0,0,16,24], "d4/de8/classstd_1_1basic__string.html#a37d7594eca3b2c47b5f0bc2447a982c9":[2,0,0,16,34], "d4/de8/classstd_1_1basic__string.html#a42961d0cef0f670eb1a2462a2b8f08c8":[2,0,0,16,15], "d4/de8/classstd_1_1basic__string.html#a43bb85d9b8916f484babb7b92d10cb42":[2,0,0,16,42], "d4/de8/classstd_1_1basic__string.html#a44aa7597b00eed7606f7952989ac6ed1":[2,0,0,16,21], "d4/de8/classstd_1_1basic__string.html#a4a618a1d6343243652cc9123e6d26593":[2,0,0,16,4], "d4/de8/classstd_1_1basic__string.html#a52b9d0b393063fdb59585f80ac803191":[2,0,0,16,5], "d4/de8/classstd_1_1basic__string.html#a5339b8e4151978ad8f67fb23a1da93a7":[2,0,0,16,0], "d4/de8/classstd_1_1basic__string.html#a55b6e4d56823c8de8ab5fbf9e33dfce5":[2,0,0,16,18], "d4/de8/classstd_1_1basic__string.html#a56c4648661953fc5e9269b4a89ed7441":[2,0,0,16,33], "d4/de8/classstd_1_1basic__string.html#a59f4cc8315d514e52ecdc743e0451e27":[2,0,0,16,41], "d4/de8/classstd_1_1basic__string.html#a5f93368f7fb6a2874bf8da801aa526d1":[2,0,0,16,43], "d4/de8/classstd_1_1basic__string.html#a617bd833ddf33273bb8049b83fc4b254":[2,0,0,16,1], "d4/de8/classstd_1_1basic__string.html#a6d31b891369dbaa90962ecf4cddf078a":[2,0,0,16,40], "d4/de8/classstd_1_1basic__string.html#a7ec81f393c688621e7857ace949111eb":[2,0,0,16,9], "d4/de8/classstd_1_1basic__string.html#a8493d62f43e0ef6a8c18adc283618ee9":[2,0,0,16,36], "d4/de8/classstd_1_1basic__string.html#a8db97eff295c3b6a6bf4631d6ec5dfdf":[2,0,0,16,23], "d4/de8/classstd_1_1basic__string.html#a8e26341ef4a38db673b8a986d881824b":[2,0,0,16,31], "d4/de8/classstd_1_1basic__string.html#a91a0362fdb3c542e2aa27c88d74370e3":[2,0,0,16,10], "d4/de8/classstd_1_1basic__string.html#a9ae54e7e4d3f24e11e92bf28ab4e7555":[2,0,0,16,38], "d4/de8/classstd_1_1basic__string.html#a9e4d69675aff6909e70935e4368ca859":[2,0,0,16,39], "d4/de8/classstd_1_1basic__string.html#a9e89f6285c48714f17596dc9b5183def":[2,0,0,16,29], "d4/de8/classstd_1_1basic__string.html#aa25030581cb9824576b8bee02eaba540":[2,0,0,16,17], "d4/de8/classstd_1_1basic__string.html#aa40b7059ca42243c7bbb557bea09336c":[2,0,0,16,2], "d4/de8/classstd_1_1basic__string.html#aa4b716dd9157b8dba708c56c89be5dc4":[2,0,0,16,26], "d4/de8/classstd_1_1basic__string.html#aa5f40b761e880a93fd8c6c3db5c0df72":[2,0,0,16,35], "d4/de8/classstd_1_1basic__string.html#aa97a7b633573d24a9944a57986800d71":[2,0,0,16,16], "d4/de8/classstd_1_1basic__string.html#ab1b0a7a408203f0126955b874de27352":[2,0,0,16,7], "d4/de8/classstd_1_1basic__string.html#ab2c981bafcfc423d2dd847c0e5fc35fd":[2,0,0,16,19], "d4/de8/classstd_1_1basic__string.html#ab66e0321e01c4483cfbef4f845f0d35c":[2,0,0,16,32], "d4/de8/classstd_1_1basic__string.html#ab8a99058684557be228b91b498e8a3e9":[2,0,0,16,12], "d4/de8/classstd_1_1basic__string.html#ac04ce8c34135d3576f1f639c8917d138":[2,0,0,16,30], "d4/de8/classstd_1_1basic__string.html#ac08e1b13601baa3477b970ebd35ebf99":[2,0,0,16,3], "d4/de8/classstd_1_1basic__string.html#ac74c043d5388cc66d0f922526f4cd395":[2,0,0,16,22], "d4/de8/classstd_1_1basic__string.html#ad0e792c2a8a518722c3e6fef0000e68f":[2,0,0,16,14], "d4/de8/classstd_1_1basic__string.html#ad9e4f9545f7d760a0975a6c3c0a75a20":[2,0,0,16,13], "d4/de8/classstd_1_1basic__string.html#ada7d4480f4f216b45818c2952042b3bd":[2,0,0,16,25], "d4/de8/classstd_1_1basic__string.html#aebc27f736e76a55864f508077c3f56d8":[2,0,0,16,20], "d4/de8/classstd_1_1basic__string.html#afec7916221582f548d4ed0656f871806":[2,0,0,16,11], "d4/de8/classstd_1_1map.html":[2,0,0,111], "d4/de8/classstd_1_1map.html#a2340c924a5187f1a63cfdf0687216763":[2,0,0,111,18], "d4/de8/classstd_1_1map.html#a2c6eaa30025b6bbcbb0cfc5963ee237c":[2,0,0,111,8], "d4/de8/classstd_1_1map.html#a3b6a55862b5d793f47b0023f53eab748":[2,0,0,111,6], "d4/de8/classstd_1_1map.html#a4b6b2b79140050d718dc72d1f1c9f0ad":[2,0,0,111,5], "d4/de8/classstd_1_1map.html#a58706f0166408a04c60bdba751d1a98d":[2,0,0,111,4], "d4/de8/classstd_1_1map.html#a73ea071e7772e050444541652f732083":[2,0,0,111,1], "d4/de8/classstd_1_1map.html#a873685a9110c9219265f1e3201282581":[2,0,0,111,3], "d4/de8/classstd_1_1map.html#a8c523966f8bbd00039d0f2b5cc3c77e5":[2,0,0,111,19], "d4/de8/classstd_1_1map.html#a8f93152ce41f03543187d01c98c034ff":[2,0,0,111,17], "d4/de8/classstd_1_1map.html#a97bf18d62e8afe85c3739cbc62abbbc6":[2,0,0,111,14], "d4/de8/classstd_1_1map.html#a9bcac17c36254c93e37f06d966d32773":[2,0,0,111,21], "d4/de8/classstd_1_1map.html#aa77322ea3800895f483a5a863a2f9356":[2,0,0,111,10], "d4/de8/classstd_1_1map.html#aa9af2db3e9feccee588c59852c389319":[2,0,0,111,0], "d4/de8/classstd_1_1map.html#ab85e6b3f71a6cd66e4c7920f6b141423":[2,0,0,111,7], "d4/de8/classstd_1_1map.html#ab8c8abbc1c9afb13828d3a04a46d9b4c":[2,0,0,111,11], "d4/de8/classstd_1_1map.html#ac8005e666248dfa867980a0d2a7d433d":[2,0,0,111,12], "d4/de8/classstd_1_1map.html#ac9e60107a51138e82a8a66d2c3bca0bf":[2,0,0,111,2], "d4/de8/classstd_1_1map.html#ad4354abcb3f30dae394e199f1230d681":[2,0,0,111,16], "d4/de8/classstd_1_1map.html#adf709df841b651865a6aa361ad6a9763":[2,0,0,111,15], "d4/de8/classstd_1_1map.html#ae02b3d1d336a42ab76f5e187ae9ef5d4":[2,0,0,111,20], "d4/de8/classstd_1_1map.html#ae82d0b4bd0fec70cc51778722e2d760a":[2,0,0,111,9], "d4/de8/classstd_1_1map.html#ae9dcf18d95d45bef7b48ddf28503c60f":[2,0,0,111,13], "d4/dfa/classstd_1_1fixed__sorted__vector.html":[2,0,0,40], "d4/dfa/classstd_1_1fixed__sorted__vector.html#a2ce3d1d05f733abbbf1bf5b42707f51a":[2,0,0,40,4], "d4/dfa/classstd_1_1fixed__sorted__vector.html#a3554132678255108808abcfb93cd9a6b":[2,0,0,40,14], "d4/dfa/classstd_1_1fixed__sorted__vector.html#a3d1973321125b85937c51627cecf7526":[2,0,0,40,15], "d4/dfa/classstd_1_1fixed__sorted__vector.html#a481527c0df696268826e6932ebce476e":[2,0,0,40,0], "d4/dfa/classstd_1_1fixed__sorted__vector.html#a4d7c31d322d6b796ef3bc3a150d9e4b6":[2,0,0,40,3], "d4/dfa/classstd_1_1fixed__sorted__vector.html#a5340ed31349b4ad6bc2010cece895c61":[2,0,0,40,8], "d4/dfa/classstd_1_1fixed__sorted__vector.html#a5a3d349013a3a8b429c8c17d01fc3a73":[2,0,0,40,13], "d4/dfa/classstd_1_1fixed__sorted__vector.html#a616d38b84b146a28959b47d3d3c457ca":[2,0,0,40,1], "d4/dfa/classstd_1_1fixed__sorted__vector.html#a6a5879b6815b4d99155138bb46333a88":[2,0,0,40,6], "d4/dfa/classstd_1_1fixed__sorted__vector.html#a71c9a896bf7d257a85c24d65789efa7d":[2,0,0,40,17], "d4/dfa/classstd_1_1fixed__sorted__vector.html#a7827372b61d7a779057d11a2f2fc7287":[2,0,0,40,10], "d4/dfa/classstd_1_1fixed__sorted__vector.html#a80357d89e033ef0e8213b3b14e675b61":[2,0,0,40,11], "d4/dfa/classstd_1_1fixed__sorted__vector.html#a819e554776546c42857db0bb4fbc474c":[2,0,0,40,16], "d4/dfa/classstd_1_1fixed__sorted__vector.html#a8dd3ad604c8a45f3a514cedf70ed0c1d":[2,0,0,40,2], "d4/dfa/classstd_1_1fixed__sorted__vector.html#abab718a13944985143bc2a882aeea657":[2,0,0,40,7], "d4/dfa/classstd_1_1fixed__sorted__vector.html#ad3a09470b09ced0d1e9b2dfe4999dcb4":[2,0,0,40,9], "d4/dfa/classstd_1_1fixed__sorted__vector.html#ad55e670afba8c3b8a947c2007188ebe8":[2,0,0,40,12], "d4/dfa/classstd_1_1fixed__sorted__vector.html#ad8536b6a839c0f97ed486f1e87871179":[2,0,0,40,5], "d4/dff/classstd_1_1list.html":[2,0,0,106], "d4/dff/classstd_1_1list.html#a012d703d9498bb5379aefab4cbd793fc":[2,0,0,106,10], "d4/dff/classstd_1_1list.html#a068c5ba29eb4c5784417063041db9876":[2,0,0,106,26], "d4/dff/classstd_1_1list.html#a11c4f88fd223f0d6f69e9812409148ac":[2,0,0,106,3], "d4/dff/classstd_1_1list.html#a1b5cf608d0dfc92d253ad2b2c61ffe92":[2,0,0,106,4], "d4/dff/classstd_1_1list.html#a25f54f28c1f8d88247acb96bdcea6816":[2,0,0,106,7], "d4/dff/classstd_1_1list.html#a3131c7319678df9ca4a822a04cf7fb6c":[2,0,0,106,29], "d4/dff/classstd_1_1list.html#a39dd6f17e8be7b52b109f62295528b5c":[2,0,0,106,2], "d4/dff/classstd_1_1list.html#a3a37b706d3d0b2f13b2428e3ca1c699c":[2,0,0,106,1], "d4/dff/classstd_1_1list.html#a3e9ec15c28ddebc1953662e58ec510ca":[2,0,0,106,19], "d4/dff/classstd_1_1list.html#a3f6fac6aa256c5db949f84a0cd2efcac":[2,0,0,106,0], "d4/dff/classstd_1_1list.html#a40e6feb7cf0b64094287e5827597da81":[2,0,0,106,8], "d4/dff/classstd_1_1list.html#a41a418c3113d8c12fe012f774be80597":[2,0,0,106,24], "d4/dff/classstd_1_1list.html#a4354c4728b382544e06fce4fc9bcc312":[2,0,0,106,20], "d4/dff/classstd_1_1list.html#a551b830dafee1df29c1140d6f313a18b":[2,0,0,106,22], "d4/dff/classstd_1_1list.html#a5ae1a58a6b82d43f7cd07e9109333d57":[2,0,0,106,14], "d4/dff/classstd_1_1list.html#a5b9334ad92fc00e1e85ea89b0897abf1":[2,0,0,106,17], "d4/dff/classstd_1_1list.html#a6ce0ffc7ab23dbf139a9cad3847cca65":[2,0,0,106,25], "d4/dff/classstd_1_1list.html#a79d4760b4b044e86ccc18f418c2dfbd5":[2,0,0,106,18], "d4/dff/classstd_1_1list.html#a7ea2991023c95d6082a982639d589122":[2,0,0,106,16], "d4/dff/classstd_1_1list.html#a8309c19812be5d7699bae2cb74b23498":[2,0,0,106,6], "d4/dff/classstd_1_1list.html#a845d0da013d055fa9d8a5fba3c83451f":[2,0,0,106,12], "d4/dff/classstd_1_1list.html#a9016e842ec79a98cfbe4af8253025cda":[2,0,0,106,21], "d4/dff/classstd_1_1list.html#a9e4100a74107d8bfdf64836fd395c428":[2,0,0,106,23], "d4/dff/classstd_1_1list.html#aa2a48b9d9d42da5c02daeecaa24f1f6b":[2,0,0,106,11], "d4/dff/classstd_1_1list.html#acad7862b982e5d322e4f43256e64094c":[2,0,0,106,27], "d4/dff/classstd_1_1list.html#adce674f11895530210a08dd9feb8221f":[2,0,0,106,9], "d4/dff/classstd_1_1list.html#adf28a3cd2d000c2e9dbb2f31d140189b":[2,0,0,106,28], "d4/dff/classstd_1_1list.html#ae9e3042311db99b0ed187cf26bcedb09":[2,0,0,106,30], "d4/dff/classstd_1_1list.html#aec0f8c316d3702cf37f24968429eec63":[2,0,0,106,15], "d4/dff/classstd_1_1list.html#af24365dafd4b435765afc393959c72da":[2,0,0,106,5], "d4/dff/classstd_1_1list.html#afd9bdd4dc99526ea4f79c9bf5cb9c006":[2,0,0,106,13], "d5/d05/classstd_1_1ramakrishna.html":[2,0,0,127], "d5/d05/classstd_1_1ramakrishna.html#a6441f28b4ef0e44eb62726b5c61ba8e0":[2,0,0,127,1], "d5/d05/classstd_1_1ramakrishna.html#aa74c6cbb95ea33a3f5343a91f34004cb":[2,0,0,127,0], "d5/d27/applications__events_8hpp.html":[3,0,1,9], "d5/d2c/smath_8hpp.html":[3,0,1,62], "d5/d38/classstd_1_1independent__bits__engine.html":[2,0,0,59], "d5/d38/classstd_1_1independent__bits__engine.html#a1daa4f3fdd1c4a805931b678d3fae5fe":[2,0,0,59,3], "d5/d38/classstd_1_1independent__bits__engine.html#a32f151de85e10db3c7818333e543d1cb":[2,0,0,59,5], "d5/d38/classstd_1_1independent__bits__engine.html#a3f7b409af91a4364b2adca735cb6f34a":[2,0,0,59,4], "d5/d38/classstd_1_1independent__bits__engine.html#a43d68292f4b0693e304146b9a32ddcb3":[2,0,0,59,2], "d5/d38/classstd_1_1independent__bits__engine.html#a569ea2356722f0905ea3abb74bb2cd6b":[2,0,0,59,1], "d5/d38/classstd_1_1independent__bits__engine.html#a5bf120f126dd5ca1964d01a4ce8d5bef":[2,0,0,59,6], "d5/d38/classstd_1_1independent__bits__engine.html#a5d7b0d9168fd124a290e25ea93541c96":[2,0,0,59,8], "d5/d38/classstd_1_1independent__bits__engine.html#a60306c9881c5ce4dc0d055d32571ac03":[2,0,0,59,9], "d5/d38/classstd_1_1independent__bits__engine.html#a7ec88d4d053d1852f3fe16f5f8610365":[2,0,0,59,0], "d5/d38/classstd_1_1independent__bits__engine.html#af31e73ded39f92a9a9c714092f6a6556":[2,0,0,59,7], "d5/d40/structstd_1_1internal_1_1slist__base__node.html":[2,0,0,1,7], "d5/d40/structstd_1_1internal_1_1slist__base__node.html#a0e1fe1f53aeebb7d860d8630a02d71ec":[2,0,0,1,7,0], "d5/d40/structstd_1_1internal_1_1slist__base__node.html#a3ad27932e24383eba50bf6e8ddefb9d9":[2,0,0,1,7,4], "d5/d40/structstd_1_1internal_1_1slist__base__node.html#a5059f904e47e8ee44777fd9f8026efb8":[2,0,0,1,7,2], "d5/d40/structstd_1_1internal_1_1slist__base__node.html#a9c43ac315223c45502b3e85c040d4a12":[2,0,0,1,7,1], "d5/d40/structstd_1_1internal_1_1slist__base__node.html#aad3c6a04ad23efc497a7a5a1b576b103":[2,0,0,1,7,3], "d5/d40/structstd_1_1internal_1_1slist__base__node.html#ab51c452c73a63bded6db92d617ac441e":[2,0,0,1,7,5], "d5/d46/classstd_1_1event.html":[2,0,0,31], "d5/d46/classstd_1_1event.html#a2555ea55a19f7438c11b448a4da310be":[2,0,0,31,0], "d5/d46/classstd_1_1event.html#a3127439e3b1ae53ff82ffbd6eb1cdb74":[2,0,0,31,1], "d5/d46/classstd_1_1event.html#a60162e40f032fd335c8f63923b4ef002":[2,0,0,31,2], "d5/d46/classstd_1_1event.html#a650674261758e63ccde58cd585caef81":[2,0,0,31,4], "d5/d46/classstd_1_1event.html#ae5bc638a246c98040e8ecfa64836f029":[2,0,0,31,5], "d5/d46/classstd_1_1event.html#ae9459294918a688d5b389ed80b54cd58":[2,0,0,31,3], "d5/d4b/classstd_1_1property.html":[2,0,0,125], "d5/d4b/classstd_1_1property.html#a098f2afe0df9c5ce4506b335611ef53e":[2,0,0,125,3], "d5/d4b/classstd_1_1property.html#a2b7254e0060ade9f44e65f3a4d71dd54":[2,0,0,125,1], "d5/d4b/classstd_1_1property.html#a556273c46a8a9cbd32b5a05375c844cd":[2,0,0,125,0], "d5/d4b/classstd_1_1property.html#aa2728918617e3d879fb41e58d7e53c24":[2,0,0,125,4], "d5/d4b/classstd_1_1property.html#ae5ddf88013535b71302ec90518934549":[2,0,0,125,5], "d5/d4b/classstd_1_1property.html#af5962d92265befccc38f8a426d11d58a":[2,0,0,125,2], "d5/d51/buffer__allocator_8hpp.html":[3,0,1,15], "d5/d61/allocator_8hpp.html":[3,0,1,7], "d5/d61/allocator_8hpp.html#a3b4c7dfb17db51bb2753517543ccd37c":[3,0,1,7,2], "d5/d61/allocator_8hpp.html#a9a2e8249bedcfb932780df5723e4ad9e":[3,0,1,7,1], "d5/d64/classstd_1_1slist.html":[2,0,0,141], "d5/d64/classstd_1_1slist.html#a04a69afc6847311533818dddfcdee97e":[2,0,0,141,4], "d5/d64/classstd_1_1slist.html#a0b6782d4bcd7dc6971e8fbb42a6ad5ce":[2,0,0,141,12], "d5/d64/classstd_1_1slist.html#a111d34dd3475c3d5b9247a70a85a30b2":[2,0,0,141,22], "d5/d64/classstd_1_1slist.html#a140815ea1f9e91fe058f933f1ae8ed55":[2,0,0,141,6], "d5/d64/classstd_1_1slist.html#a14776d9cb4de5a6ab72e848ecd996a67":[2,0,0,141,10], "d5/d64/classstd_1_1slist.html#a24c00ed63a3cd52377a77de14fe82652":[2,0,0,141,0], "d5/d64/classstd_1_1slist.html#a2977308e228e97004773dee54c91b8b5":[2,0,0,141,13], "d5/d64/classstd_1_1slist.html#a2bdb4b58fb7bdd268323735f0b33bbe6":[2,0,0,141,11], "d5/d64/classstd_1_1slist.html#a3660e14a008464ecc897c731968ecd81":[2,0,0,141,19], "d5/d64/classstd_1_1slist.html#a47166c64c1ddb6b559610a6c5f739c35":[2,0,0,141,17], "d5/d64/classstd_1_1slist.html#a495f2218b4c1e39bda6258ee9dcb9db1":[2,0,0,141,20], "d5/d64/classstd_1_1slist.html#a55470629e45e49d744d6eeab82331138":[2,0,0,141,7], "d5/d64/classstd_1_1slist.html#a5fa39130f5ef432af64b224e50d99e72":[2,0,0,141,16], "d5/d64/classstd_1_1slist.html#a61f6570d0e7572ac7d68e6e8967dd098":[2,0,0,141,5], "d5/d64/classstd_1_1slist.html#a6ae4ca7dfc3e0bd5080033904ae10c71":[2,0,0,141,9], "d5/d64/classstd_1_1slist.html#a7f3ce2758b964158f7b413bbe0e2c699":[2,0,0,141,21], "d5/d64/classstd_1_1slist.html#a8f3d02d796e1b94127a8f9ec622e7f3a":[2,0,0,141,14], "d5/d64/classstd_1_1slist.html#a9dc76627cfe746336df1102798406f04":[2,0,0,141,3], "d5/d64/classstd_1_1slist.html#aae0f045e80a1691a8dc0daa4a64d7c53":[2,0,0,141,8], "d5/d64/classstd_1_1slist.html#ab6b6cc8d2f6529076150d4b9d25421c1":[2,0,0,141,15], "d5/d64/classstd_1_1slist.html#aca19a21368914a9c7d6ba9bfd2ca7e6e":[2,0,0,141,2], "d5/d64/classstd_1_1slist.html#ace6af22ddd9ca105272f3a7e6c8dd90c":[2,0,0,141,18], "d5/d64/classstd_1_1slist.html#af578a53dfee381d366b7a881720a07d4":[2,0,0,141,1], "d5/d68/structstd_1_1is__polymorphic.html":[2,0,0,91], "d5/d6c/atomic_8hpp.html":[3,0,1,12], "d5/d6c/atomic_8hpp.html#a6257cbad5715428cc0b01d30efe1fc3f":[3,0,1,12,1], "d5/d6c/atomic_8hpp.html#a6257cbad5715428cc0b01d30efe1fc3fa1b67b1f58b6dfe544dc067460fc47332":[3,0,1,12,1,5], "d5/d6c/atomic_8hpp.html#a6257cbad5715428cc0b01d30efe1fc3fa713961552f49e86e76c18d31568396d8":[3,0,1,12,1,1], "d5/d6c/atomic_8hpp.html#a6257cbad5715428cc0b01d30efe1fc3fa71556f1ad3429c75eb63c783a8c4390e":[3,0,1,12,1,0], "d5/d6c/atomic_8hpp.html#a6257cbad5715428cc0b01d30efe1fc3fa8b17a31dea30fef995ad75d19e1d85ee":[3,0,1,12,1,3], "d5/d6c/atomic_8hpp.html#a6257cbad5715428cc0b01d30efe1fc3fad4338b1beb516c55566a43f41ad98560":[3,0,1,12,1,4], "d5/d6c/atomic_8hpp.html#a6257cbad5715428cc0b01d30efe1fc3faf4ba3803d19d0df46da5f0ae092ec08d":[3,0,1,12,1,2], "d5/d78/structstd_1_1has__trivial__assign.html":[2,0,0,50], "d5/d7a/classstd_1_1spinlock.html":[2,0,0,143], "d5/d7a/classstd_1_1spinlock.html#a01429c40f6b8a27bc844f2e7073b5262":[2,0,0,143,0], "d5/d7a/classstd_1_1spinlock.html#a1c0cb294f8af28dee9a63807a982b0ed":[2,0,0,143,6], "d5/d7a/classstd_1_1spinlock.html#a48029fe3844ce4614875c893d20a970e":[2,0,0,143,8], "d5/d7a/classstd_1_1spinlock.html#a6d010c79795532eac8503d24b5c14312":[2,0,0,143,1], "d5/d7a/classstd_1_1spinlock.html#aa4caf15c25859ff4c23fcf4d978023d2":[2,0,0,143,3], "d5/d7a/classstd_1_1spinlock.html#aa7b292b211c18e54849550385c9686cd":[2,0,0,143,2], "d5/d7a/classstd_1_1spinlock.html#abb56d76aad9b5ab8d865d2a1691ebf03":[2,0,0,143,4], "d5/d7a/classstd_1_1spinlock.html#aca18d2985a115a9f01ecd5aab1d6e12f":[2,0,0,143,7], "d5/d7a/classstd_1_1spinlock.html#ae958fb96bc80bb084032600a3834bee4":[2,0,0,143,5], "d5/d7e/structstd_1_1_sys_1_1mutex__struct.html":[2,0,0,151,0], "d5/d88/structstd_1_1string__rep.html":[2,0,0,149], "d5/d88/structstd_1_1string__rep.html#a2b07a0e88e164ee6406b2d1b9c6112c5":[2,0,0,149,0], "d5/d88/structstd_1_1string__rep.html#a811ba699f524a07fca87451ec9b7bd9a":[2,0,0,149,5], "d5/d88/structstd_1_1string__rep.html#a8c75d5341c4689f99f5357e4c7686edd":[2,0,0,149,6], "d5/d88/structstd_1_1string__rep.html#a9703e294128a2ee943237571af5bedf0":[2,0,0,149,3], "d5/d88/structstd_1_1string__rep.html#a976c3e095976d5098eafa69b61abc016":[2,0,0,149,1], "d5/d88/structstd_1_1string__rep.html#abf1f5949512a20b084a87b276f65307c":[2,0,0,149,4], "d5/d88/structstd_1_1string__rep.html#ad9d46356d507f4750b7f66b84d741bd2":[2,0,0,149,2], "d5/da8/classstd_1_1lock__base.html":[2,0,0,107], "d5/da8/classstd_1_1lock__base.html#a11a6fcfe95e53fcf7fa9ea1899795399":[2,0,0,107,2], "d5/da8/classstd_1_1lock__base.html#a40542bbcdbabc587b03363ba1e6291c6":[2,0,0,107,0], "d5/da8/classstd_1_1lock__base.html#a493cd8e3d4e08f82d1d64014153a032b":[2,0,0,107,3], "d5/da8/classstd_1_1lock__base.html#ad2292c7877a72b49f0b59e08a7392c61":[2,0,0,107,1], "d5/da8/classstd_1_1lock__base.html#ad5ab453523394a1c4b083b82766f555e":[2,0,0,107,4], "d5/da8/ext_8hpp.html":[3,0,1,2,3], "d5/da8/ext_8hpp.html#a75ea34a9c5a358814dc101008e25da63":[3,0,1,2,3,3], "d5/da8/ext_8hpp.html#af2e3a1605007b6c1c31a698b0036a4af":[3,0,1,2,3,1], "d5/da8/ext_8hpp.html#af627b3eb00e62d3b51160e17590d7cf8":[3,0,1,2,3,0], "d5/da8/ext_8hpp.html#afedf386ab72c194c06eaeb3d5c7c650a":[3,0,1,2,3,2], "d5/db6/structstd_1_1random__access__iterator__tag.html":[2,0,0,128], "d5/dcf/classstd_1_1net_1_1socket.html":[2,0,0,3,8], "d5/dcf/classstd_1_1net_1_1socket.html#a037eb0329c110f9978e504a2e9c6b850":[2,0,0,3,8,1], "d5/dcf/classstd_1_1net_1_1socket.html#a057063eaf2e2ae7e3e2a68d36aea64fe":[2,0,0,3,8,18], "d5/dcf/classstd_1_1net_1_1socket.html#a1145bdb7d5e964fd525f0635dcfd043f":[2,0,0,3,8,2], "d5/dcf/classstd_1_1net_1_1socket.html#a2adbebe226bb20438587b8cd802a74a8":[2,0,0,3,8,7], "d5/dcf/classstd_1_1net_1_1socket.html#a2c9643d14e3b5ff465bbc77391ae2bef":[2,0,0,3,8,3], "d5/dcf/classstd_1_1net_1_1socket.html#a2e846460d29b2e9e9c15201245cf0ddb":[2,0,0,3,8,25], "d5/dcf/classstd_1_1net_1_1socket.html#a3ce264c4d03e7d066e68ca59cd173baf":[2,0,0,3,8,17], "d5/dcf/classstd_1_1net_1_1socket.html#a45060a1f5a96f3fc0b579b6a12e59686":[2,0,0,3,8,5], "d5/dcf/classstd_1_1net_1_1socket.html#a49263efe677b0ed0b0db906d9b300835":[2,0,0,3,8,24], "d5/dcf/classstd_1_1net_1_1socket.html#a4dee92e90c25b542d7a5dfd2777565c1":[2,0,0,3,8,16], "d5/dcf/classstd_1_1net_1_1socket.html#a5138f6fa3c53e3b9c7acfd668fbe8080":[2,0,0,3,8,27], "d5/dcf/classstd_1_1net_1_1socket.html#a514b503b24b99d2d281ca8ea6f062c35":[2,0,0,3,8,35], "d5/dcf/classstd_1_1net_1_1socket.html#a545a96e10df6b5750fd7c5c525bc42ac":[2,0,0,3,8,21], "d5/dcf/classstd_1_1net_1_1socket.html#a5a951a5a6482ed9ebff2b61092a045ff":[2,0,0,3,8,10], "d5/dcf/classstd_1_1net_1_1socket.html#a6bb39f226ba79d033a9881ed2ab64fea":[2,0,0,3,8,36], "d5/dcf/classstd_1_1net_1_1socket.html#a6fd737591a798c982ab10d1171863b11":[2,0,0,3,8,26], "d5/dcf/classstd_1_1net_1_1socket.html#a799f9d5c22e3f0b1b9e9142b71dc548b":[2,0,0,3,8,22] };
RoseLeBlood/aSTL
docs/html/navtreeindex3.js
JavaScript
mit
20,797
/* global $,kendo,PouchDB */ var testHelper = testHelper || {}; //Returns event spy {events:array, dispose:function, reset:function}. //events[i] is {e:*}. testHelper.spyKendoEvent = function (instance, eventName) { 'use strict'; var handler = function (e) { var copy = $.extend(true, {}, e); result.events.push({ e: copy }); }, dispose = function () { instance.unbind(eventName, handler); this.reset(); }, reset = function () { result.events = []; }, result = { events: [], dispose: dispose, reset: reset }; instance.bind(eventName, handler); return result; }; //Returns promise that resolves when change event occurs on PouchDB specified number of times. testHelper.waitForDbChanges = function (db, numberOfChanges) { var counter = 0, deferred = new $.Deferred(), handler = function () { counter++; if (counter === numberOfChanges) { changes.removeListener("change", handler); deferred.resolve(); } }, changes = db.changes({ since: 'now', live: true }); changes.on("change", handler); return deferred.promise(); }; testHelper.addArrayToDataSource = function (dataSource, rows) { $.each(rows, function (_, row) { dataSource.add(row); }); };
terikon/kendo-pouchdb
tests/testHelper.js
JavaScript
mit
1,482
import * as React from 'react'; import { expect } from 'chai'; import { spy } from 'sinon'; import { createMount, describeConformanceV5, act, createClientRender } from 'test/utils'; import FormControl, { formControlClasses as classes } from '@material-ui/core/FormControl'; import Input from '@material-ui/core/Input'; import Select from '@material-ui/core/Select'; import useFormControl from './useFormControl'; describe('<FormControl />', () => { const render = createClientRender(); const mount = createMount(); function TestComponent(props) { const context = useFormControl(); React.useEffect(() => { props.contextCallback(context); }); return null; } describeConformanceV5(<FormControl />, () => ({ classes, inheritComponent: 'div', render, mount, refInstanceof: window.HTMLDivElement, testComponentPropWith: 'fieldset', muiName: 'MuiFormControl', testVariantProps: { margin: 'dense' }, skip: ['componentsProp'], })); describe('initial state', () => { it('should have no margin', () => { const { container } = render(<FormControl />); const root = container.firstChild; expect(root).not.to.have.class(classes.marginNormal); expect(root).not.to.have.class(classes.sizeSmall); }); it('can have the margin normal class', () => { const { container } = render(<FormControl margin="normal" />); const root = container.firstChild; expect(root).to.have.class(classes.marginNormal); expect(root).not.to.have.class(classes.sizeSmall); }); it('can have the margin dense class', () => { const { container } = render(<FormControl margin="dense" />); const root = container.firstChild; expect(root).to.have.class(classes.marginDense); expect(root).not.to.have.class(classes.marginNormal); }); it('should not be filled initially', () => { const readContext = spy(); render( <FormControl> <TestComponent contextCallback={readContext} /> </FormControl>, ); expect(readContext.args[0][0]).to.have.property('filled', false); }); it('should not be focused initially', () => { const readContext = spy(); render( <FormControl> <TestComponent contextCallback={readContext} /> </FormControl>, ); expect(readContext.args[0][0]).to.have.property('focused', false); }); }); describe('prop: required', () => { it('should not apply it to the DOM', () => { const { container } = render(<FormControl required />); expect(container.firstChild).not.to.have.attribute('required'); }); }); describe('prop: disabled', () => { it('will be unfocused if it gets disabled', () => { const readContext = spy(); const { container, setProps } = render( <FormControl> <Input /> <TestComponent contextCallback={readContext} /> </FormControl>, ); expect(readContext.args[0][0]).to.have.property('focused', false); act(() => { container.querySelector('input').focus(); }); expect(readContext.args[1][0]).to.have.property('focused', true); setProps({ disabled: true }); expect(readContext.args[2][0]).to.have.property('focused', false); }); }); describe('prop: focused', () => { it('should display input in focused state', () => { const readContext = spy(); const { container } = render( <FormControl focused> <Input /> <TestComponent contextCallback={readContext} /> </FormControl>, ); expect(readContext.args[0][0]).to.have.property('focused', true); container.querySelector('input').blur(); expect(readContext.args[0][0]).to.have.property('focused', true); }); it('ignores focused when disabled', () => { const readContext = spy(); render( <FormControl focused disabled> <Input /> <TestComponent contextCallback={readContext} /> </FormControl>, ); expect(readContext.args[0][0]).to.include({ disabled: true, focused: false }); }); }); describe('input', () => { it('should be filled when a value is set', () => { const readContext = spy(); render( <FormControl> <Input value="bar" /> <TestComponent contextCallback={readContext} /> </FormControl>, ); expect(readContext.args[0][0]).to.have.property('filled', true); }); it('should be filled when a defaultValue is set', () => { const readContext = spy(); render( <FormControl> <Input defaultValue="bar" /> <TestComponent contextCallback={readContext} /> </FormControl>, ); expect(readContext.args[0][0]).to.have.property('filled', true); }); it('should not be adornedStart with an endAdornment', () => { const readContext = spy(); render( <FormControl> <Input endAdornment={<div />} /> <TestComponent contextCallback={readContext} /> </FormControl>, ); expect(readContext.args[0][0]).to.have.property('adornedStart', false); }); it('should be adornedStar with a startAdornment', () => { const readContext = spy(); render( <FormControl> <Input startAdornment={<div />} /> <TestComponent contextCallback={readContext} /> </FormControl>, ); expect(readContext.args[0][0]).to.have.property('adornedStart', true); }); }); describe('select', () => { it('should not be adorned without a startAdornment', () => { const readContext = spy(); render( <FormControl> <Select value="" /> <TestComponent contextCallback={readContext} /> </FormControl>, ); expect(readContext.args[0][0]).to.have.property('adornedStart', false); }); it('should be adorned with a startAdornment', () => { const readContext = spy(); render( <FormControl> <Select value="" input={<Input startAdornment={<div />} />} /> <TestComponent contextCallback={readContext} /> </FormControl>, ); expect(readContext.args[0][0].adornedStart, true); }); }); describe('useFormControl', () => { const FormController = React.forwardRef((_, ref) => { const formControl = useFormControl(); React.useImperativeHandle(ref, () => formControl, [formControl]); return null; }); const FormControlled = React.forwardRef(function FormControlled(props, ref) { return ( <FormControl {...props}> <FormController ref={ref} /> </FormControl> ); }); describe('from props', () => { it('should have the required prop from the instance', () => { const formControlRef = React.createRef(); const { setProps } = render(<FormControlled ref={formControlRef} />); expect(formControlRef.current).to.have.property('required', false); setProps({ required: true }); expect(formControlRef.current).to.have.property('required', true); }); it('should have the error prop from the instance', () => { const formControlRef = React.createRef(); const { setProps } = render(<FormControlled ref={formControlRef} />); expect(formControlRef.current).to.have.property('error', false); setProps({ error: true }); expect(formControlRef.current).to.have.property('error', true); }); it('should have the margin prop from the instance', () => { const formControlRef = React.createRef(); const { setProps } = render(<FormControlled ref={formControlRef} />); expect(formControlRef.current).to.have.property('size', 'medium'); setProps({ size: 'small' }); expect(formControlRef.current).to.have.property('size', 'small'); }); it('should have the fullWidth prop from the instance', () => { const formControlRef = React.createRef(); const { setProps } = render(<FormControlled ref={formControlRef} />); expect(formControlRef.current).to.have.property('fullWidth', false); setProps({ fullWidth: true }); expect(formControlRef.current).to.have.property('fullWidth', true); }); }); describe('callbacks', () => { describe('onFilled', () => { it('should set the filled state', () => { const formControlRef = React.createRef(); render(<FormControlled ref={formControlRef} />); expect(formControlRef.current).to.have.property('filled', false); act(() => { formControlRef.current.onFilled(); }); expect(formControlRef.current).to.have.property('filled', true); act(() => { formControlRef.current.onFilled(); }); expect(formControlRef.current).to.have.property('filled', true); }); }); describe('onEmpty', () => { it('should clean the filled state', () => { const formControlRef = React.createRef(); render(<FormControlled ref={formControlRef} />); act(() => { formControlRef.current.onFilled(); }); expect(formControlRef.current).to.have.property('filled', true); act(() => { formControlRef.current.onEmpty(); }); expect(formControlRef.current).to.have.property('filled', false); act(() => { formControlRef.current.onEmpty(); }); expect(formControlRef.current).to.have.property('filled', false); }); }); describe('handleFocus', () => { it('should set the focused state', () => { const formControlRef = React.createRef(); render(<FormControlled ref={formControlRef} />); expect(formControlRef.current).to.have.property('focused', false); act(() => { formControlRef.current.onFocus(); }); expect(formControlRef.current).to.have.property('focused', true); act(() => { formControlRef.current.onFocus(); }); expect(formControlRef.current).to.have.property('focused', true); }); }); describe('handleBlur', () => { it('should clear the focused state', () => { const formControlRef = React.createRef(); render(<FormControlled ref={formControlRef} />); expect(formControlRef.current).to.have.property('focused', false); act(() => { formControlRef.current.onFocus(); }); expect(formControlRef.current).to.have.property('focused', true); act(() => { formControlRef.current.onBlur(); }); expect(formControlRef.current).to.have.property('focused', false); act(() => { formControlRef.current.onBlur(); }); expect(formControlRef.current).to.have.property('focused', false); }); }); }); }); });
callemall/material-ui
packages/material-ui/src/FormControl/FormControl.test.js
JavaScript
mit
11,169
const EventEmitter = require('events'); class MomentumEventEmitter extends EventEmitter {} module.exports = MomentumEventEmitter;
kylekatarnls/momentum
src/event/emitter.js
JavaScript
mit
132
module.exports = function(grunt) { var commonTasks = ['jscs', 'jshint', 'concat', 'uglify']; grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), jscs: { src: ['Gruntfile.js', 'src/*.js', 'test/utils-test.js', 'test/basicTimerSpec', 'test/timedFuncSpec.js'] }, jshint: { all: ['Gruntfile.js', 'src/*.js', 'test/utils-test.js', 'test/basicTimerSpec', 'test/timedFuncSpec.js'] }, concat: { options: { banner: [ '/*! <%= pkg.name %> <%= pkg.version %> <%=grunt.template.today("yyyy-mm-dd")%>*/\n', '(function($) {\n' ].join(''), footer: '} (jQuery));' }, dist: { src: [ 'src/constants.js', 'src/utils.js', 'src/Timer.js', 'src/index.js' ], dest: 'dist/timer.jquery.js' } }, uglify: { dist: { src: 'dist/timer.jquery.js', dest: 'dist/timer.jquery.min.js' } }, watch: { scripts: { files: ['src/*.js'], tasks: commonTasks, options: { nospawn: true } } } }); grunt.loadNpmTasks('grunt-jscs'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.registerTask('default', commonTasks); };
walmik/timer.jquery
Gruntfile.js
JavaScript
mit
1,267
var http = require("http"); var path = require('path'); var fs = require('fs'); var mkdirp = require('mkdirp'); var pg = require('pg'); var exec = require('child_process').exec; var sh = require("execSync") var util = require('util'); var info = {"good_load":0,"bad_load":0,"no_data":0}; var password="transit"; var options = { host: 'www.gtfs-data-exchange.com', path: '/api/agencies' }; http.get(options, function (http_res) { //console.log(http_res); var data = ""; http_res.on("data", function (chunk) { data += chunk; }); http_res.on("end", function () { parseAgencies(JSON.parse(data).data); }); }) .on('error', function(e) { console.log(e); console.log("Got error: " + e); }); var parseAgencies = function(agencyList){ var validAgencyCount = 0; var conString = "postgres://postgres:"+password+"@localhost:5432/gtfs"; var client = new pg.Client(conString); client.connect(function(err) { if(err) { return console.error('Could not connect to database', err); } //console.log(result.rows[0].theTime); //output: Tue Jan 15 2013 19:12:47 GMT-600 (CST) agencyList.forEach(function(agency){ if(agency['is_official'] && agency['country'] == 'United States'){ //console.log( agency['dataexchange_id']); validAgencyCount++ var options = { host: 'www.gtfs-data-exchange.com', path: '/api/agency?agency='+agency['dataexchange_id'] }; http.get(options, function (http_res) { //console.log(http_res); var data = ""; http_res.on("data", function (chunk) { data += chunk; }); http_res.on("end", function () { mkdirp(path.resolve(__dirname,"../gtfs/")+"/"+agency['dataexchange_id'], function(err){ if (err) console.error(err) //else console.log('created dir '+agency['dataexchange_id']); }); if(agency["is_official"] && agency['country'] === 'United States'){ //console.log( "Agency id: " + agency['dataexchange_id'],"File URL: " + "") } parseAgent(JSON.parse(data).data,agency,client); }); }) .on('error', function(e) { console.log(e); console.log("Got error: " + e); }); } })//end for each agency; //client.end(); }); console.log("Num Agencies:"+validAgencyCount); console.log("done"); } var download = function(url, dest, cb) { var file = fs.createWriteStream(dest); var request = http.get(url, function(response) { response.pipe(file); file.on('finish', function() { file.close(); cb(); }); }); } var gtfsdbLoad = function(schemaName,destinationStream){ var result = sh.exec("gtfsdb-load --database_url postgresql://postgres:"+password+"@localhost/gtfs --schema="+schemaName+" --is_geospatial "+destinationStream); console.log('return code ' + result.code); console.log('stdout + stderr ' + result.stdout); } var createSchema = function(client,schemaName){ var query = 'CREATE SCHEMA "'+schemaName+'" '; client.query(query, function(err, result) { if(err) { return console.error('error running query:',query, err); }}) } var writeAgency = function(agency){ var body = JSON.stringify(agency); var post_options = { hostname: "localhost", port: 1337, path: "/agency/create/", method: "POST", headers: { "Content-Type": "application/json", "Content-Length": body.length // Often this part is optional } } var post_req = http.request(post_options, function(res) { res.setEncoding('utf8'); res.on('data', function (chunk) { console.log('Response: ' + chunk); }); }); post_req.write(body); post_req.end(); } var inAPI = function(dataexchange_id,cb){ var options = { host: 'localhost', port: 1337, path: '/agency/?dataexchange_id='+dataexchange_id }; http.get(options, function (http_res) { //console.log(http_res); var data = ""; http_res.on("data", function (chunk) { data += chunk; }); http_res.on("end", function () { output =JSON.parse(data) if(output.length > 0){ cb(true); }else{ cb(false); } }); }) .on('error', function(e) { console.log(e); console.log("Got error: " + e); }); } var testQuery = function(client,schemaName,agency,destinationStream){ var query = 'select ST_AsGeoJSON(geom) as geo,route_id from "'+schemaName+'".routes where geom is not null'; client.query(query, function(err, result) { if(err) { //return console.error('error running query:',query, err); info.no_data++; console.log(util.inspect(info,false,null)); //client.query('DROP SCHEMA "'+schemaName+'"'); return console.log(schemaName+":No Table"); } if(result.rows && result.rows.length > 0){ //console.log('error check '+util.inspect(result,false,null)+' '+schemaName); if(JSON.parse(result.rows[0].geo) !== null){ agency['current_datafile'] = schemaName; agency.is_official = 1; //console.log('Writing '+agency.dataexchange_id) //console.log(util.inspect(agency,false,null)); //writeAgency(agency); inAPI(agency.dataexchange_id,function(exists){ if(exists){ console.log(agency.dataexchange_id+" exists.") }else{ console.log(agency.dataexchange_id+" doesn't exist.") writeAgency(agency); } }); //console.log(schemaName+": "+JSON.parse(result.rows[0].geo).coordinates[0][0]); info.good_load++; }else{ //client.query('DROP SCHEMA "'+schemaName+'"'); //console.log(schemaName+": No Geometry"); info.bad_load++; //gtfsdbLoad(schemaName,destinationStream) } }else{ //client.query('DROP SCHEMA "'+schemaName+'"'); //console.log(schemaName+": No Rows"); info.bad_load++; //gtfsdbLoad(schemaName,destinationStream) } //console.log(util.inspect(info,false,null)); }) } var parseAgent = function(agent,agency, client){ var i = 0; var house = agency.dataexchange_id; agent.datafiles.forEach(function(datafile){ if(i == 0){ var fileNameOrig = agent["datafiles"][0].file_url; var nameSplit = fileNameOrig.substr(29); var schemaName = fileNameOrig.substr(29).split(".")[0]; var destinationStream = path.resolve(__dirname,"../gtfs/" + house + "/" + nameSplit); testQuery(client,schemaName,agency,destinationStream); //createSchema(client,schemaName); //gtfsdbLoad(schemaName,destinationStream) //download(agent["datafiles"][0].file_url,destinationStream,function(){}); } i++; }) //console.log("agent") return agent["datafiles"][0].file_url; }
availabs/njtdm
admin/gtfs-update.js
JavaScript
mit
7,667
module.exports = (req, res, next) => { const _registration = req.requestParams.registration const match = { _registration: _registration } return global.models.getAll( global.db.registrations.RegistrationDebaters, match, global.utils.populate.registrationDebaters, res ) }
westoncolemanl/tabbr-api
controllers/registrations/debaters/getAll.js
JavaScript
mit
304
'use strict' const pkg = require('../package') module.exports = { port: 4000, title: 'slotlist.info - ArmA 3 mission and slotlist management', publicPath: '/', }
MorpheusXAUT/slotlist-frontend
build/config.js
JavaScript
mit
169
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; var createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; var inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; var possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; var slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); var toConsumableArray = function (arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; return arr2; } else { return Array.from(arr); } }; /* Possible todos: 0. Add XSLT to JML-string stylesheet (or even vice versa) 0. IE problem: Add JsonML code to handle name attribute (during element creation) 0. Element-specific: IE object-param handling Todos inspired by JsonML: https://github.com/mckamey/jsonml/blob/master/jsonml-html.js 0. duplicate attributes? 0. expand ATTR_MAP 0. equivalent of markup, to allow strings to be embedded within an object (e.g., {$value: '<div>id</div>'}); advantage over innerHTML in that it wouldn't need to work as the entire contents (nor destroy any existing content or handlers) 0. More validation? 0. JsonML DOM Level 0 listener 0. Whitespace trimming? JsonML element-specific: 0. table appending 0. canHaveChildren necessary? (attempts to append to script and img) Other Todos: 0. Note to self: Integrate research from other jml notes 0. Allow Jamilih to be seeded with an existing element, so as to be able to add/modify attributes and children 0. Allow array as single first argument 0. Settle on whether need to use null as last argument to return array (or fragment) or other way to allow appending? Options object at end instead to indicate whether returning array, fragment, first element, etc.? 0. Allow building of generic XML (pass configuration object) 0. Allow building content internally as a string (though allowing DOM methods, etc.?) 0. Support JsonML empty string element name to represent fragments? 0. Redo browser testing of jml (including ensuring IE7 can work even if test framework can't work) */ var win = typeof window !== 'undefined' && window; var doc = typeof document !== 'undefined' && document; var XmlSerializer = typeof XMLSerializer !== 'undefined' && XMLSerializer; // STATIC PROPERTIES var possibleOptions = ['$plugins', '$map' // Add any other options here ]; var NS_HTML = 'http://www.w3.org/1999/xhtml', hyphenForCamelCase = /-([a-z])/g; var ATTR_MAP = { 'readonly': 'readOnly' }; // We define separately from ATTR_DOM for clarity (and parity with JsonML) but no current need // We don't set attribute esp. for boolean atts as we want to allow setting of `undefined` // (e.g., from an empty variable) on templates to have no effect var BOOL_ATTS = ['checked', 'defaultChecked', 'defaultSelected', 'disabled', 'indeterminate', 'open', // Dialog elements 'readOnly', 'selected']; var ATTR_DOM = BOOL_ATTS.concat([// From JsonML 'accessKey', // HTMLElement 'async', 'autocapitalize', // HTMLElement 'autofocus', 'contentEditable', // HTMLElement through ElementContentEditable 'defaultValue', 'defer', 'draggable', // HTMLElement 'formnovalidate', 'hidden', // HTMLElement 'innerText', // HTMLElement 'inputMode', // HTMLElement through ElementContentEditable 'ismap', 'multiple', 'novalidate', 'pattern', 'required', 'spellcheck', // HTMLElement 'translate', // HTMLElement 'value', 'willvalidate']); // Todo: Add more to this as useful for templating // to avoid setting through nullish value var NULLABLES = ['dir', // HTMLElement 'lang', // HTMLElement 'max', 'min', 'title' // HTMLElement ]; var $ = function $(sel) { return doc.querySelector(sel); }; var $$ = function $$(sel) { return [].concat(toConsumableArray(doc.querySelectorAll(sel))); }; /** * Retrieve the (lower-cased) HTML name of a node * @static * @param {Node} node The HTML node * @returns {String} The lower-cased node name */ function _getHTMLNodeName(node) { return node.nodeName && node.nodeName.toLowerCase(); } /** * Apply styles if this is a style tag * @static * @param {Node} node The element to check whether it is a style tag */ function _applyAnyStylesheet(node) { if (!doc.createStyleSheet) { return; } if (_getHTMLNodeName(node) === 'style') { // IE var ss = doc.createStyleSheet(); // Create a stylesheet to actually do something useful ss.cssText = node.cssText; // We continue to add the style tag, however } } /** * Need this function for IE since options weren't otherwise getting added * @private * @static * @param {DOMElement} parent The parent to which to append the element * @param {DOMNode} child The element or other node to append to the parent */ function _appendNode(parent, child) { var parentName = _getHTMLNodeName(parent); var childName = _getHTMLNodeName(child); if (doc.createStyleSheet) { if (parentName === 'script') { parent.text = child.nodeValue; return; } if (parentName === 'style') { parent.cssText = child.nodeValue; // This will not apply it--just make it available within the DOM cotents return; } } if (parentName === 'template') { parent.content.appendChild(child); return; } try { parent.appendChild(child); // IE9 is now ok with this } catch (e) { if (parentName === 'select' && childName === 'option') { try { // Since this is now DOM Level 4 standard behavior (and what IE7+ can handle), we try it first parent.add(child); } catch (err) { // DOM Level 2 did require a second argument, so we try it too just in case the user is using an older version of Firefox, etc. parent.add(child, null); // IE7 has a problem with this, but IE8+ is ok } return; } throw e; } } /** * Attach event in a cross-browser fashion * @static * @param {DOMElement} el DOM element to which to attach the event * @param {String} type The DOM event (without 'on') to attach to the element * @param {Function} handler The event handler to attach to the element * @param {Boolean} [capturing] Whether or not the event should be * capturing (W3C-browsers only); default is false; NOT IN USE */ function _addEvent(el, type, handler, capturing) { el.addEventListener(type, handler, !!capturing); } /** * Creates a text node of the result of resolving an entity or character reference * @param {'entity'|'decimal'|'hexadecimal'} type Type of reference * @param {String} prefix Text to prefix immediately after the "&" * @param {String} arg The body of the reference * @returns {Text} The text node of the resolved reference */ function _createSafeReference(type, prefix, arg) { // For security reasons related to innerHTML, we ensure this string only contains potential entity characters if (!arg.match(/^\w+$/)) { throw new TypeError('Bad ' + type); } var elContainer = doc.createElement('div'); // Todo: No workaround for XML? elContainer.textContent = '&' + prefix + arg + ';'; return doc.createTextNode(elContainer.textContent); } /** * @param {String} n0 Whole expression match (including "-") * @param {String} n1 Lower-case letter match * @returns {String} Uppercased letter */ function _upperCase(n0, n1) { return n1.toUpperCase(); } /** * @private * @static */ function _getType(item) { if (typeof item === 'string') { return 'string'; } if ((typeof item === 'undefined' ? 'undefined' : _typeof(item)) === 'object') { if (item === null) { return 'null'; } if (Array.isArray(item)) { return 'array'; } if ('nodeType' in item) { if (item.nodeType === 1) { return 'element'; } if (item.nodeType === 11) { return 'fragment'; } } return 'object'; } return undefined; } /** * @private * @static */ function _fragReducer(frag, node) { frag.appendChild(node); return frag; } /** * @private * @static */ function _replaceDefiner(xmlnsObj) { return function (n0) { var retStr = xmlnsObj[''] ? ' xmlns="' + xmlnsObj[''] + '"' : n0 || ''; // Preserve XHTML for (var ns in xmlnsObj) { if (xmlnsObj.hasOwnProperty(ns)) { if (ns !== '') { retStr += ' xmlns:' + ns + '="' + xmlnsObj[ns] + '"'; } } } return retStr; }; } function _optsOrUndefinedJML() { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return jml.apply(undefined, toConsumableArray(args[0] === undefined ? args.slice(1) : args)); } /** * @private * @static */ function _jmlSingleArg(arg) { return jml(arg); } /** * @private * @static */ function _copyOrderedAtts(attArr) { var obj = {}; // Todo: Fix if allow prefixed attributes obj[attArr[0]] = attArr[1]; // array of ordered attribute-value arrays return obj; } /** * @private * @static */ function _childrenToJML(node) { return function (childNodeJML, i) { var cn = node.childNodes[i]; var j = Array.isArray(childNodeJML) ? jml.apply(undefined, toConsumableArray(childNodeJML)) : jml(childNodeJML); cn.parentNode.replaceChild(j, cn); }; } /** * @private * @static */ function _appendJML(node) { return function (childJML) { node.appendChild(jml.apply(undefined, toConsumableArray(childJML))); }; } /** * @private * @static */ function _appendJMLOrText(node) { return function (childJML) { if (typeof childJML === 'string') { node.appendChild(doc.createTextNode(childJML)); } else { node.appendChild(jml.apply(undefined, toConsumableArray(childJML))); } }; } /** * @private * @static function _DOMfromJMLOrString (childNodeJML) { if (typeof childNodeJML === 'string') { return doc.createTextNode(childNodeJML); } return jml(...childNodeJML); } */ /** * Creates an XHTML or HTML element (XHTML is preferred, but only in browsers that support); * Any element after element can be omitted, and any subsequent type or types added afterwards * @requires polyfill: Array.isArray * @requires polyfill: Array.prototype.reduce For returning a document fragment * @requires polyfill: Element.prototype.dataset For dataset functionality (Will not work in IE <= 7) * @param {String} el The element to create (by lower-case name) * @param {Object} [atts] Attributes to add with the key as the attribute name and value as the * attribute value; important for IE where the input element's type cannot * be added later after already added to the page * @param {DOMElement[]} [children] The optional children of this element (but raw DOM elements * required to be specified within arrays since * could not otherwise be distinguished from siblings being added) * @param {DOMElement} [parent] The optional parent to which to attach the element (always the last * unless followed by null, in which case it is the second-to-last) * @param {null} [returning] Can use null to indicate an array of elements should be returned * @returns {DOMElement} The newly created (and possibly already appended) element or array of elements */ var jml = function jml() { for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } var elem = doc.createDocumentFragment(); function _checkAtts(atts) { var att = void 0; for (att in atts) { if (!atts.hasOwnProperty(att)) { continue; } var attVal = atts[att]; att = att in ATTR_MAP ? ATTR_MAP[att] : att; if (NULLABLES.includes(att)) { if (attVal != null) { elem[att] = attVal; } continue; } else if (ATTR_DOM.includes(att)) { elem[att] = attVal; continue; } switch (att) { /* Todos: 0. JSON mode to prevent event addition 0. {$xmlDocument: []} // doc.implementation.createDocument 0. Accept array for any attribute with first item as prefix and second as value? 0. {$: ['xhtml', 'div']} for prefixed elements case '$': // Element with prefix? nodes[nodes.length] = elem = doc.createElementNS(attVal[0], attVal[1]); break; */ case '#': { // Document fragment nodes[nodes.length] = _optsOrUndefinedJML(opts, attVal); break; }case '$shadow': { var open = attVal.open, closed = attVal.closed; var content = attVal.content, template = attVal.template; var shadowRoot = elem.attachShadow({ mode: closed || open === false ? 'closed' : 'open' }); if (template) { if (Array.isArray(template)) { if (_getType(template[0]) === 'object') { // Has attributes template = jml.apply(undefined, ['template'].concat(toConsumableArray(template), [doc.body])); } else { // Array is for the children template = jml('template', template, doc.body); } } else if (typeof template === 'string') { template = $(template); } jml(template.content.cloneNode(true), shadowRoot); } else { if (!content) { content = open || closed; } if (content && typeof content !== 'boolean') { if (Array.isArray(content)) { jml({ '#': content }, shadowRoot); } else { jml(content, shadowRoot); } } } break; }case 'is': { // Not yet supported in browsers // Handled during element creation break; }case '$custom': { Object.assign(elem, attVal); break; }case '$define': { var _ret = function () { var localName = elem.localName.toLowerCase(); // Note: customized built-ins sadly not working yet var customizedBuiltIn = !localName.includes('-'); var def = customizedBuiltIn ? elem.getAttribute('is') : localName; if (customElements.get(def)) { return 'break'; } var getConstructor = function getConstructor(cb) { var baseClass = options && options.extends ? doc.createElement(options.extends).constructor : customizedBuiltIn ? doc.createElement(localName).constructor : HTMLElement; return cb ? function (_baseClass) { inherits(_class, _baseClass); function _class() { classCallCheck(this, _class); var _this = possibleConstructorReturn(this, (_class.__proto__ || Object.getPrototypeOf(_class)).call(this)); cb.call(_this); return _this; } return _class; }(baseClass) : function (_baseClass2) { inherits(_class2, _baseClass2); function _class2() { classCallCheck(this, _class2); return possibleConstructorReturn(this, (_class2.__proto__ || Object.getPrototypeOf(_class2)).apply(this, arguments)); } return _class2; }(baseClass); }; var constructor = void 0, options = void 0, prototype = void 0; if (Array.isArray(attVal)) { if (attVal.length <= 2) { var _attVal = slicedToArray(attVal, 2); constructor = _attVal[0]; options = _attVal[1]; if (typeof options === 'string') { options = { extends: options }; } else if (!options.hasOwnProperty('extends')) { prototype = options; } if ((typeof constructor === 'undefined' ? 'undefined' : _typeof(constructor)) === 'object') { prototype = constructor; constructor = getConstructor(); } } else { var _attVal2 = slicedToArray(attVal, 3); constructor = _attVal2[0]; prototype = _attVal2[1]; options = _attVal2[2]; if (typeof options === 'string') { options = { extends: options }; } } } else if (typeof attVal === 'function') { constructor = attVal; } else { prototype = attVal; constructor = getConstructor(); } if (!constructor.toString().startsWith('class')) { constructor = getConstructor(constructor); } if (!options && customizedBuiltIn) { options = { extends: localName }; } if (prototype) { Object.assign(constructor.prototype, prototype); } customElements.define(def, constructor, customizedBuiltIn ? options : undefined); return 'break'; }(); if (_ret === 'break') break; }case '$symbol': { var _attVal3 = slicedToArray(attVal, 2), symbol = _attVal3[0], func = _attVal3[1]; if (typeof func === 'function') { var funcBound = func.bind(elem); if (typeof symbol === 'string') { elem[Symbol.for(symbol)] = funcBound; } else { elem[symbol] = funcBound; } } else { var obj = func; obj.elem = elem; if (typeof symbol === 'string') { elem[Symbol.for(symbol)] = obj; } else { elem[symbol] = obj; } } break; }case '$data': { setMap(attVal); break; }case '$attribute': { // Attribute node var node = attVal.length === 3 ? doc.createAttributeNS(attVal[0], attVal[1]) : doc.createAttribute(attVal[0]); node.value = attVal[attVal.length - 1]; nodes[nodes.length] = node; break; }case '$text': { // Todo: Also allow as jml(['a text node']) (or should that become a fragment)? var _node = doc.createTextNode(attVal); nodes[nodes.length] = _node; break; }case '$document': { // Todo: Conditionally create XML document var _node2 = doc.implementation.createHTMLDocument(); if (attVal.childNodes) { attVal.childNodes.forEach(_childrenToJML(_node2)); // Remove any extra nodes created by createHTMLDocument(). var j = attVal.childNodes.length; while (_node2.childNodes[j]) { var cn = _node2.childNodes[j]; cn.parentNode.removeChild(cn); j++; } } else { if (attVal.$DOCTYPE) { var dt = { $DOCTYPE: attVal.$DOCTYPE }; var doctype = jml(dt); _node2.firstChild.replaceWith(doctype); } var html = _node2.childNodes[1]; var head = html.childNodes[0]; var _body = html.childNodes[1]; if (attVal.title || attVal.head) { var meta = doc.createElement('meta'); meta.setAttribute('charset', 'utf-8'); head.appendChild(meta); } if (attVal.title) { _node2.title = attVal.title; // Appends after meta } if (attVal.head) { attVal.head.forEach(_appendJML(head)); } if (attVal.body) { attVal.body.forEach(_appendJMLOrText(_body)); } } nodes[nodes.length] = _node2; break; }case '$DOCTYPE': { /* // Todo: if (attVal.internalSubset) { node = {}; } else */ var _node3 = void 0; if (attVal.entities || attVal.notations) { _node3 = { name: attVal.name, nodeName: attVal.name, nodeValue: null, nodeType: 10, entities: attVal.entities.map(_jmlSingleArg), notations: attVal.notations.map(_jmlSingleArg), publicId: attVal.publicId, systemId: attVal.systemId // internalSubset: // Todo }; } else { _node3 = doc.implementation.createDocumentType(attVal.name, attVal.publicId || '', attVal.systemId || ''); } nodes[nodes.length] = _node3; break; }case '$ENTITY': { /* // Todo: Should we auto-copy another node's properties/methods (like DocumentType) excluding or changing its non-entity node values? const node = { nodeName: attVal.name, nodeValue: null, publicId: attVal.publicId, systemId: attVal.systemId, notationName: attVal.notationName, nodeType: 6, childNodes: attVal.childNodes.map(_DOMfromJMLOrString) }; */ break; }case '$NOTATION': { // Todo: We could add further properties/methods, but unlikely to be used as is. var _node4 = { nodeName: attVal[0], publicID: attVal[1], systemID: attVal[2], nodeValue: null, nodeType: 12 }; nodes[nodes.length] = _node4; break; }case '$on': { // Events for (var p2 in attVal) { if (attVal.hasOwnProperty(p2)) { var val = attVal[p2]; if (typeof val === 'function') { val = [val, false]; } if (typeof val[0] === 'function') { _addEvent(elem, p2, val[0], val[1]); // element, event name, handler, capturing } } } break; }case 'className':case 'class': if (attVal != null) { elem.className = attVal; } break; case 'dataset': { var _ret2 = function () { // Map can be keyed with hyphenated or camel-cased properties var recurse = function recurse(attVal, startProp) { var prop = ''; var pastInitialProp = startProp !== ''; Object.keys(attVal).forEach(function (key) { var value = attVal[key]; if (pastInitialProp) { prop = startProp + key.replace(hyphenForCamelCase, _upperCase).replace(/^([a-z])/, _upperCase); } else { prop = startProp + key.replace(hyphenForCamelCase, _upperCase); } if (value === null || (typeof value === 'undefined' ? 'undefined' : _typeof(value)) !== 'object') { if (value != null) { elem.dataset[prop] = value; } prop = startProp; return; } recurse(value, prop); }); }; recurse(attVal, ''); return 'break'; // Todo: Disable this by default unless configuration explicitly allows (for security) }(); break; } case 'htmlFor':case 'for': if (elStr === 'label') { if (attVal != null) { elem.htmlFor = attVal; } break; } elem.setAttribute(att, attVal); break; case 'xmlns': // Already handled break; default: if (att.match(/^on/)) { elem[att] = attVal; // _addEvent(elem, att.slice(2), attVal, false); // This worked, but perhaps the user wishes only one event break; } if (att === 'style') { if (attVal == null) { break; } if ((typeof attVal === 'undefined' ? 'undefined' : _typeof(attVal)) === 'object') { for (var _p in attVal) { if (attVal.hasOwnProperty(_p) && attVal[_p] != null) { // Todo: Handle aggregate properties like "border" if (_p === 'float') { elem.style.cssFloat = attVal[_p]; elem.style.styleFloat = attVal[_p]; // Harmless though we could make conditional on older IE instead } else { elem.style[_p.replace(hyphenForCamelCase, _upperCase)] = attVal[_p]; } } } break; } // setAttribute unfortunately erases any existing styles elem.setAttribute(att, attVal); /* // The following reorders which is troublesome for serialization, e.g., as used in our testing if (elem.style.cssText !== undefined) { elem.style.cssText += attVal; } else { // Opera elem.style += attVal; } */ break; } var matchingPlugin = opts && opts.$plugins && opts.$plugins.find(function (p) { return p.name === att; }); if (matchingPlugin) { matchingPlugin.set({ element: elem, attribute: { name: att, value: attVal } }); break; } elem.setAttribute(att, attVal); break; } } } var nodes = []; var elStr = void 0; var opts = void 0; var isRoot = false; if (_getType(args[0]) === 'object' && Object.keys(args[0]).some(function (key) { return possibleOptions.includes(key); })) { opts = args[0]; if (opts.state !== 'child') { isRoot = true; opts.state = 'child'; } if (opts.$map && !opts.$map.root && opts.$map.root !== false) { opts.$map = { root: opts.$map }; } if ('$plugins' in opts) { if (!Array.isArray(opts.$plugins)) { throw new Error('$plugins must be an array'); } opts.$plugins.forEach(function (pluginObj) { if (!pluginObj) { throw new TypeError('Plugin must be an object'); } if (!pluginObj.name || !pluginObj.name.startsWith('$_')) { throw new TypeError('Plugin object name must be present and begin with `$_`'); } if (typeof pluginObj.set !== 'function') { throw new TypeError('Plugin object must have a `set` method'); } }); } args = args.slice(1); } var argc = args.length; var defaultMap = opts && opts.$map && opts.$map.root; var setMap = function setMap(dataVal) { var map = void 0, obj = void 0; // Boolean indicating use of default map and object if (dataVal === true) { var _defaultMap = slicedToArray(defaultMap, 2); map = _defaultMap[0]; obj = _defaultMap[1]; } else if (Array.isArray(dataVal)) { // Array of strings mapping to default if (typeof dataVal[0] === 'string') { dataVal.forEach(function (dVal) { setMap(opts.$map[dVal]); }); // Array of Map and non-map data object } else { map = dataVal[0] || defaultMap[0]; obj = dataVal[1] || defaultMap[1]; } // Map } else if (/^\[object (?:Weak)?Map\]$/.test([].toString.call(dataVal))) { map = dataVal; obj = defaultMap[1]; // Non-map data object } else { map = defaultMap[0]; obj = dataVal; } map.set(elem, obj); }; for (var i = 0; i < argc; i++) { var arg = args[i]; switch (_getType(arg)) { case 'null': // null always indicates a place-holder (only needed for last argument if want array returned) if (i === argc - 1) { _applyAnyStylesheet(nodes[0]); // We have to execute any stylesheets even if not appending or otherwise IE will never apply them // Todo: Fix to allow application of stylesheets of style tags within fragments? return nodes.length <= 1 ? nodes[0] : nodes.reduce(_fragReducer, doc.createDocumentFragment()); // nodes; } break; case 'string': // Strings indicate elements switch (arg) { case '!': nodes[nodes.length] = doc.createComment(args[++i]); break; case '?': arg = args[++i]; var procValue = args[++i]; var val = procValue; if ((typeof val === 'undefined' ? 'undefined' : _typeof(val)) === 'object') { procValue = []; for (var p in val) { if (val.hasOwnProperty(p)) { procValue.push(p + '=' + '"' + // https://www.w3.org/TR/xml-stylesheet/#NT-PseudoAttValue val[p].replace(/"/g, '&quot;') + '"'); } } procValue = procValue.join(' '); } // Firefox allows instructions with ">" in this method, but not if placed directly! try { nodes[nodes.length] = doc.createProcessingInstruction(arg, procValue); } catch (e) { // Getting NotSupportedError in IE, so we try to imitate a processing instruction with a comment // innerHTML didn't work // var elContainer = doc.createElement('div'); // elContainer.textContent = '<?' + doc.createTextNode(arg + ' ' + procValue).nodeValue + '?>'; // nodes[nodes.length] = elContainer.textContent; // Todo: any other way to resolve? Just use XML? nodes[nodes.length] = doc.createComment('?' + arg + ' ' + procValue + '?'); } break; // Browsers don't support doc.createEntityReference, so we just use this as a convenience case '&': nodes[nodes.length] = _createSafeReference('entity', '', args[++i]); break; case '#': // // Decimal character reference - ['#', '01234'] // &#01234; // probably easier to use JavaScript Unicode escapes nodes[nodes.length] = _createSafeReference('decimal', arg, String(args[++i])); break; case '#x': // Hex character reference - ['#x', '123a'] // &#x123a; // probably easier to use JavaScript Unicode escapes nodes[nodes.length] = _createSafeReference('hexadecimal', arg, args[++i]); break; case '![': // '![', ['escaped <&> text'] // <![CDATA[escaped <&> text]]> // CDATA valid in XML only, so we'll just treat as text for mutual compatibility // Todo: config (or detection via some kind of doc.documentType property?) of whether in XML try { nodes[nodes.length] = doc.createCDATASection(args[++i]); } catch (e2) { nodes[nodes.length] = doc.createTextNode(args[i]); // i already incremented } break; case '': nodes[nodes.length] = doc.createDocumentFragment(); break; default: { // An element elStr = arg; var _atts = args[i + 1]; // Todo: Fix this to depend on XML/config, not availability of methods if (_getType(_atts) === 'object' && _atts.is) { var is = _atts.is; if (doc.createElementNS) { elem = doc.createElementNS(NS_HTML, elStr, { is: is }); } else { elem = doc.createElement(elStr, { is: is }); } } else { if (doc.createElementNS) { elem = doc.createElementNS(NS_HTML, elStr); } else { elem = doc.createElement(elStr); } } nodes[nodes.length] = elem; // Add to parent break; } } break; case 'object': // Non-DOM-element objects indicate attribute-value pairs var atts = arg; if (atts.xmlns !== undefined) { // We handle this here, as otherwise may lose events, etc. // As namespace of element already set as XHTML, we need to change the namespace // elem.setAttribute('xmlns', atts.xmlns); // Doesn't work // Can't set namespaceURI dynamically, renameNode() is not supported, and setAttribute() doesn't work to change the namespace, so we resort to this hack var replacer = void 0; if (_typeof(atts.xmlns) === 'object') { replacer = _replaceDefiner(atts.xmlns); } else { replacer = ' xmlns="' + atts.xmlns + '"'; } // try { // Also fix DOMParser to work with text/html elem = nodes[nodes.length - 1] = new DOMParser().parseFromString(new XmlSerializer().serializeToString(elem) // Mozilla adds XHTML namespace .replace(' xmlns="' + NS_HTML + '"', replacer), 'application/xml').documentElement; // }catch(e) {alert(elem.outerHTML);throw e;} } var orderedArr = atts.$a ? atts.$a.map(_copyOrderedAtts) : [atts]; orderedArr.forEach(_checkAtts); break; case 'fragment': case 'element': /* 1) Last element always the parent (put null if don't want parent and want to return array) unless only atts and children (no other elements) 2) Individual elements (DOM elements or sequences of string[/object/array]) get added to parent first-in, first-added */ if (i === 0) { // Allow wrapping of element elem = arg; } if (i === argc - 1 || i === argc - 2 && args[i + 1] === null) { // parent var elsl = nodes.length; for (var k = 0; k < elsl; k++) { _appendNode(arg, nodes[k]); } // Todo: Apply stylesheets if any style tags were added elsewhere besides the first element? _applyAnyStylesheet(nodes[0]); // We have to execute any stylesheets even if not appending or otherwise IE will never apply them } else { nodes[nodes.length] = arg; } break; case 'array': // Arrays or arrays of arrays indicate child nodes var child = arg; var cl = child.length; for (var j = 0; j < cl; j++) { // Go through children array container to handle elements var childContent = child[j]; var childContentType = typeof childContent === 'undefined' ? 'undefined' : _typeof(childContent); if (childContent === undefined) { throw String('Parent array:' + JSON.stringify(args) + '; child: ' + child + '; index:' + j); } switch (childContentType) { // Todo: determine whether null or function should have special handling or be converted to text case 'string':case 'number':case 'boolean': _appendNode(elem, doc.createTextNode(childContent)); break; default: if (Array.isArray(childContent)) { // Arrays representing child elements _appendNode(elem, _optsOrUndefinedJML.apply(undefined, [opts].concat(toConsumableArray(childContent)))); } else if (childContent['#']) { // Fragment _appendNode(elem, _optsOrUndefinedJML(opts, childContent['#'])); } else { // Single DOM element children _appendNode(elem, childContent); } break; } } break; } } var ret = nodes[0] || elem; if (opts && isRoot && opts.$map && opts.$map.root) { setMap(true); } return ret; }; /** * Converts a DOM object or a string of HTML into a Jamilih object (or string) * @param {string|HTMLElement} [dom=document.documentElement] Defaults to converting the current document. * @param {object} [config={stringOutput:false}] Configuration object * @param {boolean} [config.stringOutput=false] Whether to output the Jamilih object as a string. * @returns {array|string} Array containing the elements which represent a Jamilih object, or, if `stringOutput` is true, it will be the stringified version of such an object */ jml.toJML = function (dom, config) { config = config || { stringOutput: false }; if (typeof dom === 'string') { dom = new DOMParser().parseFromString(dom, 'text/html'); // todo: Give option for XML once implemented and change JSDoc to allow for Element } var ret = []; var parent = ret; var parentIdx = 0; function invalidStateError() { // These are probably only necessary if working with text/html function DOMException() { return this; } { // INVALID_STATE_ERR per section 9.3 XHTML 5: http://www.w3.org/TR/html5/the-xhtml-syntax.html // Since we can't instantiate without this (at least in Mozilla), this mimicks at least (good idea?) var e = new DOMException(); e.code = 11; throw e; } } function addExternalID(obj, node) { if (node.systemId.includes('"') && node.systemId.includes("'")) { invalidStateError(); } var publicId = node.publicId; var systemId = node.systemId; if (systemId) { obj.systemId = systemId; } if (publicId) { obj.publicId = publicId; } } function set$$1(val) { parent[parentIdx] = val; parentIdx++; } function setChildren() { set$$1([]); parent = parent[parentIdx - 1]; parentIdx = 0; } function setObj(prop1, prop2) { parent = parent[parentIdx - 1][prop1]; parentIdx = 0; if (prop2) { parent = parent[prop2]; } } function parseDOM(node, namespaces) { // namespaces = clone(namespaces) || {}; // Ensure we're working with a copy, so different levels in the hierarchy can treat it differently /* if ((node.prefix && node.prefix.includes(':')) || (node.localName && node.localName.includes(':'))) { invalidStateError(); } */ var type = 'nodeType' in node ? node.nodeType : null; namespaces = Object.assign({}, namespaces); var xmlChars = /([\u0009\u000A\u000D\u0020-\uD7FF\uE000-\uFFFD]|[\uD800-\uDBFF][\uDC00-\uDFFF])*$/; // eslint-disable-line no-control-regex if ([2, 3, 4, 7, 8].includes(type) && !xmlChars.test(node.nodeValue)) { invalidStateError(); } var children = void 0, start = void 0, tmpParent = void 0, tmpParentIdx = void 0; function setTemp() { tmpParent = parent; tmpParentIdx = parentIdx; } function resetTemp() { parent = tmpParent; parentIdx = tmpParentIdx; parentIdx++; // Increment index in parent container of this element } switch (type) { case 1: // ELEMENT setTemp(); var nodeName = node.nodeName.toLowerCase(); // Todo: for XML, should not lower-case setChildren(); // Build child array since elements are, except at the top level, encapsulated in arrays set$$1(nodeName); start = {}; var hasNamespaceDeclaration = false; if (namespaces[node.prefix || ''] !== node.namespaceURI) { namespaces[node.prefix || ''] = node.namespaceURI; if (node.prefix) { start['xmlns:' + node.prefix] = node.namespaceURI; } else if (node.namespaceURI) { start.xmlns = node.namespaceURI; } hasNamespaceDeclaration = true; } if (node.attributes.length) { set$$1(Array.from(node.attributes).reduce(function (obj, att) { obj[att.name] = att.value; // Attr.nodeName and Attr.nodeValue are deprecated as of DOM4 as Attr no longer inherits from Node, so we can safely use name and value return obj; }, start)); } else if (hasNamespaceDeclaration) { set$$1(start); } children = node.childNodes; if (children.length) { setChildren(); // Element children array container Array.from(children).forEach(function (childNode) { parseDOM(childNode, namespaces); }); } resetTemp(); break; case undefined: // Treat as attribute node until this is fixed: https://github.com/tmpvar/jsdom/issues/1641 / https://github.com/tmpvar/jsdom/pull/1822 case 2: // ATTRIBUTE (should only get here if passing in an attribute node) set$$1({ $attribute: [node.namespaceURI, node.name, node.value] }); break; case 3: // TEXT if (config.stripWhitespace && /^\s+$/.test(node.nodeValue)) { return; } set$$1(node.nodeValue); break; case 4: // CDATA if (node.nodeValue.includes(']]' + '>')) { invalidStateError(); } set$$1(['![', node.nodeValue]); break; case 5: // ENTITY REFERENCE (probably not used in browsers since already resolved) set$$1(['&', node.nodeName]); break; case 6: // ENTITY (would need to pass in directly) setTemp(); start = {}; if (node.xmlEncoding || node.xmlVersion) { // an external entity file? start.$ENTITY = { name: node.nodeName, version: node.xmlVersion, encoding: node.xmlEncoding }; } else { start.$ENTITY = { name: node.nodeName }; if (node.publicId || node.systemId) { // External Entity? addExternalID(start.$ENTITY, node); if (node.notationName) { start.$ENTITY.NDATA = node.notationName; } } } set$$1(start); children = node.childNodes; if (children.length) { start.$ENTITY.childNodes = []; // Set position to $ENTITY's childNodes array children setObj('$ENTITY', 'childNodes'); Array.from(children).forEach(function (childNode) { parseDOM(childNode, namespaces); }); } resetTemp(); break; case 7: // PROCESSING INSTRUCTION if (/^xml$/i.test(node.target)) { invalidStateError(); } if (node.target.includes('?>')) { invalidStateError(); } if (node.target.includes(':')) { invalidStateError(); } if (node.data.includes('?>')) { invalidStateError(); } set$$1(['?', node.target, node.data]); // Todo: Could give option to attempt to convert value back into object if has pseudo-attributes break; case 8: // COMMENT if (node.nodeValue.includes('--') || node.nodeValue.length && node.nodeValue.lastIndexOf('-') === node.nodeValue.length - 1) { invalidStateError(); } set$$1(['!', node.nodeValue]); break; case 9: // DOCUMENT setTemp(); var docObj = { $document: { childNodes: [] } }; if (config.xmlDeclaration) { docObj.$document.xmlDeclaration = { version: doc.xmlVersion, encoding: doc.xmlEncoding, standAlone: doc.xmlStandalone }; } set$$1(docObj); // doc.implementation.createHTMLDocument // Set position to fragment's array children setObj('$document', 'childNodes'); children = node.childNodes; if (!children.length) { invalidStateError(); } // set({$xmlDocument: []}); // doc.implementation.createDocument // Todo: use this conditionally Array.from(children).forEach(function (childNode) { // Can't just do documentElement as there may be doctype, comments, etc. // No need for setChildren, as we have already built the container array parseDOM(childNode, namespaces); }); resetTemp(); break; case 10: // DOCUMENT TYPE setTemp(); // Can create directly by doc.implementation.createDocumentType start = { $DOCTYPE: { name: node.name } }; if (node.internalSubset) { start.internalSubset = node.internalSubset; } var pubIdChar = /^(\u0020|\u000D|\u000A|[a-zA-Z0-9]|[-'()+,./:=?;!*#@$_%])*$/; // eslint-disable-line no-control-regex if (!pubIdChar.test(node.publicId)) { invalidStateError(); } addExternalID(start.$DOCTYPE, node); // Fit in internal subset along with entities?: probably don't need as these would only differ if from DTD, and we're not rebuilding the DTD set$$1(start); // Auto-generate the internalSubset instead? Avoid entities/notations in favor of array to preserve order? var entities = node.entities; // Currently deprecated if (entities && entities.length) { start.$DOCTYPE.entities = []; setObj('$DOCTYPE', 'entities'); Array.from(entities).forEach(function (entity) { parseDOM(entity, namespaces); }); // Reset for notations parent = tmpParent; parentIdx = tmpParentIdx + 1; } var notations = node.notations; // Currently deprecated if (notations && notations.length) { start.$DOCTYPE.notations = []; setObj('$DOCTYPE', 'notations'); Array.from(notations).forEach(function (notation) { parseDOM(notation, namespaces); }); } resetTemp(); break; case 11: // DOCUMENT FRAGMENT setTemp(); set$$1({ '#': [] }); // Set position to fragment's array children setObj('#'); children = node.childNodes; Array.from(children).forEach(function (childNode) { // No need for setChildren, as we have already built the container array parseDOM(childNode, namespaces); }); resetTemp(); break; case 12: // NOTATION start = { $NOTATION: { name: node.nodeName } }; addExternalID(start.$NOTATION, node); set$$1(start); break; default: throw new TypeError('Not an XML type'); } } parseDOM(dom, {}); if (config.stringOutput) { return JSON.stringify(ret[0]); } return ret[0]; }; jml.toJMLString = function (dom, config) { return jml.toJML(dom, Object.assign(config || {}, { stringOutput: true })); }; jml.toDOM = function () { // Alias for jml() return jml.apply(undefined, arguments); }; jml.toHTML = function () { // Todo: Replace this with version of jml() that directly builds a string var ret = jml.apply(undefined, arguments); // Todo: deal with serialization of properties like 'selected', 'checked', 'value', 'defaultValue', 'for', 'dataset', 'on*', 'style'! (i.e., need to build a string ourselves) return ret.outerHTML; }; jml.toDOMString = function () { // Alias for jml.toHTML for parity with jml.toJMLString return jml.toHTML.apply(jml, arguments); }; jml.toXML = function () { var ret = jml.apply(undefined, arguments); return new XmlSerializer().serializeToString(ret); }; jml.toXMLDOMString = function () { // Alias for jml.toXML for parity with jml.toJMLString return jml.toXML.apply(jml, arguments); }; var JamilihMap = function (_Map) { inherits(JamilihMap, _Map); function JamilihMap() { classCallCheck(this, JamilihMap); return possibleConstructorReturn(this, (JamilihMap.__proto__ || Object.getPrototypeOf(JamilihMap)).apply(this, arguments)); } createClass(JamilihMap, [{ key: 'get', value: function get$$1(elem) { elem = typeof elem === 'string' ? $(elem) : elem; return get(JamilihMap.prototype.__proto__ || Object.getPrototypeOf(JamilihMap.prototype), 'get', this).call(this, elem); } }, { key: 'set', value: function set$$1(elem, value) { elem = typeof elem === 'string' ? $(elem) : elem; return get(JamilihMap.prototype.__proto__ || Object.getPrototypeOf(JamilihMap.prototype), 'set', this).call(this, elem, value); } }, { key: 'invoke', value: function invoke(elem, methodName) { var _get; elem = typeof elem === 'string' ? $(elem) : elem; for (var _len3 = arguments.length, args = Array(_len3 > 2 ? _len3 - 2 : 0), _key3 = 2; _key3 < _len3; _key3++) { args[_key3 - 2] = arguments[_key3]; } return (_get = this.get(elem))[methodName].apply(_get, [elem].concat(args)); } }]); return JamilihMap; }(Map); var JamilihWeakMap = function (_WeakMap) { inherits(JamilihWeakMap, _WeakMap); function JamilihWeakMap() { classCallCheck(this, JamilihWeakMap); return possibleConstructorReturn(this, (JamilihWeakMap.__proto__ || Object.getPrototypeOf(JamilihWeakMap)).apply(this, arguments)); } createClass(JamilihWeakMap, [{ key: 'get', value: function get$$1(elem) { elem = typeof elem === 'string' ? $(elem) : elem; return get(JamilihWeakMap.prototype.__proto__ || Object.getPrototypeOf(JamilihWeakMap.prototype), 'get', this).call(this, elem); } }, { key: 'set', value: function set$$1(elem, value) { elem = typeof elem === 'string' ? $(elem) : elem; return get(JamilihWeakMap.prototype.__proto__ || Object.getPrototypeOf(JamilihWeakMap.prototype), 'set', this).call(this, elem, value); } }, { key: 'invoke', value: function invoke(elem, methodName) { var _get2; elem = typeof elem === 'string' ? $(elem) : elem; for (var _len4 = arguments.length, args = Array(_len4 > 2 ? _len4 - 2 : 0), _key4 = 2; _key4 < _len4; _key4++) { args[_key4 - 2] = arguments[_key4]; } return (_get2 = this.get(elem))[methodName].apply(_get2, [elem].concat(args)); } }]); return JamilihWeakMap; }(WeakMap); jml.Map = JamilihMap; jml.WeakMap = JamilihWeakMap; jml.weak = function (obj) { var map = new JamilihWeakMap(); for (var _len5 = arguments.length, args = Array(_len5 > 1 ? _len5 - 1 : 0), _key5 = 1; _key5 < _len5; _key5++) { args[_key5 - 1] = arguments[_key5]; } var elem = jml.apply(undefined, [{ $map: [map, obj] }].concat(args)); return [map, elem]; }; jml.strong = function (obj) { var map = new JamilihMap(); for (var _len6 = arguments.length, args = Array(_len6 > 1 ? _len6 - 1 : 0), _key6 = 1; _key6 < _len6; _key6++) { args[_key6 - 1] = arguments[_key6]; } var elem = jml.apply(undefined, [{ $map: [map, obj] }].concat(args)); return [map, elem]; }; jml.symbol = jml.sym = jml.for = function (elem, sym) { elem = typeof elem === 'string' ? $(elem) : elem; return elem[(typeof sym === 'undefined' ? 'undefined' : _typeof(sym)) === 'symbol' ? sym : Symbol.for(sym)]; }; jml.command = function (elem, symOrMap, methodName) { elem = typeof elem === 'string' ? $(elem) : elem; var func = void 0; for (var _len7 = arguments.length, args = Array(_len7 > 3 ? _len7 - 3 : 0), _key7 = 3; _key7 < _len7; _key7++) { args[_key7 - 3] = arguments[_key7]; } if (['symbol', 'string'].includes(typeof symOrMap === 'undefined' ? 'undefined' : _typeof(symOrMap))) { var _func; func = jml.sym(elem, symOrMap); if (typeof func === 'function') { return func.apply(undefined, [methodName].concat(args)); // Already has `this` bound to `elem` } return (_func = func)[methodName].apply(_func, args); } else { var _func3; func = symOrMap.get(elem); if (typeof func === 'function') { var _func2; return (_func2 = func).call.apply(_func2, [elem, methodName].concat(args)); } return (_func3 = func)[methodName].apply(_func3, [elem].concat(args)); } // return func[methodName].call(elem, ...args); }; jml.setWindow = function (wind) { win = wind; }; jml.setDocument = function (docum) { doc = docum; if (docum && docum.body) { body = docum.body; } }; jml.setXMLSerializer = function (xmls) { XmlSerializer = xmls; }; jml.getWindow = function () { return win; }; jml.getDocument = function () { return doc; }; jml.getXMLSerializer = function () { return XmlSerializer; }; var body = doc && doc.body; var nbsp = '\xA0'; // Very commonly needed in templates export default jml; export { jml, $, $$, nbsp, body };
brettz9/open-isbn
options/jml.js
JavaScript
mit
66,746
export default from './navigation.component';
sunstorymvp/playground
src/core/navigation/index.js
JavaScript
mit
46
(function(){ 'use strict'; angular .module('app') .config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) { $stateProvider .state('edit-profile', { url:'/edit-profile/:id', templateUrl: 'edit-profile-state/edit-profile.view.html', controller: 'EditProfileController', controllerAs: 'vm', permissions: { only: 'isAuthorized' } }) }]) })();
komix/dreamtame-ui
app/edit-profile-state/edit-profile.route.js
JavaScript
mit
597
'use strict'; angular.module('<%= name %>') .service('<%= serviceName %>', function ($q, $http) { // A private cache key. var cache = {}; // Update broadcast name. var broadcastUpdateEventName = '<%= serviceName %>Change'; /** * Return the promise with the collection, from cache or the server. * * @returns {*} */ this.get = function() { if (cache) { return $q.when(cache.data); } return getDataFromBackend(); }; /** * Return promise with the collection from the server. * * @returns {$q.promise} */ function getDataFromBackend() { var deferred = $q.defer(); var url = ''; $http({ method: 'GET', url: url, params: params, transformResponse: prepareDataForLeafletMarkers }).success(function(response) { setCache(response); deferred.resolve(response); }); return deferred.promise; } /** * Save cache, and broadcast an event, because data changed. * * @param data * Object with the data to cache. */ var setCache = function(data) { // Cache data by company ID. cache = { data: data, timestamp: new Date() }; // Clear cache in 60 seconds. $timeout(function() { if (cache.data && cache.data[cacheId]) { cache.data[cacheId] = null; } }, 60000); // Broadcast a change event. $rootScope.$broadcast(broadcastUpdateEventName); }; /** * Convert the response to a collection. * * @param response * The response from the $http. * * @returns {*} * The Collection requested. */ function prepareDataForLeafletMarkers(response) { var collection; // Convert response serialized to an object. collection = angular.fromJson(reponse).data; return collection; } });
ceoaliongroo/generator-angular-element
app/templates/app/basic/service.js
JavaScript
mit
1,961
'use strict'; angular.module('myApp.contact', ['ngRoute']) .config(['$routeProvider', function($routeProvider) { $routeProvider.when('/contact', { templateUrl: 'app/view/contact.html', controller: 'contactCtrl' }); }]) .controller('contactCtrl',['$scope','$http', function($scope, $http) { $scope.result = 'hidden' $scope.resultMessage; $scope.formData; //formData is an object holding the name, email, subject, and message $scope.submitButtonDisabled = false; $scope.submitted = false; //used so that form errors are shown only after the form has been submitted $scope.submit = function(contactform) { $scope.submitted = true; $scope.submitButtonDisabled = true; if (contactform.$valid) { $http({ method : 'POST', url : 'http://localhost:8000/contact-form.php', data : $.param($scope.formData), //param method from jQuery headers : { 'Content-Type': 'application/x-www-form-urlencoded' } //set the headers so angular passing info as form data (not request payload) }).success(function(data){ console.log(data); if (data) { //success comes from the return json object $scope.submitButtonDisabled = true; $scope.resultMessage = data; $scope.result='bg-success'; } else { $scope.submitButtonDisabled = false; $scope.resultMessage = data; $scope.result='bg-danger'; } }); } else { $scope.submitButtonDisabled = false; $scope.resultMessage = 'Failed <img src="http://www.chaosm.net/blog/wp-includes/images/smilies/icon_sad.gif" alt=":(" class="wp-smiley"> Please fill out all the fields.'; $scope.result='bg-danger'; } }; var myCenter=new google.maps.LatLng(42.656021, -71.330044); var mapProp = { center:myCenter, zoom:5, mapTypeId:google.maps.MapTypeId.ROADMAP }; var map=new google.maps.Map(document.getElementById("map"),mapProp); var marker=new google.maps.Marker({ position:myCenter, }); marker.setMap(map); var infowindow = new google.maps.InfoWindow({ content:"203 University avenue Lowell, MA, 01854" }); google.maps.event.addListener(marker, 'click', function() { infowindow.open(map,marker); }); google.maps.event.addDomListener(window, 'load'); }]);
ananddharne/ananddharne.github.io
app/assets/javascripts/crontollers/contact.js
JavaScript
mit
2,961
'use strict'; angular.module('f1feeder.version.version-directive', []) .directive('appVersion', ['version', function(version) { return function(scope, elm, attrs) { elm.text(version); }; }]);
jkotrba/f1feeder
app/components/version/version-directive.js
JavaScript
mit
202
'use strict'; /** * Module Dependencies */ var gulp = require('gulp'); var sass = require('gulp-sass'); var app = require('./app.js'); /** * Config */ var PUBLIC = __dirname + '/public'; var ASSETS = PUBLIC + '/assets'; /** * Compiling */ gulp.task('sass', function(){ gulp.src(ASSETS + '/styles/sass/app.scss') .pipe(sass()) .pipe(gulp.dest(ASSETS + '/styles/css')); }); // lol gulp.task('piss', ['sass'], function() { app.init(); }); // Default gulp.task('default', ['piss']);
dictions/post
gulpfile.js
JavaScript
mit
505
import {waitFor} from './wait-for' const isRemoved = result => !result || (Array.isArray(result) && !result.length) // Check if the element is not present. // As the name implies, waitForElementToBeRemoved should check `present` --> `removed` function initialCheck(elements) { if (isRemoved(elements)) { throw new Error( 'The element(s) given to waitForElementToBeRemoved are already removed. waitForElementToBeRemoved requires that the element(s) exist(s) before waiting for removal.', ) } } async function waitForElementToBeRemoved(callback, options) { // created here so we get a nice stacktrace const timeoutError = new Error('Timed out in waitForElementToBeRemoved.') if (typeof callback !== 'function') { initialCheck(callback) const elements = Array.isArray(callback) ? callback : [callback] const getRemainingElements = elements.map(element => { let parent = element.parentElement if (parent === null) return () => null while (parent.parentElement) parent = parent.parentElement return () => (parent.contains(element) ? element : null) }) callback = () => getRemainingElements.map(c => c()).filter(Boolean) } initialCheck(callback()) return waitFor(() => { let result try { result = callback() } catch (error) { if (error.name === 'TestingLibraryElementError') { return undefined } throw error } if (!isRemoved(result)) { throw timeoutError } return undefined }, options) } export {waitForElementToBeRemoved} /* eslint require-await: "off" */
testing-library/dom-testing-library
src/wait-for-element-to-be-removed.js
JavaScript
mit
1,602
// @flow import React, { Component, PropTypes } from "react" import { connect } from "react-redux" import TextField from 'material-ui/TextField' import { CreateAuctionButton } from "../../molecules/" import * as AuctionActions from "../../../actions/auction" import { Button } from "../../atoms/" import styles from "./styles.css" export class CreateAuctionBox extends Component { constructor(props) { super(props) this.state = { name: "", minimum: "", message: "", image: "", auctionMsg: props.auctionMsg, } } change = (event) => { if ("id" in event.target && "value" in event.target) { console.log(event.target.id) console.log(event.target.value) this.setState({ [event.target.id]: event.target.value }) } } data = () => { const { name, minimum, message, image } = this.state const base = { name : name, minimum : minimum, message : message, image : image } if (firebase.auth().currentUser) { return Object.assign({}, base, { usrID : firebase.auth().currentUser.uid }) } return base } action = () => { const { name, minimum, message, image } = this.state if (name && minimum && message && image && minimum > 0) { const { dispatch } = this.props console.log(this.data()) dispatch(AuctionActions.queryCreateAuction(JSON.stringify(this.data()))) } } componentWillReceiveProps(nextProps) { if(JSON.stringify(this.state.auctionMsg) !== JSON.stringify(nextProps.auctionMsg)) { this.setState({ auctionMsg: nextProps.auctionMsg }) } } render() { const { auctionMsg } = this.state return ( <div className={ styles.root }> <h3>Create Bid</h3> <div>Status: <span style={{ color : (auctionMsg.status.toLowerCase() !== 'success' ? "red" : "green") }}>{ auctionMsg.status }</span></div> <TextField id="name" value={ this.state.name } floatingLabelText="Domain" onChange={this.change}/><br /> <TextField id="minimum" type="number" value={ this.state.minimum } floatingLabelText="Minimum" onChange={this.change}/><br /> <TextField id="message" value={ this.state.message } floatingLabelText="Message" onChange={this.change}/><br /> <TextField id="image" value={ this.state.image } floatingLabelText="Image" style={{ "marginBottom" : "1em"}} onChange={this.change}/><br /> <Button onClick={ this.action }> Create Auction </Button> </div> ) } } CreateAuctionBox.propTypes = { auctionMsg: PropTypes.object.isRequired, dispatch: PropTypes.func.isRequired, } function mapStateToProps(state) { const { auctionMsg } = state.auction return { auctionMsg, } } export default connect(mapStateToProps)(CreateAuctionBox)
BradZzz/occasio
src/components/molecules/CreateAuctionBox/CreateAuctionBox.js
JavaScript
mit
2,780
"use strict"; var expect = require('chai').expect , protolib = require(__dirname + '/../') ; describe('protolib', function() { describe('clone', function() { it('should create a clone of the given object', function() { var object = { name: 'Philip' , hello: function() { return 'Hello, my name is ' + this.name; } , date: new Date() , arr: [1, {foo: 'bar'}] }; var clone_object = protolib.clone(object); expect(clone_object).to.have.property('name', 'Philip'); expect(clone_object.hello()).to.equal('Hello, my name is Philip'); expect(clone_object.date.getMonth()).to.equal(new Date().getMonth()); expect(clone_object).to.have.deep.property('arr[0]', 1); expect(clone_object).to.have.deep.property('arr[1].foo', 'bar'); }); it('should throw an error if input is not an object or array', function() { expect(protolib.clone).to.throw('Cannot clone!'); }); }); describe('inherit', function() { it('should set the prototype of an object to the given value', function() { var proto = {foo: 'bar'}; var object = protolib.inherit(proto); expect(object).to.have.property('foo', 'bar'); proto.foo = 'baz'; expect(object).to.have.property('foo', 'baz'); }); }); describe('mixin', function() { it('should add the prototype properties to the given object', function() { var proto = {type: 'list', values: [1, 2, 3]}; var object = {readonly: true}; protolib.mixin(object, proto); expect(object).to.have.property('readonly', true); expect(object).to.have.property('type', 'list'); expect(object).to.have.deep.property('values[0]', 1); expect(object).to.have.deep.property('values[1]', 2); expect(object).to.have.deep.property('values[2]', 3); }); it('should overwrite any existing properties with duplicate names', function() { var proto = {type: 'list', values: [1, 2, 3]}; var object = {type: 'none'}; protolib.mixin(object, proto); expect(object).to.have.property('type', 'list'); expect(object).to.have.deep.property('values[0]', 1); expect(object).to.have.deep.property('values[1]', 2); expect(object).to.have.deep.property('values[2]', 3); }); }); });
Elzair/protolib
test/test.js
JavaScript
mit
2,315
console.log('load version 2.0.0');
soulteary/xSwitch.js
demo/assets/test-2.0.0.js
JavaScript
mit
34
/*! * Copyright 2014 Google Inc. 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. */ /*! * @module bigquery/dataset */ 'use strict'; var common = require('@google-cloud/common'); var extend = require('extend'); var is = require('is'); var util = require('util'); /** * @type {module:bigquery/table} * @private */ var Table = require('./table.js'); /*! Developer Documentation * * @param {module:bigquery} bigQuery - BigQuery instance. * @param {string} id - The ID of the Dataset. */ /** * Interact with your BigQuery dataset. Create a Dataset instance with * {module:bigquery#createDataset} or {module:bigquery#dataset}. * * @alias module:bigquery/dataset * @constructor * * @example * var dataset = bigquery.dataset('institutions'); */ function Dataset(bigQuery, id) { var methods = { /** * Create a dataset. * * @example * dataset.create(function(err, dataset, apiResponse) { * if (!err) { * // The dataset was created successfully. * } * }); * * //- * // If the callback is omitted, we'll return a Promise. * //- * dataset.create().then(function(data) { * var dataset = data[0]; * var apiResponse = data[1]; * }); */ create: true, /** * Check if the dataset exists. * * @param {function} callback - The callback function. * @param {?error} callback.err - An error returned while making this * request. * @param {boolean} callback.exists - Whether the dataset exists or not. * * @example * dataset.exists(function(err, exists) {}); * * //- * // If the callback is omitted, we'll return a Promise. * //- * dataset.exists().then(function(data) { * var exists = data[0]; * }); */ exists: true, /** * Get a dataset if it exists. * * You may optionally use this to "get or create" an object by providing an * object with `autoCreate` set to `true`. Any extra configuration that is * normally required for the `create` method must be contained within this * object as well. * * @param {options=} options - Configuration object. * @param {boolean} options.autoCreate - Automatically create the object if * it does not exist. Default: `false` * * @example * dataset.get(function(err, dataset, apiResponse) { * if (!err) { * // `dataset.metadata` has been populated. * } * }); * * //- * // If the callback is omitted, we'll return a Promise. * //- * dataset.get().then(function(data) { * var dataset = data[0]; * var apiResponse = data[1]; * }); */ get: true, /** * Get the metadata for the Dataset. * * @resource [Datasets: get API Documentation]{@link https://cloud.google.com/bigquery/docs/reference/v2/datasets/get} * * @param {function} callback - The callback function. * @param {?error} callback.err - An error returned while making this * request. * @param {object} callback.metadata - The dataset's metadata. * @param {object} callback.apiResponse - The full API response. * * @example * dataset.getMetadata(function(err, metadata, apiResponse) {}); * * //- * // If the callback is omitted, we'll return a Promise. * //- * dataset.getMetadata().then(function(data) { * var metadata = data[0]; * var apiResponse = data[1]; * }); */ getMetadata: true, /** * Sets the metadata of the Dataset object. * * @resource [Datasets: patch API Documentation]{@link https://cloud.google.com/bigquery/docs/reference/v2/datasets/patch} * * @param {object} metadata - Metadata to save on the Dataset. * @param {function} callback - The callback function. * @param {?error} callback.err - An error returned while making this * request. * @param {object} callback.apiResponse - The full API response. * * @example * var metadata = { * description: 'Info for every institution in the 2013 IPEDS universe' * }; * * dataset.setMetadata(metadata, function(err, apiResponse) {}); * * //- * // If the callback is omitted, we'll return a Promise. * //- * dataset.setMetadata(metadata).then(function(data) { * var apiResponse = data[0]; * }); */ setMetadata: true }; common.ServiceObject.call(this, { parent: bigQuery, baseUrl: '/datasets', id: id, createMethod: bigQuery.createDataset.bind(bigQuery), methods: methods }); this.bigQuery = bigQuery; } util.inherits(Dataset, common.ServiceObject); /** * Run a query scoped to your dataset as a readable object stream. * * See {module:bigquery#createQueryStream} for full documentation of this * method. */ Dataset.prototype.createQueryStream = function(options) { if (is.string(options)) { options = { query: options }; } options = extend(true, {}, options, { defaultDataset: { datasetId: this.id } }); return this.bigQuery.createQueryStream(options); }; /** * Create a table given a tableId or configuration object. * * @resource [Tables: insert API Documentation]{@link https://cloud.google.com/bigquery/docs/reference/v2/tables/insert} * * @param {string} id - Table id. * @param {object=} options - See a * [Table resource](https://cloud.google.com/bigquery/docs/reference/v2/tables#resource). * @param {string|object} options.schema - A comma-separated list of name:type * pairs. Valid types are "string", "integer", "float", "boolean", and * "timestamp". If the type is omitted, it is assumed to be "string". * Example: "name:string, age:integer". Schemas can also be specified as a * JSON array of fields, which allows for nested and repeated fields. See * a [Table resource](http://goo.gl/sl8Dmg) for more detailed information. * @param {function} callback - The callback function. * @param {?error} callback.err - An error returned while making this request * @param {module:bigquery/table} callback.table - The newly created table. * @param {object} callback.apiResponse - The full API response. * * @example * var tableId = 'institution_data'; * * var options = { * // From the data.gov CSV dataset (http://goo.gl/kSE7z6): * schema: 'UNITID,INSTNM,ADDR,CITY,STABBR,ZIP,FIPS,OBEREG,CHFNM,...' * }; * * dataset.createTable(tableId, options, function(err, table, apiResponse) {}); * * //- * // If the callback is omitted, we'll return a Promise. * //- * dataset.createTable(tableId, options).then(function(data) { * var table = data[0]; * var apiResponse = data[1]; * }); */ Dataset.prototype.createTable = function(id, options, callback) { var self = this; if (is.fn(options)) { callback = options; options = {}; } var body = extend(true, {}, options, { tableReference: { datasetId: this.id, projectId: this.bigQuery.projectId, tableId: id } }); if (is.string(options.schema)) { body.schema = Table.createSchemaFromString_(options.schema); } if (is.array(options.schema)) { body.schema = { fields: options.schema }; } if (body.schema && body.schema.fields) { body.schema.fields = body.schema.fields.map(function(field) { if (field.fields) { field.type = 'RECORD'; } return field; }); } this.request({ method: 'POST', uri: '/tables', json: body }, function(err, resp) { if (err) { callback(err, null, resp); return; } var table = self.table(resp.tableReference.tableId); table.metadata = resp; callback(null, table, resp); }); }; /** * Delete the dataset. * * @resource [Datasets: delete API Documentation]{@link https://cloud.google.com/bigquery/docs/reference/v2/datasets/delete} * * @param {object=} options - The configuration object. * @param {boolean} options.force - Force delete dataset and all tables. * Default: false. * @param {function} callback - The callback function. * @param {?error} callback.err - An error returned while making this request * @param {object} callback.apiResponse - The full API response. * * @example * //- * // Delete the dataset, only if it does not have any tables. * //- * dataset.delete(function(err, apiResponse) {}); * * //- * // Delete the dataset and any tables it contains. * //- * dataset.delete({ force: true }, function(err, apiResponse) {}); * * //- * // If the callback is omitted, we'll return a Promise. * //- * dataset.delete().then(function(data) { * var apiResponse = data[0]; * }); */ Dataset.prototype.delete = function(options, callback) { if (!callback) { callback = options; options = {}; } var query = { deleteContents: !!options.force }; this.request({ method: 'DELETE', uri: '', qs: query }, callback); }; /** * Get a list of tables. * * @resource [Tables: list API Documentation]{@link https://cloud.google.com/bigquery/docs/reference/v2/tables/list} * * @param {object=} query - Configuration object. * @param {boolean} query.autoPaginate - Have pagination handled automatically. * Default: true. * @param {number} query.maxApiCalls - Maximum number of API calls to make. * @param {number} query.maxResults - Maximum number of results to return. * @param {string} query.pageToken - Token returned from a previous call, to * request the next page of results. * @param {function} callback - The callback function. * @param {?error} callback.err - An error returned while making this request * @param {module:bigquery/table[]} callback.tables - The list of tables from * your Dataset. * @param {object} callback.apiResponse - The full API response. * * @example * dataset.getTables(function(err, tables, nextQuery, apiResponse) { * // If `nextQuery` is non-null, there are more results to fetch. * }); * * //- * // If the callback is omitted, we'll return a Promise. * //- * dataset.getTables().then(function(data) { * var tables = data[0]; * }); */ Dataset.prototype.getTables = function(query, callback) { var that = this; if (is.fn(query)) { callback = query; query = {}; } query = query || {}; this.request({ uri: '/tables', qs: query }, function(err, resp) { if (err) { callback(err, null, null, resp); return; } var nextQuery = null; if (resp.nextPageToken) { nextQuery = extend({}, query, { pageToken: resp.nextPageToken }); } var tables = (resp.tables || []).map(function(tableObject) { var table = that.table(tableObject.tableReference.tableId); table.metadata = tableObject; return table; }); callback(null, tables, nextQuery, resp); }); }; /** * List all or some of the {module:bigquery/table} objects in your project as a * readable object stream. * * @param {object=} query - Configuration object. See * {module:bigquery/dataset#getTables} for a complete list of options. * @return {stream} * * @example * dataset.getTablesStream() * .on('error', console.error) * .on('data', function(table) {}) * .on('end', function() { * // All tables have been retrieved * }); * * //- * // If you anticipate many results, you can end a stream early to prevent * // unnecessary processing and API requests. * //- * dataset.getTablesStream() * .on('data', function(table) { * this.end(); * }); */ Dataset.prototype.getTablesStream = common.paginator.streamify('getTables'); /** * Run a query scoped to your dataset. * * See {module:bigquery#query} for full documentation of this method. */ Dataset.prototype.query = function(options, callback) { if (is.string(options)) { options = { query: options }; } options = extend(true, {}, options, { defaultDataset: { datasetId: this.id } }); return this.bigQuery.query(options, callback); }; /** * Create a Table object. * * @param {string} id - The ID of the table. * @return {module:bigquery/table} * * @example * var institutions = dataset.table('institution_data'); */ Dataset.prototype.table = function(id) { return new Table(this, id); }; /*! Developer Documentation * * These methods can be auto-paginated. */ common.paginator.extend(Dataset, ['getTables']); /*! Developer Documentation * * All async methods (except for streams) will return a Promise in the event * that a callback is omitted. */ common.util.promisifyAll(Dataset, { exclude: ['table'] }); module.exports = Dataset;
DayanaHudson/GMUExchange
node_modules/google-cloud/node_modules/@google-cloud/bigquery/src/dataset.js
JavaScript
mit
13,273
(function(Button, set) { set += ": "; test(set + "Test btn class added", function() { var $elements; $elements = new Button($("<a>").add("<button>").add("<input>")); ok($elements.hasClass("btn"), "Buttons should be of the btn class"); }); test(set + "Test button creation, no arguments", function() { var button = new Button(); ok(button.hasClass("btn"), "Button should be of the btn class"); ok(button.is("button"), "Button should be a <button> element"); equal(button.attr("type"), "button", "Type attribute should be 'button'"); }); test(set + "Test default buttons", function() { var button = new Button(); button.primary(); equal(button.attr("class"), "btn " + button.options.PRIMARY, "Primary style button should be of the btn and '" + button.options.PRIMARY + "' classes only"); button.info(); equal(button.attr("class"), "btn " + button.options.INFO, "Info style button should be of the btn and '" + button.options.INFO + "' classes only"); button.success(); equal(button.attr("class"), "btn " + button.options.SUCCESS, "Success style button should be of the btn and '" + button.options.SUCCESS + "' classes only"); button.warning(); equal(button.attr("class"), "btn " + button.options.WARNING, "Warning style button should be of the btn and '" + button.options.WARNING + "' classes only"); button.danger(); equal(button.attr("class"), "btn " + button.options.DANGER, "Danger style button should be of the btn and '" + button.options.DANGER + "' classes only"); button.link(); equal(button.attr("class"), "btn " + button.options.LINK, "Link style button should be of the btn and '" + button.options.LINK + "' classes only"); button.defaultStyle(); equal(button.attr("class"), "btn", "Default button should be of the btn class only"); }); test(set+ "Test button sizes", function() { var button = new Button(); button.large(); equal(button.attr("class"), "btn " + button.sizes.LARGE, "Large button should be of the btn and '" + button.sizes.LARGE + "' classes only"); button.defaultSize(); equal(button.attr("class"), "btn", "Default button should be of the btn class only"); button.small(); equal(button.attr("class"), "btn " + button.sizes.SMALL, "Small button should be of the btn and '" + button.sizes.SMALL + "' classes only"); button.extraSmall(); equal(button.attr("class"), "btn " + button.sizes.EXTRASMALL, "Extra small button should be of the btn and '" + button.sizes.EXTRASMALL + "' classes only"); }); test(set + "Test block-level button", function () { var button = new Button(); button.block(); equal(button.attr("class"), "btn " + button.BLOCK, "Block level button should be of the btn and '" + button.BLOCK + "' classes only"); }); test(set + "Test disable <button> and <input> elements", function() { var buttons, hasClass; buttons = new Button($("<button>").add("<input>")); hasClass = false; buttons.disable(); equal(buttons.attr("disabled"), "disabled", "Disabled elements should have the disabled attribute value of 'disabled'"); buttons.map(function() { hasClass = hasClass || $(this).hasClass(Button.prototype.DISABLED); }); equal(hasClass, false, "Elements should not be of the '" + Button.prototype.DISABLED + "' class"); }); test(set + "Test disable <a> element", function() { var button = new Button("<a>"); button.disable(); ok(button.attr("disabled") === undefined, "Disabled anchor elements should not have the disabled attribute"); ok(button.hasClass(button.DISABLED), "Disabled anchor elements should be of the '" + button.DISABLED + "' class"); }); test(set + "Test set text", function() { var anotherButton, buttons, functionExpectedValue, oldText, text; oldText = "Hello, tester!"; text = "Hello, world!"; buttons = new Button( $("<button>") .add("<input type='button'>") .add("<input type='submit'>") .add("<input type='reset'>") .add("<input type='text'>")); //not a real button anotherButton = new Button("<button>" + oldText + "</button>"); buttons.text(text); //.eq() returns a jQuery object, so no worries about the Button.prototype.text() calls, here! equal(buttons.eq(0).text(), text, "<button> element should have text() set to " + text); equal(buttons.eq(0).attr("value"), undefined, "<button> element should not have the value attribute set"); equal(buttons.eq(1).text(), "", "<input> button element should have text() set to an empty string"); equal(buttons.eq(1).attr("value"), text, "<input> button element should have the value attribute set to " + text); equal(buttons.eq(2).text(), "", "<input> submit element should have text() set to an empty string"); equal(buttons.eq(2).attr("value"), text, "<input> submit element should have the value attribute set to " + text); equal(buttons.eq(3).text(), "", "<input> reset element should have text() set to an empty string"); equal(buttons.eq(3).attr("value"), text, "<input> reset element should have the value attribute set to " + text); equal(buttons.eq(4).text(), text, "<input> text (not a button) element should have text() set to " + text); equal(buttons.eq(4).attr("value"), undefined, "<input> text (not a button) element should not have the value attribute set"); anotherButton.text(function(index, old) { return "" + text + "-" + index + "-" + old; }); functionExpectedValue = "" + text + "-0-" + oldText; equal($.fn.text.apply(anotherButton, []), functionExpectedValue, "Setting text with this function should return '" + functionExpectedValue + "' for text()"); }); test(set + "Test get text", function() { var buttons, text; text = "Hello, world, again!"; buttons = { button: new Button("<button>" + text + "</button>"), input: { button: new Button("<input type='button' value='" + text + "'>"), submit: new Button("<input type='submit' value='" + text + "'>"), reset: new Button("<input type='reset' value='" + text + "'>"), notAButton: new Button("<input type='text' value='" + text + "'>") }, anchor: new Button("<a>" + text + "</a>") }; equal(buttons.button.text(), text, "<button> element should have text() return '" + text + "'"); equal(buttons.input.button.text(), text, "<input> button element should have text() return '" + text + "'"); equal(buttons.input.submit.text(), text, "<input> submit element should have text() return '" + text + "'"); equal(buttons.input.reset.text(), text, "<input> reset element should have text() return '" + text + "'"); equal(buttons.input.notAButton.text(), "", "<input> text (not a button) element should have text() return an empty string"); equal(buttons.anchor.text(), text, "<a> element should have text() return '" + text + "'"); }); })(uk.co.stevenmeyer.bootstrap.css.Button, "css.Button");
StevenMeyer/BootstrapLib
test/tests/2.0/css/button.js
JavaScript
mit
7,695
/// <reference path="Xrm.js" /> var EntityLogicalName = "uomschedule"; var Form_a793fa7c_8b63_43f0_b4bc_73f75a68935a_Properties = { description: "description", name: "name" }; var Form_a793fa7c_8b63_43f0_b4bc_73f75a68935a_Controls = { description: "description", name: "name" }; var pageData = { "Event": "none", "SaveMode": 1, "EventSource": null, "AuthenticationHeader": "", "CurrentTheme": "Default", "OrgLcid": 1033, "OrgUniqueName": "", "QueryStringParameters": { "_gridType": "1056", "etc": "1056", "id": "", "pagemode": "iframe", "preloadcache": "1344548892170", "rskey": "141637534" }, "ServerUrl": "", "UserId": "", "UserLcid": 1033, "UserRoles": [""], "isOutlookClient": false, "isOutlookOnline": true, "DataXml": "", "EntityName": "uomschedule", "Id": "", "IsDirty": false, "CurrentControl": "", "CurrentForm": null, "Forms": [], "FormType": 2, "ViewPortHeight": 558, "ViewPortWidth": 1231, "Attributes": [{ "Name": "description", "Value": "", "Type": "memo", "Format": "text", "IsDirty": false, "RequiredLevel": "none", "SubmitMode": "dirty", "UserPrivilege": { "canRead": true, "canUpdate": true, "canCreate": true }, "MaxLength": 2000, "Controls": [{ "Name": "description" }] }, { "Name": "name", "Value": "", "Type": "string", "Format": "text", "IsDirty": false, "RequiredLevel": "none", "SubmitMode": "dirty", "UserPrivilege": { "canRead": true, "canUpdate": true, "canCreate": true }, "MaxLength": 200, "Controls": [{ "Name": "name" }] }], "AttributesLength": 2, "Controls": [{ "Name": "description", "Type": "standard", "Disabled": false, "Visible": true, "Label": "Description", "Attribute": "description" }, { "Name": "name", "Type": "standard", "Disabled": false, "Visible": true, "Label": "Name", "Attribute": "name" }], "ControlsLength": 2, "Navigation": [], "Tabs": [{ "Label": "General", "Name": "general", "DisplayState": "expanded", "Visible": true, "Sections": [{ "Label": "UOM Schedule Information", "Name": "uom schedule information", "Visible": true, "Controls": [{ "Name": "name" }, { "Name": "description" }] }] }] }; var Xrm = new _xrm(pageData);
Nazi-Nigger/Ms-CRM-2016-Controls
Ms-CRM-2016-Controls/Ms-CRM-2016-Controls Resources/Javascript/Intellisense Files/Unit Group Form - Information.js
JavaScript
mit
2,848
// To set up environmental variables, see http://twil.io/secure const accountSid = process.env.TWILIO_ACCOUNT_SID; const authToken = process.env.TWILIO_AUTH_TOKEN; const Twilio = require('twilio').Twilio; const client = new Twilio(accountSid, authToken); const service = client.sync.services('ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'); service .syncLists('MyFirstList') .syncListItems(0) .update({ data: { number: '001', attack: '49', name: 'Bulbasaur', }, }) .then(response => { console.log(response); }) .catch(error => { console.log(error); });
TwilioDevEd/api-snippets
sync/rest/lists/update-list-item/update-list-item.3.x.js
JavaScript
mit
595
/* Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang( 'newpage', 'af', { toolbar: 'Nuwe bladsy' } );
otto-torino/gino
ckeditor/plugins/newpage/lang/af.js
JavaScript
mit
247
'use strict' const Twitter = require('twitter') const twitterOpts = require('./auth.json') const client = new Twitter(twitterOpts) const twttr = require('./twttr/') twttr.getTrendingTopics(client).then((tt) => { tt.forEach((topic, idx) => { twttr.searchTopic(client, topic).then((tweets) => { let statuses = twttr.transformTweets(tweets) console.log(statuses) // insights: word count, graphos etc. }) }) })
edravis/pulse
index.js
JavaScript
mit
437
{ babelHelpers.inheritsLoose(Test, _Foo); function Test() { return _Foo.apply(this, arguments) || this; } return Test; }
stas-vilchik/bdd-ml
data/1469.js
JavaScript
mit
135
import Aquaman from './components/Aquaman.jsx'; // eslint-disable-line no-unused-vars import '../styles/appStyles.scss';
mvezer/aquaman
src/client/js/app.js
JavaScript
mit
121
const Hapi = require('hapi'); const Request = require('request'); const port = process.env.PORT || 8080; const server = new Hapi.Server(); const cephalopods = 'http://api.gbif.org/v1/species/136'; server.connection({ port: port, host: '0.0.0.0' }); server.route({ method: 'GET', path: '/', handler: function (request, reply) { Request(cephalopods, function (err, response, body) { return reply(body); }); } }); server.start(function () { console.log('Server started on ' + port); });
nvcexploder/fishy-nodevember
index.js
JavaScript
mit
545
const {env, browsers} = require('config'); const isProd = env === 'production'; module.exports = { // parser: 'sugarss', plugins: { 'postcss-preset-env': browsers, 'cssnano': isProd ? {} : false, } };
TongChia/frontend-boilerplate
postcss.config.js
JavaScript
mit
216
$(document).ready(function() { SVGUpInstance.init('inforamaui', {"icons": { "logo":{"url":"images/inforama-icon.svg"}, "downarrow":{"url":"images/down-arrow.svg"}, "usericon":{"url":"images/user-icon.svg"} }, "classes":{ "mainstyle":{ "svgdefault":{"fillcolor":"#AA8833"}, "svghover":{"fillcolor":"#8CC63E"}, "cssdefault":{"opacity":"0.3", "width":"40px", "height":"40px", "transition":"all 0.5s"}, "csshover":{"opacity":"1", "width":"50px", "height":"50px"} } }} ); });
Inforama-dev/svgup
demos/bundles.js
JavaScript
mit
519
import _ from 'lodash' // eslint-disable-line export default function loadInitialState(req) { const user = req.user const state = { auth: {}, } if (user) { state.auth = { user: {id: user.id}, } if (req.session.accessToken) { state.auth.accessToken = req.session.accessToken.token } } if (req.csrfToken) { state.auth.csrf = req.csrfToken() } // Immutable.fromJS has a bug with objects flagged as anonymous in node 6 // https://github.com/facebook/immutable-js/issues/1001 return JSON.parse(JSON.stringify(state)) // callback(null, state) }
founderlab/fl-base-webapp
server/clientApps/loadInitialState.js
JavaScript
mit
602
import React, { Fragment } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import pluralize from 'common/utils/pluralize'; import search from './actions'; import { selectSearchResultIds, selectIsSearching, selectIsSearchComplete } from './selectors'; import Element from 'common/components/Element'; import H3 from 'common/components/H3'; import Button from 'common/components/Button'; import VocabList from 'common/components/VocabList'; import { blue, orange } from 'common/styles/colors'; SearchResults.propTypes = { ids: PropTypes.arrayOf(PropTypes.number), isSearching: PropTypes.bool, isSearchComplete: PropTypes.bool, onReset: PropTypes.func.isRequired, }; SearchResults.defaultProps = { ids: [], isSearching: false, isSearchComplete: false, }; export function SearchResults({ ids, isSearching, isSearchComplete, onReset }) { const tooBroad = ids.length >= 50; const amount = `${ids.length}${tooBroad ? '+' : ''}`; const wordsFoundText = `${amount} ${pluralize('word', ids.length)} found${ tooBroad ? '. Try refining your search keywords.' : '' }`; return ( (isSearching || isSearchComplete) && ( <Fragment> <Element flexRow flexCenter> <H3>{(isSearching && 'Searching...') || wordsFoundText}</H3> {isSearchComplete && ( <Button bgColor={orange[5]} colorHover={orange[5]} onClick={onReset}> Clear Results </Button> )} </Element> <VocabList ids={ids} bgColor={blue[5]} showSecondary showFuri /> </Fragment> ) ); } const mapStateToProps = (state, props) => ({ ids: selectSearchResultIds(state, props), isSearching: selectIsSearching(state, props), isSearchComplete: selectIsSearchComplete(state, props), }); const mapDispatchToProps = { onReset: search.clear, }; export default connect(mapStateToProps, mapDispatchToProps)(SearchResults);
Kaniwani/KW-Frontend
app/features/search/SearchResults.js
JavaScript
mit
1,946
import { toTitleCase } from 'utils'; export default values => { let newValues = { ...values }; // Add a sourceType if no source (i.e. not scraped) and no sourceType if (!newValues['source'] && !newValues['sourceType']) { newValues['sourceType'] = 'user'; } switch (newValues['sourceType']) { case 'user': newValues = { ...newValues, url: undefined, page: undefined, book: undefined, }; break; case 'website': newValues = { ...newValues, page: undefined, book: undefined }; break; case 'book': newValues = { ...newValues, url: undefined }; break; default: break; } if (Array.isArray(values['ingredients'])) { newValues = { ...newValues, ingredients: values['ingredients'].map(ingredient => ({ ...ingredient, text: ingredient.text.trim(), })), }; } return { public: true, ...newValues, title: toTitleCase(values['title']), }; };
jf248/scrape-the-plate
frontend/src/components/recipes/edit/components/Step2/normalize.js
JavaScript
mit
1,006
pinion.backend.renderer.CommentRenderer = (function($) { var constr; // public API -- constructor constr = function(settings, backend) { var _this = this, data = settings.data; this.$element = $("<div class='pinion-backend-renderer-CommentRenderer'></div>"); // TEXTWRAPPER var $textWrapper = $("<div class='pinion-textWrapper'></div>") .appendTo(this.$element); // INFOS $("<div class='pinion-comment-info'></div>") // USER .append("<div class='pinion-name'><span class='pinion-backend-icon-user'></span><span class='pinion-username'>"+data.name+"</span></div>") // TIME .append("<div class='pinion-time'><span class='pinion-backend-icon-clock'></span><span class='pinion-time-text'>"+data.created+"</span></div>") .append("<div class='pinion-mail'><span class='pinion-backend-icon-mail'></span><a href='mailto:"+data.email+"' class='pinion-mail-adress'>"+data.email+"</a></div>") .appendTo(this.$element); // COMMENT $("<div class='pinion-commentWrapper'><div class='pinion-comment-text'>"+data.text+"</div></div>") .appendTo(this.$element); var $activate = $("<div class='pinion-activate'><div class='pinion-icon'></div><div class='pinion-text'>"+pinion.translate("activate comment")+"</div></div>") .click(function() { if(_this.$element.hasClass("pinion-activated")) { _this.setClean(); } else { _this.setDirty(); } _this.$element.toggleClass("pinion-activated") }); // RENDERER BAR var bar = []; if(pinion.hasPermission("comment", "approve comment")) { bar.push($activate); } if(pinion.hasPermission("comment", "delete comment")) { bar.push(pinion.data.Delete.call(this, data, function() { _this.info.deleted = true; _this.fadeOut(300, function() { _this.setDirty(); }); })); } if(!pinion.isEmpty(bar)) { pinion.data.Bar.call(this, bar); } // INFO pinion.data.Info.call(this, ["Time"], data); // group events settings.groupEvents = true; } // public API -- prototype constr.prototype = { constructor: pinion.backend.renderer.CommentRenderer, init: function() { this.info.id = this.settings.data.id; }, reset: function() { this.$element.removeClass("pinion-activated"); } } return constr; }(jQuery));
friedolinfoerder/pinion
modules/comment/backend/js/CommentRenderer.js
JavaScript
mit
2,871
/* Copyright (c) 2004-2012, The Dojo Foundation All Rights Reserved. Available via Academic Free License >= 2.1 OR the modified BSD license. see: http://dojotoolkit.org/license for details */ if(!dojo._hasResource["dojox.lang.functional.scan"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code. dojo._hasResource["dojox.lang.functional.scan"] = true; dojo.provide("dojox.lang.functional.scan"); dojo.require("dojox.lang.functional.lambda"); // This module adds high-level functions and related constructs: // - "scan" family of functions // Notes: // - missing high-level functions are provided with the compatible API: // scanl, scanl1, scanr, scanr1 // Defined methods: // - take any valid lambda argument as the functional argument // - operate on dense arrays // - take a string as the array argument // - take an iterator objects as the array argument (only scanl, and scanl1) (function(){ var d = dojo, df = dojox.lang.functional, empty = {}; d.mixin(df, { // classic reduce-class functions scanl: function(/*Array|String|Object*/ a, /*Function|String|Array*/ f, /*Object*/ z, /*Object?*/ o){ // summary: repeatedly applies a binary function to an array from left // to right using a seed value as a starting point; returns an array // of values produced by foldl() at that point. if(typeof a == "string"){ a = a.split(""); } o = o || d.global; f = df.lambda(f); var t, n, i; if(d.isArray(a)){ // array t = new Array((n = a.length) + 1); t[0] = z; for(i = 0; i < n; z = f.call(o, z, a[i], i, a), t[++i] = z); }else if(typeof a.hasNext == "function" && typeof a.next == "function"){ // iterator t = [z]; for(i = 0; a.hasNext(); t.push(z = f.call(o, z, a.next(), i++, a))); }else{ // object/dictionary t = [z]; for(i in a){ if(!(i in empty)){ t.push(z = f.call(o, z, a[i], i, a)); } } } return t; // Array }, scanl1: function(/*Array|String|Object*/ a, /*Function|String|Array*/ f, /*Object?*/ o){ // summary: repeatedly applies a binary function to an array from left // to right; returns an array of values produced by foldl1() at that // point. if(typeof a == "string"){ a = a.split(""); } o = o || d.global; f = df.lambda(f); var t, n, z, first = true; if(d.isArray(a)){ // array t = new Array(n = a.length); t[0] = z = a[0]; for(var i = 1; i < n; t[i] = z = f.call(o, z, a[i], i, a), ++i); }else if(typeof a.hasNext == "function" && typeof a.next == "function"){ // iterator if(a.hasNext()){ t = [z = a.next()]; for(var i = 1; a.hasNext(); t.push(z = f.call(o, z, a.next(), i++, a))); } }else{ // object/dictionary for(var i in a){ if(!(i in empty)){ if(first){ t = [z = a[i]]; first = false; }else{ t.push(z = f.call(o, z, a[i], i, a)); } } } } return t; // Array }, scanr: function(/*Array|String*/ a, /*Function|String|Array*/ f, /*Object*/ z, /*Object?*/ o){ // summary: repeatedly applies a binary function to an array from right // to left using a seed value as a starting point; returns an array // of values produced by foldr() at that point. if(typeof a == "string"){ a = a.split(""); } o = o || d.global; f = df.lambda(f); var n = a.length, t = new Array(n + 1), i = n; t[n] = z; for(; i > 0; --i, z = f.call(o, z, a[i], i, a), t[i] = z); return t; // Array }, scanr1: function(/*Array|String*/ a, /*Function|String|Array*/ f, /*Object?*/ o){ // summary: repeatedly applies a binary function to an array from right // to left; returns an array of values produced by foldr1() at that // point. if(typeof a == "string"){ a = a.split(""); } o = o || d.global; f = df.lambda(f); var n = a.length, t = new Array(n), z = a[n - 1], i = n - 1; t[i] = z; for(; i > 0; --i, z = f.call(o, z, a[i], i, a), t[i] = z); return t; // Array } }); })(); }
henry-gobiernoabierto/geomoose
htdocs/libs/dojo/release/geomoose2.6/dojox/lang/functional/scan.js
JavaScript
mit
4,006
'use strict'; /* jasmine specs for directives go here */ describe('directives', function () { beforeEach(module('myApp.directives')); describe('app-version', function () { it('should print current version', function () { module(function ($provide) { $provide.value('version', 'TEST_VER'); }); inject(function ($compile, $rootScope) { var element = $compile('<span app-version></span>')($rootScope); expect(element.text()).toEqual('TEST_VER'); }); }); }); describe('Button directive', function(){ var $compile, $rootScope; beforeEach(inject(function (_$rootScope_, _$compile_) { $compile = _$compile_; $rootScope = _$rootScope_; })); it('should have "btn" class to the button element', function(){ var element = $compile('<button></button>')($rootScope); expect(element.hasClass('btn')).toBeTruthy(); }) }); describe('Pagination directive', function () { var element, $scope, lis; beforeEach(inject(function ($compile, $rootScope) { $scope = $rootScope; $scope.numPage = 5; $scope.currentPage = 2; element = $compile('<pagination num-pages="numPages" current-page="currentPage"></pagination>')($scope); $scope.$digest(); lis = function () { return element.find('li'); }; })); it('has the number of the page as text in each page item', function () { for (var i = 0;i < $scope.numPage; i++) { expect(lis.eq(i).text()).toEqual('' + i); } }); }); });
reverocean/draggable
test/unit/directivesSpec.js
JavaScript
mit
1,766
const https = require('https') const cookie = require('cookie'); var exports = module.exports = {} exports.getResponseHeaders = function(httpOptions, formData) { if (formData) { httpOptions.headers = formData.getHeaders() } return new Promise((resolve, reject) => { const request = https.request(httpOptions, (response) => { // handle http errors if (response.statusCode < 200 || response.statusCode > 299) { reject(new Error('Failed to load page, status code: ' + response.statusCode)); } // temporary data holder const body = []; // on every content chunk, push it to the data array response.on('data', () => {}); // we are done, resolve promise with those joined chunks response.on('end', () => resolve(response.headers)); }); // handle connection errors of the request request.on('error', (err) => reject(err)) request.end() }) } exports.getCookies = function(headers) { cookies = {} headers['set-cookie'].forEach((element) => { cookies = Object.assign(cookies, cookie.parse(element)) }) return cookies }
mathieupouedras/booker
services.js
JavaScript
mit
1,128
'use strict'; /** * Developed by Engagement Lab, 2019 * ============== * Route to retrieve data by url * @class api * @author Johnny Richardson * * ========== */ const keystone = global.keystone, mongoose = require('mongoose'), Bluebird = require('bluebird'); mongoose.Promise = require('bluebird'); let list = keystone.list('Story').model; var getAdjacent = (results, res, lang) => { let fields = 'key photo.public_id '; if (lang === 'en') fields += 'name'; else if (lang === 'tm') fields += 'nameTm'; else if (lang === 'hi') fields += 'nameHi'; // Get one next/prev person from selected person's sortorder let nextPerson = list.findOne({ sortOrder: { $gt: results.jsonData.sortOrder } }, fields).limit(1); let prevPerson = list.findOne({ sortOrder: { $lt: results.jsonData.sortOrder } }, fields).sort({ sortOrder: -1 }).limit(1); // Poplulate next/prev and output response Bluebird.props({ next: nextPerson, prev: prevPerson }).then(nextPrevResults => { let output = Object.assign(nextPrevResults, { person: results.jsonData }); return res.status(200).json({ status: 200, data: output }); }).catch(err => { console.log(err); }); }; var buildData = (storyId, res, lang) => { let data = null; let fields = 'key photo.public_id '; if (lang === 'en') fields += 'name subtitle'; else if (lang === 'tm') fields += 'nameTm subtitleTm'; else if (lang === 'hi') fields += 'nameHi subtitleHi'; if (storyId) { let subFields = ' description.html '; if (lang === 'tm') subFields = ' descriptionTm.html '; else if (lang === 'hi') subFields = ' descriptionHi.html '; data = list.findOne({ key: storyId }, fields + subFields + 'sortOrder -_id'); } else data = list.find({}, fields + ' -_id').sort([ ['sortOrder', 'descending'] ]); Bluebird.props({ jsonData: data }) .then(results => { // When retrieving one story, also get next/prev ones if (storyId) getAdjacent(results, res, lang); else { return res.status(200).json({ status: 200, data: results.jsonData }); } }).catch(err => { console.log(err); }) } /* * Get data */ exports.get = function (req, res) { let id = null; if (req.query.id) id = req.query.id; let lang = null; if (req.params.lang) lang = req.params.lang; return buildData(id, res, lang); }
engagementgamelab/hygiene-with-chhota-bheem
website/server/routes/api/stories.js
JavaScript
mit
2,859
import React from 'react'; import Sortable from '../../src/'; import DemoItem from '../components/DemoItem'; export default class Dynamic extends React.Component { constructor() { super(); this.state = { arr: [998, 225, 13] }; } handleSort(sortedArray) { this.setState({ arr: sortedArray }); } handleAddElement() { this.setState({ arr: this.state.arr.concat(Math.round(Math.random() * 1000)) }); } handleRemoveElement(index) { const newArr = this.state.arr.slice(); newArr.splice(index, 1); this.setState({ arr: newArr }); } render() { function renderItem(num, index) { return ( <DemoItem key={num} className="dynamic-item" sortData={num}> {num} <span className="delete" onClick={this.handleRemoveElement.bind(this, index)} >&times;</span> </DemoItem> ); } return ( <div className="demo-container"> <h4 className="demo-title"> Dynamically adding/removing children <a href="https://github.com/jasonslyvia/react-anything-sortable/tree/master/demo/pages/dynamic.js" target="_blank">source</a> </h4> <div className="dynamic-demo"> <button onClick={::this.handleAddElement}>Add 1 element</button> <Sortable onSort={::this.handleSort} dynamic> {this.state.arr.map(renderItem, this)} </Sortable> </div> </div> ); } }
jasonslyvia/react-anything-sortable
demo/pages/dynamic.js
JavaScript
mit
1,497
import expect from "expect"; import { Collection } from "./Collection"; import { Server } from "./Server"; describe("Collection", () => { describe("constructor", () => { it("should set the initial set of data", () => { const collection = new Collection([ { id: 1, name: "foo" }, { id: 2, name: "bar" }, ]); expect(collection.getAll()).toEqual([ { id: 1, name: "foo" }, { id: 2, name: "bar" }, ]); }); it("should set identifier name to id by default", () => { const collection = new Collection(); expect(collection.identifierName).toEqual("id"); }); }); describe("getCount", () => { it("should return an integer", () => { expect(new Collection().getCount()).toEqual(0); }); it("should return the collection size", () => { expect(new Collection([{}, {}]).getCount()).toEqual(2); }); it("should return the correct collection size, even when items were removed", () => { const collection = new Collection([{}, {}, {}]); collection.removeOne(1); expect(collection.getCount()).toEqual(2); }); it("should accept a query object", () => { const collection = new Collection([{}, { name: "a" }, { name: "b" }]); function filter(item) { return item.name == "a" || item.name == "b"; } expect(collection.getCount({ filter: filter })).toEqual(2); }); }); describe("getAll", () => { it("should return an array", () => { expect(new Collection().getAll()).toEqual([]); }); it("should return all collections", () => { const collection = new Collection([ { id: 1, name: "foo" }, { id: 2, name: "bar" }, ]); expect(collection.getAll()).toEqual([ { id: 1, name: "foo" }, { id: 2, name: "bar" }, ]); }); describe("sort query", () => { it("should throw an error if passed an unsupported sort argument", () => { const collection = new Collection(); expect(() => { collection.getAll({ sort: 23 }); }).toThrow(new Error("Unsupported sort type")); }); it("should sort by sort function", () => { const collection = new Collection([ { name: "c" }, { name: "a" }, { name: "b" }, ]); const expected = [ { name: "a", id: 1 }, { name: "b", id: 2 }, { name: "c", id: 0 }, ]; function sort(a, b) { if (a.name > b.name) { return 1; } if (a.name < b.name) { return -1; } // a must be equal to b return 0; } expect(collection.getAll({ sort: sort })).toEqual(expected); }); it("should sort by sort name", () => { const collection = new Collection([ { name: "c" }, { name: "a" }, { name: "b" }, ]); const expected = [ { name: "a", id: 1 }, { name: "b", id: 2 }, { name: "c", id: 0 }, ]; expect(collection.getAll({ sort: "name" })).toEqual(expected); }); it("should sort by sort name and direction", () => { const collection = new Collection([ { name: "c" }, { name: "a" }, { name: "b" }, ]); let expected; expected = [ { name: "a", id: 1 }, { name: "b", id: 2 }, { name: "c", id: 0 }, ]; expect(collection.getAll({ sort: ["name", "asc"] })).toEqual(expected); expected = [ { name: "c", id: 0 }, { name: "b", id: 2 }, { name: "a", id: 1 }, ]; expect(collection.getAll({ sort: ["name", "desc"] })).toEqual(expected); }); it("should not affect further requests", () => { const collection = new Collection([ { name: "c" }, { name: "a" }, { name: "b" }, ]); collection.getAll({ sort: "name" }); const expected = [ { name: "c", id: 0 }, { name: "a", id: 1 }, { name: "b", id: 2 }, ]; expect(collection.getAll()).toEqual(expected); }); }); describe("filter query", () => { it("should throw an error if passed an unsupported filter argument", () => { const collection = new Collection(); expect(() => { collection.getAll({ filter: 23 }); }).toThrow(new Error("Unsupported filter type")); }); it("should filter by filter function", () => { const collection = new Collection([ { name: "c" }, { name: "a" }, { name: "b" }, ]); const expected = [ { name: "c", id: 0 }, { name: "b", id: 2 }, ]; function filter(item) { return item.name !== "a"; } expect(collection.getAll({ filter: filter })).toEqual(expected); }); it("should filter by filter object", () => { const collection = new Collection([ { name: "c" }, { name: "a" }, { name: "b" }, ]); const expected = [{ name: "b", id: 2 }]; expect(collection.getAll({ filter: { name: "b" } })).toEqual(expected); }); it("should filter values with deep paths", () => { const collection = new Collection([ { name: "c", deep: { value: "c" } }, { name: "a", deep: { value: "a" } }, { name: "b", deep: { value: "b" } }, ]); const expected = [{ name: "b", deep: { value: "b" }, id: 2 }]; expect(collection.getAll({ filter: { "deep.value": "b" } })).toEqual(expected); }); it("should filter values with objects", () => { const collection = new Collection([ { name: "c", deep: { value: "c" } }, { name: "a", deep: { value: "a" } }, { name: "b", deep: { value: "b" } }, ]); const expected = [{ name: "b", deep: { value: "b" }, id: 2 }]; expect(collection.getAll({ filter: { deep: { value: "b" } } })).toEqual(expected); }); it("should filter boolean values properly", () => { const collection = new Collection([ { name: "a", is: true }, { name: "b", is: false }, { name: "c", is: true }, ]); const expectedFalse = [{ name: "b", id: 1, is: false }]; const expectedTrue = [ { name: "a", id: 0, is: true }, { name: "c", id: 2, is: true }, ]; expect(collection.getAll({ filter: { is: "false" } })).toEqual( expectedFalse ); expect(collection.getAll({ filter: { is: false } })).toEqual( expectedFalse ); expect(collection.getAll({ filter: { is: "true" } })).toEqual( expectedTrue ); expect(collection.getAll({ filter: { is: true } })).toEqual( expectedTrue ); }); it("should filter array values properly", () => { const collection = new Collection([ { tags: ["a", "b", "c"] }, { tags: ["b", "c", "d"] }, { tags: ["c", "d", "e"] }, ]); const expected = [ { id: 0, tags: ["a", "b", "c"] }, { id: 1, tags: ["b", "c", "d"] }, ]; expect(collection.getAll({ filter: { tags: "b" } })).toEqual(expected); expect(collection.getAll({ filter: { tags: "f" } })).toEqual([]); }); it("should filter array values properly within deep paths", () => { const collection = new Collection([ { deep: { tags: ["a", "b", "c"] } }, { deep: { tags: ["b", "c", "d"] } }, { deep: { tags: ["c", "d", "e"] } }, ]); const expected = [ { id: 0, deep: { tags: ["a", "b", "c"] } }, { id: 1, deep: { tags: ["b", "c", "d"] } }, ]; expect(collection.getAll({ filter: { 'deep.tags': "b" } })).toEqual(expected); expect(collection.getAll({ filter: { 'deep.tags': "f" } })).toEqual([]); }); it("should filter array values properly inside deep paths", () => { const collection = new Collection([ { tags: { deep: ["a", "b", "c"] } }, { tags: { deep: ["b", "c", "d"] } }, { tags: { deep: ["c", "d", "e"] } }, ]); const expected = [ { id: 0, tags: { deep: ["a", "b", "c"] } }, { id: 1, tags: { deep: ["b", "c", "d"] } }, ]; expect(collection.getAll({ filter: { 'tags.deep': "b" } })).toEqual(expected); expect(collection.getAll({ filter: { 'tags.deep': "f" } })).toEqual([]); }); it("should filter array values properly with deep paths", () => { const collection = new Collection([ { tags: [{ name: "a" }, { name: "b" }, { name: "c" }] }, { tags: [{ name: "b" }, { name: "c" }, { name: "d" }] }, { tags: [{ name: "c" }, { name: "d" }, { name: "e" }] }, ]); const expected = [ { id: 0, tags: [{ name: "a" }, { name: "b" }, { name: "c" }] }, { id: 1, tags: [{ name: "b" }, { name: "c" }, { name: "d" }] }, ]; expect(collection.getAll({ filter: { 'tags.name': "b" } })).toEqual(expected); expect(collection.getAll({ filter: { 'tags.name': "f" } })).toEqual([]); }); it("should filter array values properly when receiving several values within deep paths", () => { const collection = new Collection([ { deep: { tags: ["a", "b", "c"] } }, { deep: { tags: ["b", "c", "d"] } }, { deep: { tags: ["c", "d", "e"] } }, ]); const expected = [{ id: 1, deep: { tags: ["b", "c", "d"] } }]; expect(collection.getAll({ filter: { 'deep.tags': ["b", "d"] } })).toEqual( expected ); expect( collection.getAll({ filter: { 'deep.tags': ["a", "b", "e"] } }) ).toEqual([]); }); it("should filter array values properly when receiving several values with deep paths", () => { const collection = new Collection([ { tags: [{ name: "a" }, { name: "b" }, { name: "c" }] }, { tags: [{ name: "c" }, { name: "d" }, { name: "e" }] }, { tags: [{ name: "e" }, { name: "f" }, { name: "g" }] }, ]); const expected = [ { id: 0, tags: [{ name: "a" }, { name: "b" }, { name: "c" }] }, { id: 1, tags: [{ name: "c" }, { name: "d" }, { name: "e" }] } ]; expect(collection.getAll({ filter: { 'tags.name': ["c"] } })).toEqual( expected ); expect( collection.getAll({ filter: { 'tags.name': ["h", "i"] } }) ).toEqual([]); }); it("should filter array values properly when receiving several values", () => { const collection = new Collection([ { tags: ["a", "b", "c"] }, { tags: ["b", "c", "d"] }, { tags: ["c", "d", "e"] }, ]); const expected = [{ id: 1, tags: ["b", "c", "d"] }]; expect(collection.getAll({ filter: { tags: ["b", "d"] } })).toEqual( expected ); expect( collection.getAll({ filter: { tags: ["a", "b", "e"] } }) ).toEqual([]); }); it("should filter by the special q full-text filter", () => { const collection = new Collection([ { a: "Hello", b: "world" }, { a: "helloworld", b: "bunny" }, { a: "foo", b: "bar" }, { a: { b: "bar" } }, { a: "", b: "" }, { a: null, b: null }, {}, ]); expect(collection.getAll({ filter: { q: "hello" } })).toEqual([ { id: 0, a: "Hello", b: "world" }, { id: 1, a: "helloworld", b: "bunny" }, ]); expect(collection.getAll({ filter: { q: "bar" } })).toEqual([ { id: 2, a: "foo", b: "bar" }, { id: 3, a: { b: "bar" } }, ]); }); it("should filter by range using _gte, _gt, _lte, and _lt", () => { const collection = new Collection([{ v: 1 }, { v: 2 }, { v: 3 }]); expect(collection.getAll({ filter: { v_gte: 2 } })).toEqual([ { v: 2, id: 1 }, { v: 3, id: 2 }, ]); expect(collection.getAll({ filter: { v_gt: 2 } })).toEqual([ { v: 3, id: 2 }, ]); expect(collection.getAll({ filter: { v_gte: 4 } })).toEqual([]); expect(collection.getAll({ filter: { v_lte: 2 } })).toEqual([ { v: 1, id: 0 }, { v: 2, id: 1 }, ]); expect(collection.getAll({ filter: { v_lt: 2 } })).toEqual([ { v: 1, id: 0 }, ]); expect(collection.getAll({ filter: { v_lte: 0 } })).toEqual([]); }); it("should filter by inequality using _neq", () => { const collection = new Collection([{ v: 1 }, { v: 2 }, { v: 3 }]); expect(collection.getAll({ filter: { v_neq: 2 } })).toEqual([ { v: 1, id: 0 }, { v: 3, id: 2 }, ]); }); it("should filter by text search using _q", () => { const collection = new Collection([{ v: 'abCd' }, { v: 'cDef' }, { v: 'EFgh' }]); expect(collection.getAll({ filter: { v_q: 'cd' } })).toEqual([ { id: 0, v: 'abCd' }, { id: 1, v: 'cDef' } ]); expect(collection.getAll({ filter: { v_q: 'ef' } })).toEqual([ { id: 1, v: 'cDef' }, { id: 2, v: 'EFgh' } ]); }); it("should filter by array", () => { const collection = new Collection([ { a: "H" }, { a: "e" }, { a: "l" }, { a: "l" }, { a: "o" }, ]); expect(collection.getAll({ filter: { id: [] } })).toEqual([]); expect(collection.getAll({ filter: { id: [1, 2, 3] } })).toEqual([ { id: 1, a: "e" }, { id: 2, a: "l" }, { id: 3, a: "l" }, ]); expect(collection.getAll({ filter: { id: ["1", "2", "3"] } })).toEqual([ { id: 1, a: "e" }, { id: 2, a: "l" }, { id: 3, a: "l" }, ]); }); it("should combine all filters with an AND logic", () => { const collection = new Collection([{ v: 1 }, { v: 2 }, { v: 3 }]); expect(collection.getAll({ filter: { v_gte: 2, v_lte: 2 } })).toEqual([ { v: 2, id: 1 }, ]); }); it("should not affect further requests", () => { const collection = new Collection([ { name: "c" }, { name: "a" }, { name: "b" }, ]); function filter(item) { return item.name !== "a"; } collection.getAll({ filter: filter }); const expected = [ { name: "c", id: 0 }, { name: "a", id: 1 }, { name: "b", id: 2 }, ]; expect(collection.getAll()).toEqual(expected); }); }); describe("range query", () => { it("should throw an error if passed an unsupported range argument", () => { const collection = new Collection(); expect(() => { collection.getAll({ range: 23 }); }).toThrow(new Error("Unsupported range type")); }); const collection = new Collection([ { id: 0, name: "a" }, { id: 1, name: "b" }, { id: 2, name: "c" }, { id: 3, name: "d" }, { id: 4, name: "e" }, ]); it("should return a range in the collection", () => { let expected; expected = [{ id: 0, name: "a" }]; expect(collection.getAll({ range: [0, 0] })).toEqual(expected); expected = [ { id: 1, name: "b" }, { id: 2, name: "c" }, { id: 3, name: "d" }, { id: 4, name: "e" }, ]; expect(collection.getAll({ range: [1] })).toEqual(expected); expected = [ { id: 2, name: "c" }, { id: 3, name: "d" }, ]; expect(collection.getAll({ range: [2, 3] })).toEqual(expected); }); it("should not affect further requests", () => { const collection = new Collection([ { id: 0, name: "a" }, { id: 1, name: "b" }, { id: 2, name: "c" }, ]); collection.getAll({ range: [1] }); const expected = [ { id: 0, name: "a" }, { id: 1, name: "b" }, { id: 2, name: "c" }, ]; expect(collection.getAll()).toEqual(expected); }); }); describe("embed query", () => { it("should throw an error when trying to embed a non-existing collection", () => { const foos = new Collection([{ name: "John", bar_id: 123 }]); const server = new Server(); server.addCollection("foos", foos); expect(() => { foos.getAll({ embed: ["bar"] }); }).toThrow(new Error("Can't embed a non-existing collection bar")); }); it("should return the original object for missing embed one", () => { const foos = new Collection([{ name: "John", bar_id: 123 }]); const bars = new Collection([]); const server = new Server(); server.addCollection("foos", foos); server.addCollection("bars", bars); const expected = [{ id: 0, name: "John", bar_id: 123 }]; expect(foos.getAll({ embed: ["bar"] })).toEqual(expected); }); it("should return the object with the reference object for embed one", () => { const foos = new Collection([ { name: "John", bar_id: 123 }, { name: "Jane", bar_id: 456 }, ]); const bars = new Collection([ { id: 1, bar: "nobody wants me" }, { id: 123, bar: "baz" }, { id: 456, bar: "bazz" }, ]); const server = new Server(); server.addCollection("foos", foos); server.addCollection("bars", bars); const expected = [ { id: 0, name: "John", bar_id: 123, bar: { id: 123, bar: "baz" } }, { id: 1, name: "Jane", bar_id: 456, bar: { id: 456, bar: "bazz" } }, ]; expect(foos.getAll({ embed: ["bar"] })).toEqual(expected); }); it("should throw an error when trying to embed many a non-existing collection", () => { const foos = new Collection([{ name: "John", bar_id: 123 }]); const server = new Server(); server.addCollection("foos", foos); expect(() => { foos.getAll({ embed: ["bars"] }); }).toThrow(new Error("Can't embed a non-existing collection bars")); }); it("should return the object with an empty array for missing embed many", () => { const foos = new Collection([{ name: "John", bar_id: 123 }]); const bars = new Collection([{ id: 1, bar: "nobody wants me" }]); const server = new Server(); server.addCollection("foos", foos); server.addCollection("bars", bars); const expected = [{ id: 1, bar: "nobody wants me", foos: [] }]; expect(bars.getAll({ embed: ["foos"] })).toEqual(expected); }); it("should return the object with an array of references for embed many", () => { const foos = new Collection([ { id: 1, name: "John", bar_id: 123 }, { id: 2, name: "Jane", bar_id: 456 }, { id: 3, name: "Jules", bar_id: 456 }, ]); const bars = new Collection([ { id: 1, bar: "nobody wants me" }, { id: 123, bar: "baz" }, { id: 456, bar: "bazz" }, ]); const server = new Server(); server.addCollection("foos", foos); server.addCollection("bars", bars); const expected = [ { id: 1, bar: "nobody wants me", foos: [] }, { id: 123, bar: "baz", foos: [{ id: 1, name: "John", bar_id: 123 }] }, { id: 456, bar: "bazz", foos: [ { id: 2, name: "Jane", bar_id: 456 }, { id: 3, name: "Jules", bar_id: 456 }, ], }, ]; expect(bars.getAll({ embed: ["foos"] })).toEqual(expected); }); it("should return the object with an array of references for embed many using inner array", () => { const foos = new Collection([ { id: 1, name: "John" }, { id: 2, name: "Jane" }, { id: 3, name: "Jules" }, ]); const bars = new Collection([ { id: 1, bar: "nobody wants me" }, { id: 123, bar: "baz", foos: [1] }, { id: 456, bar: "bazz", foos: [2, 3] }, ]); const server = new Server(); server.addCollection("foos", foos); server.addCollection("bars", bars); const expected = [ { id: 1, bar: "nobody wants me", foos: [] }, { id: 123, bar: "baz", foos: [{ id: 1, name: "John" }] }, { id: 456, bar: "bazz", foos: [ { id: 2, name: "Jane" }, { id: 3, name: "Jules" }, ], }, ]; expect(bars.getAll({ embed: ["foos"] })).toEqual(expected); }); it("should allow multiple embeds", () => { const books = new Collection([ { id: 1, title: "Pride and Prejudice", author_id: 1 }, { id: 2, title: "Sense and Sensibility", author_id: 1 }, { id: 3, title: "War and Preace", author_id: 2 }, ]); const authors = new Collection([ { id: 1, firstName: "Jane", lastName: "Austen", country_id: 1 }, { id: 2, firstName: "Leo", lastName: "Tosltoi", country_id: 2 }, ]); const countries = new Collection([ { id: 1, name: "England" }, { id: 2, name: "Russia" }, ]); const server = new Server(); server.addCollection("books", books); server.addCollection("authors", authors); server.addCollection("countrys", countries); // nevermind the plural const expected = [ { id: 1, firstName: "Jane", lastName: "Austen", country_id: 1, books: [ { id: 1, title: "Pride and Prejudice", author_id: 1 }, { id: 2, title: "Sense and Sensibility", author_id: 1 }, ], country: { id: 1, name: "England" }, }, { id: 2, firstName: "Leo", lastName: "Tosltoi", country_id: 2, books: [{ id: 3, title: "War and Preace", author_id: 2 }], country: { id: 2, name: "Russia" }, }, ]; expect(authors.getAll({ embed: ["books", "country"] })).toEqual( expected ); }); }); describe("composite query", () => { it("should execute all commands of the query object", () => { const collection = new Collection([ { id: 0, name: "c", arg: false }, { id: 1, name: "b", arg: true }, { id: 2, name: "a", arg: true }, ]); const query = { filter: { arg: true }, sort: "name", }; const expected = [ { id: 2, name: "a", arg: true }, { id: 1, name: "b", arg: true }, ]; expect(collection.getAll(query)).toEqual(expected); }); }); }); describe("getOne", () => { it("should throw an exception when trying to get a non-existing item", () => { const collection = new Collection(); expect(() => { collection.getOne(0); }).toThrow(new Error("No item with identifier 0")); }); it("should return the first collection matching the identifier", () => { const collection = new Collection([ { id: 1, name: "foo" }, { id: 2, name: "bar" }, ]); expect(collection.getOne(1)).toEqual({ id: 1, name: "foo" }); expect(collection.getOne(2)).toEqual({ id: 2, name: "bar" }); }); it("should use the identifierName", () => { const collection = new Collection( [ { _id: 1, name: "foo" }, { _id: 2, name: "bar" }, ], "_id" ); expect(collection.getOne(1)).toEqual({ _id: 1, name: "foo" }); expect(collection.getOne(2)).toEqual({ _id: 2, name: "bar" }); }); }); describe("addOne", () => { it("should return the item inserted", () => { const collection = new Collection(); const r = collection.addOne({ name: "foo" }); expect(r.name).toEqual("foo"); }); it("should add the item", () => { const collection = new Collection(); collection.addOne({ name: "foo" }); expect(collection.getOne(0)).toEqual({ id: 0, name: "foo" }); }); it("should incement the sequence at each insertion", () => { const collection = new Collection(); expect(collection.sequence).toEqual(0); collection.addOne({ name: "foo" }); expect(collection.sequence).toEqual(1); collection.addOne({ name: "foo" }); expect(collection.sequence).toEqual(2); }); it("should set identifier if not provided", () => { const collection = new Collection(); const r1 = collection.addOne({ name: "foo" }); expect(r1.id).toEqual(0); const r2 = collection.addOne({ name: "bar" }); expect(r2.id).toEqual(1); }); it("should refuse insertion with existing identifier", () => { const collection = new Collection([{ name: "foo" }]); expect(() => { collection.addOne({ id: 0, name: "bar" }); }).toThrow(new Error("An item with the identifier 0 already exists")); }); it("should accept insertion with non-existing identifier and move sequence accordingly", () => { const collection = new Collection(); collection.addOne({ name: "foo" }); collection.addOne({ id: 12, name: "bar" }); expect(collection.sequence).toEqual(13); const r = collection.addOne({ name: "bar" }); expect(r.id).toEqual(13); }); }); describe("updateOne", () => { it("should throw an exception when trying to update a non-existing item", () => { const collection = new Collection(); expect(() => { collection.updateOne(0, { id: 0, name: "bar" }); }).toThrow(new Error("No item with identifier 0")); }); it("should return the updated item", () => { const collection = new Collection([{ name: "foo" }]); expect(collection.updateOne(0, { id: 0, name: "bar" })).toEqual({ id: 0, name: "bar", }); }); it("should update the item", () => { const collection = new Collection([{ name: "foo" }, { name: "baz" }]); collection.updateOne(0, { id: 0, name: "bar" }); expect(collection.getOne(0)).toEqual({ id: 0, name: "bar" }); expect(collection.getOne(1)).toEqual({ id: 1, name: "baz" }); }); }); describe("removeOne", () => { it("should throw an exception when trying to remove a non-existing item", () => { const collection = new Collection(); expect(() => { collection.removeOne(0); }).toThrow(new Error("No item with identifier 0")); }); it("should remove the item", () => { const collection = new Collection(); const item = collection.addOne({ name: "foo" }); collection.removeOne(item.id); expect(collection.getAll()).toEqual([]); }); it("should return the removed item", () => { const collection = new Collection(); const item = collection.addOne({}); const r = collection.removeOne(item.id); expect(r).toEqual(item); }); it("should decrement the sequence only if the removed item is the last", () => { const collection = new Collection([{ id: 0 }, { id: 1 }, { id: 2 }]); expect(collection.sequence).toEqual(3); collection.removeOne(2); expect(collection.sequence).toEqual(2); collection.removeOne(0); expect(collection.sequence).toEqual(2); const r = collection.addOne({}); expect(r.id).toEqual(2); }); }); });
marmelab/FakeRest
src/Collection.spec.js
JavaScript
mit
28,068
"use strict"; var userUtils = require("../../lib/user-utils.js"); module.exports = function(core, config, store) { core.on("setstate", function(changes) { var future = store.with(changes), userId = future.get("user"), roomId = future.get("nav", "room"), mode = future.get("nav", "mode"), cta = future.get("app", "cta"), role = future.get("entities", roomId + "_" + userId, "role"), roomObj = future.getRoom(roomId); changes.app = changes.app || {}; if (roomObj === "missing") { changes.app.cta = null; } else if (userId && !userUtils.isGuest(userId) && ((/(visitor|none)/).test(role) || !role) && (/(chat|room)/).test(mode) && !(roomObj && roomObj.guides && roomObj.guides.authorizer && roomObj.guides.authorizer.openRoom === false)) { changes.app.cta = "follow"; } else if (cta === "follow") { changes.app.cta = null; } }, 400); };
metao1/chat
store/rules/ctaFollow.js
JavaScript
mit
884
export * from './achievement'; export * from './auth'; export * from './chatlinks'; export * from './forum'; export * from './help'; export * from './emotes'; export * from './rank'; export * from './test';
QuagganBooOOoot/gitter-bot
src/commands/index.js
JavaScript
mit
207
$(function() { var FADE_TIME = 150; // ms var TYPING_TIMER_LENGTH = 400; // ms var COLORS = [ '#e21400', '#91580f', '#f8a700', '#f78b00', '#58dc00', '#287b00', '#a8f07a', '#4ae8c4', '#3b88eb', '#3824aa', '#a700ff', '#d300e7' ]; // Initialize variables var $window = $(window); var $usernameInput = $('.usernameInput'); // Input for username var $messages = $('.messages'); // Messages area var $inputMessage = $('.inputMessage'); // Input message input box var $loginPage = $('.login.page'); // The login page var $chatPage = $('.chat.page'); // The chatroom page // Prompt for setting a username var username; var connected = false; var typing = false; var lastTypingTime; var $currentInput = $usernameInput.focus(); var socket = io(); function addParticipantsMessage (data) { var message = ''; if (data.numUsers === 1) { message += "there's 1 participant"; } else { message += "there are " + data.numUsers + " participants"; } log(message); } // Sets the client's username function setUsername () { username = cleanInput($usernameInput.val().trim()); // If the username is valid if (username) { $loginPage.fadeOut(); $chatPage.show(); $loginPage.off('click'); $currentInput = $inputMessage.focus(); // Tell the server your username socket.emit('add user', username); } } // Sends a chat message function sendMessage () { var message = $inputMessage.val(); // Prevent markup from being injected into the message message = cleanInput(message); // if there is a non-empty message and a socket connection if (message && connected) { $inputMessage.val(''); addChatMessage({ username: username, message: message }); // tell server to execute 'new message' and send along one parameter socket.emit('new message', message); } } // Log a message function log (message, options) { var $el = $('<li>').addClass('log').text(message); addMessageElement($el, options); } // Adds the visual chat message to the message list function addChatMessage (data, options) { // Don't fade the message in if there is an 'X was typing' var $typingMessages = getTypingMessages(data); options = options || {}; if ($typingMessages.length !== 0) { options.fade = false; $typingMessages.remove(); } var $usernameDiv = $('<span class="username"/>') .text(data.username) .css('color', getUsernameColor(data.username)); var $messageBodyDiv = $('<span class="messageBody">') .text(data.message); var typingClass = data.typing ? 'typing' : ''; var $messageDiv = $('<li class="message"/>') .data('username', data.username) .addClass(typingClass) .append($usernameDiv, $messageBodyDiv); addMessageElement($messageDiv, options); } // Adds the visual chat typing message function addChatTyping (data) { data.typing = true; data.message = 'is typing'; addChatMessage(data); } // Removes the visual chat typing message function removeChatTyping (data) { getTypingMessages(data).fadeOut(function () { $(this).remove(); }); } // Adds a message element to the messages and scrolls to the bottom // el - The element to add as a message // options.fade - If the element should fade-in (default = true) // options.prepend - If the element should prepend // all other messages (default = false) function addMessageElement (el, options) { var $el = $(el); // Setup default options if (!options) { options = {}; } if (typeof options.fade === 'undefined') { options.fade = true; } if (typeof options.prepend === 'undefined') { options.prepend = false; } // Apply options if (options.fade) { $el.hide().fadeIn(FADE_TIME); } if (options.prepend) { $messages.prepend($el); } else { $messages.append($el); } $messages[0].scrollTop = $messages[0].scrollHeight; } // Prevents input from having injected markup function cleanInput (input) { return $('<div/>').text(input).text(); } // Updates the typing event function updateTyping () { if (connected) { if (!typing) { typing = true; socket.emit('typing'); } lastTypingTime = (new Date()).getTime(); setTimeout(function () { var typingTimer = (new Date()).getTime(); var timeDiff = typingTimer - lastTypingTime; if (timeDiff >= TYPING_TIMER_LENGTH && typing) { socket.emit('stop typing'); typing = false; } }, TYPING_TIMER_LENGTH); } } // Gets the 'X is typing' messages of a user function getTypingMessages (data) { return $('.typing.message').filter(function (i) { return $(this).data('username') === data.username; }); } // Gets the color of a username through our hash function function getUsernameColor (username) { // Compute hash code var hash = 7; for (var i = 0; i < username.length; i++) { hash = username.charCodeAt(i) + (hash << 5) - hash; } // Calculate color var index = Math.abs(hash % COLORS.length); return COLORS[index]; } // Keyboard events $window.keydown(function (event) { // Auto-focus the current input when a key is typed if (!(event.ctrlKey || event.metaKey || event.altKey)) { $currentInput.focus(); } // When the client hits ENTER on their keyboard if (event.which === 13) { if (username) { sendMessage(); socket.emit('stop typing'); typing = false; } else { setUsername(); } } }); $inputMessage.on('input', function() { updateTyping(); }); // Click events // Focus input when clicking anywhere on login page $loginPage.click(function () { $currentInput.focus(); }); // Focus input when clicking on the message input's border $inputMessage.click(function () { $inputMessage.focus(); }); // Socket events // Whenever the server emits 'login', log the login message socket.on('login', function (data) { connected = true; // Display the welcome message var message = "Welcome to Socket.IO Chat – "; log(message, { prepend: true }); addParticipantsMessage(data); }); // Whenever the server emits 'new message', update the chat body socket.on('new message', function (data) { addChatMessage(data); }); // Whenever the server emits 'user joined', log it in the chat body socket.on('user joined', function (data) { log(data.username + ' joined'); addParticipantsMessage(data); }); // Whenever the server emits 'user left', log it in the chat body socket.on('user left', function (data) { log(data.username + ' left'); addParticipantsMessage(data); removeChatTyping(data); }); // Whenever the server emits 'typing', show the typing message socket.on('typing', function (data) { addChatTyping(data); }); // Whenever the server emits 'stop typing', kill the typing message socket.on('stop typing', function (data) { removeChatTyping(data); }); socket.on('disconnect', function () { log('you have been disconnected'); }); socket.on('reconnect', function () { log('you have been reconnected'); if (username) { socket.emit('add user', username); } }); socket.on('reconnect_error', function () { log('attempt to reconnect has failed'); }); });
garrulous-gorillas/garrulous-gorillas
client/src/components/chatview/mainSocket.js
JavaScript
mit
7,606
//////////////////////////////////////////////////////////////////// // // GENERATED CLASS // // DO NOT EDIT // // See sequelize-auto-ts for edits // //////////////////////////////////////////////////////////////////// var Sequelize = require('sequelize'); exports.initialized = false; exports.SEQUELIZE; /*__each__ tables */ exports.__tableName__; /*__each__ tables */ exports.__tableNameCamel__; /*__ignore__*/ var __defineFieldType__; /*__ignore__*/ var __primaryTableName__; /*__ignore__*/ var __foreignTableName__; /*__ignore__*/ var __firstTableName__; /*__ignore__*/ var __secondTableName__; /*__ignore__*/ var __associationNameQuoted__; function initialize(database, username, password, options) { if (exports.initialized) { return; } exports.SEQUELIZE = new Sequelize(database, username, password, options); /*__startEach__ tables */ exports.__tableName__ = exports.__tableNameCamel__ = exports.SEQUELIZE.define('__tableNameSingular__', { /*__each__ realDbFields, */ '__fieldName__': __defineFieldType__ }, { timestamps: false, classMethods: { get__tableNameSingular__: function (__tableNameSingularCamel__) { var where = {}; var id = parseInt(__tableNameSingularCamel__); if (isNaN(id)) { /*__each__ realDbFields */ if (__tableNameSingularCamel__['__fieldName__'] !== undefined) { where['__fieldName__'] = __tableNameSingularCamel__['__fieldName__']; } } else { where['__idFieldName__'] = id; } return exports.__tableName__.find({ where: where }); } } }); /*__endEach__*/ /*__startEach__ references */ __primaryTableName__.hasMany(__foreignTableName__, { foreignKey: '__foreignKey__' }); __foreignTableName__.belongsTo(__primaryTableName__, { as: __associationNameQuoted__, foreignKey: '__foreignKey__' }); /*__endEach__*/ /*__startEach__ xrefs */ __firstTableName__.hasMany(__secondTableName__, { through: '__xrefTableName__' }); __secondTableName__.hasMany(__firstTableName__, { through: '__xrefTableName__' }); /*__endEach__*/ return exports; } exports.initialize = initialize; //# sourceMappingURL=sequelize-models.js.map
samuelneff/sequelize-auto-ts
lib/sequelize-models.js
JavaScript
mit
2,421
import Vue from 'vue'; import Electron from 'vue-electron'; import Resource from 'vue-resource'; import Router from 'vue-router'; import KeenUI from 'keen-ui'; import 'keen-ui/dist/keen-ui.css'; import App from './App'; import routes from './routes'; Vue.use(Electron); Vue.use(Resource); Vue.use(Router); Vue.use(KeenUI); Vue.config.debug = true; const router = new Router({ scrollBehavior: () => ({ y: 0 }), routes, }); /* eslint-disable no-new */ new Vue({ router, ...App, }).$mount('#app');
Jack-Q/messenger
desktop/app/src/renderer/main.js
JavaScript
mit
508
'use strict' import Tea from './modules/tea.core.js' global.app = () => { return Tea; }
sologeek/tea
src/main.js
JavaScript
mit
91
version https://git-lfs.github.com/spec/v1 oid sha256:b7405262706997cffc865837cffd6bd9eb92a8f12c3da71795815fb2da9be9f6 size 2483
yogeshsaroya/new-cdnjs
ajax/libs/angular.js/1.4.0-beta.6/i18n/angular-locale_ss-za.js
JavaScript
mit
129
var Imap = require('imap'), MailParser = require('mailparser').MailParser, moment = require('moment') util = require('util'), events = require('events'); var SimpleImap = function(options) { this.options = options; this.imap = null; this.start = function() { if (this.imap === null) { this.imap = new Imap(this.options); var selfImap = this.imap, self = this; selfImap.on('ready', function() { self.emit('ready'); selfImap.openBox(self.options.mailbox, false, function() { self.emit('open'); }); }); selfImap.on('mail', function(num) { selfImap.search(['UNSEEN'], function(err, result) { if (result.length) { var f = selfImap.fetch(result, { markSeen: true, struct: true, bodies: '' }); f.on('message', function(msg, seqNo) { msg.on('body', function(stream, info) { var buffer = ''; stream.on('data', function(chunk) { buffer += chunk.toString('utf8'); }); stream.on('end', function() { var mailParser = new MailParser(); mailParser.on('end', function(mailObject) { self.emit('mail', { from: mailObject.from, subject: mailObject.subject, text: mailObject.text, html: mailObject.html, date: moment(mailObject.date).format('YYYY-MM-DD HH:mm:ss') }); }); mailParser.write(buffer); mailParser.end(); }); }); }); } }); }); selfImap.on('end', function() { self.emit('end'); }); selfImap.on('error', function(err) { self.emit('error', err); }); selfImap.on('close', function(hadError) { self.emit('close', hadError); }); } this.imap.connect(); } this.stop = function() { this.imap.destroy(); } this.restart = function() { this.stop(); if (arguments.length >= 1) this.options = arguments[0]; this.start(); } this.getImap = function() { return this.imap; } }; util.inherits(SimpleImap, events.EventEmitter); module.exports = SimpleImap
iwanjunaid/simple-imap
simple-imap.js
JavaScript
mit
2,114
/* Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.lang['nl'] = { "editor": "Tekstverwerker", "editorPanel": "Tekstverwerker beheerpaneel", "common": { "editorHelp": "Druk ALT 0 voor hulp", "browseServer": "Bladeren op server", "url": "URL", "protocol": "Protocol", "upload": "Upload", "uploadSubmit": "Naar server verzenden", "image": "Afbeelding", "flash": "Flash", "form": "Formulier", "checkbox": "Selectievinkje", "radio": "Keuzerondje", "textField": "Tekstveld", "textarea": "Tekstvak", "hiddenField": "Verborgen veld", "button": "Knop", "select": "Selectieveld", "imageButton": "Afbeeldingsknop", "notSet": "<niet ingevuld>", "id": "Id", "name": "Naam", "langDir": "Schrijfrichting", "langDirLtr": "Links naar rechts (LTR)", "langDirRtl": "Rechts naar links (RTL)", "langCode": "Taalcode", "longDescr": "Lange URL-omschrijving", "cssClass": "Stylesheet-klassen", "advisoryTitle": "Adviserende titel", "cssStyle": "Stijl", "ok": "OK", "cancel": "Annuleren", "close": "Sluiten", "preview": "Voorbeeld", "resize": "Sleep om te herschalen", "generalTab": "Algemeen", "advancedTab": "Geavanceerd", "validateNumberFailed": "Deze waarde is geen geldig getal.", "confirmNewPage": "Alle aangebrachte wijzigingen gaan verloren. Weet u zeker dat u een nieuwe pagina wilt openen?", "confirmCancel": "Enkele opties zijn gewijzigd. Weet u zeker dat u dit dialoogvenster wilt sluiten?", "options": "Opties", "target": "Doelvenster", "targetNew": "Nieuw venster (_blank)", "targetTop": "Hele venster (_top)", "targetSelf": "Zelfde venster (_self)", "targetParent": "Origineel venster (_parent)", "langDirLTR": "Links naar rechts (LTR)", "langDirRTL": "Rechts naar links (RTL)", "styles": "Stijl", "cssClasses": "Stylesheet-klassen", "width": "Breedte", "height": "Hoogte", "align": "Uitlijning", "alignLeft": "Links", "alignRight": "Rechts", "alignCenter": "Centreren", "alignJustify": "Uitvullen", "alignTop": "Boven", "alignMiddle": "Midden", "alignBottom": "Onder", "alignNone": "Geen", "invalidValue": "Ongeldige waarde.", "invalidHeight": "De hoogte moet een getal zijn.", "invalidWidth": "De breedte moet een getal zijn.", "invalidCssLength": "Waarde in veld \"%1\" moet een positief nummer zijn, met of zonder een geldige CSS meeteenheid (px, %, in, cm, mm, em, ex, pt of pc).", "invalidHtmlLength": "Waarde in veld \"%1\" moet een positief nummer zijn, met of zonder een geldige HTML meeteenheid (px of %).", "invalidInlineStyle": "Waarde voor de online stijl moet bestaan uit een of meerdere tupels met het formaat \"naam : waarde\", gescheiden door puntkomma's.", "cssLengthTooltip": "Geef een nummer in voor een waarde in pixels of geef een nummer in met een geldige CSS eenheid (px, %, in, cm, mm, em, ex, pt, of pc).", "unavailable": "%1<span class=\"cke_accessibility\">, niet beschikbaar</span>" }, "about": { "copy": "Copyright &copy; $1. Alle rechten voorbehouden.", "dlgTitle": "Over CKEditor", "help": "Bekijk de $1 voor hulp.", "moreInfo": "Bezoek onze website voor licentieinformatie:", "title": "Over CKEditor", "userGuide": "CKEditor gebruiksaanwijzing" }, "basicstyles": { "bold": "Vet", "italic": "Cursief", "strike": "Doorhalen", "subscript": "Subscript", "superscript": "Superscript", "underline": "Onderstrepen" }, "bidi": {"ltr": "Schrijfrichting van links naar rechts", "rtl": "Schrijfrichting van rechts naar links"}, "blockquote": {"toolbar": "Citaatblok"}, "clipboard": { "copy": "Kopiëren", "copyError": "De beveiligingsinstelling van de browser verhinderen het automatisch kopiëren. Gebruik de sneltoets Ctrl/Cmd+C van het toetsenbord.", "cut": "Knippen", "cutError": "De beveiligingsinstelling van de browser verhinderen het automatisch knippen. Gebruik de sneltoets Ctrl/Cmd+X van het toetsenbord.", "paste": "Plakken", "pasteArea": "Plakgebied", "pasteMsg": "Plak de tekst in het volgende vak gebruikmakend van uw toetsenbord (<strong>Ctrl/Cmd+V</strong>) en klik op OK.", "securityMsg": "Door de beveiligingsinstellingen van uw browser is het niet mogelijk om direct vanuit het klembord in de editor te plakken. Middels opnieuw plakken in dit venster kunt u de tekst alsnog plakken in de editor.", "title": "Plakken" }, "button": {"selectedLabel": "%1 (Geselecteerd)"}, "colorbutton": { "auto": "Automatisch", "bgColorTitle": "Achtergrondkleur", "colors": { "000": "Zwart", "800000": "Kastanjebruin", "8B4513": "Chocoladebruin", "2F4F4F": "Donkerleigrijs", "008080": "Blauwgroen", "000080": "Marine", "4B0082": "Indigo", "696969": "Donkergrijs", "B22222": "Baksteen", "A52A2A": "Bruin", "DAA520": "Donkergeel", "006400": "Donkergroen", "40E0D0": "Turquoise", "0000CD": "Middenblauw", "800080": "Paars", "808080": "Grijs", "F00": "Rood", "FF8C00": "Donkeroranje", "FFD700": "Goud", "008000": "Groen", "0FF": "Cyaan", "00F": "Blauw", "EE82EE": "Violet", "A9A9A9": "Donkergrijs", "FFA07A": "Lichtzalm", "FFA500": "Oranje", "FFFF00": "Geel", "00FF00": "Felgroen", "AFEEEE": "Lichtturquoise", "ADD8E6": "Lichtblauw", "DDA0DD": "Pruim", "D3D3D3": "Lichtgrijs", "FFF0F5": "Linnen", "FAEBD7": "Ivoor", "FFFFE0": "Lichtgeel", "F0FFF0": "Honingdauw", "F0FFFF": "Azuur", "F0F8FF": "Licht hemelsblauw", "E6E6FA": "Lavendel", "FFF": "Wit" }, "more": "Meer kleuren...", "panelTitle": "Kleuren", "textColorTitle": "Tekstkleur" }, "colordialog": { "clear": "Wissen", "highlight": "Actief", "options": "Kleuropties", "selected": "Geselecteerde kleur", "title": "Selecteer kleur" }, "templates": { "button": "Sjablonen", "emptyListMsg": "(Geen sjablonen gedefinieerd)", "insertOption": "Vervang de huidige inhoud", "options": "Template opties", "selectPromptMsg": "Selecteer het sjabloon dat in de editor geopend moet worden (de actuele inhoud gaat verloren):", "title": "Inhoud sjablonen" }, "contextmenu": {"options": "Contextmenu opties"}, "div": { "IdInputLabel": "Id", "advisoryTitleInputLabel": "Adviserende titel", "cssClassInputLabel": "Stylesheet klassen", "edit": "Div wijzigen", "inlineStyleInputLabel": "Inline stijl", "langDirLTRLabel": "Links naar rechts (LTR)", "langDirLabel": "Schrijfrichting", "langDirRTLLabel": "Rechts naar links (RTL)", "languageCodeInputLabel": " Taalcode", "remove": "Div verwijderen", "styleSelectLabel": "Stijl", "title": "Div aanmaken", "toolbar": "Div aanmaken" }, "toolbar": { "toolbarCollapse": "Werkbalk inklappen", "toolbarExpand": "Werkbalk uitklappen", "toolbarGroups": { "document": "Document", "clipboard": "Klembord/Ongedaan maken", "editing": "Bewerken", "forms": "Formulieren", "basicstyles": "Basisstijlen", "paragraph": "Paragraaf", "links": "Links", "insert": "Invoegen", "styles": "Stijlen", "colors": "Kleuren", "tools": "Toepassingen" }, "toolbars": "Werkbalken" }, "elementspath": {"eleLabel": "Elementenpad", "eleTitle": "%1 element"}, "find": { "find": "Zoeken", "findOptions": "Zoekopties", "findWhat": "Zoeken naar:", "matchCase": "Hoofdlettergevoelig", "matchCyclic": "Doorlopend zoeken", "matchWord": "Hele woord moet voorkomen", "notFoundMsg": "De opgegeven tekst is niet gevonden.", "replace": "Vervangen", "replaceAll": "Alles vervangen", "replaceSuccessMsg": "%1 resultaten vervangen.", "replaceWith": "Vervangen met:", "title": "Zoeken en vervangen" }, "fakeobjects": { "anchor": "Interne link", "flash": "Flash animatie", "hiddenfield": "Verborgen veld", "iframe": "IFrame", "unknown": "Onbekend object" }, "flash": { "access": "Script toegang", "accessAlways": "Altijd", "accessNever": "Nooit", "accessSameDomain": "Zelfde domeinnaam", "alignAbsBottom": "Absoluut-onder", "alignAbsMiddle": "Absoluut-midden", "alignBaseline": "Basislijn", "alignTextTop": "Boven tekst", "bgcolor": "Achtergrondkleur", "chkFull": "Schermvullend toestaan", "chkLoop": "Herhalen", "chkMenu": "Flashmenu's inschakelen", "chkPlay": "Automatisch afspelen", "flashvars": "Variabelen voor Flash", "hSpace": "HSpace", "properties": "Eigenschappen Flash", "propertiesTab": "Eigenschappen", "quality": "Kwaliteit", "qualityAutoHigh": "Automatisch hoog", "qualityAutoLow": "Automatisch laag", "qualityBest": "Beste", "qualityHigh": "Hoog", "qualityLow": "Laag", "qualityMedium": "Gemiddeld", "scale": "Schaal", "scaleAll": "Alles tonen", "scaleFit": "Precies passend", "scaleNoBorder": "Geen rand", "title": "Eigenschappen Flash", "vSpace": "VSpace", "validateHSpace": "De HSpace moet een getal zijn.", "validateSrc": "De URL mag niet leeg zijn.", "validateVSpace": "De VSpace moet een getal zijn.", "windowMode": "Venster modus", "windowModeOpaque": "Ondoorzichtig", "windowModeTransparent": "Doorzichtig", "windowModeWindow": "Venster" }, "font": { "fontSize": {"label": "Lettergrootte", "voiceLabel": "Lettergrootte", "panelTitle": "Lettergrootte"}, "label": "Lettertype", "panelTitle": "Lettertype", "voiceLabel": "Lettertype" }, "forms": { "button": { "title": "Eigenschappen knop", "text": "Tekst (waarde)", "type": "Soort", "typeBtn": "Knop", "typeSbm": "Versturen", "typeRst": "Leegmaken" }, "checkboxAndRadio": { "checkboxTitle": "Eigenschappen aanvinkvakje", "radioTitle": "Eigenschappen selectievakje", "value": "Waarde", "selected": "Geselecteerd", "required": "Vereist" }, "form": { "title": "Eigenschappen formulier", "menu": "Eigenschappen formulier", "action": "Actie", "method": "Methode", "encoding": "Codering" }, "hidden": {"title": "Eigenschappen verborgen veld", "name": "Naam", "value": "Waarde"}, "select": { "title": "Eigenschappen selectieveld", "selectInfo": "Informatie", "opAvail": "Beschikbare opties", "value": "Waarde", "size": "Grootte", "lines": "Regels", "chkMulti": "Gecombineerde selecties toestaan", "required": "Vereist", "opText": "Tekst", "opValue": "Waarde", "btnAdd": "Toevoegen", "btnModify": "Wijzigen", "btnUp": "Omhoog", "btnDown": "Omlaag", "btnSetValue": "Als geselecteerde waarde instellen", "btnDelete": "Verwijderen" }, "textarea": {"title": "Eigenschappen tekstvak", "cols": "Kolommen", "rows": "Rijen"}, "textfield": { "title": "Eigenschappen tekstveld", "name": "Naam", "value": "Waarde", "charWidth": "Breedte (tekens)", "maxChars": "Maximum aantal tekens", "required": "Vereist", "type": "Soort", "typeText": "Tekst", "typePass": "Wachtwoord", "typeEmail": "E-mail", "typeSearch": "Zoeken", "typeTel": "Telefoonnummer", "typeUrl": "URL" } }, "format": { "label": "Opmaak", "panelTitle": "Opmaak", "tag_address": "Adres", "tag_div": "Normaal (DIV)", "tag_h1": "Kop 1", "tag_h2": "Kop 2", "tag_h3": "Kop 3", "tag_h4": "Kop 4", "tag_h5": "Kop 5", "tag_h6": "Kop 6", "tag_p": "Normaal", "tag_pre": "Met opmaak" }, "horizontalrule": {"toolbar": "Horizontale lijn invoegen"}, "iframe": { "border": "Framerand tonen", "noUrl": "Vul de IFrame URL in", "scrolling": "Scrollbalken inschakelen", "title": "IFrame-eigenschappen", "toolbar": "IFrame" }, "image": { "alt": "Alternatieve tekst", "border": "Rand", "btnUpload": "Naar server verzenden", "button2Img": "Wilt u de geselecteerde afbeeldingsknop vervangen door een eenvoudige afbeelding?", "hSpace": "HSpace", "img2Button": "Wilt u de geselecteerde afbeelding vervangen door een afbeeldingsknop?", "infoTab": "Informatie afbeelding", "linkTab": "Link", "lockRatio": "Afmetingen vergrendelen", "menu": "Eigenschappen afbeelding", "resetSize": "Afmetingen resetten", "title": "Eigenschappen afbeelding", "titleButton": "Eigenschappen afbeeldingsknop", "upload": "Upload", "urlMissing": "De URL naar de afbeelding ontbreekt.", "vSpace": "VSpace", "validateBorder": "Rand moet een heel nummer zijn.", "validateHSpace": "HSpace moet een heel nummer zijn.", "validateVSpace": "VSpace moet een heel nummer zijn." }, "indent": {"indent": "Inspringing vergroten", "outdent": "Inspringing verkleinen"}, "smiley": {"options": "Smiley opties", "title": "Smiley invoegen", "toolbar": "Smiley"}, "justify": {"block": "Uitvullen", "center": "Centreren", "left": "Links uitlijnen", "right": "Rechts uitlijnen"}, "language": {"button": "Taal instellen", "remove": "Taal verwijderen"}, "link": { "acccessKey": "Toegangstoets", "advanced": "Geavanceerd", "advisoryContentType": "Aanbevolen content-type", "advisoryTitle": "Adviserende titel", "anchor": { "toolbar": "Interne link", "menu": "Eigenschappen interne link", "title": "Eigenschappen interne link", "name": "Naam interne link", "errorName": "Geef de naam van de interne link op", "remove": "Interne link verwijderen" }, "anchorId": "Op kenmerk interne link", "anchorName": "Op naam interne link", "charset": "Karakterset van gelinkte bron", "cssClasses": "Stylesheet-klassen", "emailAddress": "E-mailadres", "emailBody": "Inhoud bericht", "emailSubject": "Onderwerp bericht", "id": "Id", "info": "Linkomschrijving", "langCode": "Taalcode", "langDir": "Schrijfrichting", "langDirLTR": "Links naar rechts (LTR)", "langDirRTL": "Rechts naar links (RTL)", "menu": "Link wijzigen", "name": "Naam", "noAnchors": "(Geen interne links in document gevonden)", "noEmail": "Geef een e-mailadres", "noUrl": "Geef de link van de URL", "other": "<ander>", "popupDependent": "Afhankelijk (Netscape)", "popupFeatures": "Instellingen popupvenster", "popupFullScreen": "Volledig scherm (IE)", "popupLeft": "Positie links", "popupLocationBar": "Locatiemenu", "popupMenuBar": "Menubalk", "popupResizable": "Herschaalbaar", "popupScrollBars": "Schuifbalken", "popupStatusBar": "Statusbalk", "popupToolbar": "Werkbalk", "popupTop": "Positie boven", "rel": "Relatie", "selectAnchor": "Kies een interne link", "styles": "Stijl", "tabIndex": "Tabvolgorde", "target": "Doelvenster", "targetFrame": "<frame>", "targetFrameName": "Naam doelframe", "targetPopup": "<popupvenster>", "targetPopupName": "Naam popupvenster", "title": "Link", "toAnchor": "Interne link in pagina", "toEmail": "E-mail", "toUrl": "URL", "toolbar": "Link invoegen/wijzigen", "type": "Linktype", "unlink": "Link verwijderen", "upload": "Upload" }, "list": {"bulletedlist": "Opsomming invoegen", "numberedlist": "Genummerde lijst invoegen"}, "liststyle": { "armenian": "Armeense nummering", "bulletedTitle": "Eigenschappen lijst met opsommingstekens", "circle": "Cirkel", "decimal": "Cijfers (1, 2, 3, etc.)", "decimalLeadingZero": "Cijfers beginnen met nul (01, 02, 03, etc.)", "disc": "Schijf", "georgian": "Georgische nummering (an, ban, gan, etc.)", "lowerAlpha": "Kleine letters (a, b, c, d, e, etc.)", "lowerGreek": "Grieks kleine letters (alpha, beta, gamma, etc.)", "lowerRoman": "Romeins kleine letters (i, ii, iii, iv, v, etc.)", "none": "Geen", "notset": "<niet gezet>", "numberedTitle": "Eigenschappen genummerde lijst", "square": "Vierkant", "start": "Start", "type": "Type", "upperAlpha": "Hoofdletters (A, B, C, D, E, etc.)", "upperRoman": "Romeinse hoofdletters (I, II, III, IV, V, etc.)", "validateStartNumber": "Startnummer van de lijst moet een heel nummer zijn." }, "magicline": {"title": "Hier paragraaf invoeren"}, "maximize": {"maximize": "Maximaliseren", "minimize": "Minimaliseren"}, "newpage": {"toolbar": "Nieuwe pagina"}, "pagebreak": {"alt": "Pagina-einde", "toolbar": "Pagina-einde invoegen"}, "pastetext": {"button": "Plakken als platte tekst", "title": "Plakken als platte tekst"}, "pastefromword": { "confirmCleanup": "De tekst die u wilt plakken lijkt gekopieerd te zijn vanuit Word. Wilt u de tekst opschonen voordat deze geplakt wordt?", "error": "Het was niet mogelijk om de geplakte tekst op te schonen door een interne fout", "title": "Plakken vanuit Word", "toolbar": "Plakken vanuit Word" }, "preview": {"preview": "Voorbeeld"}, "print": {"toolbar": "Afdrukken"}, "removeformat": {"toolbar": "Opmaak verwijderen"}, "save": {"toolbar": "Opslaan"}, "selectall": {"toolbar": "Alles selecteren"}, "showblocks": {"toolbar": "Toon blokken"}, "sourcearea": {"toolbar": "Broncode"}, "specialchar": { "options": "Speciale tekens opties", "title": "Selecteer speciaal teken", "toolbar": "Speciaal teken invoegen" }, "scayt": { "btn_about": "Over SCAYT", "btn_dictionaries": "Woordenboeken", "btn_disable": "SCAYT uitschakelen", "btn_enable": "SCAYT inschakelen", "btn_langs": "Talen", "btn_options": "Opties", "text_title": "Controleer de spelling tijdens het typen" }, "stylescombo": { "label": "Stijl", "panelTitle": "Opmaakstijlen", "panelTitle1": "Blok stijlen", "panelTitle2": "Inline stijlen", "panelTitle3": "Object stijlen" }, "table": { "border": "Randdikte", "caption": "Onderschrift", "cell": { "menu": "Cel", "insertBefore": "Voeg cel in voor", "insertAfter": "Voeg cel in na", "deleteCell": "Cellen verwijderen", "merge": "Cellen samenvoegen", "mergeRight": "Voeg samen naar rechts", "mergeDown": "Voeg samen naar beneden", "splitHorizontal": "Splits cel horizontaal", "splitVertical": "Splits cel vertikaal", "title": "Celeigenschappen", "cellType": "Celtype", "rowSpan": "Rijen samenvoegen", "colSpan": "Kolommen samenvoegen", "wordWrap": "Automatische terugloop", "hAlign": "Horizontale uitlijning", "vAlign": "Verticale uitlijning", "alignBaseline": "Tekstregel", "bgColor": "Achtergrondkleur", "borderColor": "Randkleur", "data": "Gegevens", "header": "Kop", "yes": "Ja", "no": "Nee", "invalidWidth": "De celbreedte moet een getal zijn.", "invalidHeight": "De celhoogte moet een getal zijn.", "invalidRowSpan": "Rijen samenvoegen moet een heel getal zijn.", "invalidColSpan": "Kolommen samenvoegen moet een heel getal zijn.", "chooseColor": "Kies" }, "cellPad": "Celopvulling", "cellSpace": "Celafstand", "column": { "menu": "Kolom", "insertBefore": "Voeg kolom in voor", "insertAfter": "Voeg kolom in na", "deleteColumn": "Kolommen verwijderen" }, "columns": "Kolommen", "deleteTable": "Tabel verwijderen", "headers": "Koppen", "headersBoth": "Beide", "headersColumn": "Eerste kolom", "headersNone": "Geen", "headersRow": "Eerste rij", "invalidBorder": "De randdikte moet een getal zijn.", "invalidCellPadding": "Celopvulling moet een getal zijn.", "invalidCellSpacing": "Celafstand moet een getal zijn.", "invalidCols": "Het aantal kolommen moet een getal zijn groter dan 0.", "invalidHeight": "De tabelhoogte moet een getal zijn.", "invalidRows": "Het aantal rijen moet een getal zijn groter dan 0.", "invalidWidth": "De tabelbreedte moet een getal zijn.", "menu": "Tabeleigenschappen", "row": { "menu": "Rij", "insertBefore": "Voeg rij in voor", "insertAfter": "Voeg rij in na", "deleteRow": "Rijen verwijderen" }, "rows": "Rijen", "summary": "Samenvatting", "title": "Tabeleigenschappen", "toolbar": "Tabel", "widthPc": "procent", "widthPx": "pixels", "widthUnit": "eenheid breedte" }, "undo": {"redo": "Opnieuw uitvoeren", "undo": "Ongedaan maken"}, "wsc": { "btnIgnore": "Negeren", "btnIgnoreAll": "Alles negeren", "btnReplace": "Vervangen", "btnReplaceAll": "Alles vervangen", "btnUndo": "Ongedaan maken", "changeTo": "Wijzig in", "errorLoading": "Er is een fout opgetreden bij het laden van de dienst: %s.", "ieSpellDownload": "De spellingscontrole is niet geïnstalleerd. Wilt u deze nu downloaden?", "manyChanges": "Klaar met spellingscontrole: %1 woorden aangepast", "noChanges": "Klaar met spellingscontrole: geen woorden aangepast", "noMispell": "Klaar met spellingscontrole: geen fouten gevonden", "noSuggestions": "- Geen suggesties -", "notAvailable": "Excuses, deze dienst is momenteel niet beschikbaar.", "notInDic": "Niet in het woordenboek", "oneChange": "Klaar met spellingscontrole: één woord aangepast", "progress": "Bezig met spellingscontrole...", "title": "Spellingscontrole", "toolbar": "Spellingscontrole" } };
sejen/abssh
web/static/js/ckeditor/lang/nl.js
JavaScript
mit
24,274
/** * Connections * * `Connections` are like "saved settings" for your adapters. What's the difference between * a connection and an adapter, you might ask? An adapter (e.g. `sails-mysql`) is generic-- * it needs some additional information to work (e.g. your database host, password, user, etc.) * A `connection` is that additional information. * * Each model must have a `connection` property (a string) which is references the name of one * of these connections. If it doesn't, the default `connection` configured in `config/models.js` * will be applied. Of course, a connection can (and usually is) shared by multiple models. * . * Note: If you're using version control, you should put your passwords/api keys * in `config/local.js`, environment variables, or use another strategy. * (this is to prevent you inadvertently sensitive credentials up to your repository.) * * For more information on configuration, check out: * http://links.sailsjs.org/docs/config/connections */ module.exports.connections = { // Local disk storage for DEVELOPMENT ONLY // // Installed by default. // localDiskDb: { adapter: 'sails-disk' }, // MySQL is the world's most popular relational database. // http://en.wikipedia.org/wiki/MySQL // // Run: // npm install sails-mysql // someMysqlServer: { adapter: 'sails-mysql', host: 'YOUR_MYSQL_SERVER_HOSTNAME_OR_IP_ADDRESS', user: 'YOUR_MYSQL_USER', password: 'YOUR_MYSQL_PASSWORD', database: 'YOUR_MYSQL_DB' }, // MongoDB is the leading NoSQL database. // http://en.wikipedia.org/wiki/MongoDB // // Run: // npm install sails-mongo // mongodb: { adapter: 'sails-mongo', host: 'localhost', port: 27017, user: '', password: '', database: 'nhop' }, // PostgreSQL is another officially supported relational database. // http://en.wikipedia.org/wiki/PostgreSQL // // Run: // npm install sails-postgresql // somePostgresqlServer: { adapter: 'sails-postgresql', host: 'YOUR_POSTGRES_SERVER_HOSTNAME_OR_IP_ADDRESS', user: 'YOUR_POSTGRES_USER', password: 'YOUR_POSTGRES_PASSWORD', database: 'YOUR_POSTGRES_DB' } // More adapters: // https://github.com/balderdashy/sails };
durgesh-priyaranjan/nhop
config/connections.js
JavaScript
mit
2,190
'use strict'; var Axes = require('../../plots/cartesian/axes'); module.exports = function formatLabels(cdi, trace, fullLayout) { var labels = {}; var mockGd = {_fullLayout: fullLayout}; var xa = Axes.getFromTrace(mockGd, trace, 'x'); var ya = Axes.getFromTrace(mockGd, trace, 'y'); labels.xLabel = Axes.tickText(xa, xa.c2l(cdi.x), true).text; labels.yLabel = Axes.tickText(ya, ya.c2l(cdi.y), true).text; return labels; };
plotly/plotly.js
src/traces/scatter/format_labels.js
JavaScript
mit
455
var app = angular.module('AtWork', [ 'atwork.system', 'atwork.users', 'atwork.posts', 'atwork.streams', 'atwork.chats', 'atwork.activities', 'atwork.notifications', 'atwork.settings', 'ngMaterial']); app.controller('AppCtrl', [ '$scope', '$route', '$rootScope', '$mdSidenav', '$mdBottomSheet', '$location', '$timeout', 'appLocation', 'appAuth', 'appWebSocket', 'appSettings', 'appSettingsValid', 'appToast', function($scope, $route, $rootScope, $mdSidenav, $mdBottomSheet, $location, $timeout, appLocation, appAuth, appWebSocket, appSettings, appSettingsValid, appToast) { $scope.barTitle = ''; $scope.search = ''; $scope.toggleSidenav = function(menuId) { $mdSidenav(menuId).toggle(); }; $scope.updateLoginStatus = function() { $scope.isLoggedIn = appAuth.isLoggedIn(); $scope.user = appAuth.getUser(); }; $scope.goHome = function() { appLocation.url('/'); }; $scope.showUserActions = function($event) { $mdBottomSheet.show({ templateUrl: '/modules/users/views/user-list.html', controller: 'UserSheet', targetEvent: $event }).then(function(clickedItem) { $scope.alert = clickedItem.name + ' clicked!'; }); }; var initiateSettings = function(cb) { appSettings.fetch(function(settings) { $rootScope.systemSettings = settings; if (cb) { cb(); } }); }; /** * Scroll the view to top on route change */ $scope.$on('$routeChangeSuccess', function() { angular.element('*[md-scroll-y]').animate({scrollTop: 0}, 300); $mdSidenav('left').close(); }); $scope.$on('loggedIn', function() { $scope.updateLoginStatus(); $scope.barTitle = ''; $scope.$broadcast('updateNotifications'); appWebSocket.conn.emit('online', {token: appAuth.getToken()}); appAuth.refreshUser(function(user) { $scope.user = user; }); /** * Fetch settings and get the app ready */ initiateSettings(function() { $scope.$on('$routeChangeStart', function (event, toState) { var valid = appSettingsValid(); if (!valid) { appToast('Please complete the setup first.'); } }); $scope.appReady = true; $scope.barTitle = $rootScope.systemSettings.tagline; $timeout(appSettingsValid); }); }); $scope.$on('loggedOut', function() { $scope.updateLoginStatus(); appWebSocket.conn.emit('logout', {token: appAuth.getToken()}); }); appWebSocket.conn.on('connect', function() { if (appAuth.isLoggedIn()) { appWebSocket.conn.emit('online', {token: appAuth.getToken()}); } }); $scope.updateLoginStatus(); $timeout(function() { if (!appAuth.isLoggedIn()) { if (window.location.href.indexOf('/activate/') == -1 && window.location.href.indexOf('/changePassword/') == -1) { appLocation.url('/login'); } initiateSettings(); $scope.appReady = true; } else { $scope.barTitle = ''; $scope.$broadcast('loggedIn'); } }); } ]);
richh93/atwork
public/app.js
JavaScript
mit
3,244
// All material copyright ESRI, All Rights Reserved, unless otherwise specified. // See https://js.arcgis.com/4.16/esri/copyright.txt for details. //>>built define("require exports ../../../../core/Logger ../../../../core/libs/gl-matrix-2/vec2f64 ../../../../core/libs/gl-matrix-2/vec3 ../../../../core/libs/gl-matrix-2/vec4 ../../../../core/libs/gl-matrix-2/vec4f64 ../../support/imageUtils ./DefaultTextureUnits ./glUtil3D ./SSAOTechnique ./Util ../../../webgl/FramebufferObject ../../../webgl/Texture ../../../webgl/Util".split(" "),function(w,r,x,y,z,A,t,B,C,u,p,v,q,D,m){var E=x.getLogger("esri.views.3d.webgl-engine.lib.SSAOHelper");r=function(){function b(a, d,b){this._enabled=!1;this._BLUR_F=2;this._attenuation=.5;this._radius=3;this._samples=16;this._viewportToRestore=t.vec4f64.create();this._rctx=d;this._techniqueRep=a;this._requestRender=b;this._ssaoTechniqueConfig=new p.SSAOTechniqueConfiguration;this._emptyTexture=u.createColorTexture(d,[1,1,1,1])}b.prototype.dispose=function(){this._emptyTexture.dispose();this._emptyTexture=null};Object.defineProperty(b.prototype,"isSupported",{get:function(){var a=this._rctx,d=-1!==a.parameters.versionString.indexOf("WebGL 0.93"), a=-1!==a.parameters.versionString.indexOf("WebGL 0.94");return!(d||a)},enumerable:!0,configurable:!0});Object.defineProperty(b.prototype,"enabled",{get:function(){return this._enabled},set:function(a){a?this.enable():this.disable()},enumerable:!0,configurable:!0});Object.defineProperty(b.prototype,"attenuation",{get:function(){return this._attenuation},set:function(a){this._attenuation=a},enumerable:!0,configurable:!0});Object.defineProperty(b.prototype,"radius",{get:function(){return this._radius}, set:function(a){this._radius=a},enumerable:!0,configurable:!0});Object.defineProperty(b.prototype,"filterRadius",{get:function(){return 4},enumerable:!0,configurable:!0});Object.defineProperty(b.prototype,"samples",{get:function(){return this._samples},set:function(a){this._samples=a;this._enabled&&this.selectPrograms()},enumerable:!0,configurable:!0});b.prototype.computeSSAO=function(a,d,b){if(this._noiseTexture){v.assert(this.enabled);var c=this._rctx,l=a.fullViewport,e=l[2],g=l[3],l=e/this._BLUR_F, k=g/this._BLUR_F;this._ssaoFBO.resize(e,g);this._blur0FBO.resize(l,k);this._blur1FBO.resize(l,k);l=1*e;k=1*g;c.bindFramebuffer(this._ssaoFBO);A.vec4.copy(this._viewportToRestore,a.fullViewport);c.setViewport(0,0,e,g);var f=this._ssaoTechnique.program,h=this._blurTechnique.program;c.bindProgram(f);c.setPipelineState(this._ssaoTechnique.pipeline);f.setUniform2f("rnmScale",e/this._noiseTexture.descriptor.width,g/this._noiseTexture.descriptor.height);f.setUniform3fv("pSphere",8>=this._samples?this._data.random8: 16>=this._samples?this._data.random16:32>=this._samples?this._data.random32:this._data.random64);e=this._data.minDiscrepancy;f.setUniform1f("numSpiralTurns",this._samples<e.length?e[this._samples]:5779);e=F;g=G;v.inverseProjectionInfo(a.projectionMatrix,a.fullWidth,a.fullHeight,e,g);f.setUniform4fv("projInfo",e);f.setUniform2fv("zScale",g);f.setUniform2f("nearFar",a.near,a.far);e=1/a.computeRenderPixelSizeAtDist(1);f.setUniform1f("projScale",1*e);f.setUniform2f("screenDimensions",l,k);var n=2*this._radius, g=z.vec3.distance(a.eye,a.center),n=20*a.computeRenderPixelSizeAtDist(g),n=Math.max(.1,n);f.setUniform1f("radius",n);f.setUniform1f("intensity",4*this._attenuation/Math.pow(n,6));f.setUniform1i("rnm",0);f.setUniform1i("normalMap",1);f.setUniform1i("depthMap",2);c.bindTexture(this._noiseTexture,0);c.bindTexture(b,1);c.bindTexture(d,2);d=u.createQuadVAO(this._rctx);c.bindVAO(d);c.drawArrays(5,0,m.vertexCount(d,"geometry"));c.bindTexture(this._ssaoFBO.colorTexture,0);c.setViewport(0,0,l/this._BLUR_F, k/this._BLUR_F);c.bindFramebuffer(this._blur0FBO);c.bindProgram(h);h.setUniform2f("screenDimensions",l,k);h.setUniform1i("tex",0);h.setUniform1i("normalMap",1);h.setUniform1i("depthMap",2);h.setUniform2f("blurSize",0,1*this._BLUR_F/k);h.setUniform1i("radius",4);h.setUniform1f("g_BlurFalloff",.08);h.setUniform2f("nearFar",a.near,a.far);5E4<g&&(e=Math.max(0,e-(g-5E4)));h.setUniform1f("projScale",e);h.setUniform2f("zScale",1,0);c.drawArrays(5,0,m.vertexCount(d,"geometry"));h.setUniform2f("blurSize", 1*this._BLUR_F/l,0);c.bindFramebuffer(this._blur1FBO);c.bindTexture(this._blur0FBO.colorTexture,0);c.drawArrays(5,0,m.vertexCount(d,"geometry"));c.setViewport(this._viewportToRestore[0],this._viewportToRestore[1],this._viewportToRestore[2],this._viewportToRestore[3])}};b.prototype.setUniforms=function(a,d){var b=this.enabled&&this._noiseTexture,c=this._rctx;c.bindTexture(b?this._blur1FBO.colorTexture:this._emptyTexture,d);c.setActiveTexture(0);a.setUniform1i("ssaoTex",d);b?a.setUniform4f("viewportPixelSz", this._viewportToRestore[0],this._viewportToRestore[1],1/this._ssaoFBO.width,1/this._ssaoFBO.height):a.setUniform4f("viewportPixelSz",-1,-1,-1,-1)};b.prototype.bindToAllPrograms=function(a){a=a.getProgramsUsingUniform("viewportPixelSz");for(var b=0;b<a.length;b++)this.setUniforms(a[b],C.DefaultTextureUnits.SSAO)};b.prototype.selectPrograms=function(){this._ssaoTechniqueConfig.samples=8>=this._samples?8:16>=this._samples?16:32>=this._samples?32:64;this._ssaoTechniqueConfig.radius=4;this._ssaoTechniqueConfig.output= 0;this._ssaoTechnique=this._techniqueRep.acquireAndReleaseExisting(p.SSAOTechnique,this._ssaoTechniqueConfig,this._ssaoTechnique);this._ssaoTechniqueConfig.output=1;this._blurTechnique=this._techniqueRep.acquireAndReleaseExisting(p.SSAOTechnique,this._ssaoTechniqueConfig,this._blurTechnique)};b.prototype.enable=function(){var a=this;this.enabled||(this.isSupported?(this._enabled=!0,this.loadResources(function(){a._enabled&&a.initialize()})):E.warn("SSAO is not supported for this browser or hardware"))}; b.prototype.loadResources=function(a){var b=this;this._data?a():w(["./SSAOHelperData"],function(d){b._data=d;a()})};b.prototype.initialize=function(){var a=this,b={target:3553,pixelFormat:6408,dataType:5121,samplingMode:9729,wrapMode:33071,width:0,height:0},k={colorTarget:0,depthStencilTarget:0};this._ssaoFBO=new q(this._rctx,k,b);this._blur0FBO=new q(this._rctx,k,b);this._blur1FBO=new q(this._rctx,k,b);B.requestImage(this._data.noiseTexture).then(function(b){a._enabled&&(a._noiseTexture=new D(a._rctx, {target:3553,pixelFormat:6408,dataType:5121,hasMipmap:!0,width:b.width,height:b.height},b),a._requestRender())});this.selectPrograms()};b.prototype.disable=function(){this.enabled&&(this._enabled=!1,this._noiseTexture&&(this._noiseTexture.dispose(),this._noiseTexture=null),this._blur1FBO&&(this._blur1FBO.dispose(),this._blur1FBO=null),this._blur0FBO&&(this._blur0FBO.dispose(),this._blur0FBO=null),this._ssaoFBO&&(this._ssaoFBO.dispose(),this._ssaoFBO=null))};b.prototype.getGpuMemoryUsage=function(){return m.getGpuMemoryUsage(this._blur0FBO)+ m.getGpuMemoryUsage(this._blur1FBO)+m.getGpuMemoryUsage(this._ssaoFBO)};return b}();var G=y.vec2f64.create(),F=t.vec4f64.create();return r});
ycabon/presentations
2020-devsummit/arcgis-js-api-road-ahead/js-api/esri/views/3d/webgl-engine/lib/SSAOHelper.js
JavaScript
mit
6,969
version https://git-lfs.github.com/spec/v1 oid sha256:ad911cfe35ed2702a6023f24dac7e20b7b1d64e5583cd53411e87b5c10fa0c35 size 16080
yogeshsaroya/new-cdnjs
ajax/libs/yui/3.16.0/series-column/series-column-coverage.js
JavaScript
mit
130
function render(node){ console.log(node); }; export default render;
song940/vxapp
packages/render/index.js
JavaScript
mit
72
(function ($, _, Backbone, models) { "use strict"; models.Widget = Backbone.Model.extend({ defaults: { "name" : "Undefined name", "range" : '30-minutes', "update_interval": '10' }, url: function() { var tmp = "/api/dashboards/" + this.get("dashboard_id") + "/widgets"; if (this.isNew()) { return tmp; } else { return tmp + "/" + this.get("id"); } }, targetsString: function() { return (this.get("targets") || "").split(';'); } }); })($, _, Backbone, app.models);
mdkarp/team_dashboard_plugin
app/assets/javascripts/team_dashboard/models/widget.js
JavaScript
mit
576
XO.View.define({ pid:'home', vid:'page2', version:'20131209', cssHost:'body', init:function(){ XO.warn('View inited:'+this.id); } });
xsin/xo
demo/helloword/js/views/home/page2.js
JavaScript
mit
165
module.exports = function (app) { var colaboradorCtrl = app.controllers.colaborador; app.get('/colaborador', colaboradorCtrl.index); app.post('/buscar_colaborador', colaboradorCtrl.find); app.get('/buscar_colaborador_id/:id', colaboradorCtrl.buscarId); app.post('/editar_colaborador/:id', colaboradorCtrl.update); app.get('/remover_colaborador/:id', colaboradorCtrl.remove); app.post('/cadastrar_colaborador', colaboradorCtrl.insert); }
nathalialanzendorf/scalapp
routes/colaborador.js
JavaScript
mit
465
import arrayToObject from './array-to-object' describe('array to object', () => { it('takes an array of object and returns an object', () => { expect(arrayToObject([ { name: 'A', age: 30, food: 'pizza' }, { name: 'B', age: 40, food: 'pasta' } ], 'name')).toEqual({ A: { age: 30, food: 'pizza' }, B: { age: 40, food: 'pasta' } }) }) })
FranckCo/Operation-Explorer
src/utils/array-to-object.test.js
JavaScript
mit
397
const clone = require('lodash/clone'); const testHelpers = require('@quoin/node-test-helpers'); const BasicTypes = require('./basic-types'); const expect = testHelpers.expect; describe("lib/core/basic-types", () => { it("should export an object", () => { expect(BasicTypes).to.be.an('object'); }); it("should expose known properties", () => { const aClone = clone(BasicTypes); testHelpers.verifyProperties(aClone, 'string', [ 'Boolean', 'Date', 'File', 'Password', 'Number', 'String', 'Text' ]); testHelpers.verifyProperties(aClone, 'function', [ 'defaultValue', 'isValid', 'typesCheck' ]); expect(aClone).to.deep.equal({}); }); describe("isValid()", () => { const isValid = BasicTypes.isValid; it("should accept 1 param", () => { expect(isValid).to.have.lengthOf(1); }); it("should recognize an existing type", () => { expect(isValid(BasicTypes.String)).to.be.true(); }); it("should not recognize an invalid type", () => { expect(isValid('foobar')).to.be.false(); }); }); });
WarpWorks/warpjs
lib/core/basic-types.unit.test.js
JavaScript
mit
1,280
import React from 'react'; import { storiesOf } from '@storybook/react'; import { linkTo, hrefTo } from '@storybook/addon-links'; import LinkTo from '@storybook/addon-links/react'; import { action } from '@storybook/addon-actions'; storiesOf('Addons|Links.Link', module) .add('First', () => <LinkTo story="Second">Go to Second</LinkTo>) .add('Second', () => <LinkTo story="First">Go to First</LinkTo>); storiesOf('Addons|Links.Button', module) .add('First', () => ( <button onClick={linkTo('Addons|Links.Button', 'Second')}>Go to "Second"</button> )) .add('Second', () => ( <button onClick={linkTo('Addons|Links.Button', 'First')}>Go to "First"</button> )); storiesOf('Addons|Links.Select', module) .add('Index', () => ( <select value="Index" onChange={linkTo('Addons|Links.Select', e => e.currentTarget.value)}> <option>Index</option> <option>First</option> <option>Second</option> <option>Third</option> </select> )) .add('First', () => <LinkTo story="Index">Go back</LinkTo>) .add('Second', () => <LinkTo story="Index">Go back</LinkTo>) .add('Third', () => <LinkTo story="Index">Go back</LinkTo>); storiesOf('Addons|Links.Href', module).add('log', () => { hrefTo('Addons|Links.Href', 'log').then(href => action('URL of this story')({ href })); return <span>See action logger</span>; }); storiesOf('Addons|Links.Scroll position', module) .addDecorator(story => ( <React.Fragment> <div style={{ marginBottom: '100vh' }}>Scroll down to see the link</div> {story()} </React.Fragment> )) .add('First', () => <LinkTo story="Second">Go to Second</LinkTo>) .add('Second', () => <LinkTo story="First">Go to First</LinkTo>);
rhalff/storybook
examples/official-storybook/stories/addon-links.stories.js
JavaScript
mit
1,718
'use strict'; var app = angular.module('Fablab'); app.controller('GlobalConfigurationEditController', function ($scope,$route, $location, ConfigurationService, NotificationService) { $scope.selected = {configuration: undefined}; $scope.loadConfiguration = function (id) { ConfigurationService.get(id, function (data) { $scope.configuration = data; }); }; $scope.save = function () { var configurationCurrent = angular.copy($scope.configuration); ConfigurationService.save(configurationCurrent, function (data) { $scope.configuration = data; NotificationService.notify("success", "configuration.notification.saved"); $route.reload(); $location.path("configurations"); }); }; } ); app.controller('ConfigurationEditController', function ($scope, $routeParams, $controller) { $controller('GlobalConfigurationEditController', {$scope: $scope}); $scope.newConfiguration = false; $scope.loadConfiguration($routeParams.id); } );
fabienvuilleumier/fb
src/main/webapp/components/configuration/configuration-edit-ctrl.js
JavaScript
mit
1,062
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x2, _x3, _x4) { var _again = true; _function: while (_again) { var object = _x2, property = _x3, receiver = _x4; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x2 = parent; _x3 = property; _x4 = receiver; _again = true; continue _function; } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } var _ResourceDecoratorJs = require("./ResourceDecorator.js"); var _ResourceDecoratorJs2 = _interopRequireDefault(_ResourceDecoratorJs); var _endpointsLoadedDataEndpointJs = require("../endpoints/LoadedDataEndpoint.js"); var _endpointsLoadedDataEndpointJs2 = _interopRequireDefault(_endpointsLoadedDataEndpointJs); var _transformersEmbeddedPropertyTransformerJs = require("../transformers/EmbeddedPropertyTransformer.js"); var _transformersEmbeddedPropertyTransformerJs2 = _interopRequireDefault(_transformersEmbeddedPropertyTransformerJs); var _endpointsPromiseEndpointJs = require("../endpoints/PromiseEndpoint.js"); var _endpointsPromiseEndpointJs2 = _interopRequireDefault(_endpointsPromiseEndpointJs); var _injectorJs = require("../injector.js"); var JsonPropertyDecorator = (function (_ResourceDecorator) { function JsonPropertyDecorator(loadedDataEndpointFactory, embeddedPropertyTransformerFactory, promiseEndpointFactory, name, path, value, options) { _classCallCheck(this, JsonPropertyDecorator); _get(Object.getPrototypeOf(JsonPropertyDecorator.prototype), "constructor", this).call(this, name); this.path = path; this.options = options || {}; this.loadedDataEndpointFactory = loadedDataEndpointFactory; this.embeddedPropertyTransformerFactory = embeddedPropertyTransformerFactory; this.promiseEndpointFactory = promiseEndpointFactory; this.value = value; } _inherits(JsonPropertyDecorator, _ResourceDecorator); _createClass(JsonPropertyDecorator, [{ key: "recordApply", value: function recordApply(target) { target.constructor.properties[this.name] = this.path; if (!target.hasOwnProperty(this.name)) { var afterSet = this.options.afterSet; var path = this.path; Object.defineProperty(target, this.name, { enumerable: true, configurable: true, get: function get() { return this.pathGet(path); }, set: function set(value) { var result = this.pathSet(path, value); if (afterSet) { afterSet.call(this); } return result; } }); } } }, { key: "resourceApply", value: function resourceApply(resource) { if (this.value !== undefined) { resource.setInitialValue(this.path, this.value); } this.recordApply(resource); } }, { key: "errorsApply", value: function errorsApply(errors) { this.recordApply(errors); } }, { key: "endpointFn", get: function () { if (!this._endpointFn) { var path = this.path; var promiseEndpointFactory = this.promiseEndpointFactory; var loadedDataEndpointFactory = this.loadedDataEndpointFactory; var embeddedPropertyTransformerFactory = this.embeddedPropertyTransformerFactory; this._endpointFn = function () { var _this = this; var uriParams = arguments[0] === undefined ? {} : arguments[0]; // 'this' in here = Endpoint var newPromise = function newPromise() { return _this.load().then(function (resource) { return loadedDataEndpointFactory(resource.self(), resource, [embeddedPropertyTransformerFactory(path)]); }); }; var newEndpoint = promiseEndpointFactory(newPromise); return newEndpoint; }; } return this._endpointFn; } }, { key: "endpointApply", value: function endpointApply(target) { this.addFunction(target, this.endpointFn); } }]); return JsonPropertyDecorator; })(_ResourceDecoratorJs2["default"]); exports["default"] = JsonPropertyDecorator; (0, _injectorJs.Inject)((0, _injectorJs.factory)(_endpointsLoadedDataEndpointJs2["default"]), (0, _injectorJs.factory)(_transformersEmbeddedPropertyTransformerJs2["default"]), (0, _injectorJs.factory)(_endpointsPromiseEndpointJs2["default"]))(JsonPropertyDecorator); module.exports = exports["default"];
XingFramework/Relayer
dist/cjs/relayer/decorators/JsonPropertyDecorator.js
JavaScript
mit
5,971
/* =================================================== */ var treeData = [ { "name": "Top Level", "parent": "null", "children": [ { "name": "Level 2: A", "parent": "Top Level", "children": [ { "name": "Son of A", "parent": "Level 2: A" }, { "name": "Daughter of A", "parent": "Level 2: A" } ] }, { "name": "Level 2: B", "parent": "Top Level", "children": [ { "name": "Son of B", "parent": "Level 2: B" }, { "name": "Daughter of B", "parent": "Level 2: B" } ] } ] } ]; /* =================================================== */ var boxHeight = 60;// var boxWidth = 130;// var fontSize = 10; var lineSpace = 2; var renderOut = "tree"; var treeOrientation = "vertical";// var goZoo = true; var el = "div#myTree";// var margin = {top: -5, right: -5, bottom: -5, left: -5};// var width = 500, height = 500;// /* =================================================== */ /* Creates a new tree layout with the default settings: the default sort order is null; the default children accessor assumes each input data is an object with a children array; the default separation function uses one node width for siblings, and two node widths for non-siblings; the default size is 1×1. */ var hierarchy = ''; if ( renderOut == "tree") { hierarchy = d3.layout.tree(); } else { hierarchy = d3.layout.cluster(); } hierarchy.nodeSize([boxWidth*1.5, boxHeight*2]); //hierarchy.size([height, width - 160]); /** The default comparator is null, which disables sorting and uses tree traversal order. * Note that if no comparator function is specified to the built-in sort method, the default order is lexicographic * function comparator(a, b) { return a.name < b.name ? -1 : a.name > b.name ? 1 : 0; } * * The current default separation function * function separation(a, b) { return (a.parent == b.parent ? 1 : 2); } *//* TREE.sort(comparator).separation(separation); */ var svg = d3.select(el).append("svg") .attr("width", width)//+ margin.left + margin.right) .attr("height", height)//+ margin.top + margin.bottom) .append("g"); /* svg.append("rect") .attr("width", width) .attr("height", height) .style("fill", "grey") .style("pointer-events", "all"); */ var zoom = d3.behavior.zoom().scaleExtent([1, 10]).on("zoom", zoomed); function zoomed() { svg.append("g").attr("transform", "translate("+ d3.event.translate +") scale("+ d3.event.scale + ")"); } if (treeOrientation == "vertical") { svg.attr("transform", "translate("+ (0+margin.left)+","+(0+margin.right)+")"+" rotate(90) scale(1)") .call(zoom); } else { svg.attr("transform", "translate(1500,50) rotate(0) scale(0.5)") .call(zoom); } if ( renderOut == "tree" ) { } else {} var drag = d3.behavior.drag() .origin(function(d) { return d; }) .on("dragstart", dragstarted) .on("drag", dragged) .on("dragend", dragended); function dragstarted(d) { d3.event.sourceEvent.stopPropagation(); d3.select(this).classed("dragging", true); } function dragged(d) { d3.select(this).attr("x", d.x = d3.event.x).attr("y", d.y = d3.event.y); } function dragended(d) { d3.select(this).classed("dragging", false); } d3.json("./flare.json", function(error, json) { if (error) throw error; /* https://github.com/mbostock/d3/wiki/Tree-Layout Runs the tree layout, returning the array of nodes associated with the specified root node. The tree layout is part of D3's family of hierarchical layouts. */ root = treeData[0]; var nodes = hierarchy.nodes(root), // nodes(json) /* Given the specified array of nodes, such as those returned by nodes, returns an array of objects representing the links from parent to child for each node. */ links = hierarchy.links(nodes); /* https://www.dashingd3js.com/svg-paths-and-d3js */ var link = svg.selectAll("path.link").data(links).enter().append("path") .attr("class", "link"); var diagonal = d3.svg.diagonal(); if ( renderOut == "tree") { diagonal = function() { var mprojection = function(d) { return [d.y, d.x]; }; var mpath = function(pathData) { return "M" + pathData[0] + ' ' + pathData[1] + " " + pathData[2]+ " " + pathData[3]; }; // link.attr("d", function(d) { return "M" + (d.source.y/2) + "," + (d.source.x) + "H" + (d.target.y/2)+ "V" + (d.target.x);}); function mdiagonal(diagonalPath, i) { var source = diagonalPath.source, target = diagonalPath.target, turnPointY = target.y/2, pathData = [source, {x: source.x, y: turnPointY}, {x: target.x, y: turnPointY}, target]; pathData = pathData.map(mprojection); return mpath(pathData); } return mdiagonal; }; } else { // Straitgh curve! diagonal.projection(function(d) { return [d.y, d.x]; }); } link.attr("d", diagonal()); /* g is a container element http://www.w3.org/TR/SVG/shapes.html#InterfaceSVGRectElement */ var node = svg.selectAll("g.node").data(nodes).enter().append("g"); node.attr("class", "node") .attr("transform", function(d) { return "translate("+ d.y +","+ d.x +")"+ "rotate("+ -90 +")"; }) .on("mouseover", mouseover) .on("mouseout", mouseout); node.append("rect") .attr('class', "recBox") .attr("x", -boxWidth/2).attr("y", -boxHeight/2) .attr("width", boxWidth).attr("height", boxHeight) .attr("rx", 50); node.append("text") .attr("id", "nodetitle") .attr("class", "nodeTitle") .attr("y", -boxHeight/2 + fontSize + 2*lineSpace) .attr("text-anchor", "middle") .text( 'd.name' ); node.append("text") .attr("id", "nodetext") .attr("class", "nodeText") .attr("y", -boxHeight/2 + 2*fontSize + 4*lineSpace) .attr("text-anchor", "middle").text('Score: 00') .call(drag); //.style("fill", "none").style("stroke", "purple").style("stroke-width", "2.5px"); // mouseover event handler function mouseover() { d3.select(this).select("rect").transition().duration(750) .attr("width", boxWidth*1.5).attr("height", boxHeight*1.5) .style("opacity", 1) .style("fill", "#c8e4f8").style("stroke", "orange").style("stroke-width", "5px"); d3.select(this).select("text#nodetitle").transition().duration(750) .attr("y", -boxHeight/2 + fontSize + 2*lineSpace) .style("font-weight", "bold") .style("font-size", "18px"); // displayInfoBox(thisNode) } // mouseout event handler function mouseout() { d3.select(this).select("rect").transition(0.5).duration(750) .attr("width", boxWidth).attr("height", boxHeight) .style("opacity", 1) .style("fill", "white").style("stroke", "purple").style("stroke-width", "2.5px"); d3.select(this).select("text#nodetitle").transition().duration(750) .attr("y", -boxHeight/2 + fontSize + 2*lineSpace) .style("font-weight", "normal") .style("font-size", "12px"); } /* // Display up the info box (for mouse overs) function displayInfoBox(node) { var nodeName = node.attr("id") var infoX = infoBoxWidth/2*0.6 var infoY = infoBoxHeight/2*1.05 var infoBox = svg.append("g") infoBox .attr("class", "popup") .attr("transform", function(d) {return "translate(" + infoX + "," + infoY + ")";}) infoBox .append("text") .attr("y", -infoBoxHeight/2 + fontSize + 2*lineSpace) .attr("text-anchor", "middle") .text(nodeName) .attr("font-size", fontSize + 8 + "px") var imgOffsetX = -infoBoxWidth/2 * 0.95 var imgOffsetY = -infoBoxHeight/2 + fontSize+8 + 2*lineSpace infoBox .append("svg:image") .attr("xlink:href", "sample_patches/"+nodeName+".png") .attr("width", infoBoxWidth*0.99) .attr("height", infoBoxHeight*0.99) .attr("transform", function(d) {return "translate(" + imgOffsetX + "," + imgOffsetY + ")";}) } */ }); d3.select(self.frameElement).style("height", height + "px");
readycyr/dashahp_caseStudy0
www/cartesian.js
JavaScript
mit
8,417
var fs = require('fs'); fs.stat('/tmp', function(err, stats) { if (err) { console.error(err); return; } console.log(stats); });
Rukeith/node-n2-example
stats.js
JavaScript
mit
158
var path = require('path'); var cmd = require('cmd-util'); var ast = cmd.ast; var iduri = cmd.iduri; exports.init = function(grunt) { var exports = {}; exports.jsConcat = function(fileObj, options) { var data = grunt.file.read(fileObj.src); var meta = ast.parseFirst(data); var records = grunt.option('concat-records'); if (grunt.util._.contains(records, meta.id)) { return ''; } records.push(meta.id); if (options.include === 'self') { return data; } var rv = meta.dependencies.map(function(dep) { if (dep.charAt(0) === '.') { var id = iduri.absolute(meta.id, dep); if (grunt.util._.contains(records, id)) { return ''; } records.push(id); var fpath = path.join(path.dirname(fileObj.src), dep); console.log('###', fpath); if (!/\.js$/.test(fpath)) fpath += '.js'; if (!grunt.file.exists(fpath)) { grunt.log.warn('##=>file ' + fpath + ' not found'); return ''; } return grunt.file.read(fpath); } else if ((/\.css$/.test(dep) && options.css2js) || options.include === 'all') { var fileInPaths; options.paths.some(function(basedir) { var fpath = path.join(basedir, dep); console.log('@@@', fpath); if (!/\.css$/.test(dep)) { fpath += '.js'; } if (grunt.file.exists(fpath)) { fileInPaths = fpath; return true; } }); if (!fileInPaths) { grunt.log.warn('@@=>file ' + dep + ' not found\n'+ fileInPaths +'\n'); } else { var data = grunt.file.read(fileInPaths); if (/\.css$/.test(dep)) { return options.css2js(data, dep); } return data; } } return ''; }).join(grunt.util.normalizelf(options.separator)); return [data, rv].join(grunt.util.normalizelf(options.separator)); }; return exports; };
immissile/Shock-resume
node_modules/grunt-cmd-concat/tasks/lib/script.js
JavaScript
mit
1,999
'use strict'; angular.module('myApp.gear', ['ngRoute']) .config(['$routeProvider', function($routeProvider) { $routeProvider.when('/gear', { templateUrl: 'gear/gear.html', controller: 'GearCtrl' }); }]) .controller('GearCtrl', ['$scope','$http', function($scope, $http) { $http.get('resources/data/gear.json'). success(function(data, status, headers, config) { $scope.content = data; }). error(function(data, status, headers, config) { // log error }); }]);
Arch-vile/muotkatunturit2015
app/gear/gear.js
JavaScript
mit
503
$("#btnAddButton").on('click', addButton); $("#btnRemoveButton").on('click', removeButton); $('#btnAddTrail').on('click', loadFiles); $(document).ready(function() { }); var counter = 0; function addButton(event) { if(counter >= 10){ alert("Only 10 textboxes are allowed"); return false; } var newTextBoxDiv = $(document.createElement('div')).attr("id", 'TextBoxDiv' + counter); var str = '<input id="inputPicture" type="file" name="addpic">' + '<input id="inputPictureLon" type="text" placeholder="lon" size="8">' + '<input id="inputPictureLat" type="text" placeholder="lat" size="8">' + '<input id="inputPictureAlt" type="text" placeholder="alt" size="8">' + '<input id="inputPictureTimestamp" type="text" placeholder="timestamp" size="8">' + '<input id="inputPictureName" type="text" placeholder="picturename" size="8">' + '<input id="inputPictureDescription" type="text" placeholder="description" size="8">'; newTextBoxDiv.after().html(str); newTextBoxDiv.appendTo("#TextBoxesGroup"); counter++; } function removeButton(event) { if (counter == 0) { alert("No more textbox to remove"); return false; } counter--; $("#TextBoxDiv" + counter).remove(); } var log = function(text) { var elem = document.getElementsByTagName('span')[1]; elem.innerHTML = text; elem.style.backgroundColor="yellow"; elem.style.color="black"; setTimeout(function() { document.getElementsByTagName('span')[1].innerHTML = ""; }, 60000); }; var picDataArray = []; var readers = []; var readerInd = 0; function loadFiles(event) { var elem; var file; picDataArray = []; readers = []; readerInd = 0; event.preventDefault(); if (window.File && window.FileReader && window.FileList && window.Blob) { //alert("File API supported.!"); for (var i=0; i<counter; i++) { readers[i] = new FileReader(); readers[i].onload = function(e) { if (e.target.error) { log("couldn't read file"); return; } picDataArray.push(btoa(e.target.result)); readerInd++; if (readerInd == counter) { sendTrail(); } }; var elem = document.getElementById('TextBoxDiv' + (i).toString()); var file = elem.children[0].files[0]; readers[i].readAsBinaryString(file); } if (counter == 0) { sendTrail(); } } else { alert('The File APIs are not fully supported in this browser.\nI will not send pictures'); sendTrail(); } } function sendTrail() { var obj; var locArray = []; var picArray = []; var coords = []; var lines = $('#textareaCoordinates').val().split('\n'); for (var i=0; i<lines.length; i++) { var words = lines[i].split(','); if (words.length == 4) { coords = []; for (var j=0; j<3; j++) { coords.push(parseFloat(words[j])); } obj = { 'timestamp': words[3], 'loc': { 'type': 'Point', 'coordinates': coords } }; locArray.push(obj); } } for (var i=0; i<counter; i++) { coords = []; coords.push($('#TextBoxDiv' + i + ' #inputPictureLon').val()); coords.push($('#TextBoxDiv' + i + ' #inputPictureLat').val()); coords.push($('#TextBoxDiv' + i + ' #inputPictureAlt').val()); obj = { 'timestamp': $('#TextBoxDiv' + i + ' #inputPictureTimestamp').val(), 'picturename': $('#TextBoxDiv' + i + ' #inputPictureName').val(), 'description': $('#TextBoxDiv' + i + ' #inputPictureDescription').val(), 'filename': $('#TextBoxDiv' + i + ' #inputPicture').val(), 'file': picDataArray[i], 'loc': { 'type': 'Point', 'coordinates': coords } }; picArray.push(obj); } var data = { 'newtrail' : [ { 'type': 'LocationCollection', 'locations': locArray }, { 'type': 'PictureCollection', 'pictures': picArray }, { 'type': 'TrailInfo', 'access': $('#inputAccess').val(), 'trailname': $('#inputTrailName').val(), 'description': $('#inputDescription').val(), 'date': $('#inputDate').val(), 'locationname': $('#inputLocationName').val() }, { 'type': 'UserInfo', 'username': $('#inputUsername').val(), 'password': $('#inputPassword').val(), } ] }; $.ajax({ type: 'POST', data: data, url: '/addtrail', dataType: 'JSON', success: function(res) { if (res.status == 'ok') { var elem = document.getElementsByTagName('span')[0]; elem.innerHTML = res.msg; elem.style.backgroundColor="blue"; elem.style.color="white"; setTimeout(function() { document.getElementsByTagName('span')[0].innerHTML = ""; }, 5000); } else { var elem = document.getElementsByTagName('span')[0]; elem.innerHTML = res.msg; elem.style.backgroundColor="red"; elem.style.color="white"; setTimeout(function() { document.getElementsByTagName('span')[0].innerHTML = ""; }, 5000); } }, error: function(xhr, textStatus) { alert("HTTP error code: " + xhr.status + " response:\n" + xhr.responseText); }, complete: function(xhr, textstatus) { } }); }
vesapehkonen/jatrailmap
nodejs/public/js/cli-trailbuilder.js
JavaScript
mit
5,082
(function (window, document, angular, jQuery, undefined) { 'use strict'; angular.module('vissensePlayground') .controller('TrackSectionsDemoCtrl', [ '$window', '$document', '$scope', 'VisSense', function ($window, $document, $scope, VisSense) { $scope.scrollToElement = function (elementId) { jQuery('html, body').animate({ scrollTop: jQuery('#' + elementId).offset().top }, 500); }; var changeOpacityOnPercentageChangeOfElementWithId = function (elementId) { var sectionElement = jQuery('#' + elementId); var onChange = function (state) { var newValue = state.percentage; var oldValue = (state.previous.percentage || 0); var difference = newValue - oldValue; var duration = 500 * Math.max(difference, 0.25); // set the opacity to the actual visibility percentage var opacity = Math.max(newValue, 0.25); sectionElement.fadeTo(duration, opacity); }; var sectionMonitor = new VisSense(sectionElement[0]).monitor({ // update when user scrolls or resizes the page strategy: VisSense.VisMon.Strategy.EventStrategy({debounce: 50}), percentagechange: function (monitor) { onChange(monitor.state()); } }).start(); $scope.$on('$destroy', function () { sectionMonitor.stop(); }); }; changeOpacityOnPercentageChangeOfElementWithId('examples-section'); changeOpacityOnPercentageChangeOfElementWithId('demo-section'); changeOpacityOnPercentageChangeOfElementWithId('plugins-section'); }]); })(window, document, angular, jQuery);
vissense/vissense-demo
app/scripts/demos/track-sections-demo-ctrl.js
JavaScript
mit
1,788
"use strict"; const commonOptions = require("../common/common-options"); // format based on https://github.com/prettier/prettier/blob/master/src/main/core-options.js module.exports = { bracketSpacing: commonOptions.bracketSpacing, singleQuote: commonOptions.singleQuote, proseWrap: commonOptions.proseWrap };
existentialism/prettier
src/language-yaml/options.js
JavaScript
mit
317
'use strict'; module.exports = config => [{ name: 'facebook-app_id', message: 'app id of facebook', store: true, when: require('./when')('facebook', config) }, { name: 'facebook_api-api_version', message: 'version of facebook api', store: true, when: require('./when')('facebook_api', config) }];
HsuTing/generator-cat
generators/template/utils/facebook.js
JavaScript
mit
314
let prop, value, i, len; for (i = 0, len = myDiv.style.length; i < len; i++) { prop = myDiv.style[i]; // alternately, myDiv.style.item(i) value = myDiv.style.getPropertyCSSValue(prop); console.log(`prop: ${value.cssText} (${value.cssValueType})`); }
msfrisbie/pjwd-src
Chapter16DOMLevels2And3/Styles/AccessingElementStyles/DOMStylePropertiesAndMethods/DOMStylePropertiesAndMethodsExample04.js
JavaScript
mit
258
var albumId; var addPictures = function (result) { UserFBAlbums.update({id: albumId}, {$set: {'paging': result.paging}}); for (var i = 0; i < result.data.length; i++) { UserFBAlbums.update({id: albumId}, {$addToSet: {'pictures': result.data[i]}}); } IonLoading.hide(); }; Template.gallery.events({ 'click .loadNext': function () { IonLoading.show(); var next = UserFBAlbums.findOne({id: albumId}).paging.next; facebookApi.getNext(next, addPictures) }, 'click .thumb': function (e) { Meteor.call('TogglePicture', this.id, function (error, result) { if (error) { console.log(error.reason); } else if (!result) { IonPopup.alert({ title: 'Too many images!', template: 'You can only select up to five images.\n Please review your "Selected Photos" album, and remove some before adding more.', okText: 'Got It.' }); } }); } }); var pictures = []; Template.gallery.helpers({ pictures: function () { if (albumId) { pictures = UserFBAlbums.findOne({id: albumId}).pictures; } return pictures; }, photosSelected: function () { var selected = 0; if (Meteor.user()) { selected = Meteor.user().profile.facebookImageIds.length; } return '(' + selected + '/5)'; }, hasNext: function () { var album = UserFBAlbums.findOne({id: albumId}); if (album && album.paging) { return album.paging.next; } return false; } }); Template.gallery.rendered = function () { if (albumId) { if (!UserFBAlbums.findOne({id: albumId}).pictures) { IonLoading.show(); } this.autorun(function () { if (UserFBAlbums.findOne({id: albumId}).pictures) { IonLoading.hide(); } else if (Session.get('fbLoaded') && Meteor.userId()) { facebookApi.getPhotos({identifier: albumId}, function (result) { addPictures(result); }); } }.bind(this)); } }; Template.gallery.created = function () { albumId = Router.current().params._albumId; this.autorun(function () { this.subscription = Meteor.subscribe('user', Meteor.userId()); }.bind(this)); if (!albumId) { var images = Meteor.user().profile.facebookImageIds; for (var i = 0; i < images.length; i++) { pictures.push({id: images[i]}); } } };
DavidFishman/dfishman
client/templates/facebookPhotos/gallery/gallery.js
JavaScript
mit
2,657
var assert = require("chai").assert; var Init = require("truffle-init"); var Migrate = require("truffle-migrate"); var Contracts = require("../lib/contracts"); var Networks = require("../lib/networks"); var path = require("path"); var fs = require("fs"); var TestRPC = require("ethereumjs-testrpc"); var Resolver = require("truffle-resolver"); var Artifactor = require("truffle-artifactor"); var Web3 = require("web3"); describe("migrate", function() { var config; var accounts; var network_id_one; var network_id_two; var from_addresses = []; before("Create a sandbox", function(done) { this.timeout(10000); Init.sandbox(function(err, result) { if (err) return done(err); config = result; config.resolver = new Resolver(config); config.artifactor = new Artifactor(config.contracts_build_directory); config.networks = {}; done(); }); }); function createProviderAndSetNetworkConfig(network, callback) { var provider = TestRPC.provider({seed: network}); var web3 = new Web3(provider); web3.eth.getAccounts(function(err, accs) { if (err) return callback(err); web3.version.getNetwork(function(err, network_id) { if (err) return callback(err); config.networks[network] = { provider: provider, network_id: network_id + "", from: accs[0] }; callback(); }); }); }; before("Get accounts and network id of network one", function(done) { createProviderAndSetNetworkConfig("primary", done); }); before("Get accounts and network id of network one", function(done) { createProviderAndSetNetworkConfig("secondary", done); }); it('profiles a new project as not having any contracts deployed', function(done) { Networks.deployed(config, function(err, networks) { if (err) return done(err); assert.equal(Object.keys(networks).length, 2, "Should have results for two networks from profiler"); assert.equal(Object.keys(networks["primary"]), 0, "Primary network should not have been deployed to"); assert.equal(Object.keys(networks["secondary"]), 0, "Secondary network should not have been deployed to"); done(); }) }); it('links libraries in initial project, and runs all migrations', function(done) { this.timeout(10000); config.network = "primary"; Contracts.compile(config.with({ all: false, quiet: true }), function(err, contracts) { if (err) return done(err); Migrate.run(config.with({ quiet: true }), function(err) { if (err) return done(err); Networks.deployed(config, function(err, networks) { if (err) return done(err); assert.equal(Object.keys(networks).length, 2, "Should have results for two networks from profiler"); assert.equal(Object.keys(networks["primary"]).length, 3, "Primary network should have three contracts deployed"); assert.isNotNull(networks["primary"]["MetaCoin"], "MetaCoin contract should have an address"); assert.isNotNull(networks["primary"]["ConvertLib"], "ConvertLib library should have an address"); assert.isNotNull(networks["primary"]["Migrations"], "Migrations contract should have an address"); assert.equal(Object.keys(networks["secondary"]), 0, "Secondary network should not have been deployed to"); done(); }); }); }); }); it('should migrate secondary network without altering primary network', function(done) { this.timeout(10000); config.network = "secondary"; var currentAddresses = {}; Networks.deployed(config, function(err, networks) { if (err) return done(err); ["MetaCoin", "ConvertLib", "Migrations"].forEach(function(contract_name) { currentAddresses[contract_name] = networks["primary"][contract_name]; }); Migrate.run(config.with({ quiet: true }), function(err, contracts) { if (err) return done(err); Networks.deployed(config, function(err, networks) { if (err) return done(err); assert.equal(Object.keys(networks).length, 2, "Should have results for two networks from profiler"); assert.equal(Object.keys(networks["primary"]).length, 3, "Primary network should have three contracts deployed"); assert.equal(networks["primary"]["MetaCoin"], currentAddresses["MetaCoin"], "MetaCoin contract updated on primary network"); assert.equal(networks["primary"]["ConvertLib"], currentAddresses["ConvertLib"], "ConvertLib library updated on primary network"); assert.equal(networks["primary"]["Migrations"], currentAddresses["Migrations"], "Migrations contract updated on primary network"); assert.equal(Object.keys(networks["secondary"]).length, 3, "Secondary network should have three contracts deployed"); assert.isNotNull(networks["secondary"]["MetaCoin"], "MetaCoin contract should have an address on secondary network"); assert.isNotNull(networks["secondary"]["ConvertLib"], "ConvertLib library should have an address on secondary network"); assert.isNotNull(networks["secondary"]["Migrations"], "Migrations contract should have an address on secondary network"); Object.keys(networks["primary"]).forEach(function(contract_name) { assert.notEqual(networks["secondary"][contract_name], networks["primary"][contract_name], "Contract " + contract_name + " has the same address on both networks") }); done(); }); }); }); }); it("should ignore files that don't start with a number", function(done) { fs.writeFileSync(path.join(config.migrations_directory, "~2_deploy_contracts.js"), "module.exports = function() {};", "utf8"); Migrate.assemble(config, function(err, migrations) { if (err) return done(err); assert.equal(migrations.length, 2, "~2_deploy_contracts.js should have been ignored!"); done(); }); }); it("should ignore non-js extensions", function(done) { fs.writeFileSync(path.join(config.migrations_directory, "2_deploy_contracts.js~"), "module.exports = function() {};", "utf8"); Migrate.assemble(config, function(err, migrations) { if (err) return done(err); assert.equal(migrations.length, 2, "2_deploy_contracts.js~ should have been ignored!"); done(); }); }); });
prashantpawar/truffle
test/migrate.js
JavaScript
mit
6,446
var LiveStream = require('../') var SubLevel = require('level-sublevel') var db = SubLevel(require('level-test')()('test-level-live-stream')) var assert = require('assert') var i = 10 var j = 10 var k = 10 LiveStream(db, {tail: true}).on('data', function (data) { console.log(data) if(data.type === 'put') assert.equal(data.key, j--) }) LiveStream(db, {old: false}).on('data', function (data) { if(data.type === 'put') assert.equal(data.key, k--) }) var a = [] var int = setInterval(function () { var key = i + '' if(Math.random() < 0.2 && a.length) { var r = ~~(Math.random()*a.length) key = a[r] a.slice(r, 1) db.del(key, function (err) { assert(err == undefined) }) } else { a.push(key) db.put(key, new Date(), function(err) { assert(err == undefined) }) if(--i) return clearInterval(int) } }, 100)
dominictarr/level-live-stream
test/index.js
JavaScript
mit
886
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { fetchIP } from '../../actions/fetchIP'; import { Snackbar } from 'react-toolbox'; import theme from './Snackbar.css'; class SnackbarComponent extends Component { constructor(props) { super(props); this.state = { active: false, message: '' }; this.handleSnackbarClick = this.handleSnackbarClick.bind(this); this.handleSnackbarTimeout = this.handleSnackbarTimeout.bind(this); } handleSnackbarClick = () => { this.setState({active: false}); }; handleSnackbarTimeout = () => { if (this._isMounted) { this.setState({active: false}); } this.props.fetchIP(); }; componentWillReceiveProps(props) { this.setState({ active: props.error, message: props.message }); } componentDidMount() { this._isMounted = true; } componentWillUnmount() { this._isMounted = false; } render() { return ( <section> <Snackbar theme={theme} action="Hide" active={this.props.weather.error} label={this.props.weather.message} timeout={1500} onClick={this.handleSnackbarClick} onTimeout={this.handleSnackbarTimeout} type="warning" /> </section> ); } } function mapDispatchToProps(dispatch) { return bindActionCreators({ fetchIP }, dispatch); } function mapStateToProps({ weather }) { return { weather }; } export default connect(mapStateToProps, mapDispatchToProps)(SnackbarComponent);
ericvandevprod/redux-d3
src/app/components/Snackbar/Snackbar.js
JavaScript
mit
1,668
// @flow import React, { type Node, Component } from 'react'; import { Image, View, ScrollView, StyleSheet, TouchableHighlight, TouchableOpacity, Dimensions, } from 'react-native'; const reactNativePackage = require('react-native/package.json'); const splitVersion = reactNativePackage.version.split('.'); const majorVersion = +splitVersion[0]; const minorVersion = +splitVersion[1]; type Slide = { index: number, style?: any, width?: number, item?: any, }; type PropsType = { images: Array<number | string>, style?: any, loop?: boolean, loopBothSides?: boolean, autoPlayWithInterval?: number, position?: number, onPositionChanged?: number => void, onPress?: Object => void, customButtons?: (number, (number, animated?: boolean) => void) => Node, customSlide?: Slide => Node, imagesWidth: number }; type StateType = { position: number, width: number, interval: any, onPositionChangedCalled: boolean, }; class ImageSlider extends Component<PropsType, StateType> { state = { position: 0, width: Dimensions.get('window').width, onPositionChangedCalled: false, interval: null, }; _ref = null; _panResponder = {}; _onRef = (ref: any) => { this._ref = ref; if (ref && this.state.position !== this._getPosition()) { this._move(this._getPosition()); } }; // In iOS you can pop view by swiping left, with active ScrollView // you can't do that. This View on top of ScrollView enables call of // pop function. _popHelperView = () => !this.props.loopBothSides && this._getPosition() === 0 && ( <View style={{ position: 'absolute', width: 50, height: '100%' }} /> ); _move = (index: number, animated: boolean = true, autoCalled: boolean = true) => { if (!this.autoPlayFlag && autoCalled) { return; } const isUpdating = index !== this._getPosition(); const x = (this.props.imagesWidth ? this.props.imagesWidth : Dimensions.get("window").width) * index; this._ref && this._ref.scrollTo({ y: 0, x, animated }); this.setState({ position: index }); if ( isUpdating && this.props.onPositionChanged && index < this.props.images.length && index > -1 ) { this.props.onPositionChanged(index); this.setState({ onPositionChangedCalled: true }); } this._setInterval(); }; _getPosition() { if (typeof this.props.position === 'number') { return this.props.position % this.props.images.length; } return this.state.position % this.props.images.length; } componentDidUpdate(prevProps: Object) { const { position, autoPlayFlag } = this.props; this.autoPlayFlag = autoPlayFlag; if (position && prevProps.position !== position) { this._move(position); } } _clearInterval = () => this.state.interval && clearInterval(this.state.interval); _setInterval = () => { this._clearInterval(); const { autoPlayWithInterval, images, loop, loopBothSides } = this.props; if (autoPlayWithInterval) { this.setState({ interval: setInterval( () => this._move( !(loop || loopBothSides) && this.state.position === images.length - 1 ? 0 : this.state.position + 1, ), autoPlayWithInterval, ), }); } }; _handleScroll = (event: Object) => { const { position, width } = this.state; const { loop, loopBothSides, images, onPositionChanged } = this.props; const { x } = event.nativeEvent.contentOffset; if ( (loop || loopBothSides) && x.toFixed() >= +(width * images.length).toFixed() ) { return this._move(0, false); } else if (loopBothSides && x.toFixed() <= +(-width).toFixed()) { return this._move(images.length - 1, false); } let newPosition = 0; if (position !== -1 && position !== images.length) { newPosition = Math.round(event.nativeEvent.contentOffset.x / width); this.setState({ position: newPosition }); } if ( onPositionChanged && !this.state.onPositionChangedCalled && newPosition < images.length && newPosition > -1 ) { onPositionChanged(newPosition); } else { this.setState({ onPositionChangedCalled: false }); } this._setInterval(); }; componentDidMount() { this._setInterval(); } componentWillUnmount() { this._clearInterval(); } _onLayout = () => { this.setState({ width: Dimensions.get('window').width }); this._move(this.state.position, false); }; _renderImage = (image: any, index: number) => { const { width } = Dimensions.get('window'); const { onPress, customSlide } = this.props; const offset = { marginLeft: index === -1 ? -width : 0 }; const imageStyle = [styles.image, { width }, offset]; if (customSlide) { return customSlide({ item: image, style: imageStyle, index, width }); } const imageObject = typeof image === 'string' ? { uri: image } : image; const imageComponent = ( <Image key={index} source={imageObject} style={[imageStyle]} /> ); if (onPress) { return ( <TouchableOpacity key={index} style={[imageStyle, offset]} onPress={() => onPress && onPress({ image, index })} delayPressIn={200} > {imageComponent} </TouchableOpacity> ); } return imageComponent; }; // We make shure, that, when loop is active, // fake images at the begin and at the end of ScrollView // do not scroll. _scrollEnabled = (position: number) => position !== -1 && position !== this.props.images.length; moveNext = () => { const next = (this.state.position + 1) % this.props.images.length; this._move(next, true, false); } movePrev = () => { const prev = (this.state.position + this.props.images.length - 1) % this.props.images.length; this._move(prev, true, false); } render() { const { onPress, customButtons, style, loop, images, loopBothSides, } = this.props; const position = this._getPosition(); const scrollEnabled = this._scrollEnabled(position); return ( <View style={[styles.container, style]} onLayout={this._onLayout}> <ScrollView onLayout={this._onLayout} ref={ref => this._onRef(ref)} onMomentumScrollEnd={this._handleScroll} scrollEventThrottle={16} pagingEnabled={true} bounces={loopBothSides} contentInset={loopBothSides ? { left: this.state.width } : {}} horizontal={true} scrollEnabled={scrollEnabled} showsHorizontalScrollIndicator={false} style={[styles.scrollViewContainer, style]} > {loopBothSides && this._renderImage(images[images.length - 1], -1)} {images.map(this._renderImage)} {(loop || loopBothSides) && this._renderImage(images[0], images.length)} </ScrollView> {customButtons ? ( customButtons(position, this._move) ) : ( <View style={styles.buttons}> {this.props.images.map((image, index) => ( <TouchableHighlight key={index} underlayColor="#ccc" onPress={() => this._move(index)} style={[ styles.button, position === index && styles.buttonSelected, ]} > <View /> </TouchableHighlight> ))} </View> )} {this._popHelperView()} </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, }, scrollViewContainer: { flexDirection: 'row', backgroundColor: '#222', }, image: { width: 200, height: '100%', }, buttons: { height: 15, marginTop: -15, justifyContent: 'center', alignItems: 'center', flexDirection: 'row', }, button: { margin: 3, width: 8, height: 8, borderRadius: 8 / 2, backgroundColor: '#ccc', opacity: 0.9, }, buttonSelected: { opacity: 1, backgroundColor: '#fff', }, }); export default ImageSlider;
PaulBGD/react-native-image-slider
ImageSlider.js
JavaScript
mit
8,352
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @emails oncall+relay * @format */ 'use strict'; const RelayClassic = require('../../RelayPublic'); const RelayQuery = require('../../query/RelayQuery'); const RelayTestUtils = require('RelayTestUtils'); const flattenRelayQuery = require('../flattenRelayQuery'); const generateRQLFieldAlias = require('../../query/generateRQLFieldAlias'); const splitDeferredRelayQueries = require('../splitDeferredRelayQueries'); describe('splitDeferredRelayQueries()', () => { // helper functions const {defer, getNode, getRefNode} = RelayTestUtils; // remove the root `id` field function filterGeneratedRootFields(node) { const children = node .getChildren() .filter( child => !(child instanceof RelayQuery.Field && child.isGenerated()), ); return node.clone(children); } beforeEach(() => { // Reset query numbers back to q0. jest.resetModules(); expect.extend(RelayTestUtils.matchers); }); it('returns the original query when there are no fragments', () => { const node = RelayClassic.QL`query{node(id:"4"){id,name}}`; const queryNode = getNode(node); const {required, deferred} = splitDeferredRelayQueries(queryNode); expect(required).toBe(queryNode); expect(deferred).toEqual([]); }); it('returns the original query when there are no deferred fragments', () => { const fragment = RelayClassic.QL`fragment on User{hometown{name}}`; const node = RelayClassic.QL` query { node(id:"4") { id name ${fragment} } } `; const queryNode = getNode(node); const {required, deferred} = splitDeferredRelayQueries(queryNode); expect(required).toBe(queryNode); expect(deferred).toEqual([]); }); it('splits a deferred fragment on the viewer root', () => { const fragment = RelayClassic.QL` fragment on Viewer { newsFeed(first: 10) { edges { node { id actorCount } } } } `; const node = RelayClassic.QL` query { viewer { actor { id } ${defer(fragment)} } } `; const queryNode = getNode(node); const {required, deferred} = splitDeferredRelayQueries(queryNode); // required part expect(required.getName()).toBe(queryNode.getName()); expect(required).toEqualQueryRoot( getNode(RelayClassic.QL`query{viewer{actor{id}}}`), ); expect(required.getID()).toBe('q3'); // deferred part expect(deferred.length).toBe(1); expect(deferred[0].required.getName()).toBe(queryNode.getName()); expect(deferred[0].required).toEqualQueryRoot( getNode( RelayClassic.QL` query { viewer { ${fragment} } } `, ), ); expect(deferred[0].required.getID()).toBe('q2'); expect(deferred[0].required.isDeferred()).toBe(true); // no nested deferreds expect(deferred[0].deferred).toEqual([]); }); it('splits a deferred fragment on a query without an ID argument', () => { const fragment = RelayClassic.QL` fragment on Actor { name } `; const node = RelayClassic.QL` query { username(name:"yuzhi") { id ${defer(fragment)} } } `; const queryNode = getNode(node); const {deferred} = splitDeferredRelayQueries(queryNode); expect(deferred.length).toBe(1); expect(deferred[0].required.getConcreteQueryNode().metadata).toEqual({ identifyingArgName: 'name', identifyingArgType: 'String!', isAbstract: true, isPlural: false, }); }); it('splits a nested feed on the viewer root', () => { const nestedFragment = RelayClassic.QL` fragment on Viewer { newsFeed(first: 10) { edges { node { id actorCount } } } } `; const fragment = RelayClassic.QL` fragment on Viewer { actor { name } ${defer(nestedFragment)} } `; const node = RelayClassic.QL` query { viewer { actor { id } ${fragment} } } `; const queryNode = getNode(node); const {required, deferred} = splitDeferredRelayQueries(queryNode); // required part expect(required.getName()).toBe(queryNode.getName()); expect(required).toEqualQueryRoot( getNode( RelayClassic.QL` query { viewer { actor { id } ${RelayClassic.QL` fragment on Viewer { actor { name, } } `} } } `, ), ); // deferred part expect(deferred.length).toBe(1); expect(deferred[0].required.getName()).toBe(queryNode.getName()); expect(deferred[0].required).toEqualQueryRoot( getNode( RelayClassic.QL` query { viewer { ${nestedFragment} } } `, ), ); expect(deferred[0].required.isDeferred()).toBe(true); // no nested deferreds expect(deferred[0].deferred).toEqual([]); }); it('splits nested deferred fragments', () => { const nestedFragment = RelayClassic.QL`fragment on NonNodeStory{message{text}}`; const fragment = RelayClassic.QL` fragment on Viewer { newsFeed(first: 10) { edges { node { tracking ${defer(nestedFragment)} } } } } `; const node = RelayClassic.QL` query { viewer { actor { name } ${defer(fragment)} } } `; const queryNode = getNode(node); const {required, deferred} = splitDeferredRelayQueries(queryNode); // required part expect(required.getName()).toBe(queryNode.getName()); expect(required).toEqualQueryRoot( getNode( RelayClassic.QL` query { viewer{actor{id,name}} } `, ), ); expect(required.getID()).toBe('q5'); // deferred part expect(deferred.length).toBe(1); expect(deferred[0].required.getName()).toBe(queryNode.getName()); expect(deferred[0].required).toEqualQueryRoot( getNode( RelayClassic.QL` query { viewer { ${RelayClassic.QL` fragment on Viewer { newsFeed(first: 10) { edges { cursor, node { id, tracking } }, pageInfo { hasNextPage, hasPreviousPage } } } `} } } `, ), ); expect(deferred[0].required.getID()).toBe('q4'); expect(deferred[0].required.isDeferred()).toBe(true); // nested deferred part expect(deferred[0].deferred.length).toBe(1); expect(deferred[0].deferred[0].required.getName()).toBe( queryNode.getName(), ); // TODO (#7891872): test unflattened queries. The expected output's `edges` // field has two `node` children: // - the requisite `node{id}` // - the nested deferred fragment expect( flattenRelayQuery(deferred[0].deferred[0].required), ).toEqualQueryRoot( flattenRelayQuery( getNode( RelayClassic.QL` query { viewer { newsFeed(first: 10) { edges { cursor node { ${nestedFragment} id } } pageInfo { hasNextPage hasPreviousPage } } } } `, ), ), ); expect(deferred[0].deferred[0].required.getID()).toBe('q2'); expect(deferred[0].deferred[0].required.isDeferred()).toBe(true); // no nested nested deferreds expect(deferred[0].deferred[0].deferred).toEqual([]); }); it('splits deferred fragments using ref queries', () => { const fragment = RelayClassic.QL`fragment on Page{profilePicture{uri}}`; const node = RelayClassic.QL` query { node(id:"4") { id name hometown { ${defer(fragment)} } } } `; const queryNode = getNode(node); const {required, deferred} = splitDeferredRelayQueries(queryNode); // required part expect(required.getName()).toBe(queryNode.getName()); expect(required).toEqualQueryRoot( getNode(RelayClassic.QL`query{node(id:"4"){hometown{id},id,name}}`), ); expect(required.getID()).toBe('q1'); expect( required .getFieldByStorageKey('hometown') .getFieldByStorageKey('id') .isRefQueryDependency(), ).toBe(true); // deferred part expect(deferred.length).toBe(1); expect(deferred[0].required.getName()).toBe(queryNode.getName()); expect(deferred[0].required).toEqualQueryRoot( filterGeneratedRootFields( getRefNode( RelayClassic.QL` query { nodes(ids:$ref_q1) { ${fragment} } } `, {path: '$.*.hometown.id'}, ), ), ); expect(deferred[0].required.getID()).toBe('q2'); expect(deferred[0].required.isDeferred()).toBe(true); // no nested deferreds expect(deferred[0].deferred).toEqual([]); }); it('splits a nested deferred fragments as a ref queries', () => { const nestedFragment = RelayClassic.QL`fragment on Page{profilePicture{uri}}`; const fragment = RelayClassic.QL` fragment on User { hometown { name ${defer(nestedFragment)} } } `; const node = RelayClassic.QL` query { node(id:"4") { id name ${defer(fragment)} } } `; const queryNode = getNode(node); const {required, deferred} = splitDeferredRelayQueries(queryNode); // required part expect(required.getName()).toBe(queryNode.getName()); expect(required).toEqualQueryRoot( getNode(RelayClassic.QL`query{node(id:"4"){id,name}}`), ); expect(required.getID()).toBe('q3'); // deferred part expect(deferred.length).toBe(1); expect(deferred[0].required.getName()).toBe(queryNode.getName()); expect(deferred[0].required).toEqualQueryRoot( getNode( RelayClassic.QL` query { node(id:"4") { ${RelayClassic.QL`fragment on User{hometown{name}}`}, id } } `, ), ); expect(deferred[0].required.getID()).toBe('q2'); expect(deferred[0].required.isDeferred()).toBe(true); expect( deferred[0].required .getChildren()[0] // node(4){hometown} (fragment) .getChildren()[0] // node(4){hometown} (field) .getChildren()[0] // node(4){hometown{id}} (field) .isRefQueryDependency(), ).toBe(true); // nested deferred part expect(deferred[0].deferred.length).toBe(1); expect(deferred[0].deferred[0].required.getName()).toBe( queryNode.getName(), ); expect(deferred[0].deferred[0].required).toEqualQueryRoot( filterGeneratedRootFields( getRefNode( RelayClassic.QL` query { nodes(ids:$ref_q2) { ${nestedFragment} } } `, {path: '$.*.hometown.id'}, ), ), ); expect(deferred[0].deferred[0].required.getID()).toBe('q4'); expect(deferred[0].deferred[0].required.isDeferred()).toBe(true); // no nested nested deferreds expect(deferred[0].deferred[0].deferred).toEqual([]); }); it('splits a deferred fragment nested inside a ref query', () => { // this time, going to defer something inside the ref const nestedFragment = RelayClassic.QL`fragment on Page{address{city}}`; const fragment = RelayClassic.QL` fragment on Page { profilePicture { uri } ${defer(nestedFragment)} } `; const node = RelayClassic.QL` query { node(id:"4") { id name hometown { ${defer(fragment)} } } } `; const queryNode = getNode(node); const {required, deferred} = splitDeferredRelayQueries(queryNode); // required part expect(required.getName()).toBe(queryNode.getName()); expect(required).toEqualQueryRoot( getNode(RelayClassic.QL`query{node(id:"4"){hometown{id},id,name}}`), ); expect( required .getFieldByStorageKey('hometown') .getFieldByStorageKey('id') .isRefQueryDependency(), ).toBe(true); expect(required.getID()).toBe('q1'); // deferred part expect(deferred.length).toBe(1); expect(deferred[0].required.getName()).toBe(queryNode.getName()); expect(deferred[0].required).toEqualQueryRoot( filterGeneratedRootFields( getRefNode( RelayClassic.QL` query { nodes(ids:$ref_q1) { ${RelayClassic.QL`fragment on Page{id,profilePicture{uri}}`} } } `, {path: '$.*.hometown.id'}, ), ), ); expect(deferred[0].required.getID()).toBe('q2'); expect(deferred[0].required.isDeferred()).toBe(true); // nested deferred part expect(deferred[0].deferred.length).toBe(1); expect(deferred[0].deferred[0].required.getName()).toBe( queryNode.getName(), ); expect(deferred[0].deferred[0].required).toEqualQueryRoot( filterGeneratedRootFields( getRefNode( RelayClassic.QL` query { nodes(ids:$ref_q2) { ${nestedFragment} } } `, {path: '$.*.hometown.id'}, ), ), ); expect(deferred[0].deferred[0].required.getID()).toBe('q3'); expect(deferred[0].deferred[0].required.isDeferred()).toBe(true); // no nested nested deferreds expect(deferred[0].deferred[0].deferred).toEqual([]); }); it('drops the required portion if it is empty', () => { const fragment = RelayClassic.QL` fragment on Viewer { newsFeed(first: 10) { edges { node { id actorCount } } } } `; const node = RelayClassic.QL` query { viewer { ${defer(fragment)} } } `; const queryNode = getNode(node); const {required, deferred} = splitDeferredRelayQueries(queryNode); // required part expect(required).toBe(null); // deferred part expect(deferred.length).toBe(1); expect(deferred[0].required.getName()).toBe(queryNode.getName()); expect(deferred[0].required).toEqualQueryRoot( getNode( RelayClassic.QL` query { viewer { ${fragment} } } `, ), ); expect(deferred[0].required.isDeferred()).toBe(true); // no nested deferred part expect(deferred[0].deferred).toEqual([]); }); it('handles a nested defer with no required part', () => { const nestedFragment = RelayClassic.QL`fragment on Viewer{primaryEmail}`; const fragment = RelayClassic.QL` fragment on Viewer { ${defer(nestedFragment)} } `; const node = RelayClassic.QL` query { viewer { isFbEmployee ${defer(fragment)} } } `; const queryNode = getNode(node); const {required, deferred} = splitDeferredRelayQueries(queryNode); // required part expect(required.getName()).toBe(queryNode.getName()); expect(required).toEqualQueryRoot( getNode( RelayClassic.QL` query { viewer{isFbEmployee} } `, ), ); // deferred part expect(deferred.length).toBe(1); expect(deferred[0].required).toBe(null); // nested deferred part expect(deferred[0].deferred.length).toBe(1); expect(deferred[0].deferred[0].required.getName()).toBe( queryNode.getName(), ); expect(deferred[0].deferred[0].required).toEqualQueryRoot( getNode( RelayClassic.QL` query { viewer { ${nestedFragment} } } `, ), ); expect(deferred[0].deferred[0].required.isDeferred()).toBe(true); // no nested nested deferreds expect(deferred[0].deferred[0].deferred).toEqual([]); }); it('handles a nested ref query defer with no required part', () => { const nestedFragment = RelayClassic.QL`fragment on Actor{hometown{name}}`; const fragment = RelayClassic.QL` fragment on Viewer { ${defer(nestedFragment)} } `; const node = RelayClassic.QL` query { viewer { actor { name ${defer(fragment)} } } } `; const queryNode = getNode(node); const {required, deferred} = splitDeferredRelayQueries(queryNode); // required part expect(required.getName()).toBe(queryNode.getName()); expect(required).toEqualQueryRoot( getNode( RelayClassic.QL` query { viewer{actor{id,name}} } `, ), ); expect(required.getID()).toBe('q1'); expect( required .getFieldByStorageKey('actor') .getFieldByStorageKey('id') .isRefQueryDependency(), ).toBe(true); // deferred part expect(deferred.length).toBe(1); expect(deferred[0].required).toBe(null); // nested deferred part expect(deferred[0].deferred.length).toBe(1); expect(deferred[0].deferred[0].required.getName()).toBe( queryNode.getName(), ); expect(deferred[0].deferred[0].required).toEqualQueryRoot( filterGeneratedRootFields( getRefNode( RelayClassic.QL` query { nodes(ids:$ref_q1) { ${nestedFragment} } } `, {path: '$.*.actor.id'}, ), ), ); expect(deferred[0].deferred[0].required.getID()).toBe('q2'); expect(deferred[0].deferred[0].required.isDeferred()).toBe(true); // no nested nested deferreds expect(deferred[0].deferred[0].deferred).toEqual([]); }); it('handles paths with plural fields', () => { const fragment = RelayClassic.QL`fragment on Actor{name}`; const node = RelayClassic.QL` query { node(id:"123") { actors { id ${defer(fragment)} } } } `; const queryNode = getNode(node); const {required, deferred} = splitDeferredRelayQueries(queryNode); // required part expect(required.getName()).toBe(queryNode.getName()); expect(required).toEqualQueryRoot( getNode( RelayClassic.QL` query { node(id:"123") { actors { id } } } `, ), ); expect(required.getID()).toBe('q1'); // deferred part expect(deferred.length).toBe(1); expect(deferred[0].required.getName()).toBe(queryNode.getName()); expect(deferred[0].required).toEqualQueryRoot( filterGeneratedRootFields( getRefNode( RelayClassic.QL` query { nodes(ids:$ref_q1) { ${fragment} } } `, {path: '$.*.actors.*.id'}, ), ), ); expect(deferred[0].required.getID()).toBe('q2'); expect(deferred[0].required.isDeferred()).toBe(true); // no nested deferreds expect(deferred[0].deferred).toEqual([]); }); it('works with nested node ancestors', () => { const fragment = RelayClassic.QL`fragment on Node{name}`; const node = RelayClassic.QL` query { viewer { actor { hometown { ${defer(fragment)} } } } } `; const queryNode = getNode(node); const {required, deferred} = splitDeferredRelayQueries(queryNode); // required part expect(required.getName()).toBe(queryNode.getName()); expect(required).toEqualQueryRoot( getNode( RelayClassic.QL` query { viewer { actor { hometown { id } } } } `, ), ); expect(required.getID()).toBe('q1'); // deferred part expect(deferred.length).toBe(1); expect(deferred[0].required.getName()).toBe(queryNode.getName()); expect(deferred[0].required).toEqualQueryRoot( filterGeneratedRootFields( getRefNode( RelayClassic.QL` query { nodes(ids:$ref_q1) { ${fragment} } } `, {path: '$.*.actor.hometown.id'}, ), ), ); expect(deferred[0].required.getID()).toBe('q2'); expect(deferred[0].required.isDeferred()).toBe(true); // no nested deferreds expect(deferred[0].deferred).toEqual([]); }); it('uses the auto-generated alias in ref query paths', () => { const fragment = RelayClassic.QL`fragment on User{firstName}`; const node = RelayClassic.QL` query { node(id:"4") { friends(first: 5) { edges { node { name ${defer(fragment)} } } } } } `; const queryNode = getNode(node); const {required, deferred} = splitDeferredRelayQueries(queryNode); // required part expect(required.getName()).toBe(queryNode.getName()); expect(required).toEqualQueryRoot( getNode( RelayClassic.QL` query { node(id:"4") { friends(first: 5) { edges { node { id name } } } } } `, ), ); expect(required.getID()).toBe('q1'); // deferred part const alias = generateRQLFieldAlias('friends.first(5)'); expect(deferred.length).toBe(1); expect(deferred[0].required.getName()).toBe(queryNode.getName()); expect(deferred[0].required).toEqualQueryRoot( filterGeneratedRootFields( getRefNode( RelayClassic.QL` query { nodes(ids:$ref_q1) { ${fragment} } } `, {path: '$.*.' + alias + '.edges.*.node.id'}, ), ), ); expect(deferred[0].required.getID()).toBe('q2'); expect(deferred[0].required.isDeferred()).toBe(true); // no nested deferreds expect(deferred[0].deferred).toEqual([]); }); it('correctly produces multi-level JSONPaths in ref queries', () => { const fragment = RelayClassic.QL`fragment on Actor{name}`; const node = RelayClassic.QL` query { node(id:"4") { friends(first: 5) { edges { node { ${defer(fragment)} } } } } } `; const queryNode = getNode(node); const {required, deferred} = splitDeferredRelayQueries(queryNode); // required part expect(required.getName()).toBe(queryNode.getName()); expect(required).toEqualQueryRoot( getNode( RelayClassic.QL` query { node(id:"4") { friends(first: 5) { edges { node { id } } } } } `, ), ); expect(required.getID()).toBe('q1'); // deferred part const alias = generateRQLFieldAlias('friends.first(5)'); expect(deferred.length).toBe(1); expect(deferred[0].required.getName()).toBe(queryNode.getName()); expect(deferred[0].required).toEqualQueryRoot( filterGeneratedRootFields( getRefNode( RelayClassic.QL` query { nodes(ids:$ref_q1) { ${fragment} } } `, {path: '$.*.' + alias + '.edges.*.node.id'}, ), ), ); expect(deferred[0].required.getID()).toBe('q2'); expect(deferred[0].required.isDeferred()).toBe(true); // no nested deferreds expect(deferred[0].deferred).toEqual([]); }); it('handles fragments that are not nodes', () => { const fragment = RelayClassic.QL`fragment on Image{uri}`; const node = RelayClassic.QL` query { node(id:"4") { id profilePicture(size: 100) { ${defer(fragment)} } } } `; const queryNode = getNode(node); const {required, deferred} = splitDeferredRelayQueries(queryNode); // required part expect(required.getName()).toBe(queryNode.getName()); expect(required).toEqualQueryRoot( getNode(RelayClassic.QL`query{node(id:"4"){id}}`), ); // deferred part expect(deferred.length).toBe(1); expect(deferred[0].required.getName()).toBe(queryNode.getName()); expect(deferred[0].required).toEqualQueryRoot( getNode( RelayClassic.QL` query { node(id:"4") { profilePicture(size: 100) { ${fragment} } } } `, ), ); expect(deferred[0].required.isDeferred()).toBe(true); // no nested deferreds expect(deferred[0].deferred).toEqual([]); }); it('omits required queries with only generated `id` fields', () => { const fragment = RelayClassic.QL`fragment on Node{name}`; const node = RelayClassic.QL` query { node(id:"4") { ${defer(fragment)} } } `; const queryNode = getNode(node); const {required, deferred} = splitDeferredRelayQueries(queryNode); // required part expect(required).toBe(null); // deferred part expect(deferred.length).toBe(1); expect(deferred[0].required.getName()).toBe(queryNode.getName()); expect(deferred[0].required).toEqualQueryRoot( getNode( RelayClassic.QL` query { node(id:"4") { ${fragment} } } `, ), ); expect(deferred[0].required.isDeferred()).toBe(true); // no nested deferreds expect(deferred[0].deferred).toEqual([]); }); it('does not omit "empty" required ref query dependencies', () => { // It isn't possible to produce an "empty" ref query dependency with // `RelayClassic.QL`, but in order to be future-proof against this possible edge // case, we create such a query by hand. const fragment = RelayClassic.QL`fragment on Node{name}`; const id = RelayQuery.Field.build({ fieldName: 'id', metadata: {isRequisite: true}, type: 'String', }); const typename = RelayQuery.Field.build({ fieldName: '__typename', metadata: {isRequisite: true}, type: 'String', }); let queryNode = RelayQuery.Root.build( 'splitDeferredRelayQueries', 'node', '4', [ id, typename, RelayQuery.Field.build({ fieldName: 'hometown', children: [id, getNode(defer(fragment))], metadata: { canHaveSubselections: true, isGenerated: true, inferredPrimaryKey: 'id', inferredRootCallName: 'node', }, type: 'Page', }), ], { identifyingArgName: 'id', }, ); queryNode = queryNode.clone( queryNode.getChildren().map((outerChild, ii) => { if (ii === 1) { return outerChild.clone( outerChild.getChildren().map((innerChild, jj) => { if (jj === 0) { return innerChild.cloneAsRefQueryDependency(); } else { return innerChild; } }), ); } else { return outerChild; } }), ); const {required, deferred} = splitDeferredRelayQueries(queryNode); // required part expect(deferred[0].required.getName()).toBe(queryNode.getName()); expect(required).toEqualQueryRoot( getNode( RelayClassic.QL` query { node(id:"4"){hometown{id},id} } `, ), ); expect(required.getID()).toBe('q1'); // deferred part expect(deferred.length).toBe(1); expect(deferred[0].required.getName()).toBe(queryNode.getName()); expect(deferred[0].required).toEqualQueryRoot( filterGeneratedRootFields( getRefNode( RelayClassic.QL` query { nodes(ids:$ref_q1) { ${fragment} } } `, {path: '$.*.hometown.id'}, ), ), ); expect(deferred[0].required.getID()).toBe('q2'); expect(deferred[0].required.isDeferred()).toBe(true); // no nested deferreds expect(deferred[0].deferred).toEqual([]); }); it('preserves required queries with only a non-generated `id` field', () => { const fragment = RelayClassic.QL`fragment on Node{name}`; const node = RelayClassic.QL` query { node(id:"4") { id ${defer(fragment)} } } `; const queryNode = getNode(node); const {required, deferred} = splitDeferredRelayQueries(queryNode); // required part expect(deferred[0].required.getName()).toBe(queryNode.getName()); expect(required).toEqualQueryRoot( getNode(RelayClassic.QL`query{node(id:"4"){id}}`), ); // deferred part expect(deferred.length).toBe(1); expect(deferred[0].required.getName()).toBe(queryNode.getName()); expect(deferred[0].required).toEqualQueryRoot( getNode( RelayClassic.QL` query { node(id:"4") { ${fragment} } } `, ), ); expect(deferred[0].required.isDeferred()).toBe(true); // no nested deferreds expect(deferred[0].deferred).toEqual([]); }); it('does not split empty fragments', () => { // null fragment could be caused by an `if`/`unless` call + a GK const nullFragment = RelayClassic.QL`fragment on Viewer{${null}}`; const fragment = RelayClassic.QL`fragment on Viewer{${nullFragment}}`; const node = RelayClassic.QL` query { viewer { primaryEmail ${defer(fragment)} } } `; const queryNode = getNode(node); const {required, deferred} = splitDeferredRelayQueries(queryNode); expect(required.getName()).toBe(queryNode.getName()); expect(required).toEqualQueryRoot( getNode( RelayClassic.QL` query { viewer{primaryEmail} } `, ), ); expect(deferred.length).toBe(0); }); it('does not flatten fragments when splitting root queries', () => { const fragment = RelayClassic.QL`fragment on Node{name}`; const query = getNode( RelayClassic.QL` query { node(id:"4") { ${defer(fragment)} } } `, ); const {deferred} = splitDeferredRelayQueries(query); expect(deferred.length).toBe(1); expect(deferred[0].required).toContainQueryNode(getNode(fragment)); }); it('does not flatten fragments when splitting ref queries', () => { const fragment = RelayClassic.QL`fragment on Feedback{likers{count}}`; const query = getNode( RelayClassic.QL` query { node(id:"STORY_ID") { feedback { ${defer(fragment)} } } } `, ); const {deferred} = splitDeferredRelayQueries(query); expect(deferred.length).toBe(1); expect(deferred[0].required).toContainQueryNode(getNode(fragment)); }); });
freiksenet/relay
packages/react-relay/classic/traversal/__tests__/splitDeferredRelayQueries-test.js
JavaScript
mit
32,018
var util = require('util'); var bleno = require('bleno'); var BlenoPrimaryService = bleno.PrimaryService; var ParkCharacteristic = require('./parkCharacteristic'); function DeviceInformationService() { DeviceInformationService.super_.call(this, { uuid: 'ec00', characteristics: [ new ParkCharacteristic() ] }); } util.inherits(DeviceInformationService, BlenoPrimaryService); module.exports = DeviceInformationService;
DriverCity/SPARK
src/smart_meter/src/BLENode/src/device-information-service.js
JavaScript
mit
444
const expect = require('chai').expect const includeMimeType = require('../src/file').includeMimeType const findInFile = require('../src/file').findInFile describe('file : includeMimeType', () => { it('MIME_TYPES_IGNORED contain this mime type', () => { expect(includeMimeType('test/directoryTest/file2.png')).to.be.true }) it('MIME_TYPES_IGNORED not contain this mime type', () => { expect(includeMimeType('test/directoryTest/file1.js')).to.be.false }) }) describe('file : findInFile', () => { it('will some results (string)', () => { const results = findInFile('foo', 'test/directoryTest/file1.js') expect(results).to.be.eql({ 1: [5], 2: [12], 3: [5, 18] }) }) it('will some results (regExp)', () => { const results = findInFile(/foo/, 'test/directoryTest/file1.js') expect(results).to.be.eql({ 1: [5], 2: [12], 3: [5, 18] }) }) it('will nothing (string)', () => { const results = findInFile('nothing', 'test/directoryTest/file1.js') expect(results).to.be.eql({}) }) it('will nothing (regExp)', () => { const results = findInFile(/nothing/, 'test/directoryTest/file1.js') expect(results).to.be.eql({}) }) })
arncet/position-in-file
test/file.spec.js
JavaScript
mit
1,224
var fs = require('fs'); var assert = require('assert'); var JSZip = require('jszip'); var path = require('path') var compareWorkbooks = require('./util/compareworkbooks.js') var excelbuilder = require('..'); describe('It generates a simple workbook', function () { it('generates a ZIP file we can save', function (done) { var workbook = excelbuilder.createWorkbook(); var table = [ [1, 2, "", 4, 5], [2, 4, null, 16, 20], [1, 4, NaN, 16, 25], [4, 8, undefined, 16, 20] ] var sheet1 = workbook.createSheet('sheet1', table[0].length, table.length); table.forEach(function (row, rowIdx) { row.forEach(function (val, colIdx) { sheet1.set(colIdx + 1, rowIdx + 1, val) }) }) workbook.generate(function (err, zip) { if (err) throw err; zip.generateAsync({type: "nodebuffer"}).then(function (buffer) { var OUTFILE = './test/out/example.xlsx'; fs.writeFile(OUTFILE, buffer, function (err) { console.log('open \"' + OUTFILE + "\""); compareWorkbooks('./test/files/example.xlsx', OUTFILE, function (err, result) { if (err) throw err; // assert(result) done(err); }); }); }); }); }); });
protobi/msexcel-builder
test/na.js
JavaScript
mit
1,273
var Cat = require('../src/Cat'); require('chai').should(); describe('This should pass if mutated', function(){ it('yes it should', function(){ var name = Math.random(); true.should.equal(true); }); });
TeamSentinaught/sentinaught
integration-tests/fails/rubbishTests.js
JavaScript
mit
208
var today = new Date(); var birthday = new Date(1981, 1, 16); var age = today.getTime() - birthday.getTime(); alert(age); // alert(age / 1000 / 60 / 60 / 24/ 365.25);
TheHagueUniversity/2017_1.1_programming-extended-course
wk2exercises/wk2exercise06/scripts/main.js
JavaScript
mit
172
/* * Datagrid.js */ function dg_send(url, grid, form, page, tamano, orderby, orderdirection) { var oForm = $("#"+form); var oGrid = $("#"+grid); var oLoader = $("#loader_"+grid); $('#Form_'+grid+'_page').val(page); $('#Form_'+grid+'_tamano').val(tamano); $('#Form_'+grid+'_orderby').val(orderby); $('#Form_'+grid+'_orderdirection').val(orderdirection); $(oLoader).width($(oGrid).width()) $(oLoader).height($(oGrid).height()) jQuery(oLoader).show(); $.ajax({ type: "POST", url: Routing.generate(url), data: ($(oForm).serialize()+'&datagrid='+grid), success: function(data){ data = data.replace(/^\s*|\s*$/g,""); $(oGrid).html(data); }, error: function(XMLHttpRequest, textStatus, errorThrown){ jQuery(oLoader).hide(); $("#dialog-modal").html("Error: "+XMLHttpRequest.status + ' ' + XMLHttpRequest.statusText); $("#dialog-modal").dialog("open"); } }); } function dg_delitem(urlreload, urldelete, grid, form, deletekey) { if (confirm("¿Está seguro que desea eliminar?")) { var oForm = $("#"+form); var oGrid = $("#"+grid); var oLoader = $("#loader_"+grid); $('#Form_'+grid+'_deletekey').val(deletekey); $(oLoader).width($(oGrid).width()) $(oLoader).height($(oGrid).height()) jQuery(oLoader).show(); $.ajax({ type: "POST", url: Routing.generate(urldelete), data: $(oForm).serialize(), success: function(data){ data = data.replace(/^\s*|\s*$/g,""); if(data == 'OK'){ dg_reload(urlreload, grid, form); }else{ jQuery(oLoader).hide(); $("#dialog-modal").html(data); $("#dialog-modal").dialog("open"); } }, error: function(XMLHttpRequest, textStatus, errorThrown){ jQuery(oLoader).hide(); $("#dialog-modal").html("Error: "+XMLHttpRequest.status + ' ' + XMLHttpRequest.statusText); $("#dialog-modal").dialog("open"); } }); } } function dg_reload(url, grid, form) { dg_send(url, grid, form, $('#Form_'+grid+'_page').val(), $('#Form_'+grid+'_tamano').val(), $('#Form_'+grid+'_orderby').val(), $('#Form_'+grid+'_orderdirection').val() ); }
wiccano/Symfony2-SoftwareFreedomDay2012
src/Admin/DashboardBundle/Resources/public/js/components/datagrid.js
JavaScript
mit
2,133
"use strict"; exports.buttonEvent = function(id) { return function(cb) { return function() { var el = document.getElementById(id); el.addEventListener('click', function(ev) { cb(); }); } }; }; exports.keydownEvent = function(el) { return function(cb) { return function() { window.addEventListener('keydown', function(ev) { cb(ev)(); }); } }; }; exports.resizeEvent = function(cb) { return function() { var resizeDelay = 250; // ms delay before running resize logic var resizeTimeout = null; var throttled = function() { if (resizeTimeout) { clearTimeout(resizeTimeout); } resizeTimeout = setTimeout(function() { resizeTimeout = null; cb(exports.windowInnerSize())(); }, resizeDelay); }; window.addEventListener('resize', throttled, false); }; }; exports.windowInnerSize = function() { var w = window.innerWidth; var h = window.innerHeight; return { width: w, height: h }; }; exports.setWindow = function(k) { return function(v) { return function() { window[k] = v; }; }; }; exports.setElementContents = function(el) { return function(html) { return function() { el.innerHTML = html; }; }; }; var debugDivId = "debugDiv"; exports.initDebugDiv = function(radius) { return function() { var view = document.getElementById("browser"); var div = document.getElementById(debugDivId); if (!div) { div = document.createElement("div"); view.appendChild(div); } div.id = debugDivId; div.style['position'] = "relative"; div.style['left'] = "0.0"; div.style['top'] = "0.0"; div.style['border-radius'] = "50%"; div.style['width'] = (radius * 2.0) + "px"; div.style['height'] = (radius * 2.0) + "px"; div.style['z-index'] = "100"; div.style['backgroundColor'] = "red"; div.style['pointer-events'] = "none"; div.style['display'] = "inline-block"; div.style['visibility'] = "hidden"; div.dataset.radius = radius; return div; }; }; var getDebugDiv = function() { var div = document.getElementById(debugDivId); if (!div) { return initDebugDiv(10.0)(); } else { return div; } }; exports.setDebugDivVisibility = function(s) { return function() { var div = getDebugDiv(); div.style['visibility'] = s; }; }; exports.setDebugDivPoint = function(p) { return function() { var div = getDebugDiv(); var r = div.dataset.radius | 1.0; var x = p.x - r; var y = p.y - r * 2.0; // var y = p.y; div.style['left'] = x + "px"; div.style['top'] = y + "px"; }; };
chfi/purescript-genetics-browser
src/Genetics/Browser/UI.js
JavaScript
mit
2,967
window.appConf = { author: 'React Drive CMS', dashboardId: '1-on_GfmvaEcOk7HcWfKb8B6KFRv166RkLN2YmDEtDn4', sendContactMessageUrlId: 'AKfycbyL4vW1UWs4mskuDjLoLmf1Hjan1rTLEca6i2Hi2H_4CtKUN84d', shortname: 'easydrivecms', root: 'react-drive-cms', }
misterfresh/react-drive-cms
conf.js
JavaScript
mit
274
import Express from 'express'; import compression from 'compression'; import mongoose from 'mongoose'; import bodyParser from 'body-parser'; import path from 'path'; import morgan from 'morgan'; //import jwt from 'jsonwebtoken'; import IntlWrapper from '../client/modules/Intl/IntlWrapper'; // Webpack Requirements import webpack from 'webpack'; import config from '../webpack.config.dev'; import webpackDevMiddleware from 'webpack-dev-middleware'; import webpackHotMiddleware from 'webpack-hot-middleware'; // var apiRoutes = express.Router(); // Initialize the Express App const app = new Express(); const apiRoutes = require('express').Router(); // Run Webpack dev server in development mode if (process.env.NODE_ENV === 'development') { const compiler = webpack(config); app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: config.output.publicPath })); app.use(webpackHotMiddleware(compiler)); } // React And Redux Setup import { configureStore } from '../client/store'; import { Provider } from 'react-redux'; import React from 'react'; import { renderToString } from 'react-dom/server'; import { match, RouterContext } from 'react-router'; import Helmet from 'react-helmet'; // Import required modules import routes from '../client/routes'; import { fetchComponentData } from './util/fetchData'; import posts from './routes/post.routes'; import signup from './routes/signup.routes'; import login from './routes/login.routes'; import sms from './routes/sms.routes'; import dummyData from './dummyData'; import serverConfig from './config'; // Set native promises as mongoose promise mongoose.Promise = global.Promise; // MongoDB Connection mongoose.connect(serverConfig.mongoURL, (error) => { if (error) { console.error('Please make sure Mongodb is installed and running!'); // eslint-disable-line no-console throw error; } // feed some dummy data in DB. dummyData(); }); // Apply body Parser and server public assets and routes app.use(compression()); app.use(bodyParser.json({ limit: '20mb' })); app.use(bodyParser.urlencoded({ limit: '20mb', extended: false })); app.use(morgan('dev')); app.use(Express.static(path.resolve(__dirname, '../dist'))); app.use('/api', [posts, signup, login, sms]); app.set('superSecret', config.secret); // Render Initial HTML const renderFullPage = (html, initialState) => { const head = Helmet.rewind(); // Import Manifests const assetsManifest = process.env.webpackAssets && JSON.parse(process.env.webpackAssets); const chunkManifest = process.env.webpackChunkAssets && JSON.parse(process.env.webpackChunkAssets); return ` <!doctype html> <html> <head> ${head.base.toString()} ${head.title.toString()} ${head.meta.toString()} ${head.link.toString()} ${head.script.toString()} ${process.env.NODE_ENV === 'production' ? `<link rel='stylesheet' href='${assetsManifest['/app.css']}' />` : ''} <link href='https://fonts.googleapis.com/css?family=Lato:400,300,700' rel='stylesheet' type='text/css'/> <link rel="shortcut icon" href="http://res.cloudinary.com/hashnode/image/upload/v1455629445/static_imgs/mern/mern-favicon-circle-fill.png" type="image/png" /> </head> <body> <div id="root">${html}</div> <script> window.__INITIAL_STATE__ = ${JSON.stringify(initialState)}; ${process.env.NODE_ENV === 'production' ? `//<![CDATA[ window.webpackManifest = ${JSON.stringify(chunkManifest)}; //]]>` : ''} </script> <script src='${process.env.NODE_ENV === 'production' ? assetsManifest['/vendor.js'] : '/vendor.js'}'></script> <script src='${process.env.NODE_ENV === 'production' ? assetsManifest['/app.js'] : '/app.js'}'></script> </body> </html> `; }; const renderError = err => { const softTab = '&#32;&#32;&#32;&#32;'; const errTrace = process.env.NODE_ENV !== 'production' ? `:<br><br><pre style="color:red">${softTab}${err.stack.replace(/\n/g, `<br>${softTab}`)}</pre>` : ''; return renderFullPage(`Server Error${errTrace}`, {}); }; // Server Side Rendering based on routes matched by React-router. app.use((req, res, next) => { match({ routes, location: req.url }, (err, redirectLocation, renderProps) => { if (err) { return res.status(500).end(renderError(err)); } if (redirectLocation) { return res.redirect(302, redirectLocation.pathname + redirectLocation.search); } if (!renderProps) { return next(); } const store = configureStore(); return fetchComponentData(store, renderProps.components, renderProps.params) .then(() => { const initialView = renderToString( <Provider store={store}> <IntlWrapper> <RouterContext {...renderProps} /> </IntlWrapper> </Provider> ); const finalState = store.getState(); res .set('Content-Type', 'text/html') .status(200) .end(renderFullPage(initialView, finalState)); }) .catch((error) => next(error)); }); }); // route to authenticate a user (POST http://localhost:8080/api/authenticate) // route middleware to verify a token // apiRoutes.use(function(req, res, next) { // // check header or url parameters or post parameters for token // var token = req.body.token || req.query.token || req.headers['x-access-token']; // // decode token // if (token) { // // verifies secret and checks exp // jwt.verify(token, app.get('superSecret'), function(err, decoded) { // if (err) { // return res.json({ success: false, message: 'Failed to authenticate token.' }); // } else { // // if everything is good, save to request for use in other routes // req.decoded = decoded; // next(); // } // }); // } else { // // if there is no token // // return an error // return res.status(403).send({ // success: false, // message: 'No token provided.' // }); // } // }); // route to show a random message (GET http://localhost:8080/api/) // route to return all users (GET http://localhost:8080/api/users) // apply the routes to our application with the prefix /api //app.use('/api', apiRoutes); // start app app.listen(serverConfig.port, (error) => { if (!error) { console.log(`MERN is running on port: ${serverConfig.port}! Build something amazing!`); // eslint-disable-line } }); export default app;
jyothigundeti/sample-app
server/server.js
JavaScript
mit
6,574
module.exports = flatten([ require("./base/dualfilter"), require("./base/filter"), require("./base/mirrorBlocks"), require("./base/overlayMask"), require("./base/split"), require("./base/splitMask"), require("./colourset/lerp"), require("./colourset/distinct"), require("./colourset/chunks"), require("./colourset/alpha"), require("./extras/swatch"), require("./extras/text"), require("./filter/bevel"), require("./filter/disolve"), require("./filter/roughen"), require("./filter/sharpen"), require("./filter/splash"), require("./lines/straight"), require("./lines/curve"), require("./lines/scribble"), require("./mask/halfmask"), require("./overlay/lines"), require("./overlay/network"), require("./overlay/shapes"), require("./overlay/sparkles"), require("./pallete/monochrome"), require("./pallete/hightlightAndMidtone"), require("./pallete/bicolor"), require("./pointset/static"), require("./pointset/linear"), require("./pointset/circular"), require("./pointset/grid"), require("./pointset/spiral"), require("./pointset/tree"), require("./shapes/polygon"), require("./shapes/stars"), require("./shapes/ring"), require("./shapes/circle"), require("./simple/blockColor"), require("./simple/blockOverlay"), require("./spacial/radial"), require("./spacial/chaos"), require("./spacial/linear"), require("./tiles/squares"), require("./tiles/triangles"), ]) function flatten( m ){ var retval = []; for ( var id in m ){ if ( m[id].push ){ retval = retval.concat(m[id]); }else{ retval.push(m[id]); } } return retval; }
chris-j-major/unique-wallpaper
parts/all.js
JavaScript
mit
1,651
'use strict'; angular.module('myApp').directive('loginDirective',function(){ return{ templateUrl:'partials/tpl/login.tpl.html' } });
jaygood/angular-sessions
app/js/directives/loginDrc.js
JavaScript
mit
145
datab = [{},{"Document Version":{"colspan":"1","rowspan":"1","text":"1.1"},"Date":{"colspan":"1","rowspan":"1","text":"October 30,2003"},"Author":{"colspan":"1","rowspan":"1","text":"WG 6"},"Description":{"colspan":"1","rowspan":"1","text":"For Final Text"}},{"Document Version":{"colspan":"1","rowspan":"1","text":"1.2"},"Date":{"colspan":"1","rowspan":"1","text":"August 30, 2007"},"Author":{"colspan":"1","rowspan":"1","text":"WG 6"},"Description":{"colspan":"1","rowspan":"1","text":"Revised Introduction"}}];
vupeter/posdaJS
lib/json/book/part02/table_E.3.1-1.js
JavaScript
mit
513
function Rook(loc, isWhite, asset){ Piece.call(this, loc, isWhite, asset); this.name = "Rook"; } Rook.prototype = Object.create(Piece.prototype); Rook.prototype.constructor = Rook; Rook.prototype.getValidMoveSet = function(board) { var result = []; var currentX = this.loc.x+1; var currentY = this.loc.y; var currentSpeculation = new Point(currentX, currentY); //moving right while(board.inBounds(currentSpeculation) && !board.locOccupied(currentSpeculation)){ result.push(currentSpeculation); currentX += 1; currentSpeculation = new Point(currentX, currentY); } var cap = board.getPieceAt(currentSpeculation); if(cap){ if(cap.isWhite() !== this.white){ result.push(currentSpeculation); } } //moving left currentX = this.loc.x-1; currentY = this.loc.y; currentSpeculation = new Point(currentX, currentY); while(board.inBounds(currentSpeculation) && !board.locOccupied(currentSpeculation)){ result.push(currentSpeculation); currentX -= 1; currentSpeculation = new Point(currentX, currentY); } cap = board.getPieceAt(currentSpeculation); if(cap){ if(cap.isWhite() !== this.white){ result.push(currentSpeculation); } } //moving up currentX = this.loc.x; currentY = this.loc.y-1; currentSpeculation = new Point(currentX, currentY); while(board.inBounds(currentSpeculation) && !board.locOccupied(currentSpeculation)){ result.push(currentSpeculation); currentY -= 1; currentSpeculation = new Point(currentX, currentY); } cap = board.getPieceAt(currentSpeculation); if(cap){ if(cap.isWhite() !== this.white){ result.push(currentSpeculation); } } //moving down currentX = this.loc.x; currentY = this.loc.y+1; currentSpeculation = new Point(currentX, currentY); while(board.inBounds(currentSpeculation) && !board.locOccupied(currentSpeculation)){ result.push(currentSpeculation); currentY += 1; currentSpeculation = new Point(currentX, currentY); } cap = board.getPieceAt(currentSpeculation); if(cap){ if(cap.isWhite() !== this.white){ result.push(currentSpeculation); } } return result; };
xLeachimx/ChessCast
webapp/cast-receiver/javascript/rook.js
JavaScript
mit
2,168
var dir_72c031272133aec1d916095cf903ecf1 = [ [ "HTTP", "dir_7e5fd1ff9265fa651882e3ad4d93cc88.html", "dir_7e5fd1ff9265fa651882e3ad4d93cc88" ], [ "Module", "dir_10705d0e5b4538c0e815cbe3b6497638.html", "dir_10705d0e5b4538c0e815cbe3b6497638" ] ];
SaltAPI/SaltAPI.github.io
Doxygen/html/dir_72c031272133aec1d916095cf903ecf1.js
JavaScript
mit
250
var flow = require('js-flow'), assert = require('assert'), tubes = require('evo-tubes'); describe('evo-states', function () { var TIMEOUT = 60000; var sandbox; beforeEach(function (done) { this.timeout(TIMEOUT); (sandbox = new tubes.Sandbox()) .add(new tubes.Environment({ nodes: 4 })) .add(new tubes.NeuronFactory()) .add(new tubes.Connector()) .add(new tubes.States()) .start(done); }); afterEach(function (done) { sandbox.cleanup(done); }); it('synchronize', function (done) { this.timeout(TIMEOUT); var connector = sandbox.res('evo-connector'); flow.steps() .next('clientsReady') .next(function (next) { flow.each([this.clients[0], this.clients[1]]) .keys() .do(function (index, client, next) { client.commit({ key: 'val' + index }, next); }) .run(next); }) .next(function (next) { this.waitForSync({ key: 'key' }, function (data, client, index) { return [0, 1].every(function (i) { var nodeVal = data.d[connector.clients[i].localId]; return nodeVal && nodeVal.d == 'val' + i; }); }, next); }) .with(sandbox.res('evo-states')) .run(done) }); });
evo-cloud/states
test/states-int-test.js
JavaScript
mit
1,527
/** * @authors JayChenFE * @date 2017-03-21 11:17:13 * @version $1.0$ */ /** * 主要核心逻辑入口 **/ const fs = require('fs'); const path = require('path'); const staticServer = require('./static-server'); class App { constructor() { } initServer() { //方便增加别的逻辑 //返回一个函数 return (request, response) => { let { url } = request; let body = staticServer(url); response.writeHead(200, 'resolve ok', { 'X-Powered-By': 'Node.js' }); response.end(body); // const staticPrefix = path.resolve(process.cwd(), 'public'); // let staticFun = url => { // if (url == '/') { // url = '/index.html'; // } // let _path = getPath(url); // // fs.readFile(_path, 'binary', (error, data) => { // // if (error) { // // data="NOT FOUND"; // // } // // response.end(data,'binary'); // // }); // fs.readFile(_path, (error, data) => { // if (error) { // data = `NOT FOUND ${error.stack}`; // } // response.end(data); // }); // }; // staticFun(url); // if (url == '/css/index.css') { // fs.readFile('./public/css/index.css', 'utf-8', (error, data) => { // response.end(data); // }); // } // if (url == '/js/index.js') { // fs.readFile('./public/js/index.js', 'utf-8', (error, data) => { // response.end(data); // }); // } // if (url == '/') { // //第一个路径相对的是process.cwd(); // fs.readFile('./public/index.html', 'utf-8', (error, data) => { // response.end(data); // }); // } }; } } module.exports = App;
JayChenFE/pure-node-notebook
lesson2/app/index.js
JavaScript
mit
1,646
define('controllers/menuController',['jqueryui'],function($){ $('#faq').dialog({ modal:true, autoOpen: false, height:window.innerHeight * 0.75, width:window.innerWidth * 0.75, draggable:false }); $('#faq-button').click(function(event){ $('#faq').dialog('open'); }); $('#signin').dialog({ modal:true, autoOpen: false, height:window.innerHeight * 0.75, width:window.innerWidth * 0.75, draggable:false }); $('#signin-button').click(function(event){ $('#signin').dialog('open'); }); $('#facebook-login').click(function(event){ $(document).trigger('facebook-login'); }); });
harryphan/teachme
public/js/controllers/menuController.js
JavaScript
mit
742
const _ = require("lodash"); const Path = require("path-parser"); const { URL } = require("url"); const mongoose = require("mongoose"); const requireSignIn = require("../middlewares/requireSignIn"); const requireCredits = require("../middlewares/requireCredits"); const Mailer = require("../services/Mailer"); const surveyTemplate = require("../services/templates/surveyTemplate"); const Survey = mongoose.model("surveys"); module.exports = app => { app.get("/api/surveys", requireSignIn, async (req, res) => { const surveys = await Survey.find({ _user: req.user.id }).select({ recipients: false }); res.send(surveys); }); app.get("/api/surveys/:surveyID/:choice", (req, res) => { res.send("Thank you for your response."); }); app.post("/api/surveys/webhooks", (req, res) => { const parsedURL = new Path("/api/surveys/:surveyID/:choice"); _.chain(req.body) .map(({ email, url }) => { //do not destructure because match can be null const match = parsedURL.test(new URL(url).pathname); if (match) { return { email, surveyID: match.surveyID, choice: match.choice }; } }) .compact() .uniqBy("email", "surveyID") .each(({ surveyID, email, choice }) => { Survey.updateOne( { _id: surveyID, recipients: { $elemMatch: { email: email, responded: false } } }, { $inc: { [choice]: 1 }, $set: { "recipients.$.responded": true }, lastResponded: new Date() } ).exec(); }) .value(); res.send({}); }); app.post("/api/surveys", requireSignIn, requireCredits, async (req, res) => { const { title, subject, body, recipients } = req.body; const survey = new Survey({ title, subject, body, recipients: recipients.split(",").map(email => ({ email: email.trim() })), _user: req.user.id, dateSent: Date.now() }); const mailer = new Mailer(survey, surveyTemplate(survey)); try { await mailer.send(); await survey.save(); req.user.credits -= 1; const user = await req.user.save(); res.send(user); } catch (err) { res.status(422).send(err); } }); };
ibramos/The-Feed
server/routes/surveyRoutes.js
JavaScript
mit
2,308
// Geometry building functions import Vector from '../vector'; import Geo from '../geo'; import earcut from 'earcut'; var Builders; export default Builders = {}; Builders.debug = false; Builders.tile_bounds = [ { x: 0, y: 0}, { x: Geo.tile_scale, y: -Geo.tile_scale } // TODO: correct for flipped y-axis? ]; // Re-scale UVs from [0, 1] range to a smaller area within the image Builders.scaleTexcoordsToSprite = function (uv, area_origin, area_size, tex_size) { var area_origin_y = tex_size[1] - area_origin[1] - area_size[1]; var suv = []; suv[0] = (uv[0] * area_size[0] + area_origin[0]) / tex_size[0]; suv[1] = (uv[1] * area_size[1] + area_origin_y) / tex_size[1]; return suv; }; Builders.getTexcoordsForSprite = function (area_origin, area_size, tex_size) { return [ Builders.scaleTexcoordsToSprite([0, 0], area_origin, area_size, tex_size), Builders.scaleTexcoordsToSprite([1, 1], area_origin, area_size, tex_size) ]; }; // Tesselate a flat 2D polygon // x & y coordinates will be set as first two elements of provided vertex_template Builders.buildPolygons = function ( polygons, vertex_data, vertex_template, { texcoord_index, texcoord_scale, texcoord_normalize }) { if (texcoord_index) { texcoord_normalize = texcoord_normalize || 1; var [[min_u, min_v], [max_u, max_v]] = texcoord_scale || [[0, 0], [1, 1]]; } var num_polygons = polygons.length; for (var p=0; p < num_polygons; p++) { var polygon = polygons[p]; // Find polygon extents to calculate UVs, fit them to the axis-aligned bounding box if (texcoord_index) { var [min_x, min_y, max_x, max_y] = Geo.findBoundingBox(polygon); var span_x = max_x - min_x; var span_y = max_y - min_y; var scale_u = (max_u - min_u) / span_x; var scale_v = (max_v - min_v) / span_y; } // Tessellate var vertices = Builders.triangulatePolygon(polygon); // Add vertex data var num_vertices = vertices.length; for (var v=0; v < num_vertices; v++) { var vertex = vertices[v]; vertex_template[0] = vertex[0]; vertex_template[1] = vertex[1]; // Add UVs if (texcoord_index) { vertex_template[texcoord_index + 0] = ((vertex[0] - min_x) * scale_u + min_u) * texcoord_normalize; vertex_template[texcoord_index + 1] = ((vertex[1] - min_y) * scale_v + min_v) * texcoord_normalize; } vertex_data.addVertex(vertex_template); } } }; // Tesselate and extrude a flat 2D polygon into a simple 3D model with fixed height and add to GL vertex buffer Builders.buildExtrudedPolygons = function ( polygons, z, height, min_height, vertex_data, vertex_template, normal_index, normal_normalize, { texcoord_index, texcoord_scale, texcoord_normalize }) { // Top var min_z = z + (min_height || 0); var max_z = z + height; vertex_template[2] = max_z; Builders.buildPolygons(polygons, vertex_data, vertex_template, { texcoord_index, texcoord_scale, texcoord_normalize }); // Walls // Fit UVs to wall quad if (texcoord_index) { texcoord_normalize = texcoord_normalize || 1; var [[min_u, min_v], [max_u, max_v]] = texcoord_scale || [[0, 0], [1, 1]]; var texcoords = [ [min_u, max_v], [min_u, min_v], [max_u, min_v], [max_u, min_v], [max_u, max_v], [min_u, max_v] ]; } var num_polygons = polygons.length; for (var p=0; p < num_polygons; p++) { var polygon = polygons[p]; for (var q=0; q < polygon.length; q++) { var contour = polygon[q]; for (var w=0; w < contour.length - 1; w++) { // Two triangles for the quad formed by each vertex pair, going from bottom to top height var wall_vertices = [ // Triangle [contour[w+1][0], contour[w+1][1], max_z], [contour[w+1][0], contour[w+1][1], min_z], [contour[w][0], contour[w][1], min_z], // Triangle [contour[w][0], contour[w][1], min_z], [contour[w][0], contour[w][1], max_z], [contour[w+1][0], contour[w+1][1], max_z] ]; // Calc the normal of the wall from up vector and one segment of the wall triangles var normal = Vector.cross( [0, 0, 1], Vector.normalize([contour[w+1][0] - contour[w][0], contour[w+1][1] - contour[w][1], 0]) ); // Update vertex template with current surface normal vertex_template[normal_index + 0] = normal[0] * normal_normalize; vertex_template[normal_index + 1] = normal[1] * normal_normalize; vertex_template[normal_index + 2] = normal[2] * normal_normalize; for (var wv=0; wv < wall_vertices.length; wv++) { vertex_template[0] = wall_vertices[wv][0]; vertex_template[1] = wall_vertices[wv][1]; vertex_template[2] = wall_vertices[wv][2]; if (texcoord_index) { vertex_template[texcoord_index + 0] = texcoords[wv][0] * texcoord_normalize; vertex_template[texcoord_index + 1] = texcoords[wv][1] * texcoord_normalize; } vertex_data.addVertex(vertex_template); } } } } }; // Build tessellated triangles for a polyline Builders.buildPolylines = function ( lines, width, vertex_data, vertex_template, { closed_polygon, remove_tile_edges, tile_edge_tolerance, texcoord_index, texcoord_scale, texcoord_normalize, scaling_index, scaling_normalize, join, cap }) { var cornersOnCap = (cap === "square") ? 2 : ((cap === "round") ? 3 : 0); // Butt is the implicit default var trianglesOnJoin = (join === "bevel") ? 1 : ((join === "round") ? 3 : 0); // Miter is the implicit default // Build variables texcoord_normalize = texcoord_normalize || 1; var [[min_u, min_v], [max_u, max_v]] = texcoord_scale || [[0, 0], [1, 1]]; // Values that are constant for each line and are passed to helper functions var constants = { vertex_data, vertex_template, halfWidth: width/2, vertices: [], scaling_index, scaling_normalize, scalingVecs: scaling_index && [], texcoord_index, texcoords: texcoord_index && [], texcoord_normalize, min_u, min_v, max_u, max_v, nPairs: 0 }; for (var ln = 0; ln < lines.length; ln++) { var line = lines[ln]; var lineSize = line.length; // Ignore non-lines if (lineSize < 2) { continue; } // Initialize variables var coordPrev = [0, 0], // Previous point coordinates coordCurr = [0, 0], // Current point coordinates coordNext = [0, 0]; // Next point coordinates var normPrev = [0, 0], // Right normal to segment between previous and current m_points normCurr = [0, 0], // Right normal at current point, scaled for miter joint normNext = [0, 0]; // Right normal to segment between current and next m_points var isPrev = false, isNext = true; // Add vertices to buffer according to their index indexPairs(constants); // Do this with the rest (except the last one) for (let i = 0; i < lineSize ; i++) { // There is a next one? isNext = i+1 < lineSize; if (isPrev) { // If there is a previous one, copy the current (previous) values on *Prev coordPrev = coordCurr; normPrev = Vector.normalize(Vector.perp(coordPrev, line[i])); } else if (i === 0 && closed_polygon === true) { // If it's the first point and is a closed polygon var needToClose = true; if (remove_tile_edges) { if(Builders.isOnTileEdge(line[i], line[lineSize-2], { tolerance: tile_edge_tolerance })) { needToClose = false; } } if (needToClose) { coordPrev = line[lineSize-2]; normPrev = Vector.normalize(Vector.perp(coordPrev, line[i])); isPrev = true; } } // Assign current coordinate coordCurr = line[i]; if (isNext) { coordNext = line[i+1]; } else if (closed_polygon === true) { // If it's the last point in a closed polygon coordNext = line[1]; isNext = true; } if (isNext) { // If it's not the last one get next coordinates and calculate the right normal normNext = Vector.normalize(Vector.perp(coordCurr, coordNext)); if (remove_tile_edges) { if (Builders.isOnTileEdge(coordCurr, coordNext, { tolerance: tile_edge_tolerance })) { normCurr = Vector.normalize(Vector.perp(coordPrev, coordCurr)); if (isPrev) { addVertexPair(coordCurr, normCurr, i/lineSize, constants); constants.nPairs++; // Add vertices to buffer acording their index indexPairs(constants); } isPrev = false; continue; } } } // Compute current normal if (isPrev) { // If there is a PREVIOUS ... if (isNext) { // ... and a NEXT ONE, compute previous and next normals (scaled by the angle with the last prev) normCurr = Vector.normalize(Vector.add(normPrev, normNext)); var scale = 2 / (1 + Math.abs(Vector.dot(normPrev, normCurr))); normCurr = Vector.mult(normCurr,scale*scale); } else { // ... and there is NOT a NEXT ONE, copy the previous next one (which is the current one) normCurr = Vector.normalize(Vector.perp(coordPrev, coordCurr)); } } else { // If there is NO PREVIOUS ... if (isNext) { // ... and a NEXT ONE, normNext = Vector.normalize(Vector.perp(coordCurr, coordNext)); normCurr = normNext; } else { // ... and NO NEXT ONE, nothing to do (without prev or next one this is just a point) continue; } } if (isPrev || isNext) { // If it's the BEGINNING of a LINE if (i === 0 && !isPrev && !closed_polygon) { addCap(coordCurr, normCurr, cornersOnCap, true, constants); } // If it's a JOIN if(trianglesOnJoin !== 0 && isPrev && isNext) { addJoin([coordPrev, coordCurr, coordNext], [normPrev,normCurr, normNext], i/lineSize, trianglesOnJoin, constants); } else { addVertexPair(coordCurr, normCurr, i/(lineSize-1), constants); } if (isNext) { constants.nPairs++; } isPrev = true; } } // Add vertices to buffer according to their index indexPairs(constants); // If it's the END of a LINE if(!closed_polygon) { addCap(coordCurr, normCurr, cornersOnCap , false, constants); } } }; // Add to equidistant pairs of vertices (internal method for polyline builder) function addVertex(coord, normal, uv, { halfWidth, vertices, scalingVecs, texcoords }) { if (scalingVecs) { // a. If scaling is on add the vertex (the currCoord) and the scaling Vecs (normals pointing where to extrude the vertices) vertices.push(coord); scalingVecs.push(normal); } else { // b. Add the extruded vertices vertices.push([coord[0] + normal[0] * halfWidth, coord[1] + normal[1] * halfWidth]); } // c) Add UVs if they are enabled if (texcoords) { texcoords.push(uv); } } // Add to equidistant pairs of vertices (internal method for polyline builder) function addVertexPair (coord, normal, v_pct, constants) { addVertex(coord, normal, [constants.max_u, (1-v_pct)*constants.min_v + v_pct*constants.max_v], constants); addVertex(coord, Vector.neg(normal), [constants.min_u, (1-v_pct)*constants.min_v + v_pct*constants.max_v], constants); } // Tessalate a FAN geometry between points A B // using their normals from a center \ . . / // and interpolating their UVs \ p / // \./ // C function addFan (coord, nA, nC, nB, uA, uC, uB, signed, numTriangles, constants) { if (numTriangles < 1) { return; } // Add previous vertices to buffer and clear the buffers and index pairs // because we are going to add more triangles. indexPairs(constants); var normCurr = Vector.set(nA); var normPrev = [0,0]; var angle_delta = Vector.dot(nA, nB); if (angle_delta < -1) { angle_delta = -1; } angle_delta = Math.acos(angle_delta)/numTriangles; if (!signed) { angle_delta *= -1; } var uvCurr = Vector.set(uA); var uv_delta = Vector.div(Vector.sub(uB,uA), numTriangles); // Add the FIRST and CENTER vertex // The triangles will be composed in a FAN style around it addVertex(coord, nC, uC, constants); // Add first corner addVertex(coord, normCurr, uA, constants); // Iterate through the rest of the corners for (var t = 0; t < numTriangles; t++) { normPrev = Vector.normalize(normCurr); normCurr = Vector.rot( Vector.normalize(normCurr), angle_delta); // Rotate the extrusion normal if (numTriangles === 4 && (t === 0 || t === numTriangles - 2)) { var scale = 2 / (1 + Math.abs(Vector.dot(normPrev, normCurr))); normCurr = Vector.mult(normCurr, scale*scale); } uvCurr = Vector.add(uvCurr,uv_delta); addVertex(coord, normCurr, uvCurr, constants); // Add computed corner } for (var i = 0; i < numTriangles; i++) { if (signed) { addIndex(i+2, constants); addIndex(0, constants); addIndex(i+1, constants); } else { addIndex(i+1, constants); addIndex(0, constants); addIndex(i+2, constants); } } // Clear the buffer constants.vertices = []; if (constants.scalingVecs) { constants.scalingVecs = []; } if (constants.texcoords) { constants.texcoords = []; } } // Add special joins (not miter) types that require FAN tessellations // Using http://www.codeproject.com/Articles/226569/Drawing-polylines-by-tessellation as reference function addJoin (coords, normals, v_pct, nTriangles, constants) { var T = [Vector.set(normals[0]), Vector.set(normals[1]), Vector.set(normals[2])]; var signed = Vector.signed_area(coords[0], coords[1], coords[2]) > 0; var nA = T[0], // normal to point A (aT) nC = Vector.neg(T[1]), // normal to center (-vP) nB = T[2]; // normal to point B (bT) var uA = [constants.max_u, (1-v_pct)*constants.min_v + v_pct*constants.max_v], uC = [constants.min_u, (1-v_pct)*constants.min_v + v_pct*constants.max_v], uB = [constants.max_u, (1-v_pct)*constants.min_v + v_pct*constants.max_v]; if (signed) { addVertex(coords[1], nA, uA, constants); addVertex(coords[1], nC, uC, constants); } else { nA = Vector.neg(T[0]); nC = T[1]; nB = Vector.neg(T[2]); uA = [constants.min_u, (1-v_pct)*constants.min_v + v_pct*constants.max_v]; uC = [constants.max_u, (1-v_pct)*constants.min_v + v_pct*constants.max_v]; uB = [constants.min_u, (1-v_pct)*constants.min_v + v_pct*constants.max_v]; addVertex(coords[1], nC, uC, constants); addVertex(coords[1], nA, uA, constants); } addFan(coords[1], nA, nC, nB, uA, uC, uB, signed, nTriangles, constants); if (signed) { addVertex(coords[1], nB, uB, constants); addVertex(coords[1], nC, uC, constants); } else { addVertex(coords[1], nC, uC, constants); addVertex(coords[1], nB, uB, constants); } } // Function to add the vertex need for line caps, // because re-use the buffers needs to be at the end function addCap (coord, normal, numCorners, isBeginning, constants) { if (numCorners < 1) { return; } // UVs var uvA = [constants.min_u,constants.min_v], // Beginning angle UVs uvC = [constants.min_u+(constants.max_u-constants.min_u)/2, constants.min_v], // center point UVs uvB = [constants.max_u,constants.min_v]; // Ending angle UVs if (!isBeginning) { uvA = [constants.min_u,constants.max_v], // Begining angle UVs uvC = [constants.min_u+(constants.max_u-constants.min_u)/2, constants.max_v], // center point UVs uvB = [constants.max_u,constants.max_v]; } addFan( coord, Vector.neg(normal), [0, 0], normal, uvA, uvC, uvB, isBeginning, numCorners*2, constants); } // Add a vertex based on the index position into the VBO (internal method for polyline builder) function addIndex (index, { vertex_data, vertex_template, halfWidth, vertices, scaling_index, scaling_normalize, scalingVecs, texcoord_index, texcoords, texcoord_normalize }) { // Prevent access to undefined vertices if (index >= vertices.length) { return; } // set vertex position vertex_template[0] = vertices[index][0]; vertex_template[1] = vertices[index][1]; // set UVs if (texcoord_index) { vertex_template[texcoord_index + 0] = texcoords[index][0] * texcoord_normalize; vertex_template[texcoord_index + 1] = texcoords[index][1] * texcoord_normalize; } // set Scaling vertex (X, Y normal direction + Z halfwidth as attribute) if (scaling_index) { vertex_template[scaling_index + 0] = scalingVecs[index][0] * scaling_normalize; vertex_template[scaling_index + 1] = scalingVecs[index][1] * scaling_normalize; vertex_template[scaling_index + 2] = halfWidth; } // Add vertex to VBO vertex_data.addVertex(vertex_template); } // Add the index vertex to the VBO and clean the buffers function indexPairs (constants) { // Add vertices to buffer acording their index for (var i = 0; i < constants.nPairs; i++) { addIndex(2*i+2, constants); addIndex(2*i+1, constants); addIndex(2*i+0, constants); addIndex(2*i+2, constants); addIndex(2*i+3, constants); addIndex(2*i+1, constants); } constants.nPairs = 0; // Clean the buffer constants.vertices = []; if (constants.scalingVecs) { constants.scalingVecs = []; } if (constants.texcoords) { constants.texcoords = []; } } // Build a billboard sprite quad centered on a point. Sprites are intended to be drawn in screenspace, and have // properties for width, height, angle, and a scale factor that can be used to interpolate the screenspace size // of a sprite between two zoom levels. Builders.buildQuadsForPoints = function ( points, width, height, angle, scale, vertex_data, vertex_template, scaling_index, { texcoord_index, texcoord_scale, texcoord_normalize }) { let w2 = width / 2; let h2 = height / 2; let scaling = [ [-w2, -h2], [w2, -h2], [w2, h2], [-w2, -h2], [w2, h2], [-w2, h2] ]; let texcoords; if (texcoord_index) { texcoord_normalize = texcoord_normalize || 1; let [[min_u, min_v], [max_u, max_v]] = texcoord_scale || [[0, 0], [1, 1]]; texcoords = [ [min_u, min_v], [max_u, min_v], [max_u, max_v], [min_u, min_v], [max_u, max_v], [min_u, max_v] ]; } let num_points = points.length; for (let p=0; p < num_points; p++) { let point = points[p]; for (let pos=0; pos < 6; pos++) { // Add texcoords if (texcoord_index) { vertex_template[texcoord_index + 0] = texcoords[pos][0] * texcoord_normalize; vertex_template[texcoord_index + 1] = texcoords[pos][1] * texcoord_normalize; } vertex_template[0] = point[0]; vertex_template[1] = point[1]; vertex_template[scaling_index + 0] = scaling[pos][0]; vertex_template[scaling_index + 1] = scaling[pos][1]; vertex_template[scaling_index + 2] = angle; vertex_template[scaling_index + 3] = scale; vertex_data.addVertex(vertex_template); } } }; /* Utility functions */ // Triangulation using earcut // https://github.com/mapbox/earcut Builders.triangulatePolygon = function (contours) { return earcut(contours); }; // Tests if a line segment (from point A to B) is nearly coincident with the edge of a tile Builders.isOnTileEdge = function (pa, pb, options) { options = options || {}; var tolerance_function = options.tolerance_function || Builders.valuesWithinTolerance; var tolerance = options.tolerance || 1; var tile_min = Builders.tile_bounds[0]; var tile_max = Builders.tile_bounds[1]; var edge = null; if (tolerance_function(pa[0], tile_min.x, tolerance) && tolerance_function(pb[0], tile_min.x, tolerance)) { edge = 'left'; } else if (tolerance_function(pa[0], tile_max.x, tolerance) && tolerance_function(pb[0], tile_max.x, tolerance)) { edge = 'right'; } else if (tolerance_function(pa[1], tile_min.y, tolerance) && tolerance_function(pb[1], tile_min.y, tolerance)) { edge = 'top'; } else if (tolerance_function(pa[1], tile_max.y, tolerance) && tolerance_function(pb[1], tile_max.y, tolerance)) { edge = 'bottom'; } return edge; }; Builders.valuesWithinTolerance = function (a, b, tolerance) { tolerance = tolerance || 1; return (Math.abs(a - b) < tolerance); };
rosamcgee/tangram
src/styles/builders.js
JavaScript
mit
23,298
#target "InDesign" #include "../datetimef.js" var today = new Date(2014, 2, 8, 13, 23, 46, 300); // => Sat Mar 08 2014 13:23:46 GMT+0900 var ret = []; var t = function(done, expect) { done_str = done; if (done === expect) { ret.push("[Passed]: return => " + expect); } else { ret.push("[Failed]: expect " + expect + ", but return => " + done); } } // tests t( datetimef(today)+"", Error("No Format")+""); t( datetimef(today, 123)+"", Error("No Format")+""); t( datetimef(today, ""), ""); t( datetimef(today, "%X"), "%X"); t( datetimef("today", "%Y")+"", Error("Not Date")+""); t( datetimef(today, "%Y"), "2014"); t( datetimef(today, "%y"), "14"); t( datetimef(today, "%m"), "03"); t( datetimef(today, "%B"), "March"); t( datetimef(today, "%b"), "Mar"); t( datetimef(today, "%d"), "08"); t( datetimef(today, "%e"), " 8"); t( datetimef(today, "%j"), "67"); t( datetimef(today, "%H"), "13"); t( datetimef(today, "%k"), "13"); t( datetimef(today, "%I"), "01"); t( datetimef(today, "%l"), " 1"); t( datetimef(today, "%p"), "PM"); t( datetimef(today, "%P"), "pm"); t( datetimef(today, "%M"), "23"); t( datetimef(today, "%S"), "46"); t( datetimef(today, "%L"), "300"); t( datetimef(today, "%z"), "-0900"); t( datetimef(today, "%A"), "Saturday"); t( datetimef(today, "%a"), "Sat"); t( datetimef(today, "%u"), "7"); t( datetimef(today, "%w"), "6"); t( datetimef(today, "%s"), "1394252626300"); t( datetimef(today, "%Y%m%d"), "20140308" ); t( datetimef(today, "%F"), "2014-03-08" ); t( datetimef(today, "%Y-%m"), "2014-03" ); t( datetimef(today, "%Y"), "2014" ); t( datetimef(today, "%Y%j"), "201467" ); t( datetimef(today, "%Y-%j"), "2014-67" ); t( datetimef(today, "%H%M%S"), "132346" ); t( datetimef(today, "%T"), "13:23:46" ); t( datetimef(today, "%H%M"), "1323" ); t( datetimef(today, "%H:%M"), "13:23" ); t( datetimef(today, "%H"), "13" ); t( datetimef(today, "%H%M%S,%L"), "132346,300" ); t( datetimef(today, "%T,%L"), "13:23:46,300" ); t( datetimef(today, "%H%M%S.%L"), "132346.300" ); t( datetimef(today, "%T.%L"), "13:23:46.300" ); t( datetimef(today, "%H%M%S%z"), "132346-0900" ); t( datetimef(today, "%Y%m%dT%H%M%S%z"), "20140308T132346-0900" ); t( datetimef(today, "%Y%jT%H%M%S%z"), "201467T132346-0900" ); t( datetimef(today, "%Y%m%dT%H%M"), "20140308T1323" ); t( datetimef(today, "%FT%R"), "2014-03-08T13:23" ); t( datetimef(today, "%Y%jT%H%MZ"), "201467T1323Z" ); t( datetimef(today, "%Y-%jT%RZ"), "2014-67T13:23Z" ); $.writeln(ret.join("\n")); /* toString,toSource [Passed]: return => エラー: No Format [Passed]: return => エラー: No Format [Passed]: return => [Passed]: return => %X [Passed]: return => エラー: Not Date [Passed]: return => 2014 [Passed]: return => 14 [Passed]: return => 03 [Passed]: return => March [Passed]: return => Mar [Passed]: return => 08 [Passed]: return =>  8 [Passed]: return => 67 [Passed]: return => 13 [Passed]: return => 13 [Passed]: return => 01 [Passed]: return =>  1 [Passed]: return => PM [Passed]: return => pm [Passed]: return => 23 [Passed]: return => 46 [Passed]: return => 300 [Passed]: return => -0900 [Passed]: return => Saturday [Passed]: return => Sat [Passed]: return => 7 [Passed]: return => 6 [Passed]: return => 1394252626300 [Passed]: return => 20140308 [Passed]: return => 2014-03-08 [Passed]: return => 2014-03 [Passed]: return => 2014 [Passed]: return => 201467 [Passed]: return => 2014-67 [Passed]: return => 132346 [Passed]: return => 13:23:46 [Passed]: return => 1323 [Passed]: return => 13:23 [Passed]: return => 13 [Passed]: return => 132346,300 [Passed]: return => 13:23:46,300 [Passed]: return => 132346.300 [Passed]: return => 13:23:46.300 [Passed]: return => 132346-0900 [Passed]: return => 20140308T132346-0900 [Passed]: return => 201467T132346-0900 [Passed]: return => 20140308T1323 [Passed]: return => 2014-03-08T13:23 [Passed]: return => 201467T1323Z [Passed]: return => 2014-67T13:23Z */
milligramme/datetimef.js
test/datetimef_test.js
JavaScript
mit
3,900
import { all } from 'redux-saga/effects'; import WatchUsers from 'sagas/users'; export default function *WatchSagas() { yield all([ WatchUsers() ]); }
donofkarma/react-starter
app/sagas/index.js
JavaScript
mit
169
//initialize Settings. zsi.init({ baseURL : base_url ,errorUpdateURL : base_url + "common/errors_update" ,sqlConsoleName : "runsql" ,excludeAjaxWatch : ["checkDataExist","employe_search_json"] }); //check cookie and load user menus. var userInfo = readCookie("userinfo"); if(userInfo){ if(isLocalStorageSupport()) { userInfo = JSON.parse(localStorage.getItem("userinfo")); var menuInfo = localStorage.getItem("menuInfo"); if(menuInfo){ displayMenu( JSON.parse(menuInfo)); } }else{ loadMenu(); loadUserInfo(); } }else{ loadMenu(); loadUserInfo(); } function isLocalStorageSupport(){ if(typeof(Storage) !== "undefined") return true; else return false; } function loadMenu(){ $.getJSON(base_url + "menu_types/getdata_json",function(data){ if(isLocalStorageSupport()) { localStorage.setItem("menuInfo", JSON.stringify(data)); } displayMenu(data); }); } function loadUserInfo(){ $.getJSON(base_url + "users/getuserinfo",function(data){ createCookie("userinfo", "*",1); localStorage.setItem("userinfo", JSON.stringify(data)); userInfo = data; }); } function displayMenu(data){ var nav = $("#navbar-main"); var m = '<ul class="nav navbar-nav">'; $.each(data,function(){ var mlength= this.subMenus.length; m += '<li class="dropdown">'; m += '<a data-toggle="dropdown" class="dropdown-toggle" href="#">' + this.name + ( mlength >0 ? '<span class="caret"></span>':'') + '</a>'; if(mlength>0){ m +='<ul class="dropdown-menu">'; $.each(this.subMenus,function(){ m +='<li><a href="' + base_url + this.url + '">' + this.name + '</a></li>'; }); m +='</ul>'; } m += '</>'; }); m +='<url>'; nav.append(m); }
smager/app-ci01
assets/js/jsdb/zsi_init.js
JavaScript
mit
2,098