code
stringlengths 2
1.05M
|
---|
/*
Adapted from http://stackoverflow.com/a/18884988.
See http://stackoverflow.com/a/22513545 for an approach to improving performance.
*/
var defaultDiacriticsRemovalMap = [{
'base': "A",
'letters': /(A|Ⓐ|A|À|Á|Â|Ầ|Ấ|Ẫ|Ẩ|Ã|Ā|Ă|Ằ|Ắ|Ẵ|Ẳ|Ȧ|Ǡ|Ä|Ǟ|Ả|Å|Ǻ|Ǎ|Ȁ|Ȃ|Ạ|Ậ|Ặ|Ḁ|Ą|Ⱥ|Ɐ|[\u0041\u24B6\uFF21\u00C0\u00C1\u00C2\u1EA6\u1EA4\u1EAA\u1EA8\u00C3\u0100\u0102\u1EB0\u1EAE\u1EB4\u1EB2\u0226\u01E0\u00C4\u01DE\u1EA2\u00C5\u01FA\u01CD\u0200\u0202\u1EA0\u1EAC\u1EB6\u1E00\u0104\u023A\u2C6F])/g
}, {
'base': "AA",
'letters': /(Ꜳ|[\uA732])/g
}, {
'base': "AE",
'letters': /(Æ|Ǽ|Ǣ|[\u00C6\u01FC\u01E2])/g
}, {
'base': "AO",
'letters': /(Ꜵ|[\uA734])/g
}, {
'base': "AU",
'letters': /(Ꜷ|[\uA736])/g
}, {
'base': "AV",
'letters': /(Ꜹ|Ꜻ|[\uA738\uA73A])/g
}, {
'base': "AY",
'letters': /(Ꜽ|[\uA73C])/g
}, {
'base': "B",
'letters': /(B|Ⓑ|B|Ḃ|Ḅ|Ḇ|Ƀ|Ƃ|Ɓ|[\u0042\u24B7\uFF22\u1E02\u1E04\u1E06\u0243\u0182\u0181])/g
}, {
'base': "C",
'letters': /(C|Ⓒ|C|Ć|Ĉ|Ċ|Č|Ç|Ḉ|Ƈ|Ȼ|Ꜿ|[\u0043\u24B8\uFF23\u0106\u0108\u010A\u010C\u00C7\u1E08\u0187\u023B\uA73E])/g
}, {
'base': "D",
'letters': /(D|Ⓓ|D|Ḋ|Ď|Ḍ|Ḑ|Ḓ|Ḏ|Đ|Ƌ|Ɗ|Ɖ|Ꝺ|Ð|[\u0044\u24B9\uFF24\u1E0A\u010E\u1E0C\u1E10\u1E12\u1E0E\u0110\u018B\u018A\u0189\uA779\u00D0])/g
}, {
'base': "DZ",
'letters': /(DZ|DŽ|[\u01F1\u01C4])/g
}, {
'base': "Dz",
'letters': /(Dz|Dž|[\u01F2\u01C5])/g
}, {
'base': "E",
'letters': /(E|Ⓔ|E|È|É|Ê|Ề|Ế|Ễ|Ể|Ẽ|Ē|Ḕ|Ḗ|Ĕ|Ė|Ë|Ẻ|Ě|Ȅ|Ȇ|Ẹ|Ệ|Ȩ|Ḝ|Ę|Ḙ|Ḛ|Ɛ|Ǝ|[\u0045\u24BA\uFF25\u00C8\u00C9\u00CA\u1EC0\u1EBE\u1EC4\u1EC2\u1EBC\u0112\u1E14\u1E16\u0114\u0116\u00CB\u1EBA\u011A\u0204\u0206\u1EB8\u1EC6\u0228\u1E1C\u0118\u1E18\u1E1A\u0190\u018E])/g
}, {
'base': "F",
'letters': /(F|Ⓕ|F|Ḟ|Ƒ|Ꝼ|[\u0046\u24BB\uFF26\u1E1E\u0191\uA77B])/g
}, {
'base': "G",
'letters': /(G|Ⓖ|G|Ǵ|Ĝ|Ḡ|Ğ|Ġ|Ǧ|Ģ|Ǥ|Ɠ|Ꞡ|Ᵹ|Ꝿ|[\u0047\u24BC\uFF27\u01F4\u011C\u1E20\u011E\u0120\u01E6\u0122\u01E4\u0193\uA7A0\uA77D\uA77E])/g
}, {
'base': "H",
'letters': /(H|Ⓗ|H|Ĥ|Ḣ|Ḧ|Ȟ|Ḥ|Ḩ|Ḫ|Ħ|Ⱨ|Ⱶ|Ɥ|[\u0048\u24BD\uFF28\u0124\u1E22\u1E26\u021E\u1E24\u1E28\u1E2A\u0126\u2C67\u2C75\uA78D])/g
}, {
'base': "I",
'letters': /(I|Ⓘ|I|Ì|Í|Î|Ĩ|Ī|Ĭ|İ|Ï|Ḯ|Ỉ|Ǐ|Ȉ|Ȋ|Ị|Į|Ḭ|Ɨ|[\u0049\u24BE\uFF29\u00CC\u00CD\u00CE\u0128\u012A\u012C\u0130\u00CF\u1E2E\u1EC8\u01CF\u0208\u020A\u1ECA\u012E\u1E2C\u0197])/g
}, {
'base': "J",
'letters': /(J|Ⓙ|J|Ĵ|Ɉ|[\u004A\u24BF\uFF2A\u0134\u0248])/g
}, {
'base': "K",
'letters': /(K|Ⓚ|K|Ḱ|Ǩ|Ḳ|Ķ|Ḵ|Ƙ|Ⱪ|Ꝁ|Ꝃ|Ꝅ|Ꞣ|[\u004B\u24C0\uFF2B\u1E30\u01E8\u1E32\u0136\u1E34\u0198\u2C69\uA740\uA742\uA744\uA7A2])/g
}, {
'base': "L",
'letters': /(L|Ⓛ|L|Ŀ|Ĺ|Ľ|Ḷ|Ḹ|Ļ|Ḽ|Ḻ|Ł|Ƚ|Ɫ|Ⱡ|Ꝉ|Ꝇ|Ꞁ|[\u004C\u24C1\uFF2C\u013F\u0139\u013D\u1E36\u1E38\u013B\u1E3C\u1E3A\u0141\u023D\u2C62\u2C60\uA748\uA746\uA780])/g
}, {
'base': "LJ",
'letters': /(LJ|[\u01C7])/g
}, {
'base': "Lj",
'letters': /(Lj|[\u01C8])/g
}, {
'base': "M",
'letters': /(M|Ⓜ|M|Ḿ|Ṁ|Ṃ|Ɱ|Ɯ|[\u004D\u24C2\uFF2D\u1E3E\u1E40\u1E42\u2C6E\u019C])/g
}, {
'base': "N",
'letters': /(N|Ⓝ|N|Ǹ|Ń|Ñ|Ṅ|Ň|Ṇ|Ņ|Ṋ|Ṉ|Ƞ|Ɲ|Ꞑ|Ꞥ|Ŋ|[\u004E\u24C3\uFF2E\u01F8\u0143\u00D1\u1E44\u0147\u1E46\u0145\u1E4A\u1E48\u0220\u019D\uA790\uA7A4\u014A])/g
}, {
'base': "NJ",
'letters': /(NJ|[\u01CA])/g
}, {
'base': "Nj",
'letters': /(Nj|[\u01CB])/g
}, {
'base': "O",
'letters': /(O|Ⓞ|O|Ò|Ó|Ô|Ồ|Ố|Ỗ|Ổ|Õ|Ṍ|Ȭ|Ṏ|Ō|Ṑ|Ṓ|Ŏ|Ȯ|Ȱ|Ö|Ȫ|Ỏ|Ő|Ǒ|Ȍ|Ȏ|Ơ|Ờ|Ớ|Ỡ|Ở|Ợ|Ọ|Ộ|Ǫ|Ǭ|Ø|Ǿ|Ɔ|Ɵ|Ꝋ|Ꝍ|[\u004F\u24C4\uFF2F\u00D2\u00D3\u00D4\u1ED2\u1ED0\u1ED6\u1ED4\u00D5\u1E4C\u022C\u1E4E\u014C\u1E50\u1E52\u014E\u022E\u0230\u00D6\u022A\u1ECE\u0150\u01D1\u020C\u020E\u01A0\u1EDC\u1EDA\u1EE0\u1EDE\u1EE2\u1ECC\u1ED8\u01EA\u01EC\u00D8\u01FE\u0186\u019F\uA74A\uA74C])/g
}, {
'base': "OE",
'letters': /(Œ|[\u0152])/g
}, {
'base': "OI",
'letters': /(Ƣ|[\u01A2])/g
}, {
'base': "OO",
'letters': /(Ꝏ|[\uA74E])/g
}, {
'base': "OU",
'letters': /(Ȣ|[\u0222])/g
}, {
'base': "P",
'letters': /(P|Ⓟ|P|Ṕ|Ṗ|Ƥ|Ᵽ|Ꝑ|Ꝓ|Ꝕ|[\u0050\u24C5\uFF30\u1E54\u1E56\u01A4\u2C63\uA750\uA752\uA754])/g
}, {
'base': "Q",
'letters': /(Q|Ⓠ|Q|Ꝗ|Ꝙ|Ɋ|[\u0051\u24C6\uFF31\uA756\uA758\u024A])/g
}, {
'base': "R",
'letters': /(R|Ⓡ|R|Ŕ|Ṙ|Ř|Ȑ|Ȓ|Ṛ|Ṝ|Ŗ|Ṟ|Ɍ|Ɽ|Ꝛ|Ꞧ|Ꞃ|[\u0052\u24C7\uFF32\u0154\u1E58\u0158\u0210\u0212\u1E5A\u1E5C\u0156\u1E5E\u024C\u2C64\uA75A\uA7A6\uA782])/g
}, {
'base': "S",
'letters': /(S|Ⓢ|S|ẞ|Ś|Ṥ|Ŝ|Ṡ|Š|Ṧ|Ṣ|Ṩ|Ș|Ş|Ȿ|Ꞩ|Ꞅ|[\u0053\u24C8\uFF33\u1E9E\u015A\u1E64\u015C\u1E60\u0160\u1E66\u1E62\u1E68\u0218\u015E\u2C7E\uA7A8\uA784])/g
}, {
'base': "T",
'letters': /(T|Ⓣ|T|Ṫ|Ť|Ṭ|Ț|Ţ|Ṱ|Ṯ|Ŧ|Ƭ|Ʈ|Ⱦ|Ꞇ|[\u0054\u24C9\uFF34\u1E6A\u0164\u1E6C\u021A\u0162\u1E70\u1E6E\u0166\u01AC\u01AE\u023E\uA786])/g
}, {
'base': "TH",
'letters': /(Þ|[\u00DE])/g
}, {
'base': "TZ",
'letters': /(Ꜩ|[\uA728])/g
}, {
'base': "U",
'letters': /(U|Ⓤ|U|Ù|Ú|Û|Ũ|Ṹ|Ū|Ṻ|Ŭ|Ü|Ǜ|Ǘ|Ǖ|Ǚ|Ủ|Ů|Ű|Ǔ|Ȕ|Ȗ|Ư|Ừ|Ứ|Ữ|Ử|Ự|Ụ|Ṳ|Ų|Ṷ|Ṵ|Ʉ|[\u0055\u24CA\uFF35\u00D9\u00DA\u00DB\u0168\u1E78\u016A\u1E7A\u016C\u00DC\u01DB\u01D7\u01D5\u01D9\u1EE6\u016E\u0170\u01D3\u0214\u0216\u01AF\u1EEA\u1EE8\u1EEE\u1EEC\u1EF0\u1EE4\u1E72\u0172\u1E76\u1E74\u0244])/g
}, {
'base': "V",
'letters': /(V|Ⓥ|V|Ṽ|Ṿ|Ʋ|Ꝟ|Ʌ|[\u0056\u24CB\uFF36\u1E7C\u1E7E\u01B2\uA75E\u0245])/g
}, {
'base': "VY",
'letters': /(Ꝡ|[\uA760])/g
}, {
'base': "W",
'letters': /(W|Ⓦ|W|Ẁ|Ẃ|Ŵ|Ẇ|Ẅ|Ẉ|Ⱳ|[\u0057\u24CC\uFF37\u1E80\u1E82\u0174\u1E86\u1E84\u1E88\u2C72])/g
}, {
'base': "X",
'letters': /(X|Ⓧ|X|Ẋ|Ẍ|[\u0058\u24CD\uFF38\u1E8A\u1E8C])/g
}, {
'base': "Y",
'letters': /(Y|Ⓨ|Y|Ỳ|Ý|Ŷ|Ỹ|Ȳ|Ẏ|Ÿ|Ỷ|Ỵ|Ƴ|Ɏ|Ỿ|[\u0059\u24CE\uFF39\u1EF2\u00DD\u0176\u1EF8\u0232\u1E8E\u0178\u1EF6\u1EF4\u01B3\u024E\u1EFE])/g
}, {
'base': "Z",
'letters': /(Z|Ⓩ|Z|Ź|Ẑ|Ż|Ž|Ẓ|Ẕ|Ƶ|Ȥ|Ɀ|Ⱬ|Ꝣ|[\u005A\u24CF\uFF3A\u0179\u1E90\u017B\u017D\u1E92\u1E94\u01B5\u0224\u2C7F\u2C6B\uA762])/g
}, {
'base': "a",
'letters': /(a|ⓐ|a|ẚ|à|á|â|ầ|ấ|ẫ|ẩ|ã|ā|ă|ằ|ắ|ẵ|ẳ|ȧ|ǡ|ä|ǟ|ả|å|ǻ|ǎ|ȁ|ȃ|ạ|ậ|ặ|ḁ|ą|ⱥ|ɐ|[\u0061\u24D0\uFF41\u1E9A\u00E0\u00E1\u00E2\u1EA7\u1EA5\u1EAB\u1EA9\u00E3\u0101\u0103\u1EB1\u1EAF\u1EB5\u1EB3\u0227\u01E1\u00E4\u01DF\u1EA3\u00E5\u01FB\u01CE\u0201\u0203\u1EA1\u1EAD\u1EB7\u1E01\u0105\u2C65\u0250])/g
}, {
'base': "aa",
'letters': /(ꜳ|[\uA733])/g
}, {
'base': "ae",
'letters': /(æ|ǽ|ǣ|[\u00E6\u01FD\u01E3])/g
}, {
'base': "ao",
'letters': /(ꜵ|[\uA735])/g
}, {
'base': "au",
'letters': /(ꜷ|[\uA737])/g
}, {
'base': "av",
'letters': /(ꜹ|ꜻ|[\uA739\uA73B])/g
}, {
'base': "ay",
'letters': /(ꜽ|[\uA73D])/g
}, {
'base': "b",
'letters': /(b|ⓑ|b|ḃ|ḅ|ḇ|ƀ|ƃ|ɓ|[\u0062\u24D1\uFF42\u1E03\u1E05\u1E07\u0180\u0183\u0253])/g
}, {
'base': "c",
'letters': /(c|ⓒ|c|ć|ĉ|ċ|č|ç|ḉ|ƈ|ȼ|ꜿ|ↄ|[\u0063\u24D2\uFF43\u0107\u0109\u010B\u010D\u00E7\u1E09\u0188\u023C\uA73F\u2184])/g
}, {
'base': "d",
'letters': /(d|ⓓ|d|ḋ|ď|ḍ|ḑ|ḓ|ḏ|đ|ƌ|ɖ|ɗ|ꝺ|ð|[\u0064\u24D3\uFF44\u1E0B\u010F\u1E0D\u1E11\u1E13\u1E0F\u0111\u018C\u0256\u0257\uA77A\u00F0])/g
}, {
'base': "dz",
'letters': /(dz|dž|[\u01F3\u01C6])/g
}, {
'base': "e",
'letters': /(e|ⓔ|e|è|é|ê|ề|ế|ễ|ể|ẽ|ē|ḕ|ḗ|ĕ|ė|ë|ẻ|ě|ȅ|ȇ|ẹ|ệ|ȩ|ḝ|ę|ḙ|ḛ|ɇ|ɛ|ǝ|[\u0065\u24D4\uFF45\u00E8\u00E9\u00EA\u1EC1\u1EBF\u1EC5\u1EC3\u1EBD\u0113\u1E15\u1E17\u0115\u0117\u00EB\u1EBB\u011B\u0205\u0207\u1EB9\u1EC7\u0229\u1E1D\u0119\u1E19\u1E1B\u0247\u025B\u01DD])/g
}, {
'base': "f",
'letters': /(f|ⓕ|f|ḟ|ƒ|ꝼ|[\u0066\u24D5\uFF46\u1E1F\u0192\uA77C])/g
}, {
'base': "g",
'letters': /(g|ⓖ|g|ǵ|ĝ|ḡ|ğ|ġ|ǧ|ģ|ǥ|ɠ|ꞡ|ᵹ|ꝿ|[\u0067\u24D6\uFF47\u01F5\u011D\u1E21\u011F\u0121\u01E7\u0123\u01E5\u0260\uA7A1\u1D79\uA77F])/g
}, {
'base': "h",
'letters': /(h|ⓗ|h|ĥ|ḣ|ḧ|ȟ|ḥ|ḩ|ḫ|ẖ|ħ|ⱨ|ⱶ|ɥ|[\u0068\u24D7\uFF48\u0125\u1E23\u1E27\u021F\u1E25\u1E29\u1E2B\u1E96\u0127\u2C68\u2C76\u0265])/g
}, {
'base': "hv",
'letters': /(ƕ|[\u0195])/g
}, {
'base': "i",
'letters': /(i|ⓘ|i|ì|í|î|ĩ|ī|ĭ|ï|ḯ|ỉ|ǐ|ȉ|ȋ|ị|į|ḭ|ɨ|ı|[\u0069\u24D8\uFF49\u00EC\u00ED\u00EE\u0129\u012B\u012D\u00EF\u1E2F\u1EC9\u01D0\u0209\u020B\u1ECB\u012F\u1E2D\u0268\u0131])/g
}, {
'base': "ij",
'letters': /(ij|[\u0133])/g
}, {
'base': "j",
'letters': /(j|ⓙ|j|ĵ|ǰ|ɉ|[\u006A\u24D9\uFF4A\u0135\u01F0\u0249])/g
}, {
'base': "k",
'letters': /(k|ⓚ|k|ḱ|ǩ|ḳ|ķ|ḵ|ƙ|ⱪ|ꝁ|ꝃ|ꝅ|ꞣ|[\u006B\u24DA\uFF4B\u1E31\u01E9\u1E33\u0137\u1E35\u0199\u2C6A\uA741\uA743\uA745\uA7A3])/g
}, {
'base': "l",
'letters': /(l|ⓛ|l|ŀ|ĺ|ľ|ḷ|ḹ|ļ|ḽ|ḻ|ł|ƚ|ɫ|ⱡ|ꝉ|ꞁ|ꝇ|[\u006C\u24DB\uFF4C\u0140\u013A\u013E\u1E37\u1E39\u013C\u1E3D\u1E3B\u0142\u019A\u026B\u2C61\uA749\uA781\uA747])/g
}, {
'base': "lj",
'letters': /(lj|[\u01C9])/g
}, {
'base': "m",
'letters': /(m|ⓜ|m|ḿ|ṁ|ṃ|ɱ|ɯ|[\u006D\u24DC\uFF4D\u1E3F\u1E41\u1E43\u0271\u026F])/g
}, {
'base': "n",
'letters': /(n|ⓝ|n|ǹ|ń|ñ|ṅ|ň|ṇ|ņ|ṋ|ṉ|ƞ|ɲ|ʼn|ꞑ|ꞥ|ŋ|[\u006E\u24DD\uFF4E\u01F9\u0144\u00F1\u1E45\u0148\u1E47\u0146\u1E4B\u1E49\u019E\u0272\u0149\uA791\uA7A5\u014B])/g
}, {
'base': "nj",
'letters': /(nj|[\u01CC])/g
}, {
'base': "o",
'letters': /(o|ⓞ|o|ò|ó|ô|ồ|ố|ỗ|ổ|õ|ṍ|ȭ|ṏ|ō|ṑ|ṓ|ŏ|ȯ|ȱ|ö|ȫ|ỏ|ő|ǒ|ȍ|ȏ|ơ|ờ|ớ|ỡ|ở|ợ|ọ|ộ|ǫ|ǭ|ø|ǿ|ɔ|ꝋ|ꝍ|ɵ|[\u006F\u24DE\uFF4F\u00F2\u00F3\u00F4\u1ED3\u1ED1\u1ED7\u1ED5\u00F5\u1E4D\u022D\u1E4F\u014D\u1E51\u1E53\u014F\u022F\u0231\u00F6\u022B\u1ECF\u0151\u01D2\u020D\u020F\u01A1\u1EDD\u1EDB\u1EE1\u1EDF\u1EE3\u1ECD\u1ED9\u01EB\u01ED\u00F8\u01FF\u0254\uA74B\uA74D\u0275])/g
}, {
'base': "oe",
'letters': /(œ|[\u0153])/g
}, {
'base': "oi",
'letters': /(ƣ|[\u01A3])/g
}, {
'base': "ou",
'letters': /(ȣ|[\u0223])/g
}, {
'base': "oo",
'letters': /(ꝏ|[\uA74F])/g
}, {
'base': "p",
'letters': /(p|ⓟ|p|ṕ|ṗ|ƥ|ᵽ|ꝑ|ꝓ|ꝕ|[\u0070\u24DF\uFF50\u1E55\u1E57\u01A5\u1D7D\uA751\uA753\uA755])/g
}, {
'base': "q",
'letters': /(q|ⓠ|q|ɋ|ꝗ|ꝙ|[\u0071\u24E0\uFF51\u024B\uA757\uA759])/g
}, {
'base': "r",
'letters': /(r|ⓡ|r|ŕ|ṙ|ř|ȑ|ȓ|ṛ|ṝ|ŗ|ṟ|ɍ|ɽ|ꝛ|ꞧ|ꞃ|[\u0072\u24E1\uFF52\u0155\u1E59\u0159\u0211\u0213\u1E5B\u1E5D\u0157\u1E5F\u024D\u027D\uA75B\uA7A7\uA783])/g
}, {
'base': "s",
'letters': /(s|ⓢ|s|ś|ṥ|ŝ|ṡ|š|ṧ|ṣ|ṩ|ș|ş|ȿ|ꞩ|ꞅ|ẛ|ſ|[\u0073\u24E2\uFF53\u015B\u1E65\u015D\u1E61\u0161\u1E67\u1E63\u1E69\u0219\u015F\u023F\uA7A9\uA785\u1E9B\u017F])/g
}, {
'base': "ss",
'letters': /(ß|[\u00DF])/g
}, {
'base': "t",
'letters': /(t|ⓣ|t|ṫ|ẗ|ť|ṭ|ț|ţ|ṱ|ṯ|ŧ|ƭ|ʈ|ⱦ|ꞇ|[\u0074\u24E3\uFF54\u1E6B\u1E97\u0165\u1E6D\u021B\u0163\u1E71\u1E6F\u0167\u01AD\u0288\u2C66\uA787])/g
}, {
'base': "th",
'letters': /(þ|[\u00FE])/g
}, {
'base': "tz",
'letters': /(ꜩ|[\uA729])/g
}, {
'base': "u",
'letters': /(u|ⓤ|u|ù|ú|û|ũ|ṹ|ū|ṻ|ŭ|ü|ǜ|ǘ|ǖ|ǚ|ủ|ů|ű|ǔ|ȕ|ȗ|ư|ừ|ứ|ữ|ử|ự|ụ|ṳ|ų|ṷ|ṵ|ʉ|[\u0075\u24E4\uFF55\u00F9\u00FA\u00FB\u0169\u1E79\u016B\u1E7B\u016D\u00FC\u01DC\u01D8\u01D6\u01DA\u1EE7\u016F\u0171\u01D4\u0215\u0217\u01B0\u1EEB\u1EE9\u1EEF\u1EED\u1EF1\u1EE5\u1E73\u0173\u1E77\u1E75\u0289])/g
}, {
'base': "v",
'letters': /(v|ⓥ|v|ṽ|ṿ|ʋ|ꝟ|ʌ|[\u0076\u24E5\uFF56\u1E7D\u1E7F\u028B\uA75F\u028C])/g
}, {
'base': "vy",
'letters': /(ꝡ|[\uA761])/g
}, {
'base': "w",
'letters': /(w|ⓦ|w|ẁ|ẃ|ŵ|ẇ|ẅ|ẘ|ẉ|ⱳ|[\u0077\u24E6\uFF57\u1E81\u1E83\u0175\u1E87\u1E85\u1E98\u1E89\u2C73])/g
}, {
'base': "x",
'letters': /(x|ⓧ|x|ẋ|ẍ|[\u0078\u24E7\uFF58\u1E8B\u1E8D])/g
}, {
'base': "y",
'letters': /(y|ⓨ|y|ỳ|ý|ŷ|ỹ|ȳ|ẏ|ÿ|ỷ|ẙ|ỵ|ƴ|ɏ|ỿ|[\u0079\u24E8\uFF59\u1EF3\u00FD\u0177\u1EF9\u0233\u1E8F\u00FF\u1EF7\u1E99\u1EF5\u01B4\u024F\u1EFF])/g
}, {
'base': "z",
'letters': /(z|ⓩ|z|ź|ẑ|ż|ž|ẓ|ẕ|ƶ|ȥ|ɀ|ⱬ|ꝣ|[\u007A\u24E9\uFF5A\u017A\u1E91\u017C\u017E\u1E93\u1E95\u01B6\u0225\u0240\u2C6C\uA763])/g
}];
/* exported removeDiacritics */
window.removeDiacritics =function(str) {
for (var i = 0; i < defaultDiacriticsRemovalMap.length; i++) {
str = str.replace(defaultDiacriticsRemovalMap[i].letters, defaultDiacriticsRemovalMap[i].base);
}
return str;
};
|
/*
* HomePage Messages
*
* This contains all the text for the HomePage component.
*/
import { defineMessages } from 'react-intl';
export default defineMessages({
word0: {
id: 'boilerplate.containers.HomePage.word0',
defaultMessage: 'We make',
},
title1: {
id: 'boilerplate.containers.HomePage.word1',
defaultMessage: '\xa0social content',
},
});
|
var app = require('zondajs');
app.component('message', {
hello: 'hello world'
});
app.component('messageService', function(message){
return {
print: function(){
console.log('Message from the service using dependency injection: ' + message.hello);
}
};
});
|
// CURRENTLY NOT USED
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import Contacts from '../components/Contacts'
import * as ContactActions from '../actions/contacts'
function mapStateToProps(state) {
return {
state: state // :)
}
}
function mapDispatchToProps(dispatch) {
var boundActionCreators = bindActionCreators(ContactActions, dispatch)
console.log("[App.js] boundActionCreators:", boundActionCreators);
return boundActionCreators
}
export default connect(mapStateToProps, mapDispatchToProps)(Contacts)
|
import { CULLFACE_NONE, PRIMITIVE_TRISTRIP, SEMANTIC_POSITION, TYPE_FLOAT32 } from './constants.js';
import { VertexBuffer } from './vertex-buffer.js';
import { VertexFormat } from './vertex-format.js';
import { VertexIterator } from './vertex-iterator.js';
/** @typedef {import('../math/vec4.js').Vec4} Vec4 */
/** @typedef {import('./graphics-device.js').GraphicsDevice} GraphicsDevice */
/** @typedef {import('./render-target.js').RenderTarget} RenderTarget */
/** @typedef {import('./shader.js').Shader} Shader */
// Primitive for drawFullscreenQuad
const primitive = {
type: PRIMITIVE_TRISTRIP,
base: 0,
count: 4,
indexed: false
};
/**
* Base class for all post effects. Post effects take a a render target as input apply effects to
* it and then render the result to an output render target or the screen if no output is
* specified.
*/
class PostEffect {
/**
* Create a new PostEffect instance.
*
* @param {GraphicsDevice} graphicsDevice - The graphics device of the application.
*/
constructor(graphicsDevice) {
/**
* The graphics device of the application.
*
* @type {GraphicsDevice}
*/
this.device = graphicsDevice;
/**
* The shader definition for the fullscreen quad. Needs to be set by the custom post effect
* (default is null). Used when calling {@link drawFullscreenQuad}.
*
* @type {Shader|null}
*/
this.shader = null;
/**
* The vertex buffer for the fullscreen quad. Used when calling {@link drawFullscreenQuad}.
*
* @type {VertexBuffer}
*/
this.vertexBuffer = createFullscreenQuad(graphicsDevice);
/**
* The property that should to be set to `true` (by the custom post effect) if a depth map
* is necessary (default is false).
*
* @type {boolean}
*/
this.needsDepthBuffer = false;
this.depthMap = null;
}
/**
* Render the post effect using the specified inputTarget to the specified outputTarget.
*
* @param {RenderTarget} inputTarget - The input render target.
* @param {RenderTarget} outputTarget - The output render target. If null then this will be the
* screen.
* @param {Vec4} [rect] - The rect of the current camera. If not specified, it will default to
* [0, 0, 1, 1].
*/
render(inputTarget, outputTarget, rect) {
}
}
/**
* Create a vertex buffer with 4 vertices representing a fullscreen quad.
*
* @param {GraphicsDevice} device - The graphics device.
* @returns {VertexBuffer} - The fullscreen quad vertex buffer.
* @ignore
*/
function createFullscreenQuad(device) {
// Create the vertex format
const vertexFormat = new VertexFormat(device, [
{ semantic: SEMANTIC_POSITION, components: 2, type: TYPE_FLOAT32 }
]);
// Create a vertex buffer
const vertexBuffer = new VertexBuffer(device, vertexFormat, 4);
// Fill the vertex buffer
const iterator = new VertexIterator(vertexBuffer);
iterator.element[SEMANTIC_POSITION].set(-1.0, -1.0);
iterator.next();
iterator.element[SEMANTIC_POSITION].set(1.0, -1.0);
iterator.next();
iterator.element[SEMANTIC_POSITION].set(-1.0, 1.0);
iterator.next();
iterator.element[SEMANTIC_POSITION].set(1.0, 1.0);
iterator.end();
return vertexBuffer;
}
/**
* Draw a screen-space rectangle in a render target. Primarily meant to be used in custom post
* effects based on {@link PostEffect}.
*
* @param {GraphicsDevice} device - The graphics device of the application.
* @param {RenderTarget} target - The output render target.
* @param {VertexBuffer} vertexBuffer - The vertex buffer for the rectangle mesh. When calling from
* a custom post effect, pass the field {@link PostEffect#vertexBuffer}.
* @param {Shader} shader - The shader to be used for drawing the rectangle. When calling from a
* custom post effect, pass the field {@link PostEffect#shader}.
* @param {Vec4} [rect] - The normalized screen-space position (rect.x, rect.y) and size (rect.z,
* rect.w) of the rectangle. Default is [0, 0, 1, 1].
*/
function drawFullscreenQuad(device, target, vertexBuffer, shader, rect) {
const oldRt = device.getRenderTarget();
device.setRenderTarget(target);
device.updateBegin();
let w = target ? target.width : device.width;
let h = target ? target.height : device.height;
let x = 0;
let y = 0;
if (rect) {
x = rect.x * w;
y = rect.y * h;
w *= rect.z;
h *= rect.w;
}
const oldVx = device.vx;
const oldVy = device.vy;
const oldVw = device.vw;
const oldVh = device.vh;
device.setViewport(x, y, w, h);
const oldSx = device.sx;
const oldSy = device.sy;
const oldSw = device.sw;
const oldSh = device.sh;
device.setScissor(x, y, w, h);
const oldBlending = device.getBlending();
const oldDepthTest = device.getDepthTest();
const oldDepthWrite = device.getDepthWrite();
const oldCullMode = device.getCullMode();
const oldWR = device.writeRed;
const oldWG = device.writeGreen;
const oldWB = device.writeBlue;
const oldWA = device.writeAlpha;
device.setBlending(false);
device.setDepthTest(false);
device.setDepthWrite(false);
device.setCullMode(CULLFACE_NONE);
device.setColorWrite(true, true, true, true);
device.setVertexBuffer(vertexBuffer, 0);
device.setShader(shader);
device.draw(primitive);
device.setBlending(oldBlending);
device.setDepthTest(oldDepthTest);
device.setDepthWrite(oldDepthWrite);
device.setCullMode(oldCullMode);
device.setColorWrite(oldWR, oldWG, oldWB, oldWA);
device.updateEnd();
device.setRenderTarget(oldRt);
device.updateBegin();
device.setViewport(oldVx, oldVy, oldVw, oldVh);
device.setScissor(oldSx, oldSy, oldSw, oldSh);
}
export { createFullscreenQuad, drawFullscreenQuad, PostEffect };
|
angular.module('app')
.service('TarefaService', TarefaService);
function TarefaService() {
var tarefas = [];
var service = {
listarTarefas: listarTarefas,
adicionarTarefa: adicionarTarefa,
alterarStatusTarefa: alterarStatusTarefa
};
return service;
function listarTarefas() {
return tarefas;
}
function adicionarTarefa(tarefa) {
tarefas.push({
descricao: tarefa.descricao,
concluido: false
})
}
function alterarStatusTarefa(index) {
tarefas[index].concluido = !tarefas[index].concluido;
}
}
|
/* MIT License. Copyright © 2015-2018, Richard Rodger and other contributors. */
'use strict'
var _ = require('lodash')
var Sneeze = require('sneeze')
var Nid = require('nid')
var Rif = require('rif')
var Discover = require('node-discover')
var Ip = require('ip')
var Optioner = require('optioner')
var Joi = Optioner.Joi
module.exports = mesh
var DEFAULT_HOST = (module.exports.DEFAULT_HOST = '127.0.0.1')
var DEFAULT_PORT = (module.exports.DEFAULT_PORT = 39999)
var intern = (module.exports.intern = make_intern())
var optioner = Optioner({
pin: Joi.alternatives().try(Joi.string(), Joi.object()),
pins: Joi.array(),
host: Joi.string(),
port: Joi.number().integer().min(0).max(65535),
isbase: false,
model: 'consume',
listen: Joi.array(),
auto: true,
make_entry: intern.default_make_entry,
jointime: 111, // join and wait for network details
// Explicitly allow overrides of specific local patterns. This is not supported
// by default to prevent infinite loops between subling services with same pins.
override: false,
discover: {
defined: {
active: true,
},
guess: {
active: true,
},
multicast: {
active: true,
address: null,
// max_search: 22,
max_search: 2,
search_interval: 111,
},
registry: {
// Not active by default, need to explicitly turn it on.
active: false,
// check registry periodically
refresh_interval: 1111,
// remove first entry with this probability
// live base nodes will add themselves back in
prune_first_probability: 0.01,
// leave at least this many base entries
prune_bound: 11,
},
custom: {
active: true,
find: function (seneca, options, bases, next) {
next([], false)
},
},
// stop discovery if defined bases are provided
stop: true,
},
monitor: false,
sneeze: null,
})
function mesh(options) {
var seneca = this
seneca.depends('balance-client')
var opts = optioner.check(options)
var closed = false
var bases = []
var sneeze
seneca.add('role:mesh,get:bases', function get_bases(msg, done) {
done(null, { bases: [].concat(bases) })
})
var balance_map = {}
var mid = Nid()
// fixed network interface specification, as per format of
// require('os').networkInterfaces. Merged with and overrides same.
var rif = Rif(opts.netif)
// opts.base is deprecated
var isbase = !!(opts.isbase || opts.base)
opts.isbase = isbase
var pin = opts.pin || opts.pins
if (isbase) {
pin = Array.isArray(pin) ? pin : [].concat('role:mesh,base:' + seneca.id)
//pin = ['']
}
opts.host = intern.resolve_interface(opts.host, rif)
var tag = opts.tag
var listen = opts.listen || [{ pin: pin, model: opts.model || 'consume' }]
var balance_client_opts = opts.balance_client || {}
seneca.use('balance-client$mesh~' + mid, balance_client_opts)
seneca.add('init:mesh', init)
function init(msg, init_done) {
var seneca = this
intern.find_bases(seneca, opts, rif, function (found_bases) {
bases = found_bases
seneca.log.debug({
kind: 'mesh',
host: opts.host,
port: opts.port,
bases: bases,
opts: opts,
})
var sneeze_opts = opts.sneeze || {}
sneeze_opts.bases = bases
sneeze_opts.isbase = isbase
sneeze_opts.port = opts.port || void 0
sneeze_opts.host = opts.host || void 0
sneeze_opts.identifier = seneca.id
sneeze_opts.monitor = sneeze_opts.monitor || {
active: !!opts.monitor,
}
sneeze_opts.tag =
void 0 !== sneeze_opts.tag
? sneeze_opts.tag
: void 0 !== tag
? null === tag
? null
: 'seneca~' + tag
: 'seneca~mesh'
seneca.add(
'role:transport,cmd:listen',
intern.make_transport_listen(opts, join, listen, init_done)
)
// call seneca.listen as a convenience
// subsequent seneca.listen calls will still publish to network
if (opts.auto) {
_.each(listen, function (listen_opts) {
if (opts.host && null == listen_opts.host) {
listen_opts.host = opts.host
}
if ('@' === (listen_opts.host && listen_opts.host[0])) {
listen_opts.host = rif(listen_opts.host.substring(1))
}
listen_opts.port =
null != listen_opts.port
? listen_opts.port
: function () {
return 50000 + Math.floor(10000 * Math.random())
}
listen_opts.model = listen_opts.model || 'consume'
listen_opts.ismesh = true
seneca.listen(listen_opts)
})
}
function join(instance, raw_config, done) {
var client_instance = instance.root.delegate()
var config = seneca.util.clean(raw_config || {}, { proto: false })
if (!config.pin && !config.pins) {
config.pin = 'null:true'
}
config.pin = intern.resolve_pins(instance, config)
delete config.pins
var instance_sneeze_opts = _.clone(sneeze_opts)
instance_sneeze_opts.identifier =
sneeze_opts.identifier + '~' + config.pin + '~' + Date.now()
sneeze = Sneeze(instance_sneeze_opts)
var meta = {
config: seneca.util.clean(config),
instance: instance.id,
}
sneeze.on('error', function (err) {
seneca.log.warn(err)
})
sneeze.on('add', add_client)
sneeze.on('remove', remove_client)
sneeze.on('ready', done)
seneca.add('role:seneca,cmd:close', function (msg, done) {
closed = true
if (sneeze) {
sneeze.leave()
}
this.prior(msg, done)
})
seneca.add('role:mesh,get:members', function get_members(msg, done) {
var members = []
_.each(sneeze.members(), function (member) {
var m = opts.make_entry(member)
members.push(void 0 === m ? intern.default_make_entry(member) : m)
})
this.prior(msg, function (err, out) {
if (err) {
done(err)
}
var list = (out && out.list) || []
var outlist = list.concat(members)
done(null, { list: outlist })
})
})
sneeze.join(meta)
function add_client(meta) {
if (closed) return
// ignore myself
if (client_instance.id === meta.instance) {
return
}
var config = meta.config || {}
var pins = intern.resolve_pins(client_instance, config)
_.each(pins, function (pin) {
var pin_config = intern.make_pin_config(
client_instance,
meta,
pin,
config
)
var has_balance_client = !!balance_map[pin_config.pin]
var target_map = (balance_map[pin_config.pin] =
balance_map[pin_config.pin] || {})
// this is a duplicate, so ignore
if (target_map[pin_config.id]) {
return
}
var actmeta = client_instance.find(pin, { exact: true })
var override =
true === opts.override ||
(Array.isArray(opts.override) && opts.override.includes(pin))
if (actmeta) {
// Prevent infinite loops between sibling services by
// not supporting local overrides unless explicitly granted.
if (!actmeta.client && !override) {
return
}
}
target_map[pin_config.id] = true
pin_config.override = override
if (!has_balance_client) {
// no balancer for this pin, so add one
var balance_client_config = {
type: 'balance',
pin: pin,
model: config.model,
override: override,
}
client_instance.client(balance_client_config)
}
client_instance.act('role:transport,type:balance,add:client', {
config: pin_config,
})
})
}
function remove_client(meta) {
if (closed) return
// ignore myself
if (client_instance.id === meta.instance) {
return
}
var config = meta.config || {}
var pins = intern.resolve_pins(client_instance, config)
_.each(pins, function (pin) {
var pin_config = intern.make_pin_config(
client_instance,
meta,
pin,
config
)
var target_map = balance_map[pin_config.pin]
if (target_map) {
delete target_map[pin_config.id]
}
client_instance.act('role:transport,type:balance,remove:client', {
config: pin_config,
meta: meta,
})
})
}
}
})
}
}
function make_intern() {
return {
make_transport_listen: function (opts, join, listen, init_done) {
var listen_count = 0
var last_mesh_listen_err = null
return function (msg, done) {
var seneca = this
var ismesh = msg.config && msg.config.ismesh
// count of the mesh auto listens
listen_count += ismesh ? 1 : 0
seneca.prior(msg, function (err, out) {
var seneca = this
if (err) {
last_mesh_listen_err = ismesh ? err : last_mesh_listen_err
return done(err)
}
if (ismesh) {
join(seneca.delegate(), out, function () {
done()
// only finish mesh plugin init if all auto listens attempted
if (listen.length === listen_count) {
setTimeout(function () {
init_done(last_mesh_listen_err)
}, opts.jointime)
}
})
} else {
done()
}
})
}
},
resolve_interface: function (spec, rif) {
var out = spec
spec = null == spec ? '' : spec
if ('@' === spec[0]) {
if (1 === spec.length) {
out = '0.0.0.0'
} else {
out = rif(spec.substring(1))
}
}
return out
},
find_bases: function (seneca, opts, rif, done) {
var bases = []
intern.addbase_funcmap.custom = function (seneca, opts, bases, next) {
opts.discover.custom.find(seneca, opts, bases, function (add, stop) {
add = add || []
next(add, null == stop ? 0 < add.length : !!stop)
})
}
// order is significant
var addbases = ['defined', 'custom', 'registry', 'multicast', 'guess']
var abI = -1
var addbase
next()
function next(add, stop) {
bases = bases.concat(add || [])
if (stop && opts.discover.stop) abI = addbases.length
do {
++abI
} while (abI < addbases.length && !opts.discover[addbases[abI]].active)
addbase = addbases[abI]
if (null == addbase) {
bases = intern.resolve_bases(bases, opts, rif)
return done(bases)
}
intern.addbase_funcmap[addbase](seneca, opts, bases, next)
}
},
addbase_funcmap: {
defined: function (seneca, opts, bases, next) {
var add = (opts.sneeze || {}).bases || opts.bases || opts.remotes || []
add = add.filter(function (base) {
return base && 0 < base.length
})
next(add, 0 < add.length)
},
// order significant! depends on defined as uses bases.length
guess: function (seneca, opts, bases, next) {
var add = []
var host = opts.host
if (0 === bases.length) {
if (null != host && host !== DEFAULT_HOST) {
add.push(host + ':' + DEFAULT_PORT)
}
add.push(DEFAULT_HOST + ':' + DEFAULT_PORT)
}
next(add)
},
multicast: function (seneca, opts, bases, next) {
var add = []
var mc_opts = opts.discover.multicast
// Determine broadcast address using subnetmask
if (_.isString(mc_opts.address) && '/' === mc_opts.address[0]) {
var netprefix = parseInt(mc_opts.address.substring(1), 10)
mc_opts.address = Ip.subnet(
opts.host,
Ip.fromPrefixLen(netprefix)
).broadcastAddress
}
var d = Discover({
broadcast: mc_opts.address,
advertisement: {
seneca_mesh: true,
isbase: opts.isbase,
host: opts.host || DEFAULT_HOST,
port: opts.port || DEFAULT_PORT,
},
})
var findCount = 0
var fi = setInterval(function () {
var count = 0
d.eachNode(function (node) {
var nd = node.advertisement
if (nd.seneca_mesh) {
add.push(nd.host + ':' + nd.port)
count++
}
})
if (0 < count || mc_opts.max_search < findCount) {
// only bases should keep broadcasting
if (!opts.isbase) {
d.stop()
}
clearInterval(fi)
next(add, 0 < add.length)
}
findCount++
}, mc_opts.search_interval)
},
registry: function (seneca, opts, bases, next) {
var first = true
var base_addr =
(opts.host || DEFAULT_HOST) + ':' + (opts.port || DEFAULT_PORT)
if (opts.isbase) {
var ri = opts.discover.registry.refresh_interval
ri = ri + ri * (Math.random() - 0.5)
setInterval(getset_bases, ri)
}
getset_bases()
function getset_bases() {
seneca.act(
'role:registry,cmd:get,default$:{}',
{ key: 'seneca-mesh/' + (opts.tag || '-') + '/bases' },
function (err, out) {
if (err) return
var add = (out.value || '').split(',')
add = add.filter(function (base) {
return 0 < base.length
})
if (first) {
first = false
next(add, 0 < add.length)
}
if (opts.isbase) {
var prune_first =
Math.random() < opts.discover.registry.prune_first_probability
if (prune_first || -1 === add.indexOf(base_addr)) {
add.push(base_addr)
add = _.uniq(add)
if (
prune_first &&
opts.discover.registry.prune_bound < add.length
) {
add.shift()
}
var val = add.join(',')
seneca.act('role:registry,cmd:set,default$:{}', {
key: 'seneca-mesh/' + (opts.tag || '-') + '/bases',
value: val,
})
}
}
}
)
}
},
},
default_make_entry: function (member) {
var entry = member
var meta = member.meta
if (meta.tag$ && meta.tag$.match(/^seneca~/)) {
entry = {
pin: meta.config.pin,
port: meta.config.port,
host: meta.config.host,
type: meta.config.type,
model: meta.config.model,
instance: meta.instance,
}
}
return entry
},
resolve_bases: function (orig_bases, opts, rif) {
opts = opts || {}
var host = opts.host
// remove empties
var bases = (orig_bases || []).filter(function (base) {
return base && 0 < base.length
})
var append = []
// first pass: defaults and interfacesx
bases = bases.map(function (base) {
// host:port -> host:port
// :port -> DEFAULT_HOST:port, host:port
// host -> host:DEFAULT_PORT
var parts = base.match(/^(.+):(\d+)$/)
if (parts) {
parts = parts.slice(1, 3)
} else {
if (':' === base[0]) {
parts = [DEFAULT_HOST, base.substring(1)]
if (host) {
append.push(host + ':' + parts[1])
}
} else {
parts = [base, DEFAULT_PORT]
}
}
if ('@' === (parts[0] && parts[0][0])) {
parts[0] = rif(parts[0].substring(1))
}
return parts.join(':')
})
bases = bases.concat(append)
// TODO second pass: ranges
// host:10-12 -> host:10, host:11, host:12
// a.b.c.10-12:port -> a.b.c.10:port, a.b.c.11:port, a.b.c.12:port
return bases
},
resolve_pins: function (instance, config) {
var pins = config.pins || config.pin || []
pins = _.isArray(pins) ? pins : [pins]
pins = _.flatten(
_.map(pins, function (pin) {
return _.isString(pin) ? pin.split(';') : pin
})
)
pins = _.map(pins, function (pin) {
return instance.util.pincanon(pin)
})
return pins
},
make_pin_config: function (instance, meta, canonical_pin, config) {
var pin_config = _.clone(config)
delete pin_config.pins
delete pin_config.pin
pin_config.pin = canonical_pin
pin_config.id = instance.util.pattern(pin_config) + '~' + meta.identifier$
return pin_config
},
}
}
|
cc.Class({
extends: cc.Component,
properties: {
_id:1,
_num:1,
_cost:1,
goods_num:cc.Label,
goods_cost:cc.Label,
goods_icon:cc.Sprite,
goods_spf:cc.SpriteFrame,
},
// use this for initialization
onLoad: function () {
this.node.on('setgoods',function(event){
var msg = event.detail;
this._id = msg.id;
this._num = msg.num;
this._cost = msg.cost;
this.goods_num.string = this._num/10000;
this.goods_cost.string = this._cost;
},this);
},
// called every frame, uncomment this function to activate update callback
// update: function (dt) {
// },
});
|
var isDragging = false;
var isDraggingArrow = false;
var start_pos = {x:0, z:0};
var box_vertices = [null,null];
var selected_nodes = [];
var bounds;
var tracer = new Tracer();
var $toolTip = $('#toolTip');
var $toolTip2 = $('#toolTip2');
var $toolTip3 = $('#toolTip3');
var $selectbox = $('#selectbox');
var $plot = $('#plot');
var $infobox = $('#infobox');
var $resizable = $('.resizable');
var raycaster = new THREE.Raycaster();
raycaster.linePrecision = 8;
var mouse = new THREE.Vector2();
var highlightedObj = null;
var mouseInEnv = true;
var mouseOverGUI = false;
var mouseOverPlot = false;
$('#gui').on('mouseenter', function() {
mouseOverGUI = true;
mouseInEnv = false;
})
$('#plot').on('mouseenter', function() {
mouseOverPlot = true;
mouseInEnv = false;
})
$('#gui').on('mouseleave', function() {
mouseOverGUI = false;
if (!mouseOverPlot) {
mouseInEnv = true;
}
});
$('#plot').on('mouseleave', function() {
mouseOverPlot = false;
if (!mouseOverGUI) {
mouseInEnv = true;
}
});
window.addEventListener('resize', function(){
onWindowResizeThree();
// if (_nodes) updateNodes(_nodes, _h, _viewMode);
}, false);
window.addEventListener('dblclick',function() {
if (mouseInEnv) {
if (highlightedObj != null && highlightedObj.beams) {
var node = highlightedObj
if (!node.fixed) {
node.setFixed(true,{x:1,z:1,c:1});
globals.geom.constraints.push(node);
} else {
node.setFixed(false);
var index = globals.geom.constraints.indexOf(node);
globals.geom.constraints.splice(index,1);
}
// console.log(geom)
// console.log('fix node ' + highlightedObj.index);
} else if (highlightedObj != null && highlightedObj.nodes) {
//double clicked on beam --> subdivide
console.log('subdivide')
subdivideBeam(highlightedObj);
}
}
render();
}, false);
window.addEventListener('mousedown', function(e){
if (mouseInEnv) {
isDragging = true;
start_pos.x = ( e.clientX / window.innerWidth ) * 2 - 1;
start_pos.z = - ( e.clientY / window.innerHeight ) * 2 + 1;
box_vertices[0] = new THREE.Vector3(start_pos.x,start_pos.z,0).unproject(camera);
$selectbox.show();
$selectbox.css({height:0, width:0});
selected_nodes = [];
// window.removeEventListener( 'mousemove', mouseMove );
}
render();
}, false);
window.addEventListener('mouseup', function(){
if (mouseInEnv) {
isDragging = false;
$selectbox.hide();
if (bounds != null) {
_.each(globals.geom.nodes, function(node) {
if (node.x0 < bounds.max.x && node.x0 > bounds.min.x) {
if (node.z0 > bounds.max.z && node.z0 < bounds.min.z) {
node.highlight();
selected_nodes.push(node);
}
}
});
}
selectAction(selected_nodes, bounds);
// window.addEventListener( 'mousemove', mouseMove, false );
}
render();
}, false);
window.addEventListener( 'mousemove', mouseMove, false );
var lattice = {};
lattice.round = function(number, precision) {
var factor = Math.pow(10, precision);
var tempNumber = number * factor;
var roundedTempNumber = Math.round(tempNumber);
return roundedTempNumber / factor;
};
lattice.roundUp = function(number, precision) {
var factor = Math.pow(10, precision);
var tempNumber = (number+Math.pow(10,-precision)/2.) * factor;
var roundedTempNumber = Math.round(tempNumber);
return roundedTempNumber / factor;
};
lattice.roundDown = function(number, precision) {
var factor = Math.pow(10, precision);
var tempNumber = (number-Math.pow(10,-precision)/2.) * factor;
var roundedTempNumber = Math.round(tempNumber);
return roundedTempNumber / factor;
};
function selectAction(nodes, bnds=null) {
if (globals.control_parameters.selectMode == "add_geom") {
var minx = lattice.roundUp(bnds.min.x,-2)
var maxx = lattice.roundDown(bnds.max.x,-2)
var minz = lattice.roundDown(bnds.min.z,-2)
var maxz = lattice.roundUp(bnds.max.z,-2)
var parts = getParts(nodes);
addGeometry(minx,maxx,minz,maxz);
return;
}
if (globals.control_parameters.selectMode == "make_rigid") {
var parts = getParts(nodes);
_.each(parts, function(part) {
part.changeType('rigid');
});
}
if (globals.control_parameters.selectMode == "make_1DoF") {
var parts = getParts(nodes);
_.each(parts, function(part) {
part.changeType('1DoF');
});
}
if (globals.control_parameters.selectMode == "make_2DoF") {
var parts = getParts(nodes);
_.each(parts, function(part) {
part.changeType('2DoF');
});
}
if (globals.control_parameters.selectMode == "make_none") {
var parts = getParts(nodes);
_.each(parts, function(part) {
part.changeType('none');
});
}
if (globals.control_parameters.selectMode == "sub_geom") {
var parts = getParts(nodes);
console.log("remove parts:")
console.log(parts)
_.each(parts, function(part) {
part.ripupBeams();
part.destroy();
})
reindex(globals.geom.nodes);
reindex(globals.geom.beams);
console.log(globals.geom);
}
var sub_nodes = [];
var sub_beams = [];
_.each(nodes, function(node) {
if (globals.control_parameters.selectMode == "fix") {
if (!node.fixed) {
node.setFixed(true,{x:1,z:1,c:1});
globals.geom.constraints.push(node);
}
return;
}
if (globals.control_parameters.selectMode == "un-fix") {
if (node.fixed) {
node.setFixed(false);
var index = globals.geom.constraints.indexOf(node);
globals.geom.constraints.splice(index,1);
}
return;
}
if (globals.control_parameters.selectMode == "force") {
if (!node.fixed && node.externalForce == null) {
node.addExternalForce(new THREE.Vector3(globals.control_parameters.fv_x,0,-globals.control_parameters.fv_y));
}
return;
}
if (globals.control_parameters.selectMode == "un-force") {
if (node.externalForce != null) {
node.removeExternalForce();
}
return;
}
if (globals.control_parameters.selectMode == "trace") {
tracer.traceNode(node);
return;
}
if (globals.control_parameters.selectMode == "un-trace") {
tracer.removeNode(node);
return;
}
// if (globals.control_parameters.selectMode == "sub_geom") {
// // if (node.fixed) {
// // node.setFixed(false);
// // var index = globals.geom.constraints.indexOf(node);
// // globals.geom.constraints.splice(index,1);
// // }
// // if (node.externalForce != null) {
// // node.removeExternalForce();
// // }
// // removeNode(node);
// // node.destroy();
// return;
// }
});
// if (globals.control_parameters.selectMode == "sub_geom") {
// reindex(globals.geom.nodes);
// }
}
function getSelectBounds(vertices) {
var _min = {x:0, z:0};
var _max = {x:0, z:0};
if (vertices[1].x < vertices[0].x) {
_min.x = vertices[1].x;
} else {
_min.x = vertices[0].x;
}
if (vertices[1].z < vertices[0].z) {
_max.z = vertices[1].z;
} else {
_max.z = vertices[0].z;
}
if (vertices[1].x > vertices[0].x) {
_max.x = vertices[1].x;
} else {
_max.x = vertices[0].x;
}
if (vertices[1].z > vertices[0].z) {
_min.z = vertices[1].z;
} else {
_min.z = vertices[0].z;
}
return {
min: _min,
max: _max
}
}
function mouseMove(e){
if (mouseInEnv) {
e.preventDefault();
mouse.x = ( e.clientX / window.innerWidth ) * 2 - 1;
mouse.y = - ( e.clientY / window.innerHeight ) * 2 + 1;
raycaster.setFromCamera(mouse, camera);
if (isDragging) {
box_vertices[1] = new THREE.Vector3(mouse.x,mouse.y,0).unproject(camera);
bounds = getSelectBounds(box_vertices);
_.each(globals.geom.nodes, function(node) {
if (node.x0 < bounds.max.x && node.x0 > bounds.min.x) {
if (node.z0 > bounds.max.z && node.z0 < bounds.min.z) {
node.highlight();
} else {
node.unhighlight();
}
} else {
node.unhighlight();
}
});
var tmp1 = new THREE.Vector3(bounds.min.x, 0, bounds.min.z).project( camera );
var tmp2 = new THREE.Vector3(bounds.max.x, 0, bounds.max.z).project( camera );
var selectbounds = [(tmp1.x+1)/2*window.innerWidth,
(-tmp1.y+1)/2*window.innerHeight,
(tmp2.x+1)/2*window.innerWidth,
(-tmp2.y+1)/2*window.innerHeight];
$selectbox.css({left:selectbounds[0], top:selectbounds[3]});
$selectbox.css({height:selectbounds[1]-selectbounds[3], width:selectbounds[2]-selectbounds[0]});
render();
} else {
var intersections = raycaster.intersectObjects(wrapper.children.concat(beamWrapper.children));
highlightedObj = null;
if (intersections.length > 0) { // to do: set priority to nodes first
var node_selected = false;
_.each(intersections, function (thing) {
if (thing.object && thing.object._myNode) {
node_selected = true;
thing.object._myNode.highlight();
highlightedObj = thing.object._myNode;
}
});
if (!node_selected) {
_.each(intersections, function (thing) {
if (thing.object && thing.object._myBeam) {
thing.object._myBeam.highlight();
highlightedObj = thing.object._myBeam;
}
});
}
render();
}
if (highlightedObj) {
var text = null;
var text2 = null;
var text3 = null;
var pos0 = [0, 0];
var pos1 = [0, 0];
var pos2 = [0, 0];
var offset = [0, 0];
var offset2 = [0, 0];
if (highlightedObj.beams) {
// text = "node " + highlightedObj.index
var tmp = highlightedObj.getPosition().clone().project( camera )
pos0 = [(tmp.x+1)/2*window.innerWidth,
(-tmp.y+1)/2*window.innerHeight];
text1 = "<p><b>node " + highlightedObj.index + "</b><br>";
$toolTip.html(text1);
$toolTip.css({top:pos0[1]-40, left: pos0[0]});
$toolTip.show();
} else if (highlightedObj.nodes) {
// it's a beam
highlightedObj.nodes[0].highlight();
highlightedObj.nodes[1].highlight();
var angle = highlightedObj.getAngle(highlightedObj.vertices[0]);
var tmp = highlightedObj.nodes[0].getPosition().clone().project( camera )
pos0 = [(tmp.x+1)/2*window.innerWidth,
(-tmp.y+1)/2*window.innerHeight];
var tmp = highlightedObj.nodes[1].getPosition().clone().project( camera )
pos1 = [(tmp.x+1)/2*window.innerWidth,
(-tmp.y+1)/2*window.innerHeight];
pos2 = [(pos0[0]+pos1[0])/2, (pos0[1]+pos1[1])/2.]
offset = [-60*Math.sin(angle),60*Math.cos(angle)];
offset2 = [40*Math.sin(angle),-40*Math.cos(angle)];
text1 = "<p><b>node " + highlightedObj.nodes[0].index + "</b><br>";
text2 = "<p><b>node " + highlightedObj.nodes[1].index + "</b><br>";
text3 = "<p><b>beam " + highlightedObj.index + "</b><br>";
if (highlightedObj.f_local != null) {
var forces = forces2text(highlightedObj.f_local.toArray());
// console.log(highlightedObj.f_local.toArray().flatten)
text1 += "fx: " + forces[0] + "<br>"
text1 += "fy: " + forces[1] + "<br>"
text1 += "m: " + forces[2] + "<br>"
text2 += "fx: " + forces[3] + "<br>"
text2 += "fy: " + forces[4] + "<br>"
text2 += "m: " + forces[5] + "<br>"
}
text1 += "</p>"
text2 += "</p>"
$toolTip.html(text1);
$toolTip.css({top:pos0[1]+offset[1], left: pos0[0]+offset[0]});
$toolTip.show();
$toolTip2.html(text2);
$toolTip2.css({top:pos1[1]+offset[1], left: pos1[0]+offset[0]});
$toolTip2.show();
$toolTip3.html(text3);
$toolTip3.css({top:pos2[1]+offset2[1], left: pos2[0]+offset2[0]});
$toolTip3.show();
}
} else {
_.each(beamWrapper.children, function (beam) {
beam._myBeam.unhighlight();
});
_.each(wrapper.children, function (node) {
if (node._myNode) {
node._myNode.unhighlight();
}
});
$toolTip.hide();
$toolTip2.hide();
$toolTip3.hide();
highlightedObj = null;
render();
}
}
}
}
function forces2text(fmatrix) {
output = []
// fmatrix.forEach(function (value, index, matrix) {
_.each(_.flatten(fmatrix), function(value) {
output.push(value.toFixed(2));
});
return output;
}
function displayMessage(message) {
// $infobox.html("<p><b>"+message+"</b></p>");
// // console.log($infobox)
// $infobox.show();
// $infobox.hide();
// $infobox.show();
}
function hideMessage() {
// $infobox.css({display:none});
// $infobox.hide();
// console.log($infobox)
}
function forceRedraw(el) {
var t = el.ownerDocument.createTextNode(' ');
el.appendChild(t);
setTimeout(function() { el.removeChild(t); }, 0);
}
|
var searchData=
[
['fastio_2eh',['fastio.h',['../fastio_8h.html',1,'']]],
['fatstructs_2eh',['FatStructs.h',['../_fat_structs_8h.html',1,'']]]
];
|
// check rdns against list of regexps
//
// WARNING: this plugin is deprecated. see 'haraka -h access' to upgrade
//
// this plugin will be removed in a future version of Haraka.
exports.register = function () {
this.logwarn("NOTICE: deprecated, use 'connect.rdns_access' instead!");
};
exports.hook_connect = function (next, connection) {
var deny_list = this.config.get('rdns.deny_regexps', 'list');
var allow_list = this.config.get('rdns.allow_regexps', 'list');
for (var i=0,l=deny_list.length; i < l; i++) {
var re = new RegExp(deny_list[i]);
if (re.test(connection.remote.host)) {
for (var i=0,l=allow_list.length; i < l; i++) {
var re = new RegExp(allow_list[i]);
if (re.test(connection.remote.host)) {
connection.loginfo(this, "rdns matched: " + allow_list[i] +
", allowing");
return next();
}
}
connection.loginfo(this, "rdns matched: " + deny_list[i] + ", blocking");
return next(DENY, "Connection from a known bad host");
}
}
return next();
};
|
describe("Text Package", function() {
it("should fail", function() {
expects(false).toBeTruthy();
});
});
|
(function() {
"use strict";
App.IndexRoute = Ember.Route.extend({
model: function() {
return this.store.find('product');
}
});
})();
|
'use strict';
var Promise = require('ember-cli/lib/ext/promise');
var exec = Promise.denodeify(require('child_process').exec);
var path = require('path');
var pkg = require('../package.json');
var fs = require('fs');
var template = require('lodash/template');
var Task = require('ember-cli/lib/models/task');
var gitEnvironmentVariables = {
GIT_AUTHOR_NAME: 'candycane-cli',
GIT_AUTHOR_EMAIL: 'candycane-cli@candycaneapi.com',
get GIT_COMMITTER_NAME(){ return this.GIT_AUTHOR_NAME; },
get GIT_COMMITTER_EMAIL(){ return this.GIT_AUTHOR_EMAIL; }
};
module.exports = Task.extend({
run: function(commandOptions) {
var chalk = require('chalk');
var ui = this.ui;
if(commandOptions.skipGit) { return Promise.resolve(); }
return exec('git --version')
.then(function() {
return exec('git init')
.then(function() {
return exec('git add .');
})
.then(function(){
var commitTemplate = fs.readFileSync(path.join(__dirname, '../utilities/INITIAL_COMMIT_MESSAGE.txt'));
var commitMessage = template(commitTemplate)(pkg);
return exec('git commit -m "' + commitMessage + '"', {env: gitEnvironmentVariables});
})
.then(function(){
ui.writeLine(chalk.green('Successfully initialized git.'));
});
}).catch(function(/*error*/){
// if git is not found or an error was thrown during the `git`
// init process just swallow any errors here
});
}
});
module.exports.overrideCore = true;
|
const deffy = require("deffy")
const CommentSchema = new Bloggify.db.Schema({
author: Object,
body: {
type: String,
text: true
},
created_at: {
type: Date,
index: true
},
topic: {
type: String,
index: true
},
votes: [String]
})
// Hooks
CommentSchema.pre("save", function (next) {
this.wasNew = this.isNew
next()
})
CommentSchema.post("save", function () {
if (this.wasNew) {
Bloggify.emit("comment:created", this)
}
})
// Create comment
CommentSchema.statics.createComment = data => {
data.body = deffy(data.body, "").trim()
data.votes = []
if (!data.body.length) {
return Promise.reject(Bloggify.errors.COMMENT_BODY_IS_BLANK())
}
return new Comment(data).save()
}
// Get comment
CommentSchema.statics.getComment = filters => {
return Comment.findOne(filters)
}
// Query comments
CommentSchema.statics.queryComments = opts => {
opts = opts || {}
let topics = []
return Comment.find(opts.filters, opts.fields).sort({
created_at: 1
}).exec()
}
const Comment = module.exports = Bloggify.db.model("Comment", CommentSchema)
|
/*
* This file will be overwritten in the build process on Jenkins.
* See https://gita.sys.kth.se/Infosys/zermatt/blob/master/jenkins/buildinfo-to-node-module.sh
*/
module.exports = {
gitBranch: 'NOT SET BY HUDSON',
gitCommit: 'NOT SET BY HUDSON',
jenkinsBuild: 'NOT SET BY HUDSON',
jenkinsBuildDate: 'NOT SET BY HUDSON',
dockerName: 'NOT SET BY HUDSON',
dockerVersion: 'NOT SET BY HUDSON'
}
|
var browserFakeUserAgent = 'Fake/5.0 (FakeOS) AppleWebKit/123 (KHTML, like Gecko) Fake/12.3.4567.89 Fake/123.45';
(function(that) {
if (typeof RecordRTC !== 'undefined') {
return;
}
if (!that) {
return;
}
if (typeof window !== 'undefined') {
return;
}
if (typeof global === 'undefined') {
return;
}
global.navigator = {
userAgent: browserFakeUserAgent,
getUserMedia: function() {}
};
if (!global.console) {
global.console = {};
}
if (typeof global.console.log === 'undefined' || typeof global.console.error === 'undefined') {
global.console.error = global.console.log = global.console.log || function() {
console.log(arguments);
};
}
if (typeof document === 'undefined') {
/*global document:true */
that.document = {
documentElement: {
appendChild: function() {
return '';
}
}
};
document.createElement = document.captureStream = document.mozCaptureStream = function() {
var obj = {
getContext: function() {
return obj;
},
play: function() {},
pause: function() {},
drawImage: function() {},
toDataURL: function() {
return '';
},
style: {}
};
return obj;
};
that.HTMLVideoElement = function() {};
}
if (typeof location === 'undefined') {
/*global location:true */
that.location = {
protocol: 'file:',
href: '',
hash: ''
};
}
if (typeof screen === 'undefined') {
/*global screen:true */
that.screen = {
width: 0,
height: 0
};
}
if (typeof URL === 'undefined') {
/*global screen:true */
that.URL = {
createObjectURL: function() {
return '';
},
revokeObjectURL: function() {
return '';
}
};
}
/*global window:true */
that.window = global;
})(typeof global !== 'undefined' ? global : null);
|
'use strict'
angular.module('app', [])
.controller('MainController', function ($scope) {
var rolls = [],
currentRoll = 0;
$scope.roll = function (pins) {
rolls[currentRoll++] = pins;
};
function isSpare(frameIndex) {
return rolls[frameIndex] + rolls[frameIndex + 1] == 10;
}
function strikeBonus(frameIndex) {
return rolls[frameIndex + 1] + rolls[frameIndex + 2];
}
function spareBonus(frameIndex) {
return rolls[frameIndex + 2];
}
function sumOfBallsInFrame(frameIndex) {
return rolls[frameIndex] + rolls[frameIndex + 1];
}
function isStrike(frameIndex) {
return rolls[frameIndex] == 10;
}
$scope.score = function () {
var score = 0,
frameIndex = 0;
for (var frame = 0; frame < 10; frame++) {
if (isStrike(frameIndex)) { //strike
score += 10 + strikeBonus(frameIndex);
frameIndex++;
} else if (isSpare(frameIndex)) {
score += 10 + spareBonus(frameIndex);
frameIndex += 2;
} else {
score += sumOfBallsInFrame(frameIndex);
frameIndex += 2;
}
}
return score;
}
})
|
/* !
This is the setup script to register all demo related AccDC Object declarations.
This file is only parsed when the Live Demo tab is opened from the left navigation links.
*/
// Configure the AccDC Objects for all of the demos on the Live Demo tab
/* !
IMPORTANT : Note that the first argument for $A() is set to the 'mcDemo' AccDC Object.
mcDemo is the Live Demo AccDC tab control instance previously declared at
http : // whatsock.com / js / ready.js , which is now the top - level parent object for all of the AccDC Object declarations below.
Also within the mcDemo AccDC Object, this.children will now contain an array of all first level child objects declared herein.
With this hierarchy established, AccDC Objects can now traverse up and down the parent / children chain to reference / modify / invoke properties and methods.
E.G. this.parent.parent.parent.close(); will activate the close method three levels up the chain, and close the object.
Similarly, this.children[0].children[0].role = 'Wizard'; will change the role property for the object two levels down the chain.
*/
$A($A.reg.mcDemo,
[
// Dynamic Editor with XML Generated Menus
{
// Unique ID for the AccDC Object
id: 'demoEditor',
// Role for the Screen Reader Accessible Hidden Text
role: 'Dynamic Editor',
// Set heading level for screen reader users
ariaLevel: 3,
mode: 1,
source: 'files/demo/editor.html #dynEdit',
// Event binders
bind: 'click',
// CSS Selector to identify triggering elements
trigger: 'a.editLink',
// Class name for the AccDC Object
className: 'demoDynamicEditor',
// Class name for the Close link
closeClassName: 'close',
// Set the initial positioning relative to the triggering element
autoPosition: 11,
cssObj:
{
position: 'absolute'
},
// Move focus to the beginning of the AccDC Object when opened
forceFocus: true,
// Set shadowing
shadow:
{
horizontal: '5px',
vertical: '5px',
blur: '5px',
color: '#000000'
},
// Run script only once after the AccDC Object is first rendered
runOnceAfter: function(dc){
// Create the Tooltip AccDC Object that is displayed whenever a submenu link is activated
$A(dc,
[
{
id: 'tooltip',
role: 'Tooltip',
// Display plain text
source: 'Disabled',
// Configure behaviors
allowReopen: true,
returnFocus: false,
showHiddenClose: false,
className: 'announceMsg',
// Automatically position the tooltip AccDC Object to the right of the triggering element (allows for position : relative offset differences)
autoPosition: 3,
// Set inline styling
cssObj:
{
position: 'relative'
},
// Add an additional px offset to increase padding between objects
offsetLeft: 10,
runBefore: function(dc){
// Add a negative height offset to account for position : relative
dc.offsetTop = -dc.triggerObj.offsetHeight;
},
runAfter: function(dc){
// Announce the text within the containerDiv property for screen reader users
$A.announce(dc.containerDiv);
},
// Automatically close when the timeout value in milliseconds is reached
timeoutVal: 2000,
timeout: function(dc){
// Close the tooltip object after 2 seconds
dc.close();
}
}
]);
},
// Run script every time after the Editor AccDC Object is rendered
runAfter: function(dc){
var $textarea = $A.query('textarea.editor')[0], section = $A.query('div.dynContent')[0];
// Populate content
$textarea.value = section.innerText || section.textContent;
// Add auto expand functionality to the textarea tag
elastic($textarea, 300);
// Create a nested AccDC Object to render horizontal Menu Bar menus
$A(dc,
[
{
id: 'demoMenuBar',
role: 'Menu Bar',
ariaLevel: 4,
isStatic: 'div.dynEditorTop',
autoStart: true,
returnFocus: false,
showHiddenClose: false,
mode: 6,
className: 'demoMenuBarDiv',
// Configure AJAX options
ajaxOptions:
{
url: 'files/demo/menubar.xml',
// Set the dataType to text to allow local script execution
dataType: 'text'
},
// Execute handler when the AJAX request fires the success callback
hSuccess: function(options, data, textStatus, xhRequest, dc){
// Convert the returned text to an XML document for local parsing
dc.xmlDoc = str2xml(data);
// set the start string for the content property
dc.content = '<div class="demoMenuBar clearfix">';
// Add Menu Bar menu links as parsed from the XML DOM and append them to the content property
$A.query('menubar > *', dc.xmlDoc, function(){
dc.content += '<div><a class="demoMenu-' + this.nodeName + '">'
+ this.attributes.getNamedItem('text').value + '</a></div>';
});
dc.content += '</div>';
},
// Run script after the horizontal Menu Bar links have been rendered
runAfter: function(dc){
// Create an array to hold the AccDC Object declarations for each horizontal Menu Bar menu
var menuObjects = [];
$A.query('menubar > *', dc.xmlDoc, function(i){
// Expand the object array for each submenu
menuObjects.push(
{
id: 'demoMenu' + i,
role: this.attributes.getNamedItem('text').value,
source: this.childNodes[0].nodeValue,
trigger: 'a.demoMenu-' + this.nodeName
});
});
// Create a key / value map to be merged with all of the objects in the prior array
var overrides =
{
ariaLevel: 5,
// Enable tab functionality
isTab: true,
// Set screen reader role text
tabRole: 'Menu',
// Set screen reader state text
tabState: 'Open',
bind: 'click focus',
// Automatically position the dropdown menu AccDC Object beneath the triggering element
autoPosition: 5,
// Add an additional px offset to increase padding between objects
offsetTop: 5,
// Set the offset type
cssObj:
{
position: 'relative'
},
className: 'demoSubMenus',
// Run script before the dropdown menu AccDC Object is opened
runBefore: function(dc){
// Dynamically subtract the top offset to account for the height of the triggering element, plus 5px for padding
dc.offsetTop = -dc.triggerObj.offsetHeight + 5;
},
// Run script after the dropdown menu AccDC Object is opened
runAfter: function(dc){
// Add a click handler to every submenu link when rendered
$A.bind('#' + dc.containerId + ' a', 'click', function(ev){
// Configure and open the AccDC Object with id = "tooltip"
var ndc = $A.reg.tooltip;
// Set the triggerObj property
ndc.triggerObj = this;
// Open the AccDC Object
ndc.open();
ev.preventDefault();
});
// Change inline styling for the triggering element
$A.css(dc.triggerObj,
{
color: '#ffffff',
backgroundColor: '#3A5FCD'
});
},
// Run script after the AccDC Object for a horizontal Menu Bar menu link is closed
runAfterClose: function(dc){
// Change inline styling for the triggering element
$A.css(dc.triggerObj,
{
color: '#000000',
backgroundColor: '#ffffff'
});
},
mouseOut: function(ev, dc){
// Close the currently open menu when the mouse moves out
dc.close();
}
};
// Invoke $A to register all AccDC Objects configured above
$A(dc, menuObjects, overrides);
// Change inline styling for the triggering element
$A.css(dc.triggerObj,
{
color: '#ffffff',
backgroundColor: '#3A5FCD'
});
},
// Run script after the horizontal Menu Bar menu links are closed
runAfterClose: function(dc){
$A.css(dc.triggerObj,
{
color: '#000000',
backgroundColor: '#ffffff'
});
}
}
// End of nested menus object array
]);
},
// Run script before the AccDC Object is closed
runBeforeClose: function(dc){
// Add the modified text to the container object within the main page
var container = $A.query('.dynContent')[0];
container.innerHTML = '';
container.appendChild(document.createTextNode($A.query('textarea.editor', dc.containerDiv)[0].value.replace(/<|>/g,
'')));
}
}
// End of AccDC Object array
],
{
// Merge the following key / value with all objects declared in the prior array
allowMultiple: true
});
// Keyboard Accessible Drag and Drop
// Bind a click handler to the Convert button
$A.bind('input.morphBtn', 'click', function(ev){
// Configure the Keyboard accessible drag and drop sample by morphing all planet images into draggable AccDC Objects
$A.query('div.dndContainer ul li > img', function(i, obj){
// Also, similar to the first $A declaration above, set the mcDemo AccDC Object as the parent
$A.morph($A.reg.mcDemo, obj,
{
// Dynamically generate a unique ID
id: 'list' + i,
// Use the alt attribute value of the image to set the role (to be used later for keyboard accessibility)
role: $A.getAttr(obj, 'alt'),
// Prevent hidden boundary information from being displayed to screen reader users
showHiddenBounds: false,
// Prevent the object from being closable from the keyboard.
showHiddenClose: false,
// Set initial visual styling
cssObj:
{
position: 'absolute',
zIndex: 3
},
// Make the object draggable
isDraggable: true,
// Set temporary variables for tracking
inUniverse: true,
dropped: false,
// Store object to prevent same - side drop triggering
currentZone: null,
// Run script after rendering completes
runAfter: function(dc){
// Set additional styling for the drag links to allow for color contrast differences
dc.accDD.dragLinkStyle =
{
color: 'white',
backgroundColor: 'black',
border: 'solid thin white'
};
// CSS to reset positioning
dc.clearCSS =
{
zIndex: 3,
top: '',
left: '',
height: '',
width: ''
};
// Save references to the relevant list objects to prevent unnecessary queries later
var lists = $A.query('div.dndContainer ul, div.dndContainer ol');
// Set initial drag and drop options
dc.dropTarget = 'div.subDivR';
// Limit dragging to the bounds of a specific container
dc.drag.confineTo = 'div.dndContainer';
// Enable keyboard accessibility for the drag and drop action
dc.accDD.on = true;
// Set the drop animation duration in milliseconds
dc.accDD.duration = 3000;
// Set a point to return keyboard focus to after dragging has begun to ensure keyboard accessibility
dc.accDD.returnFocusTo = 'div.subDivL ul';
// Configure the drag / drop event handlers
dc.onDragStart = function(ev, dd, dc){
dc.css('z-index', 4);
dc.originalXY =
{
top: dd.originalY,
left: dd.originalX
};
};
dc.onDrop = function(ev, dd, dc){
if (dc.currentZone != this){
dc.currentZone = this;
dc.dropped = true;
var tmp = dc.dropTarget;
// Remove old drag and drop bindings
dc.unsetDrag();
// Clear drag styling
dc.css(dc.clearCSS);
if (dc.inUniverse){
dc.inUniverse = false;
dc.dropTarget = 'div.subDivL';
dc.accDD.returnFocusTo = 'div.subDivR ol';
// Move the dragged element into the galaxy list
lists[1].appendChild(dc.accDCObj.parentNode);
}
else{
dc.inUniverse = true;
dc.dropTarget = 'div.subDivR';
dc.accDD.returnFocusTo = 'div.subDivL ul';
// Move the dragged element into the Universe list
lists[0].appendChild(dc.accDCObj.parentNode);
}
// Now set drag and drop bindings with the newly configured options
dc.setDrag();
}
};
dc.onDragEnd = function(ev, dd, dc){
// Check if a valid drop has occurred, and move back to the starting point if not
if (!dc.dropped)
dropIntoTheSun(dc);
dc.dropped = false;
};
// Now set initial event bindings
dc.setDrag();
// Expand parent li tag to account for position absolute
$A.css(dc.accDCObj.parentNode,
{
height: dc.accDCObj.offsetHeight,
width: dc.accDCObj.offsetWidth
});
dc.accDCObj.parentNode.appendChild($A.createEl('div', null,
{
clear: 'both'
}, null, document.createTextNode(' ')));
}
});
});
// Make the sun a draggable AccDC Object as well
var sunImg = $A.query('div.dndContainer img.sun')[0];
$A.morph($A.reg.mcDemo, sunImg,
{
id: 'sun',
role: 'Sun',
showHiddenBounds: false,
showHiddenClose: false,
isDraggable: true,
drag:
{
confineTo: 'div.dndContainer'
},
cssObj:
{
position: 'absolute',
// Copy the current coordinates for the image
left: xOffset(sunImg).left,
top: xOffset(sunImg).top,
// Set the depth
zIndex: 2
}
});
// Change the status message and announce it to screen reader users
$A.announce($A.getEl('morphI').innerHTML = 'Converted all images into draggable AccDC Objects');
ev.preventDefault();
});
function dropIntoTheSun(dc){
var sun = firstChild($A.reg.sun.containerDiv, 'img'), planet = firstChild(dc.containerDiv, 'img'),
additional = sun.offsetHeight / 2, sunOS = xOffset(sun);
// Move planet to the sun
transition(dc.accDCObj,
{
top: sunOS.top + additional,
left: sunOS.left + additional
},
{
duration: 3000,
complete: function(cb){
// Fall into the sun
transition(dc.accDCObj,
{
height: 0,
width: 0,
transform: 360
},
{
duration: 2000,
step: function(cb){
// cb contains cb.top and cb.left to match the wrapper, so sync the image to this at runtime
$A.css(planet, cb);
},
complete: function(cb){
// Stick the planet behind the sun and resize it, including both the wrapper and the image
$A.css(
[
dc.accDCObj,
planet
],
{
zIndex: 1,
height: '20px',
width: '20px'
});
// Move the planet back to its original position
transition(dc.accDCObj, dc.originalXY,
{
duration: 3000,
complete: function(cb){
// Bring the planet to the front once again
$A.css(dc.accDCObj, 'z-index', 4);
// Zoom the planet back into focus
transition(dc.accDCObj,
{
height: 75,
width: 75,
transform: 0
},
{
duration: 2000,
step: function(cb){
$A.css(planet, cb);
},
complete: function(cb){
// Now clear css !
dc.css(dc.clearCSS);
}
});
}
});
}
});
}
});
}
|
var e = 'Some string' + ' from mixed/e.js';
|
/**
* Merge object functional
*
* @type {object}
* @return {object}
*
* @author Faizal Pribadi <ical.rabbit@gmail.com>
* @version 0.1.0
*/
exports = module.exports = function (object1, object2) {
'use strict';
var keys;
// TODO: fix no input argument object to default object
if (typeof object1 !== 'object' && typeof object2 !== 'object') {
object1 = {};
object2 = {};
}
for(keys in object2) {
if (object2.hasOwnProperty(keys)) {
object1[keys] = object2[keys];
}
}
return object1;
};
|
"use strict";
let ServiceBroker = require("../src/service-broker");
// Create broker #1
let broker1 = new ServiceBroker({
nodeID: "node-1",
transporter: "NATS",
logger: console,
tracking: {
enabled: true
}
});
let c1 = 0;
broker1.createService({
name: "first",
actions: {
async "5"(ctx) {
this.logger.info(`${ctx.action.name} begin. ID: ${++c1}`);
await ctx.call("slow.5");
this.logger.info(`${ctx.action.name} end. ID: ${c1}`);
},
async "10"(ctx) {
this.logger.info(`${ctx.action.name} begin. ID: ${++c1}`);
await ctx.call("slow.10");
this.logger.info(`${ctx.action.name} end. ID: ${c1}`);
}
}
});
// Create broker #2
let broker2 = new ServiceBroker({
nodeID: "node-2",
transporter: "NATS",
logger: console,
tracking: {
enabled: true
}
});
let c2 = 0;
broker2.createService({
name: "slow",
actions: {
async "5"(ctx) {
this.logger.info(`${ctx.action.name} begin. ID: ${++c2}`);
await this.Promise.delay(5 * 1000);
this.logger.info(`${ctx.action.name} end. ID: ${c2}`);
},
async "10"(ctx) {
this.logger.info(`${ctx.action.name} begin. ID: ${++c2}`);
await this.Promise.delay(10 * 1000);
this.logger.info(`${ctx.action.name} end. ID: ${c2}`);
}
},
events: {
async "slow-5"(ctx) {
this.logger.info(`${ctx.event.name} begin. ID: ${++c2}`);
await this.Promise.delay(5 * 1000);
this.logger.info(`${ctx.event.name} end. ID: ${c2}`);
}
}
});
broker1.Promise.all([
broker1.start(),
broker2.start()
]).then(async () => {
//broker1.repl();
//broker1.call("first.5");
//broker1.call("slow.5");
broker1.emit("slow-5");
await broker1.Promise.delay(2 * 1000);
broker1.stop();
broker2.stop();
});
|
import { combineReducers } from 'redux'
// import { combineReducers } from 'redux-immutablejs';
import postsByApi from './postsByApi'
import changeType from './changeType'
//将两个reducer合并成一个reducer,也就将全局的state加上postsByReddit,selectedReddit两个属性,每个属性都有自己的state
const rootReducer = combineReducers({
postsByApi,
})
export default rootReducer
|
//header div
import React from 'react';
import styles from '../css/App.css';
export default class Header extends React.Component {
constructor(props) {
super(props);
this.state = {
status:'disconnected'
}
}
render() {
return (
<header className={styles.header}>
<div>
<h3>this client is: {this.props.status}</h3>
</div>
<div>
</div>
</header>
);
}
}
|
'use babel';
import {CompositeDisposable} from 'atom';
export default {
mzlpSortView: null,
modalPanel: null,
subscriptions: null,
editor: null,
activate(state) {
this.subscriptions = new CompositeDisposable();
this.subscriptions.add(atom.commands.add('atom-workspace', {
'mzlp-sort:ifSorting': () => this.ifSorting()
}));
this.subscriptions.add(atom.commands.add('atom-workspace', {
'mzlp-sort:gSorting': () => this.gSorting()
}));
this.subscriptions.add(atom.commands.add('atom-workspace', {
'mzlp-sort:orSorting': () => this.orSorting()
}));
},
deactivate() {
},
serialize() {
return {};
},
getIndexList() {
//우선순위에 맞게 변수명 인덱싱 - (리터럴정렬기준3)
let list = ["N_TAG_NIL_ID",
"N_TAG_ON",
"N_TAG_OFF",
"N_TAG_UNDEFINED_ID",
"N_TAG_BREAK_ID",
"N_TAG_SIGNAL_ID",
"N_TAG_NONE_ID",
"N_TAG_MANUAL_VAD_DISCONNECTED_ID",
"N_TAG_MANUAL_NETWORK_DISCONNECTED_ID",
"N_TAG_MANUAL_PTT_ID",
"N_TAG_INNER_RESULT_ID",
"N_TAG_SERVER_INNER_RESULT_ID",
"N_TAG_AUTO_RESULT_ID",
"N_TAG_DRIVING_BACK_ID",
"N_TAG_EXIT_BACK_ID",
"N_TAG_EXIT_EXIT_ID",
"N_TAG_HOUSE_NUMBER_BACK_STEP_ID",
"N_TAG_HELP_ID",
"N_TAG_EXIT_ID",
"N_TAG_BACK_ID",
"N_TAG_YES_ID",
"N_TAG_NO_ID",
"N_TAG_LINE_NUMBER_ID",
"N_TAG_NEXT_PAGE_ID",
"N_TAG_PREVIOUS_PAGE_ID",
"N_TAG_MANUAL_INPUT_ID",
"N_TAG_MANUAL_QUESTION_MARK_ID",
"N_TAG_MANUAL_PHONE_QUESTION_MARK_ID",
"N_TAG_MANUAL_RADIO_QUESTION_MARK_ID",
"N_TAG_MANUAL_MEDIA_QUESTION_MARK_ID",
"N_TAG_MANUAL_UVO_QUESTION_MARK_ID",
"N_TAG_MANUAL_DMB_QUESTION_MARK_ID",
"N_TAG_MANUAL_NAVI_QUESTION_MARK_ID",
"N_TAG_POI_NAME_ID",
"N_TAG_NAVI_LOCATION_DP_ID",
"N_TAG_PHONE_HELP_ID",
"N_TAG_PHONE_CALL_ID",
"N_TAG_VAD_CALL_ID",
"N_TAG_VAD_MOBILE_ID",
"N_TAG_MANUAL_VAD_MOBILE_ID",
"N_TAG_VAD_OFFICE_ID",
"N_TAG_MANUAL_VAD_OFFICE_ID",
"N_TAG_VAD_HOME_ID",
"N_TAG_MANUAL_VAD_HOME_ID",
"N_TAG_VAD_OTHER_ID",
"N_TAG_MANUAL_VAD_OTHER_ID",
"N_TAG_PHONE_DIAL_NUMBER_ID",
"N_TAG_VAD_NUMBER_ID",
"N_TAG_VAD_NUM_SLOT_ID",
"N_TAG_PHONE_MOBILE_ID",
"N_TAG_PHONE_HOME_ID",
"N_TAG_PHONE_OFFICE_ID",
"N_TAG_PHONE_OTHER_ID",
"N_TAG_PHONE_DIAL_ID",
"N_TAG_PHONE_CORRECTION_ID",
"N_TAG_PHONE_DELETE_ID",
"N_TAG_CHANGE_BT_DEVICE_ID",
"N_TAG_NAME_ID",
"N_TAG_NAME_FULL_FIRST_ID",
"N_TAG_NAME_REVERSE_LAST_ID",
"N_TAG_NAME_FIRST_ID",
"N_TAG_NAME_LAST_ID",
"N_TAG_OTHER_NUMBERS_ID",
"N_TAG_RADIO_ID",
"N_TAG_RADIO_HELP_ID",
"N_TAG_FM_ID",
"N_TAG_FM_NUMBER1_ID",
"N_TAG_FM_NUMBER2_ID",
"N_TAG_FM_FREQUENCY_ID",
"N_TAG_AM_ID",
"N_TAG_AM_FREQUENCY_ID",
"N_TAG_PRESET_NUMBER_ID",
"N_TAG_SIRIUSXM_ID",
"N_TAG_SIRIUSXM_CHANNEL_NUMBER_ID",
"N_TAG_CHANNEL_NUMBER_ID",
"N_TAG_RADIO_AST_ID",
"N_TAG_RADIO_STATION_ID",
"N_TAG_FM_LIST_ID",
"N_TAG_AM_LIST_ID",
"N_TAG_AM_FREQ_SLOT_ID",
"N_TAG_MANUAL_FM_ID",
"N_TAG_MANUAL_AM_ID",
"N_TAG_MANUAL_PRESET_ID",
"N_TAG_MANUAL_CHANNEL_ID",
"N_TAG_RADIO_BROADCAST_ID",
"N_TAG_PANDORA_RADIO_ID",
"N_TAG_SKIP_ID",
"N_TAG_THUMBS_UP_ID",
"N_TAG_THUMBS_DOWN_ID",
"N_TAG_MEDIA_HELP_ID",
"N_TAG_MUSIC_ID",
"N_TAG_CD_ID",
"N_TAG_IPOD_ID",
"N_TAG_BT_AUDIO_ID",
"N_TAG_AUX_ID",
"N_TAG_MY_MUSIC_ID",
"N_TAG_USB_ID",
"N_TAG_PLAY_ID",
"N_TAG_PAUSE_ID",
"N_TAG_PLAY_TRACK_NUMBER_ID",
"N_TAG_SHUFFLE_ID",
"N_TAG_SHUFFLE_OFF_ID",
"N_TAG_REPEAT_ID",
"N_TAG_REPEAT_OFF_ID",
"N_TAG_VIDEO_ID",
"N_TAG_VOICE_MEMO_ID",
"N_TAG_MANUAL_TRACK_ID",
"N_TAG_PRIM_FRONT_IPOD_ID",
"N_TAG_PRIM_REAR_IPOD_ID",
"N_TAG_PRIM_FRONT_USB_ID",
"N_TAG_PRIM_REAR_USB_ID",
"N_TAG_PRIM_USB_MUSIC_ID",
"N_TAG_PRIM_FRONT_USB_MUSIC_ID",
"N_TAG_PRIM_REAR_USB_MUSIC_ID",
"N_TAG_PRIM_USB_VIDEO_ID",
"N_TAG_PRIM_FRONT_USB_VIDEO_ID",
"N_TAG_PRIM_REAR_USB_VIDEO_ID",
"N_TAG_PRIM_DVD_ID",
"N_TAG_UVO_HELP_ID",
"N_TAG_ROADSIDE_ASSIST_ID",
"N_TAG_VEHICLE_DIAGNOSTICS_ID",
"N_TAG_ESERVICES_GUIDE_ID",
"N_TAG_UVO_HELP_EV_ID",
"N_TAG_EV_SERVICES_GUIDE_ID",
"N_TAG_CARPLAY_ID",
"N_TAG_ANDROID_AUTO_ID",
"N_TAG_DMB_ID",
"N_TAG_DMB_HELP_ID",
"N_TAG_DMB_AST_ID",
"N_TAG_DMB_LIST_ID",
"N_TAG_STATION_LIST_ID",
"N_TAG_NAVIGATION_HELP_ID",
"N_TAG_CATEGORY_NAME_BIG_ID",
"N_TAG_CATEGORY_NAME_MID_ID",
"N_TAG_CATEGORY_NAME_SMALL_ID",
"N_TAG_SHOW_MAP_ID",
"N_TAG_PREVIOUS_POINT_ID",
"N_TAG_PREVIOUS_DESTINATION_ID",
"N_TAG_PREVIOUS_SEARCH_ID",
"N_TAG_PREVIOUS_START_ID",
"N_TAG_TRAFFIC_INFO_ID",
"N_TAG_GO_HOME_ID",
"N_TAG_GO_TO_OFFICE_ID",
"N_TAG_NAVI_DIAL_ID",
"N_TAG_TURN_GUIDANCE_ON_ID",
"N_TAG_TURN_GUIDANCE_OFF_ID",
"N_TAG_CANCEL_ROUTE_ID",
"N_TAG_DESTINATION_INFO_ID",
"N_TAG_ROUTE_OPTION_ID",
"N_TAG_SHOW_ROUTE_ID",
"N_TAG_NAVI_LOCATION_ID",
"N_TAG_NAVI_GANGWONDO_ID",
"N_TAG_NAVI_GYEONGGIDO_ID",
"N_TAG_NAVI_GYEONGSANGNAMDO_ID",
"N_TAG_NAVI_GYEONGSANGBUKDO_ID",
"N_TAG_NAVI_GWANGJU_ID",
"N_TAG_NAVI_DAEGU_ID",
"N_TAG_NAVI_DAEJEON_ID",
"N_TAG_NAVI_BUSAN_ID",
"N_TAG_NAVI_SEOUL_ID",
"N_TAG_NAVI_SEJONG_ID",
"N_TAG_NAVI_ULSAN_ID",
"N_TAG_NAVI_INCHEON_ID",
"N_TAG_NAVI_JEOLLANAMDO_ID",
"N_TAG_NAVI_JEOLLABUKDO_ID",
"N_TAG_NAVI_JEJUDO_ID",
"N_TAG_NAVI_CHUNGCHEONGNAMDO_ID",
"N_TAG_NAVI_CHUNGCHEONGBUKDO_ID",
"N_TAG_FIND_ADDRESS_ID",
"N_TAG_FIND_FULL_ADDRESS_ID",
"N_TAG_FIND_ADDRESS_STATE_ID",
"N_TAG_STATE_NAME_ID",
"N_TAG_AL_ID",
"N_TAG_AK_ID",
"N_TAG_AZ_ID",
"N_TAG_AR_ID",
"N_TAG_CA_ID",
"N_TAG_CO_ID",
"N_TAG_CT_ID",
"N_TAG_DE_ID",
"N_TAG_DC_ID",
"N_TAG_FL_ID",
"N_TAG_GA_ID",
"N_TAG_HI_ID",
"N_TAG_ID_ID",
"N_TAG_IL_ID",
"N_TAG_IN_ID",
"N_TAG_IA_ID",
"N_TAG_KS_ID",
"N_TAG_KY_ID",
"N_TAG_LA_ID",
"N_TAG_ME_ID",
"N_TAG_MD_ID",
"N_TAG_MA_ID",
"N_TAG_MI_ID",
"N_TAG_MN_ID",
"N_TAG_MS_ID",
"N_TAG_MO_ID",
"N_TAG_MT_ID",
"N_TAG_NE_ID",
"N_TAG_NV_ID",
"N_TAG_NH_ID",
"N_TAG_NJ_ID",
"N_TAG_NM_ID",
"N_TAG_NY_ID",
"N_TAG_NC_ID",
"N_TAG_ND_ID",
"N_TAG_OH_ID",
"N_TAG_OK_ID",
"N_TAG_OR_ID",
"N_TAG_PA_ID",
"N_TAG_RI_ID",
"N_TAG_SC_ID",
"N_TAG_SD_ID",
"N_TAG_TN_ID",
"N_TAG_TX_ID",
"N_TAG_UT_ID",
"N_TAG_VT_ID",
"N_TAG_VA_ID",
"N_TAG_WA_ID",
"N_TAG_WV_ID",
"N_TAG_WI_ID",
"N_TAG_WY_ID",
"N_TAG_PR_ID",
"N_TAG_AB_ID",
"N_TAG_BC_ID",
"N_TAG_MB_ID",
"N_TAG_NB_ID",
"N_TAG_NL_ID",
"N_TAG_NS_ID",
"N_TAG_NT_ID",
"N_TAG_NU_ID",
"N_TAG_ON_ID",
"N_TAG_PE_ID",
"N_TAG_QC_ID",
"N_TAG_SK_ID",
"N_TAG_YT_ID",
"N_TAG_ZOOM_OUT_ID",
"N_TAG_ZOOM_IN_ID",
"N_TAG_CATEGORY_BIG_RESTAURANTS_ID",
"N_TAG_CATEGORY_BIG_AUTOMOTIVE_ID",
"N_TAG_CATEGORY_BIG_TRAVEL_ID",
"N_TAG_CATEGORY_BIG_SHOPPING_ID",
"N_TAG_CATEGORY_BIG_RECREATION_ID",
"N_TAG_CATEGORY_BIG_FINANCIAL_SERVICES_ID",
"N_TAG_CATEGORY_BIG_COMMUNITY_ID",
"N_TAG_CATEGORY_BIG_SERVICES_ID",
"N_TAG_FIND_POI_ID",
"N_TAG_FIND_CATEGORY_ID",
"N_TAG_NEAR_CURRENT_POSITION_ID",
"N_TAG_NEAR_DESTINATION_ID",
"N_TAG_ALONG_ROUTE_ID",
"N_TAG_NAVI_YES_ID",
"N_TAG_NAVI_NO_ID",
"N_TAG_NAVI_LINE_NUMBER_ID",
"N_TAG_NONE_OF_THEM_ID",
"N_TAG_ADDRESS_STEP_EDIT_ID",
"N_TAG_EMERGENCY_SERVICES_ID",
"N_TAG_POLICE_STATION_ID",
"N_TAG_HOSPITAL_ID",
"N_TAG_DEALERSHIP_ID",
"N_TAG_ROAD_ASSISTANCE_ID",
"N_TAG_CHANGE_HOUSE_NUMBER_ID",
"N_TAG_USER_HOUSE_NUMBER_ID",
"N_TAG_STREET_CITY_STEP_ID",
"N_TAG_HOUSE_NUMBER_STEP_ID",
"N_TAG_CHANGE_STREET_CITY_ID",
"N_TAG_USER_STREET_CITY_ID",
"N_TAG_MY_POIS_ID",
"N_TAG_LOCAL_SEARCH_ID",
"N_TAG_ADD_WAYPOINT_ID",
"N_TAG_DELETE_WAYPOINT_ID",
"N_TAG_DESTINATION_SEARCH_ID",
"N_TAG_CATEGORY_NAME_ID",
"N_TAG_CHANGE_HOME_ID",
"N_TAG_CHANGE_OFFICE_ID",
"N_TAG_STOP_GUIDANCE_ID",
"N_TAG_RESUME_GUIDANCE_ID",
"N_TAG_UNSUPPORTED_SERVER_ID",
"N_TAG_FIND_SERVER_ID",
"N_TAG_DOMAIN_UDE_ID",
"N_TAG_POI_ADDRESS_SERVER_ID",
"N_TAG_FIND_POI_ADDRESS_SERVER_ID",
"N_TAG_SEND_MESSAGE_ID",
"N_TAG_DOMAIN_SMS_ID",
"N_TAG_SEND_MESSAGE_NAME_ID",
"N_TAG_MESSAGE_BODY_ID",
"N_TAG_SERVER_DICTATION_ID",
"N_TAG_WAIT_SERVER_ID",
"N_LEXEME_MANUAL_VAD_DISCONNECTED",
"N_LEXEME_MANUAL_NETWORK_DISCONNECTED",
"N_LEXEME_MANUAL_PTT",
"N_LEXEME_NUMBER",
"N_LEXEME_INNER_RESULT",
"N_LEXEME_SERVER_INNER_RESULT",
"N_LEXEME_AUTO_RESULT",
"N_LEXEME_DRIVING_BACK",
"N_LEXEME_EXIT_BACK",
"N_LEXEME_EXIT_EXIT",
"N_LEXEME_HOUSE_NUMBER_BACK_STEP",
"N_LEXEME_HELP",
"N_LEXEME_EXIT",
"N_LEXEME_BACK",
"N_LEXEME_YES",
"N_LEXEME_NO",
"N_LEXEME_LINE_NUMBER",
"N_LEXEME_NEXT_PAGE",
"N_LEXEME_PREVIOUS_PAGE",
"N_LEXEME_MANUAL_INPUT",
"N_LEXEME_MANUAL_QUESTION_MARK",
"N_LEXEME_SMART_VUI",
"N_LEXEME_CALL",
"N_LEXEME_MANUAL_VAD_MOBILE",
"N_LEXEME_MANUAL_VAD_OFFICE",
"N_LEXEME_MANUAL_VAD_HOME",
"N_LEXEME_MANUAL_VAD_OTHER",
"N_LEXEME_PHONE_DIAL_NUMBER",
"N_LEXEME_MOBILE",
"N_LEXEME_HOME",
"N_LEXEME_OFFICE",
"N_LEXEME_OTHER",
"N_LEXEME_CORRECTION",
"N_LEXEME_DELETE",
"N_LEXEME_CHANGE_BT_DEVICE",
"N_LEXEME_NAME",
"N_LEXEME_AM",
"N_LEXEME_CHANNEL_NUMBER",
"N_LEXEME_FM",
"N_LEXEME_FM_NUMBER1",
"N_LEXEME_FM_NUMBER2",
"N_LEXEME_MANUAL_AM",
"N_LEXEME_MANUAL_CHANNEL",
"N_LEXEME_MANUAL_FM",
"N_LEXEME_MANUAL_PRESET",
"N_LEXEME_PRESET_NUMBER",
"N_LEXEME_RADIO",
"N_LEXEME_RADIO_STATION",
"N_LEXEME_SIRIUSXM",
"N_LEXEME_SIRIUSXM_CHANNEL_NUMBER",
"N_LEXEME_PANDORA_RADIO",
"N_LEXEME_SKIP",
"N_LEXEME_THUMBS_UP",
"N_LEXEME_THUMBS_DOWN",
"N_LEXEME_MEDIA",
"N_LEXEME_CD",
"N_LEXEME_IPOD",
"N_LEXEME_BT_AUDIO",
"N_LEXEME_AUX",
"N_LEXEME_MY_MUSIC",
"N_LEXEME_USB",
"N_LEXEME_PLAY",
"N_LEXEME_PAUSE",
"N_LEXEME_PLAY_TRACK_NUMBER",
"N_LEXEME_SHUFFLE",
"N_LEXEME_SHUFFLE_OFF",
"N_LEXEME_REPEAT",
"N_LEXEME_REPEAT_OFF",
"N_LEXEME_VIDEO",
"N_LEXEME_VOICE_MEMO",
"N_LEXEME_MANUAL_TRACK",
"N_LEXEME_PRIM_FRONT_IPOD",
"N_LEXEME_PRIM_REAR_IPOD",
"N_LEXEME_PRIM_FRONT_USB",
"N_LEXEME_PRIM_REAR_USB",
"N_LEXEME_PRIM_USB_MUSIC",
"N_LEXEME_PRIM_FRONT_USB_MUSIC",
"N_LEXEME_PRIM_REAR_USB_MUSIC",
"N_LEXEME_PRIM_USB_VIDEO",
"N_LEXEME_PRIM_FRONT_USB_VIDEO",
"N_LEXEME_PRIM_REAR_USB_VIDEO",
"N_LEXEME_PRIM_DVD",
"N_LEXEME_UVO_HELP",
"N_LEXEME_ROADSIDE_ASSIST",
"N_LEXEME_VEHICLE_DIAGNOSTICS",
"N_LEXEME_ESERVICES_GUIDE",
"N_LEXEME_UVO_HELP_EV",
"N_LEXEME_EV_SERVICES_GUIDE",
"N_LEXEME_CARPLAY",
"N_LEXEME_ANDROID_AUTO",
"N_LEXEME_DMB",
"N_LEXEME_AST",
"N_LEXEME_STATION_LIST",
"N_LEXEME_NAVIGATION",
"N_LEXEME_DESTINATION_SEARCH",
"N_LEXEME_CATEGORY_NAME",
"N_LEXEME_CATEGORY_NAME_BIG",
"N_LEXEME_CATEGORY_NAME_MID",
"N_LEXEME_CATEGORY_NAME_SMALL",
"N_LEXEME_PREVIOUS_POINT",
"N_LEXEME_PREVIOUS_DESTINATION",
"N_LEXEME_PREVIOUS_SEARCH",
"N_LEXEME_PREVIOUS_START",
"N_LEXEME_TRAFFIC_INFO",
"N_LEXEME_CHANGE_HOME",
"N_LEXEME_CHANGE_OFFICE",
"N_LEXEME_TURN_GUIDANCE_ON",
"N_LEXEME_TURN_GUIDANCE_OFF",
"N_LEXEME_CANCEL_ROUTE",
"N_LEXEME_DESTINATION_INFO",
"N_LEXEME_ROUTE_OPTION",
"N_LEXEME_SHOW_ROUTE",
"N_LEXEME_NAVI_LOCATION",
"N_LEXEME_FIND_ADDRESS",
"N_LEXEME_FIND_FULL_ADDRESS",
"N_LEXEME_FIND_ADDRESS_STATE",
"N_LEXEME_HOUSE_NUMBER",
"N_LEXEME_STATE_NAME",
"N_LEXEME_CITY_NAME",
"N_LEXEME_STREET_NAME",
"N_LEXEME_ZOOM_OUT",
"N_LEXEME_ZOOM_IN",
"N_LEXEME_FIND_POI",
"N_LEXEME_FIND_CATEGORY",
"N_LEXEME_NEAR_CURRENT_POSITION",
"N_LEXEME_NEAR_DESTINATION",
"N_LEXEME_ALONG_ROUTE",
"N_LEXEME_NONE_OF_THEM",
"N_LEXEME_ADDRESS_STEP_EDIT",
"N_LEXEME_EMERGENCY_SERVICES",
"N_LEXEME_POLICE_STATION",
"N_LEXEME_HOSPITAL",
"N_LEXEME_DEALERSHIP",
"N_LEXEME_ROAD_ASSISTANCE",
"N_LEXEME_CHANGE_HOUSE_NUMBER",
"N_LEXEME_STREET_CITY_STEP",
"N_LEXEME_HOUSE_NUMBER_STEP",
"N_LEXEME_CHANGE_STREET_CITY",
"N_LEXEME_MY_POIS",
"N_LEXEME_LOCAL_SEARCH",
"N_LEXEME_ADD_WAYPOINT",
"N_LEXEME_POI_NAME_GANGWONDO",
"N_LEXEME_POI_NAME_GYEONGGIDO",
"N_LEXEME_POI_NAME_GYEONGSANGNAMDO",
"N_LEXEME_POI_NAME_GYEONGSANGBUKDO",
"N_LEXEME_POI_NAME_GWANGJU",
"N_LEXEME_POI_NAME_DAEGU",
"N_LEXEME_POI_NAME_DAEJEON",
"N_LEXEME_POI_NAME_BUSAN",
"N_LEXEME_POI_NAME_SEOUL",
"N_LEXEME_POI_NAME_SEJONG",
"N_LEXEME_POI_NAME_ULSAN",
"N_LEXEME_POI_NAME_INCHEON",
"N_LEXEME_POI_NAME_JEOLLANAMDO",
"N_LEXEME_POI_NAME_JEOLLABUKDO",
"N_LEXEME_POI_NAME_JEJUDO",
"N_LEXEME_POI_NAME_CHUNGCHEONGNAMDO",
"N_LEXEME_POI_NAME_CHUNGCHEONGBUKDO",
"N_LEXEME_UNSUPPORTED_SERVER",
"N_LEXEME_DOMAIN",
"N_LEXEME_NAVIGATION_SERVER",
"N_LEXEME_SERVER_REJECTION",
"N_LEXEME_SEND_MESSAGE",
"N_LEXEME_SEND_MESSAGE_NAME",
"N_LEXEME_SEND_MESSAGE_SERVER",
"N_LEXEME_SLOT",
"N_LEXEME_WAIT_SERVER",
"N_DIALOG_DIALOG_BOOT",
"N_DIALOG_VIRTUAL_TTS_BT",
"N_DIALOG_VIRTUAL_TTS_SMS",
"N_DIALOG_VIRTUAL_TTS_NAVI",
"N_DIALOG_VIRTUAL_SERVER_DICTATION",
"N_DIALOG_NO_RECOG_DRIVING",
"N_DIALOG_NO_RECOG_BACK",
"N_DIALOG_NO_RECOG_EXIT",
"N_DIALOG_NO_RECOG_HOUSE_NUMBER_STEP",
"N_DIALOG_MAINMENU",
"N_DIALOG_MAINMENU_HELP_CATEGORY",
"N_DIALOG_MAINMENU_SELECT",
"N_DIALOG_NBEST_LIST",
"N_DIALOG_BT_VAD",
"N_DIALOG_BT_VAD_CATEGORY",
"N_DIALOG_BT_VAD_CATEGORY_NUM",
"N_DIALOG_BT_VAD_LIST",
"N_DIALOG_BT_VAD_NUM_LOCAL",
"N_DIALOG_BT_VAD_NUM_SELECT",
"N_DIALOG_BT_VAD_SELECT",
"N_DIALOG_BT_DEVICE_LIST",
"N_DIALOG_BT_VAD_NBEST_SELECT",
"N_DIALOG_MAINMENU_HELP_PHONE",
"N_DIALOG_LOCAL_VR_BT_VAD",
"N_DIALOG_LOCAL_VR_BT_VAD_NUM_LOCAL",
"N_DIALOG_AV_BROADCAST_LIST",
"N_DIALOG_MAINMENU_AM_FREQUENCY",
"N_DIALOG_MAINMENU_FM_FREQUENCY",
"N_DIALOG_MAINMENU_HELP_RADIO",
"N_DIALOG_MAINMENU_RADIO_PRESET",
"N_DIALOG_MAINMENU_SIRIUSXM_CHANNEL",
"N_DIALOG_MAINMENU_RADIO_STATION",
"N_DIALOG_LOCAL_VR_MAINMENU_AM_FREQUENCY",
"N_DIALOG_LOCAL_VR_MAINMENU_FM_FREQUENCY",
"N_DIALOG_LOCAL_VR_MAINMENU_SIRIUSXM_CHANNEL",
"N_DIALOG_MAINMENU_HELP_MEDIA",
"N_DIALOG_MAINMENU_TRACKLIST",
"N_DIALOG_MAINMENU_HELP_UVO",
"N_DIALOG_MAINMENU_HELP_DMB",
"N_DIALOG_NAVI_NBEST_LIST",
"N_DIALOG_MAINMENU_HELP_NAVIGATION",
"N_DIALOG_NAVI_POI_LOCATION",
"N_DIALOG_NAVI_LIST",
"N_DIALOG_NAVI_FIND_CATEGORY_LIST",
"N_DIALOG_NAVI_FIND_CATEGORY_NONE_LIST",
"N_DIALOG_NAVI_SELECT",
"N_DIALOG_NAVI_WAY_SELECT",
"N_DIALOG_NAVI_DEL_WAY_SELECT",
"N_DIALOG_NAVI_CALL_SELECT",
"N_DIALOG_NAVI_CALL_WAY_SELECT",
"N_DIALOG_NAVI_YESNO_SELECT",
"N_DIALOG_NAVI_YESNO_WAY_SELECT",
"N_DIALOG_NAVI_PRE_YESNO_CALL_SELECT",
"N_DIALOG_NAVI_PRE_CALL_WAY_SELECT",
"N_DIALOG_NAVI_PREVIOUS_POINT",
"N_DIALOG_NAVI_PREVIOUS_DESTINATION",
"N_DIALOG_NAVI_PREVIOUS_SEARCH",
"N_DIALOG_NAVI_PREVIOUS_START",
"N_DIALOG_NAVI_ROUTE_OPTION",
"N_DIALOG_NAVI_PRE_YESNO_SELECT",
"N_DIALOG_NAVI_PRE_WAY_SELECT",
"N_DIALOG_NAVI_ADDRESS_SELECT",
"N_DIALOG_NAVI_ADDRESS_WAY_SELECT",
"N_DIALOG_NAVI_CHANGE_HOUSE_NUMBER",
"N_DIALOG_NAVI_CHANGE_STREET_CITY",
"N_DIALOG_NAVI_FIND_BIG_CATEGORY",
"N_DIALOG_NAVI_FIND_CATEGORY",
"N_DIALOG_NAVI_FIND_MID_CATEGORY",
"N_DIALOG_NAVI_REGISTER_HOME_SELECT",
"N_DIALOG_NAVI_REGISTER_OFFICE_SELECT",
"N_DIALOG_NAVI_REGISTER_HOME_SELECT_STEP",
"N_DIALOG_NAVI_REGISTER_OFFICE_SELECT_STEP",
"N_DIALOG_NAVI_REGISTER_HOME_NONE_HOUSE_NUMBER_SELECT_STEP",
"N_DIALOG_NAVI_REGISTER_OFFICE_NONE_HOUSE_NUMBER_SELECT_STEP",
"N_DIALOG_NAVI_ADDRESS_LIST",
"N_DIALOG_NAVI_FULL_ADDRESS_LIST",
"N_DIALOG_NAVI_VDE_LOCATION",
"N_DIALOG_NAVI_VDE_STREETCITY_STEP",
"N_DIALOG_NAVI_VDE_HOUSE_NUMBER_STEP",
"N_DIALOG_NAVI_VDE_ADDRESS_SELECT_STEP",
"N_DIALOG_NAVI_VDE_ADDRESS_WAY_SELECT_STEP",
"N_DIALOG_NAVI_VDE_NONE_HOUSE_NUMBER_STEP",
"N_DIALOG_NAVI_VDE_NONE_HOUSE_NUMBER_WAY_STEP",
"N_DIALOG_LOCAL_VR_NAVI_FIND_BIG_CATEGORY",
"N_DIALOG_LOCAL_VR_NAVI_VDE_LOCATION",
"N_DIALOG_LOCAL_VR_NAVI_FIND_CATEGORY",
"N_DIALOG_LOCAL_VR_NAVI_POI_LOCATION",
"N_DIALOG_BT_SMS",
"N_DIALOG_BT_SMS_MESSAGE",
"N_DIALOG_BT_SMS_SELECT",
"N_DIALOG_NAVI_FIND_SERVER",
"N_DIALOG_LOCAL_VR_BT_SMS",
"N_DIALOG_LOCAL_VR_NAVI_FIND_SERVER"];
let index_list = [];
for (let i in list) {
index_list.push({"value": list[i], "index": i})
}
return index_list;
},
ifSorting() {
that = this;
this.editor = atom.workspace.getActiveTextEditor();
let index_list = this.getIndexList();
//서치할 텍스트 정규표현식
let regex = /\tIF\s*[\w.$]*\s*=\s*[\"\\]*@([\w._]*)[\n\s\w\!\s가-힣\{\}\[\]\/?.,;:|\)*~`!^\-_+<>@\#$%&\\\=\(\'\"]*?\n\t\tEND/g;
let array = [];
let notexistarray = []; //리스트에 존재하지 않는 변수
let selected = this.editor.getSelectedBufferRange(); //선택한 텍스트 Range
let selected_text = this.editor.getTextInBufferRange(selected); //선택한 텍스트
let check_num_of_obj = 0;
//선택한 범위안에 정규표현식에 맞는 텍스트 객체 배열에 추가 (인덱스 리스트를 참고하여 같은 변수값은 해당 인덱스 인덱싱)
this.editor.scanInBufferRange(regex, selected, function (obj) {
check_num_of_obj++;
let is_exist = false;
for (let i in index_list) {
if (index_list[i].value == obj.match[1]) {
array.push({"item": obj.match[0], "keyword": obj.match[1], "index": index_list[i].index});
is_exist = true;
}
}
if (is_exist == false) {
notexistarray.push({"item": obj.match[0], "keyword": obj.match[1]})
}
})
//인덱스값 기준으로 객체배열 정렬
array.sort(function (a, b) {
return a.index - b.index;
})
//객체의 텍스트값 append & 줄바꿈 처리
let items = "";
for (let i in array) {
items += array[i].item;
if (i != array.length - 1) {
items += "\n\n";
}
}
console.log("배열 길이 : " + array.length + " 객체 수 : " + check_num_of_obj);
console.log("라인수" + this.getLineCount(items));
//에러처리 - regex에 걸리는 객체 수와 인덱스 리스트에 걸린 객체 수 비교, 선택된 라인수와 정렬된 라인수 비교(주석,위아래 공백 )
console.log(this.getLineCount(selected_text) - this.getLineCount(items));
if (array.length == check_num_of_obj && (this.getLineCount(selected_text) - this.getLineCount(items)) < 6) {
this.editor.insertText(items)
atom.notifications.addSuccess(array.length + "개 요소 정렬 완료")
} else {
if (notexistarray.length != 0) {
let string = "검색 되지 않는 변수가 있습니다."
for (let i in notexistarray) {
string += notexistarray[i].keyword + " ";
}
atom.notifications.addError(string)
}
atom.notifications.addError("오류가 있습니다! (if문 형식 if앞에 탭1개, else앞에 탭2개, 변수명을 확인해주세요)")
}
}
,
gSorting() {
that = this;
let index_list = this.getIndexList();
this.editor = atom.workspace.getActiveTextEditor();
//서치할 텍스트 정규표현식
let regex = /\\@([\w\!가-힣\{\}\[\]\/?.,;:|\)*~`!^\-_+<>@\#$%&\\\=\(]*)/g;
let array = [];
let notexistarray = []; //리스트에 존재하지 않는 변수
let selected = this.editor.getSelectedBufferRange(); //선택한 텍스트 Range
let selected_text = this.editor.getTextInBufferRange(selected); //선택한 텍스트
let check_num_of_obj = 0;
//선택한 범위안에 정규표현식에 맞는 텍스트 객체 배열에 추가 (인덱스 리스트를 참고하여 같은 변수값은 해당 인덱스 인덱싱)
this.editor.scanInBufferRange(regex, selected, function (obj) {
check_num_of_obj++;
let is_exist = false;
for (let i in index_list) {
if (index_list[i].value == obj.match[1]) {
array.push({"item": obj.match[0], "keyword": obj.match[1], "index": index_list[i].index});
is_exist = true;
}
}
if (is_exist == false) {
notexistarray.push({"item": obj.match[0], "keyword": obj.match[1]})
}
})
//인덱스값 기준으로 객체배열 정렬
array.sort(function (a, b) {
return a.index - b.index;
})
console.log(array)
//객체의 텍스트값 append & 줄바꿈 처리
let items = "";
for (let i in array) {
if (i == 0) {
items += array[i].item;
} else items += " " + array[i].item;
}
console.log(items)
console.log(notexistarray);
console.log(array.length, check_num_of_obj);
console.log(this.getLineCount(items));
if (array.length == check_num_of_obj && notexistarray.length == 0) {
atom.notifications.addSuccess(array.length + "개 요소 정렬 완료")
this.editor.insertText(items)
} else {
if (notexistarray.length != 0) {
let string = "검색 되지 않는 변수가 있습니다."
for (let i in notexistarray) {
string += notexistarray[i].keyword + " ";
}
atom.notifications.addError(string)
}
atom.notifications.addError("에러가 있습니다. 선택범위를 확인해주세요.")
}
},
orSorting() {
that = this;
let index_list = this.getIndexList();
this.editor = atom.workspace.getActiveTextEditor();
//서치할 텍스트 정규표현식
//let regex = /N.CID\s+=\s+\@([\w\!가-힣\{\}\[\]\/?.,;:|\)*~`!^\-_+<>@\#$%&\\\=\(]*)/g;
let regex = /[\w.]*\s+=\s+\"?\\?\@([\w\!가-힣\{\}\[\]\/?.,;:|\)*~`!^\-_+<>@\#$%&\\\=\(]*)\"?/g;
let array = [];
let notexistarray = []; //리스트에 존재하지 않는 변수
let selected = this.editor.getSelectedBufferRange(); //선택한 텍스트 Range
let selected_text = this.editor.getTextInBufferRange(selected); //선택한 텍스트
let check_num_of_obj = 0;
//선택한 범위안에 정규표현식에 맞는 텍스트 객체 배열에 추가 (인덱스 리스트를 참고하여 같은 변수값은 해당 인덱스 인덱싱)
this.editor.scanInBufferRange(regex, selected, function (obj) {
check_num_of_obj++;
let is_exist = false;
for (let i in index_list) {
if (index_list[i].value == obj.match[1]) {
array.push({"item": obj.match[0], "keyword": obj.match[1], "index": index_list[i].index});
is_exist = true;
}
}
if (is_exist == false) {
notexistarray.push({"item": obj.match[0], "keyword": obj.match[1]})
}
})
//인덱스값 기준으로 객체배열 정렬
array.sort(function (a, b) {
return a.index - b.index;
})
console.log(array)
//객체의 텍스트값 append & 줄바꿈 처리
let items = "";
for (let i in array) {
if (i == 0) {
items += array[i].item;
} else items += " | " + array[i].item;
}
console.log(items)
console.log(notexistarray);
console.log(array.length, check_num_of_obj);
console.log(this.getLineCount(items));
if (array.length == check_num_of_obj && notexistarray.length == 0) {
atom.notifications.addSuccess(array.length + "개 요소 정렬 완료")
this.editor.insertText(items)
} else {
if (notexistarray.length != 0) {
let string = "검색 되지 않는 변수가 있습니다."
for (let i in notexistarray) {
string += notexistarray[i].keyword + " ";
}
atom.notifications.addError(string)
}
atom.notifications.addError("에러가 있습니다. 선택범위를 확인해주세요.")
}
},
//Text의 라인수를 계산한다.
getLineCount(text) {
return text.split(/\r\n|\r|\n/).length;
}
};
|
'use strict';
var pubnub = PUBNUB({
publish_key:'demo',
subscribe_key:'demo',
uuid:'angular-ds'
});
// Declare app level module which depends on views, and components
angular.module('myApp', [
'ngRoute',
'pubnub.angular.service',
'myApp.view1',
'myApp.view2',
'myApp.version'
]).
config(['$routeProvider', function($routeProvider) {
$routeProvider.otherwise({redirectTo: '/view1'});
}]);
|
import { setupHexagonClick } from './eventListeners/units';
import { hexagonMath } from './utils/';
/*-----------------------
-------- PUBLIC ---------
-----------------------*/
/**
* Handles the selection of hexagons on the map
*
* @namespace flatworld.extensions.hexagons
* @class selectHexagonObject
* @return {Object} Return methods inside object
*/
const selectHexagonObject = {
pluginName: 'selectHexagonObject',
init,
}
/**
* @method init
* @param {Map} givenMap Instantiated Map class object
* @param {Object} protectedProperties Holds all the non-public properties to use
* @param {Array} params Rest of the parameters. Like pathWeight (function), getTerrainLayerName(() => string),
* getData(function)
*/
function init(params) {
if (!params.pathWeight || typeof params.pathWeight !== 'function') {
const error = new Error(`Hexagon plugin requires parameters property! This parameter must have "pathWeight"-property
that is a callback, which returns the weight of the path for path finder. So it must be callback that return
integer`, params);
throw error;
}
this.mapInstance.hexagonIndexes = createHexagonDataStructure(() => this.mapInstance.allMapObjects[params.getTerrainLayerName()]);
setupHexagonClick(this.mapInstance, params.pathWeight, params.getData);
return Promise.resolve();
}
function createHexagonDataStructure(getLayers) {
const hexagonIndexes = {};
const objArray = getLayers();
let indexes;
objArray.forEach(obj => {
const correctCoords = obj.getMapCoordinates();
indexes = hexagonMath.coordinatesToIndexes(correctCoords);
hexagonIndexes[indexes.x] = hexagonIndexes[indexes.x] || {};
hexagonIndexes[indexes.x][indexes.y] = obj;
})
return hexagonIndexes;
}
/*-----------------------
---------- API ----------
-----------------------*/
const _tests = {
createHexagonDataStructure
};
export {
selectHexagonObject,
_tests
};
|
// https://github.com/kriasoft/react-starter-kit/blob/master/docs/recipes/how-to-implement-routing.md
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import moment from 'moment';
import path from 'path';
import express from 'express';
import cookieParser from 'cookie-parser';
import bodyParser from 'body-parser';
import expressJwt from 'express-jwt';
import expressGraphQL from 'express-graphql';
import jwt from 'jsonwebtoken';
import PrettyError from 'pretty-error';
import _httpErrorPages from 'http-error-pages';
import ical from 'ical-generator';
import schema from './data/schema';
import { handleCalendarWebhook, handleTwilioWebhook } from './hooks';
// import { logLogin } from './data/database/login';
import { reactMiddleware, reactErrorMiddleware } from './reactMiddleware';
import API from './api/';
import config from './config';
const PEOPLE_PREFIX = 'people/';
const app = express();
//
// Tell any CSS tooling (such as Material UI) to use all vendor prefixes if the
// user agent is not known.
// -----------------------------------------------------------------------------
global.navigator = global.navigator || {};
global.navigator.userAgent = global.navigator.userAgent || 'all';
//
// Register Node.js middleware
// -----------------------------------------------------------------------------
app.use(express.static(path.resolve(__dirname, 'public')));
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
//
// Authentication
// -----------------------------------------------------------------------------
function checkingUser(req, _payload, done) {
const secret = config.auth.jwt.secret;
// req.payload = { foo: 'bar' };
// console.log(`checking req.url`, req.url);
// console.log(`payload`, payload);
// if (payload.data) {
// logLogin(payload.data.username, payload);
// }
done(null, secret);
}
function populatePayload(req, _res, next) {
const token = req.cookies.token;
if (token) {
const decoded = jwt.verify(token, config.auth.jwt.secret);
req.payload = decoded;
}
return next();
}
// super temporary lin #######
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', 'http://*.soho.sg');
if (req.method === 'OPTIONS') {
res.header('Access-Control-Allow-Methods', 'PUT, POST, PATCH, DELETE, GET');
return res.status(200).json({});
}
return next();
});
/* bot denial */
app.use((req, res, next) => {
if (req.headers.from === 'googlebot(at)googlebot.com') {
return res.status(401).json({
message: 'Unathorized Access',
});
}
return next();
});
/* to populate cross cookies, tech debt */
app.use((req, res, next) => {
if (req.query.token) {
// console.log('req.query.token', req.query.token);
const expiresIn = 60 * 60 * 24 * 180; // 180 days
res.cookie('token', req.query.token, {
maxAge: 1000 * expiresIn,
httpOnly: true,
});
/* tech debt */
res.cookie('jwt', req.query.token, {
maxAge: 1000 * expiresIn,
httpOnly: true,
});
return next();
}
return next();
});
app.use(
expressJwt({
secret: checkingUser,
credentialsRequired: true,
getToken: function fromHeaderOrQuerystring(req) {
// console.log(`Object.keys(req)`, Object.keys(req));
// console.log(`req.cookies`, JSON.stringify(req.cookies, null, 2));
if (req.cookies.token) {
return req.cookies.token;
} else if (req.query && req.query.token) {
return req.query.token;
} else if (req.headers && req.headers.authorization) {
return req.headers.authorization; // base64Credentials;
}
return null;
},
}).unless({
path: [
'/events/calendar',
/\/general*/,
/\/assets*/,
/\/page+/,
/\/p+/,
/\/api+/,
/\/webhooks+/,
],
}),
);
// Error handler for express-jwt
app.use(populatePayload);
app.use(reactErrorMiddleware);
//
// Register API middleware
// -----------------------------------------------------------------------------
app.use(
'/graphql',
expressGraphQL(async req => ({
schema,
graphiql: __DEV__,
rootValue: { request: req },
pretty: __DEV__,
})),
);
app.use('/events/calendar', async (req, res, next) => {
// console.error('handleCalendarWebhook typeof', typeof handleCalendarWebhook);
try {
await handleCalendarWebhook(req.headers);
res.json({ ok: true });
} catch (e) {
console.error(`handleCalendarWebhook`, e);
next(e);
}
});
app.use('/webhooks/twilio', async (req, res) => {
handleTwilioWebhook(req);
res.send('null');
res.status(201).end();
});
app.use('/public/appointment/confirm/:eventId', async (req, res) => {
const { eventId } = req.params;
await API({ action: 'patchEvent', status: 'confirmed', eventId });
res.send(
`<!doctype html><html><body style="background-color:#373277"><h1><center><span style="color:white">Your Appointment is confirmed!</span></center></h1></body></html>`,
);
});
app.use('/general/confirmation/:eventId', async (req, res, next) => {
const { eventId } = req.params;
if (eventId === 'images') return;
const event = await API({ action: 'getEvent', eventId });
req.data = {
event,
workAddress: config.app.workAddress,
oldWorkAddress: config.app.oldWorkAddress,
safeEntryLink: config.app.safeEntryLink,
oldSafeEntryLink: config.app.oldSafeEntryLink,
};
await API({
action: 'patchEvent',
status: 'confirmed',
confirmed: moment().format('lll'),
eventId,
});
reactMiddleware(req, res, next);
});
app.use('/general/reservation/:eventId', async (req, res, next) => {
const { eventId } = req.params;
if (eventId === 'images') return;
const event = await API({ action: 'getEvent', eventId });
req.data = {
event,
workAddress: config.app.workAddress,
oldWorkAddress: config.app.oldWorkAddress,
safeEntryLink: config.app.safeEntryLink,
oldSafeEntryLink: config.app.oldSafeEntryLink,
};
const now = moment();
const appointmentEnd = moment(event.end.dateTime);
// eslint-disable-next-line consistent-return
if (now.isAfter(appointmentEnd)) {
res.redirect('/');
} else {
reactMiddleware(req, res, next);
}
});
app.use('/general/calendar/:eventId', async (req, res) => {
const { eventId } = req.params;
if (eventId === 'images') return;
const event = await API({ action: 'getEvent', eventId });
const customerId = event.extendedProperties.shared.resourceName;
const cal = ical({
domain: config.app.workDomain,
name: config.app.workCalendar,
});
cal.createEvent({
start: event.start.dateTime,
end: event.end.dateTime,
summary: 'Rare Beauty Appointment',
description: `
We do Lash Extensions, Facial, Waxing, Threading and More
Appointment(s) are found @ ${config.app.customerURL}/${customerId.substring(
PEOPLE_PREFIX.length,
customerId.length,
)}/appointments
`,
location: config.app.workAddress,
url:
(event.extendedProperties && event.extendedProperties.shared.shortURL) ||
config.app.workDomain,
});
// eslint-disable-next-line consistent-return
return cal.serve(res);
// next(req, res, next);
});
//
// Register server-side rendering middleware
// -----------------------------------------------------------------------------
app.use('*', reactMiddleware);
//
// Error handling
// -----------------------------------------------------------------------------
if (__DEV__) {
const pe = new PrettyError();
pe.skipNodeFiles();
pe.skipPackage('express');
// eslint-disable-next-line no-unused-vars
app.use(reactErrorMiddleware);
} else {
_httpErrorPages(app);
}
//
// Launch the server
// -----------------------------------------------------------------------------
if (!module.hot) {
app.listen(config.port, () => {
console.info(`The server is running at http://localhost:${config.port}/`);
});
} else {
// development mode
app.hot = module.hot;
module.hot.accept('./router');
}
export default app;
|
var struct__OrgDattoDattoRDPServerIface =
[
[ "handle_register", "struct__OrgDattoDattoRDPServerIface.html#acf30e13e7448818417ab696922ab8c74", null ],
[ "parent_iface", "struct__OrgDattoDattoRDPServerIface.html#af40ed7a7e3ea913d66df8217cf9fbaa0", null ]
];
|
import createShadow from '../../shared/create-shadow.js';
import effectInit from '../../shared/effect-init.js';
import effectTarget from '../../shared/effect-target.js';
import effectVirtualTransitionEnd from '../../shared/effect-virtual-transition-end.js';
export default function EffectCards({ swiper, extendParams, on }) {
extendParams({
cardsEffect: {
slideShadows: true,
transformEl: null,
},
});
const setTranslate = () => {
const { slides, activeIndex } = swiper;
const params = swiper.params.cardsEffect;
const { startTranslate, isTouched } = swiper.touchEventsData;
const currentTranslate = swiper.translate;
for (let i = 0; i < slides.length; i += 1) {
const $slideEl = slides.eq(i);
const slideProgress = $slideEl[0].progress;
const progress = Math.min(Math.max(slideProgress, -4), 4);
let offset = $slideEl[0].swiperSlideOffset;
if (swiper.params.centeredSlides && !swiper.params.cssMode) {
swiper.$wrapperEl.transform(`translateX(${swiper.minTranslate()}px)`);
}
if (swiper.params.centeredSlides && swiper.params.cssMode) {
offset -= slides[0].swiperSlideOffset;
}
let tX = swiper.params.cssMode ? -offset - swiper.translate : -offset;
let tY = 0;
const tZ = -100 * Math.abs(progress);
let scale = 1;
let rotate = -2 * progress;
let tXAdd = 8 - Math.abs(progress) * 0.75;
const isSwipeToNext =
(i === activeIndex || i === activeIndex - 1) &&
progress > 0 &&
progress < 1 &&
(isTouched || swiper.params.cssMode) &&
currentTranslate < startTranslate;
const isSwipeToPrev =
(i === activeIndex || i === activeIndex + 1) &&
progress < 0 &&
progress > -1 &&
(isTouched || swiper.params.cssMode) &&
currentTranslate > startTranslate;
if (isSwipeToNext || isSwipeToPrev) {
const subProgress = (1 - Math.abs((Math.abs(progress) - 0.5) / 0.5)) ** 0.5;
rotate += -28 * progress * subProgress;
scale += -0.5 * subProgress;
tXAdd += 96 * subProgress;
tY = `${-25 * subProgress * Math.abs(progress)}%`;
}
if (progress < 0) {
// next
tX = `calc(${tX}px + (${tXAdd * Math.abs(progress)}%))`;
} else if (progress > 0) {
// prev
tX = `calc(${tX}px + (-${tXAdd * Math.abs(progress)}%))`;
} else {
tX = `${tX}px`;
}
if (!swiper.isHorizontal()) {
const prevY = tY;
tY = tX;
tX = prevY;
}
const scaleString =
progress < 0 ? `${1 + (1 - scale) * progress}` : `${1 - (1 - scale) * progress}`;
const transform = `
translate3d(${tX}, ${tY}, ${tZ}px)
rotateZ(${rotate}deg)
scale(${scaleString})
`;
if (params.slideShadows) {
// Set shadows
let $shadowEl = $slideEl.find('.swiper-slide-shadow');
if ($shadowEl.length === 0) {
$shadowEl = createShadow(params, $slideEl);
}
if ($shadowEl.length)
$shadowEl[0].style.opacity = Math.min(Math.max((Math.abs(progress) - 0.5) / 0.5, 0), 1);
}
$slideEl[0].style.zIndex = -Math.abs(Math.round(slideProgress)) + slides.length;
const $targetEl = effectTarget(params, $slideEl);
$targetEl.transform(transform);
}
};
const setTransition = (duration) => {
const { transformEl } = swiper.params.cardsEffect;
const $transitionElements = transformEl ? swiper.slides.find(transformEl) : swiper.slides;
$transitionElements.transition(duration).find('.swiper-slide-shadow').transition(duration);
effectVirtualTransitionEnd({ swiper, duration, transformEl });
};
effectInit({
effect: 'cards',
swiper,
on,
setTranslate,
setTransition,
perspective: () => true,
overwriteParams: () => ({
watchSlidesProgress: true,
virtualTranslate: !swiper.params.cssMode,
}),
});
}
|
var sourceFiles = './app';
var publicAssets = './build';
module.exports = {
sourceFiles: sourceFiles,
publicAssets: publicAssets,
styles: {
src: sourceFiles + '/**/*.scss',
dest: publicAssets + '/assets',
outputName: 'adobe-weather.css',
},
templates: {
src: sourceFiles + '/**/*.template.html',
dest: sourceFiles + '/templates',
templateCacheOptions: {
moduleSystem: 'Browserify',
standalone: true,
transformUrl: function (url) {
return url.substring(url.lastIndexOf('/') + 1);
},
},
},
scripts: {
jshint: {
src: sourceFiles + '/**/*.js',
},
bundleConfigs: {
entries: sourceFiles + '/app.js',
dest: publicAssets + '/assets',
outputName: 'adobe-weather.js',
},
},
browserSync: {
proxy: 'localhost:4000',
open: false,
},
html: {
src: sourceFiles + '/index.html',
dest: publicAssets,
},
test: {
configFile: process.cwd() + '/karma.conf.js'
},
};
|
var React = require('react-native');
if (window) {
window.AsyncStorage = AsyncStorage;
}
console.log('loaded AsyncStorage');
module.exports = React.AsyncStorage;
|
import React from 'react';
import { renderHook } from '@testing-library/react-hooks';
import { render } from '@testing-library/react';
import { useTranslation } from '../src/useTranslation';
jest.unmock('../src/useTranslation');
describe('useTranslation', () => {
let instance;
beforeEach(() => {
instance = {
language: 'en',
languages: ['en', 'fr'],
services: {
resourceStore: {
data: {},
},
backendConnector: { backend: {}, state: { 'en|notLoadedNS': 1, 'fr|notLoadedNS': 1 } },
},
isInitialized: true,
changeLanguage: () => {},
getFixedT: () => message => message,
hasResourceBundle: (lng, ns) => ns === 'alreadyLoadedNS',
loadNamespaces: () => {},
on: () => {},
off: () => {},
options: {},
};
});
function TestComponentNotReady({ i18n }) {
const { t } = useTranslation(['notLoadedNS', 'alreadyLoadedNS'], { i18n });
return <div>{t('keyOne')}</div>;
}
it('should throw a suspense if not ready (having not all ns)', async () => {
expect(() => {
console.error = jest.fn(); // silent down the error boundary error from react-dom
render(<TestComponentNotReady i18n={instance} />);
}).toThrow(
'TestComponentNotReady suspended while rendering, but no fallback UI was specified.',
);
expect(console.error).toHaveBeenCalled(); // silent down the error boundary error from react-dom
});
it('should render correct content if ready (having all ns)', () => {
const { result } = renderHook(() => useTranslation('alreadyLoadedNS', { i18n: instance }));
const { t } = result.current;
expect(t('keyOne')).toBe('keyOne');
});
it('should ignore suspense if no backend defined', () => {
const instance2 = { ...instance };
instance2.services.backendConnector = { backend: false };
const { result } = renderHook(() =>
useTranslation(['notLoadedNS', 'alreadyLoadedNS'], { i18n: instance2 }),
);
const { t } = result.current;
expect(t('keyOne')).toBe('keyOne');
});
it('should ignore suspense if failed loading ns and no fallback lng is defined', () => {
const instance2 = { ...instance };
instance2.services.backendConnector = {
backend: {},
state: { 'en|notLoadedNS': -1 },
};
instance2.services.options = { fallbackLng: false };
const { result } = renderHook(() =>
useTranslation(['notLoadedNS', 'alreadyLoadedNS'], { i18n: instance2 }),
);
const { t } = result.current;
expect(t('keyOne')).toBe('keyOne');
});
it('should ignore suspense if failed loading ns but has fallback loaded', () => {
const instance2 = { ...instance };
instance2.services.backendConnector = {
backend: {},
state: { 'en|notLoadedNS': -1, 'fr|notLoadedNS': 2 },
};
const { result } = renderHook(() =>
useTranslation(['notLoadedNS', 'alreadyLoadedNS'], { i18n: instance2 }),
);
const { t } = result.current;
expect(t('keyOne')).toBe('keyOne');
});
it('should ignore suspense if failed loading ns and has fallback failing too', () => {
const instance2 = { ...instance };
instance2.services.backendConnector = {
backend: {},
state: { 'en|notLoadedNS': -1, 'fr|notLoadedNS': -1 },
};
const { result } = renderHook(() =>
useTranslation(['notLoadedNS', 'alreadyLoadedNS'], { i18n: instance2 }),
);
const { t } = result.current;
expect(t('keyOne')).toBe('keyOne');
});
it('should ignore suspense if set useSuspense to false', () => {
const instance2 = { ...instance };
instance2.options.react = { useSuspense: false };
instance2.services.backendConnector = {
backend: {},
state: { 'en|notLoadedNS': 1, 'fr|notLoadedNS': 1 },
};
const { result } = renderHook(() =>
useTranslation(['notLoadedNS', 'alreadyLoadedNS'], { i18n: instance2 }),
);
const { t } = result.current;
expect(t('keyOne')).toBe('keyOne');
});
});
|
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
/**
* Article Schema
*/
var profs_schema = new Schema(
{
Sigle: {
type: String
},
Nom: {
type: String
}
},
{
collection: 'sigle_prof'
}
);
mongoose.model('profs', profs_schema);
|
var traverse = require("../../traverse");
var t = require("../../types");
exports.Property =
exports.MethodDefinition = function (node, parent, file) {
if (node.kind !== "memo") return;
node.kind = "get";
var value = node.value;
t.ensureBlock(value);
var key = node.key;
if (t.isIdentifier(key) && !node.computed) {
key = t.literal(key.name);
}
traverse(value, {
enter: function (node) {
if (t.isFunction(node)) return;
if (t.isReturnStatement(node) && node.argument) {
node.argument = t.memberExpression(t.callExpression(file.addDeclaration("define-property"), [
t.thisExpression(),
key,
node.argument
]), key, true);
}
}
});
};
|
/**
* Part of the evias/nem-cli package.
*
* NOTICE OF LICENSE
*
* Licensed under MIT License.
*
* This source file is subject to the MIT License that is
* bundled with this package in the LICENSE file.
*
* @package evias/nem-cli
* @author Grégory Saive <greg@evias.be> (https://github.com/evias)
* @license MIT License
* @copyright (c) 2017, Grégory Saive <greg@evias.be>
* @link https://github.com/evias/nem-cli
*/
(function() {
var sdk = require("nem-sdk").default;
var Command = function(ConsoleInput) {
this.run = function() {
console.log("");
ConsoleInput.ask("Your XEM Address", /[A-Z\-0-9]+/, function(address) {
var nodeChar = address.substr(0, 1);
var nodeHost = "http://bigalice2.nem.ninja";
if (nodeChar === 'N') {
nodeHost = "http://hugealice.nem.ninja";
}
address = address.replace(/-/g, '');
console.log("This can take some time, please be patient..");
readTrxs_(address, nodeHost, null, printCount_);
});
};
};
var globalCnt = 0;
var totalAmt = 0;
var hasTrxs = {};
var readTrxs_ = function(addr, host, lastId, doneCallback) {
//console.log("[DEBUG] Issuing NIS request with lastId : " + lastId + "..");
if (lastId === null)
totalAmt = 0;
var node = sdk.model.objects.create("endpoint")(host, 7890);
sdk.com.requests.account.transactions.incoming(node, addr, null, lastId)
.then(function(res) {
if (res.code >= 2) {
console.log("error: ", res);
return false;
}
var isDone = false;
var cntTrx = res.data.length;
//console.log("[DEBUG] Read " + cntTrx + " transactions chunk..");
for (var i = 0; i < res.data.length; i++) {
lastId = res.data[i].meta.id;
var lastHash = res.data[i].meta.hash.data;
if (hasTrxs.hasOwnProperty(lastId)) {
//console.log("[DEBUG] Found already Read: " + lastId + ".. Done.");
isDone = true;
break;
}
var transferType = sdk.model.transactionTypes.transfer;
var multisigType = sdk.model.transactionTypes.multisigTransaction;
var transactionType = res.data[i].transaction.type;
var isTypeRelevant = transactionType === transferType || transactionType === multisigType;
// if its multisig, check that the inner transaction is TRANSFER
if (transactionType === multisigType) {
isTypeRelevant &= res.data[i].transaction.otherTrans.type === transferType;
}
if (!isTypeRelevant) {
// transaction not relevant
console.log("[DEBUG] Skipping Transaction: " + JSON.stringify(res.data[i]));
continue;
}
var trxMicroXEM = getTrxRawAmount_(res.data[i], 'nem:xem');
//console.log("[DEBUG] Micro XEM Amount found: " + trxMicroXEM + " with transaction hash: " + lastHash);
//if (!trxMicroXEM)
//console.log("[DEBUG] 0 XEM Transaction: " + JSON.stringify(res.data[i]));
hasTrxs[lastId] = true;
totalAmt = totalAmt + trxMicroXEM;
globalCnt++;
}
if (isDone || cntTrx < 25) {
return doneCallback(globalCnt, totalAmt);
}
readTrxs_(addr, host, lastId, doneCallback);
}, function(err) {
console.log("error: ", err);
return false;
});
};
var getTrxRawAmount_ = function(trxMetaDataPair, currency) {
if (!currency) currency = 'nem:xem';
currency = currency.toLowerCase();
var meta = trxMetaDataPair.meta;
var content = trxMetaDataPair.transaction;
var isMultisig = content.type === sdk.model.transactionTypes.multisigTransaction;
// multisig tx have content in `transaction.otherTrans`
var realContent = isMultisig ? content.otherTrans : content;
var isMosaic = realContent.mosaics && realContent.mosaics.length > 0;
var lookupNS = currency.replace(/:[^:]+$/, "");
var lookupMos = currency.replace(/^[^:]+:/, "");
if (isMosaic) {
// from microXEM to XEM (amount is *multiplier*)
var multiplier = realContent.amount / Math.pow(10, 6);
// now look for XEM
for (var i in realContent.mosaics) {
var mosaic = realContent.mosaics[i];
var isLookupMosaic = mosaic.mosaicId.namespaceId == lookupNS &&
mosaic.mosaicId.name == lookupMos;
if (!isLookupMosaic)
continue;
return multiplier * mosaic.quantity;
}
// no XEM in transaction.
return 0;
}
if (currency !== 'nem:xem')
// trying to read a Mosaic amount but none found
return 0;
// not a mosaic transer, `content.amount` is our XEM amount.
return realContent.amount;
};
var printCount_ = function(countTotal, globalAmount) {
console.log("Transactions Count: ");
console.log("----------------------------------");
console.log("Total Count: " + countTotal);
console.log("Total Amount: " + (globalAmount / Math.pow(10, 6)).toFixed(6) + " XEM");
console.log("----------------------------------");
process.exit();
};
module.exports.Command = Command;
}());
|
var fs = require('fs')
var path = require('path')
var os = require('os')
var exercise = require('workshopper-exercise')()
var filecheck = require('workshopper-exercise/filecheck')
var execute = require('workshopper-exercise/execute')
var comparestdout = require('workshopper-exercise/comparestdout')
var wrappedexec = require('workshopper-wrappedexec')
var after = require('after')
var rimraf = require('rimraf')
var files = require('./file-list')
var testDir = path.join(os.tmpdir(), '_learnyounode_' + process.pid)
// checks that the submission file actually exists
exercise = filecheck(exercise)
// execute the solution and submission in parallel with spawn()
exercise = execute(exercise)
// compare stdout of solution and submission
exercise = comparestdout(exercise)
// wrap up the child process in a phantom wrapper that can
// mess with the global environment and inspect execution
exercise = wrappedexec(exercise)
// a module we want run just prior to the submission in the
// child process
exercise.wrapModule(require.resolve('../my_first_io/wrap'))
// set up the data file to be passed to the submission
exercise.addSetup(function (mode, callback) {
// mode == 'run' || 'verify'
// supply the dir and extensions as args to the 'execute' processor for both
// solution and submission spawn()
// using unshift here because wrappedexec needs to use additional
// args to do its magic
this.submissionArgs.unshift('md')
this.submissionArgs.unshift(testDir)
this.solutionArgs.unshift('md')
this.solutionArgs.unshift(testDir)
fs.mkdir(testDir, function (err) {
if (err) {
return callback(err)
}
var done = after(files.length, callback)
files.forEach(function (f) {
fs.writeFile(
path.join(testDir, f)
, 'nothing to see here'
, 'utf8'
, done
)
})
})
})
// add a processor only for 'verify' calls
exercise.addVerifyProcessor(function (callback) {
var usedSync = false
var usedAsync = false
Object.keys(exercise.wrapData.fsCalls).forEach(function (m) {
if (/Sync$/.test(m)) {
usedSync = true
this.emit('fail', this.__('fail.sync', {method: 'fs.' + m + '()'}))
} else {
usedAsync = true
this.emit('pass', this.__('pass.async', {method: 'fs.' + m + '()'}))
}
}.bind(this))
if (!usedSync && !usedAsync) { // https://github.com/nodeschool/discussions/issues/356
this.emit('fail', this.__('fail.unused'))
}
callback(null, usedAsync && !usedSync)
})
// cleanup for both run and verify
exercise.addCleanup(function (mode, passed, callback) {
// mode == 'run' || 'verify'
rimraf(testDir, callback)
})
module.exports = exercise
|
const express = require('express');
const app = express();
const errorHandler = require('./error-handler');
const morgan = require('morgan');
const redirectHttp = require('./redirect-http')();
const cors = require('cors')();
const checkDb = require('./check-connection')();
const ensureAuth = require('./auth/ensure-auth')();
const ensureAdmin = require('./auth/ensure-admin')();
const beers = require('./routes/beers');
const reviews = require('./routes/reviews');
const auth = require('./routes/auth');
const admin = require('./routes/admin');
app.use(morgan('dev'));
// Redirect http to https only in production
if(process.env.NODE_ENV === 'production') {
app.use(redirectHttp);
}
app.use(cors);
app.use(express.static('./public'));
app.use(checkDb);
app.use('/api/auth', auth);
app.use('/api/beers', ensureAuth, beers);
app.use('/api/reviews', ensureAuth, reviews);
app.use('/api/admin', ensureAuth, ensureAdmin, admin);
app.use(errorHandler);
module.exports = app;
|
var rewire = require('rewire');
var InsertQuery = rewire('./InsertQuery.js');
var StatementMock = require('./_Statement.Spec.js'),
DBClientMock = require('./DBClient.Spec.js');
describe('lib/cassandra/InsertQuery.js', function () {
var query, spy, DBClientSpy;
beforeEach(function () {
spy = StatementMock.createSpy();
DBClientSpy = DBClientMock.createSpy();
InsertQuery.__set__('_Statement', spy);
InsertQuery.__set__('cassandraDB', DBClientSpy);
query = new InsertQuery('keyspace', 'table');
});
describe('toString ()', function () {
it('should generate a blank query', function () {
expect(query.toString()).toEqual('');
});
it('should return a query string with INSERT', function () {
expect(query.insertValues({key1: 'val1'}).toString()).toEqual('INSERT');
});
it('should return a query string with INSERT USING', function () {
expect(query.insertValues({key1: 'val1'}).usingOptions({TTL: 1}).toString()).toEqual('INSERT USING');
});
});
describe('execute (callback)', function () {
it('should execute the query', function () {
query.insertValues({key1: 'val1'}).usingOptions({TTL: 1}).execute(function () {
});
expect(DBClientSpy.getConnection().execute.calls.argsFor(0)[0]).toEqual('INSERT USING');
expect(DBClientSpy.getConnection().execute.calls.argsFor(0)[1]).toEqual([]);
expect(DBClientSpy.getConnection().execute.calls.argsFor(0)[2]).toEqual({prepare: true});
expect(DBClientSpy.getConnection().execute.calls.argsFor(0)[3]).toEqual(jasmine.any(Function));
});
});
});
// Mock for testing purposes
var InsertQueryMock = function () {
var self = this;
this.createSpy = function () {
return function () {
self.spy = jasmine.createSpyObj('InsertQuery', ['insertValues', 'usingOptions', 'toString', 'execute']);
self.spy.insertValues.and.returnValue('INSERT');
self.spy.usingOptions.and.returnValue('USING');
self.spy.toString.and.returnValue('INSERT USING');
return self.spy;
};
};
};
module.exports = new InsertQueryMock();
|
'use strict';
var path = require('path');
var webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
context: __dirname,
debug: process.env.NODE_ENV !== 'production',
devtool: 'sourcemap',
entry: './index.js',
eslint: {
failOnError: true
},
externals: [
{
react: {
root: 'React',
commonjs: 'react',
commonjs2: 'react',
amd: 'react'
}
}
],
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel-loader',
query: {
cacheDirectory: true,
optional: ['runtime'],
stage: 0
},
exclude: /node_modules/
}, {
test: /\.scss$/,
loader: ExtractTextPlugin.extract('style-loader', 'css-loader?-advanced!sass-loader?sourceMap'),
exclude: /node_modules/
}
],
preLoaders: [
{
test: /\.js$/,
loader: 'eslint-loader',
exclude: /node_modules/
}
]
},
output: {
path: path.join(__dirname, '..', 'build'),
filename: 'components.js',
library: 'Components',
libraryTarget: 'umd'
},
plugins: [
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurenceOrderPlugin(true),
new webpack.optimize.AggressiveMergingPlugin(),
new ExtractTextPlugin('components.css', { allChunks: true })
],
resolve: {
extensions: ['', '.js'],
modulesDirectories: ['components', 'node_modules']
},
resolveLoader: {
root: path.join(__dirname, '..', 'node_modules')
}
};
|
export {
NEW_TWEET,
};
const NEW_TWEET = `NEW_TWEET`;
|
'use strict'
const { compose, filter, head, map, match } = require('ramda')
const { countMatches, combineArrValuesAsSemver, lowerSubjectProp, dotSplit, dotJoin,
toInt } = require('../utils')
// matchSemVer :: String -> [String]
const matchSemVer = match(/\d{1,3}.\d{1,5}.\d{1,5}/)
// arrayifySemver :: String -> [Int]
const arrayifySemver = compose(map(toInt), dotSplit, head, matchSemVer)
module.exports = GitVersion
/**
* Module init function.
* @method GitVersion
* @param {Array} commits Parsed array of git commits
* @param {String} [currentVersion] SemVer representation of the current version
*/
function GitVersion ({ commits, currentVersion }) {
function version (keywords, suppliedVersion) {
const version = arrayifySemver(suppliedVersion || currentVersion)
const minorPredicate = compose(countMatches(keywords.minor), lowerSubjectProp)
const patchPredicate = compose(countMatches(keywords.patch), lowerSubjectProp)
const minors = filter(minorPredicate, commits)
const patches = filter(patchPredicate, commits)
const minorValue = (minors.length > 0) ? 1 : minors.length
const patchValue = (minorValue > 0) ? 0 : (patches.length > 0) ? 1 : 0
const diff = [ 0, minorValue, patchValue ]
return {
current: dotJoin(version),
diff: dotJoin(diff),
next: compose(dotJoin, combineArrValuesAsSemver(version))(diff),
commits: { minors, patches }
}
}
return {
version
}
}
|
'use strict';
angular.module('mean.quartos', []);
|
define('require/less', ['require', 'less'], function(require, less) {
var lessAPI = {};
lessAPI.pluginBuilder = './less-builder';
if (typeof window === 'undefined') {
lessAPI.load = function(n, r, load) {
load();
}
return lessAPI;
}
lessAPI.normalize = function(name, normalize) {
if (name.substr(name.length - 5, 5) == '.less')
name = name.substr(0, name.length - 5);
name = normalize(name);
return name;
}
var head = document.getElementsByTagName('head')[0];
var base = document.getElementsByTagName('base');
base = base && base[0] && base[0] && base[0].href;
var pagePath = (base || window.location.href.split('#')[0].split('?')[0]).split('/');
pagePath[pagePath.length - 1] = '';
pagePath = pagePath.join('/');
var styleCnt = 0;
var curStyle;
lessAPI.inject = function(css) {
if (styleCnt < 31) {
curStyle = document.createElement('style');
curStyle.type = 'text/css';
head.appendChild(curStyle);
styleCnt++;
}
if (curStyle.styleSheet)
curStyle.styleSheet.cssText += css;
else
curStyle.appendChild(document.createTextNode(css));
}
lessAPI.load = function(lessId, req, load, config) {
var defaultConfig = {};
var lessConfig = config ? (config.less || config) : defaultConfig;
if (! ('env' in lessConfig))
lessConfig.env = 'development';
var globalLess = window.less;
if (! globalLess)
window.less = lessConfig;
else if (! globalLess.Parser) {
if (lessConfig === defaultConfig)
lessConfig = globalLess;
globalLess = null;
}
require(globalLess ? ['./normalize'] : ['./normalize', './lessc'], function(normalize, lessc) {
if (! lessc)
lessc = globalLess;
if (! ("fileExt" in lessConfig))
lessConfig.fileExt = ".less";
var fileUrl = lessId;
if (fileUrl.substring(fileUrl.length - 4) !== ".css" && lessConfig.fileExt)
fileUrl += lessConfig.fileExt;
fileUrl = normalize.absoluteURI(req.toUrl(fileUrl), pagePath);
lessc.render('@import (' + (lessConfig.importOption || 'multiple') + ') "' + fileUrl + '";', lessConfig, function(err, output) {
if (err)
return load.error(err);
lessAPI.inject(normalize(output.css, fileUrl, pagePath));
setTimeout(load, 7);
}, lessConfig);
});
}
return lessAPI;
});
|
function
f(
o,
p
) {
var
{
x,
y
} = o;
var
[
a,
,
c
] = p;
}
|
import vueForm from './components/vue-form';
import messages from './components/messages';
import validate from './components/validate';
import field from './components/field';
import vueFormValidator from './directives/vue-form-validator';
import extend from 'extend';
import { config } from './config';
import { vueFormConfig } from './providers';
function VueFormBase (options) {
const c = extend(true, {}, config, options);
this.provide = () => ({
[vueFormConfig]: c
})
this.components = {
[c.formComponent]: vueForm,
[c.messagesComponent]: messages,
[c.validateComponent]: validate,
[c.fieldComponent]: field,
};
this.directives = { vueFormValidator };
}
export default class VueForm extends VueFormBase {
static install(Vue, options) {
Vue.mixin(new this(options));
}
static get installed() {
return !!this.install.done;
}
static set installed(val) {
this.install.done = val;
}
}
VueFormBase.call(VueForm);
// temp fix for vue 2.3.0
VueForm.options = new VueForm();
|
define(
[
"../App.js"
],
function (app)
{
return app.controller("Cerberus.Module.TemplateAdmin.Controller.ListTemplates",
[
"$scope",
"$state",
"$stateParams",
"Cerberus.Localization",
"Cerberus.Tool.TemplateEngine.Service.Template",
function ($scope, $state, $stateParams, Localization, TemplateService)
{
$scope.Localization = Localization;
TemplateService.GetTemplates()
.then(function (templates)
{
$scope.Templates = templates;
});
$scope.EditTemplate = function (template)
{
document.location.href = String.format("/Tool/TemplateEditor/#/Design/{0}", template.Id);
};
$scope.RemoveTemplate = function (template)
{
TemplateService.RemoveTemplate(template.Id)
.then(function (result)
{
if (result)
{
$scope.Templates.RemoveValue("Id", template.Id);
}
});
};
$scope.CloneTemplate = function (template)
{
TemplateService.CloneTemplate(template.Id)
.then(function (template)
{
$state.go("EditTemplateSettings", { TemplateId: template.Id });
});
};
}
]);
});
|
exports.hello = {
name: 'hello',
description: 'I will make suer the user is logged in and return info needed to start up',
outputExample:{
},
run: function(api, data, next) {
var connection = data.connection;
data.response.success = true;
if (connection.user.currentMatch) {
connection.user.getMatch(function(err, match) {
if (err) {
data.response.error = 1;
data.response.message = "Failed to populate match for user";
return next();
}
data.response.user = connection.user.toJSON({
virtuals: true
});
if (match) {
console.log(match);
data.response.user.currentMatch = match.toJSON({
virtuals: true
});
}
next();
});
} else {
data.response.user = connection.user.toJSON({
virtuals: true
});
next();
}
}
};
|
/* jshint esnext:true */
var names = ['Brian', 'Madeline'];
assert.deepEqual(['Thomas', ...names], ['Thomas', 'Brian', 'Madeline']);
assert.deepEqual([1, 2, ...[3, 4, 5]], [1, 2, 3, 4, 5]);
|
;(function(Form, Fieldset) {
var same = deepEqual;
module('Fieldset#initialize', {
setup: function() {
this.sinon = sinon.sandbox.create();
},
teardown: function() {
this.sinon.restore();
}
});
test('creates the schema', function() {
this.sinon.spy(Fieldset.prototype, 'createSchema');
var fields = {
title: new Form.Field({ key: 'title' }),
author: new Form.Field({ key: 'author' })
};
var options = {
fields: fields,
schema: { legend: 'Test', fields: ['title', 'author'] }
};
var fs = new Fieldset(options);
same(fs.createSchema.callCount, 1);
same(fs.createSchema.args[0][0], options.schema);
same(fs.schema, options.schema);
});
test('stores fields defined in the schema', function() {
var fields = {
title: new Form.Field({ key: 'title' }),
author: new Form.Field({ key: 'author' })
};
var options = {
fields: fields,
schema: ['title', 'author']
};
var fs = new Fieldset(options);
same(_.keys(fs.fields), ['title', 'author']);
});
test('overrides defaults', function() {
var options = {
fields: { title: new Form.Field({ key: 'title' }) },
schema: ['title'],
template: _.template('<b></b>')
};
var fs = new Fieldset(options);
same(fs.template, options.template);
});
test('first, uses template defined in options', function() {
var optionsTemplate = _.template('<div class="options" data-fields></div>'),
schemaTemplate = _.template('<div class="schema" data-fields></div>'),
protoTemplate = _.template('<div class="prototype" data-fields></div>'),
constructorTemplate = _.template('<div class="constructor" data-fields></div>');
var CustomFieldset = Fieldset.extend({
template: protoTemplate
}, {
template: constructorTemplate
});
var fieldset = new CustomFieldset({
template: optionsTemplate,
schema: { fields: [], template: schemaTemplate }
});
same(fieldset.template, optionsTemplate);
});
test('second, uses template defined in schema', function() {
var schemaTemplate = _.template('<div class="schema" data-fields></div>'),
protoTemplate = _.template('<div class="prototype" data-fields></div>'),
constructorTemplate = _.template('<div class="constructor" data-fields></div>');
var CustomFieldset = Fieldset.extend({
template: protoTemplate
}, {
template: constructorTemplate
});
var fieldset = new CustomFieldset({
schema: { fields: [], template: schemaTemplate }
});
same(fieldset.template, schemaTemplate);
});
test('third, uses template defined on prototype', function() {
var protoTemplate = _.template('<div class="prototype" data-fields></div>'),
constructorTemplate = _.template('<div class="constructor" data-fields></div>');
var CustomFieldset = Fieldset.extend({
template: protoTemplate
}, {
template: constructorTemplate
});
var fieldset = new CustomFieldset({
schema: { fields: [] }
});
same(fieldset.template, protoTemplate);
});
test('fourth, uses template defined on constructor', function() {
var constructorTemplate = _.template('<div class="constructor" data-fields></div>');
var CustomFieldset = Fieldset.extend({
}, {
template: constructorTemplate
});
var fieldset = new CustomFieldset({
schema: { fields: [] },
});
same(fieldset.template, constructorTemplate);
});
test('Uses Backbone.$ not global', function() {
var old$ = window.$,
exceptionCaught = false;
window.$ = null;
try {
var fields = {
title: new Form.Field({ key: 'title' }),
author: new Form.Field({ key: 'author' })
};
var options = {
fields: fields,
schema: { legend: 'Test', fields: ['title', 'author'] }
};
var fs = new Fieldset(options).render();
} catch(e) {
exceptionCaught = true;
}
window.$ = old$;
ok(!exceptionCaught, ' using global \'$\' to render');
});
module('Fieldset#createSchema', {
setup: function() {
this.sinon = sinon.sandbox.create();
},
teardown: function() {
this.sinon.restore();
}
});
test('converts an array schema into an object with legend', function() {
var options = {
fields: {
title: new Form.Field({ key: 'title' }),
author: new Form.Field({ key: 'author' })
},
schema: ['title', 'author']
};
var fs = new Fieldset(options);
var schema = fs.createSchema(options.schema);
same(schema, { legend:null, fields: ['title', 'author'] });
});
test('returns fully formed schema as is', function() {
var options = {
fields: {
title: new Form.Field({ key: 'title' }),
author: new Form.Field({ key: 'author' })
},
schema: { legend: 'Main', fields: ['title', 'author'] }
}
var fs = new Fieldset(options);
var schema = fs.createSchema(options.schema);
same(schema, options.schema);
});
module('Fieldset#getFieldAt');
test('returns field at a given index', function() {
var fs = new Fieldset({
fields: {
title: new Form.Field({ key: 'title' }),
author: new Form.Field({ key: 'author' })
},
schema: { legend: 'Main', fields: ['title', 'author'] }
});
same(fs.getFieldAt(0), fs.fields.title);
same(fs.getFieldAt(1), fs.fields.author);
});
module('Fieldset#templateData');
test('returns schema', function() {
var fs = new Fieldset({
fields: {
title: new Form.Field({ key: 'title' }),
author: new Form.Field({ key: 'author' })
},
schema: { legend: 'Main', fields: ['title', 'author'] }
});
same(fs.templateData(), fs.schema);
});
module('Fieldset#render', {
setup: function() {
this.sinon = sinon.sandbox.create();
this.sinon.stub(Form.Field.prototype, 'render', function() {
this.setElement($('<field class="'+this.key+'" />'));
return this;
});
},
teardown: function() {
this.sinon.restore();
}
});
test('returns self', function() {
var fs = new Fieldset({
fields: {
title: new Form.Field({ key: 'title' }),
author: new Form.Field({ key: 'author' })
},
schema: { legend: 'Main', fields: ['title', 'author'] }
});
var returnedValue = fs.render();
same(returnedValue, fs);
});
test('with data-fields placeholder, on inner element', function() {
var fs = new Fieldset({
fields: {
title: new Form.Field({ key: 'title' }),
author: new Form.Field({ key: 'author' })
},
schema: { legend: 'Main', fields: ['title', 'author'] },
template: _.template('<div><%= legend %><b data-fields></b></div>')
});
fs.render();
same(fs.$el.html(), 'Main<b data-fields=""><field class="title"></field><field class="author"></field></b>');
});
test('with data-fields placeholder, on outermost element', function() {
var fs = new Fieldset({
fields: {
title: new Form.Field({ key: 'title' }),
author: new Form.Field({ key: 'author' })
},
schema: { legend: 'Main', fields: ['title', 'author'] },
template: _.template('<b data-fields><%= legend %></b>')
});
fs.render();
same(fs.$el.html(), 'Main<field class="title"></field><field class="author"></field>');
});
module('Form#remove', {
setup: function() {
this.sinon = sinon.sandbox.create();
this.sinon.spy(Form.Field.prototype, 'remove');
},
teardown: function() {
this.sinon.restore();
}
});
test('removes fieldsets, fields and self', function() {
var fs = new Fieldset({
fields: {
title: new Form.Field({ key: 'title' }),
author: new Form.Field({ key: 'author' })
},
schema: { legend: 'Main', fields: ['title', 'author'] }
});
fs.remove();
same(Form.Field.prototype.remove.callCount, 2);
});
})(Backbone.Form, Backbone.Form.Fieldset);
|
/*
* Copyright (c) 2016 airbug Inc. http://airbug.com
*
* bugcore may be freely distributed under the MIT license.
*/
//-------------------------------------------------------------------------------
// Annotations
//-------------------------------------------------------------------------------
//@Export('MathUtil')
//@Require('Class')
//@Require('Obj')
//-------------------------------------------------------------------------------
// Context
//-------------------------------------------------------------------------------
require('bugpack').context("*", function(bugpack) {
//-------------------------------------------------------------------------------
// BugPack
//-------------------------------------------------------------------------------
var Class = bugpack.require('Class');
var Obj = bugpack.require('Obj');
//-------------------------------------------------------------------------------
// Declare Class
//-------------------------------------------------------------------------------
/**
* @class
* @extends {Obj}
*/
var MathUtil = Class.extend(Obj, {
_name: "MathUtil"
});
//-------------------------------------------------------------------------------
// Static Methods
//-------------------------------------------------------------------------------
/**
* @static
* @param {number} degrees
* @return {number}
*/
MathUtil.degreesToRadians = function (degrees) {
return degrees * (Math.PI / 180);
};
/**
* @static
* @param {number} radians
* @return {number}
*/
MathUtil.radiansToDegrees = function (radians) {
return radians * (180 / Math.PI);
};
//-------------------------------------------------------------------------------
// Exports
//-------------------------------------------------------------------------------
bugpack.export('MathUtil', MathUtil);
});
|
/**
* CellLineRecord.js
*
* @description :: TODO: You might write a short summary of how this model works and what it represents here.
* @docs :: http://sailsjs.org/#!documentation/models
*/
module.exports = {
attributes: {
requests: {
model: 'request'
},
line: {
model: 'cellLine'
},
users: {
model: 'user'
},
job: {
type: 'string'
},
positions: {
model: 'position'
},
units: {
model: 'unit'
},
sagposition : {
type: 'string'
},
account: {
model: 'cellAccount'
},
prodsestrs: {
model: 'ProdEstr'
},
minutes: {
type: 'integer',
defaultsTo: 0
},
dataplan: {
type: 'integer',
defaultsTo: 0
},
docid: {
type: 'integer',
},
obs : {
type: 'string'
},
active: {
type: 'boolean',
defaultsTo: true
}
}
};
|
import $ from 'jquery';
import Handlebars from 'handlebars';
import bootbox from 'bootbox';
import i18next from 'i18next';
import moment from 'moment';
import application from '../application';
import ViewController from '../viewcontroller';
import OccupantForm from './occupantform';
import ContractDocumentsForm from './contractdocumentsform';
const LOCA = application.get('LOCA');
class OccupantMiddelware extends ViewController {
constructor() {
super({
domViewId: '#view-occupant',
domListId: '#occupants',
defaultMenuId: 'occupants-menu',
listSelectionLabel: 'Selected tenant',
listSelectionMenuId: '#occupants-selection-menu',
urls: {
overview: '/api/occupants/overview',
items: '/api/occupants',
},
});
this.form = new OccupantForm();
this.documentsForm = new ContractDocumentsForm();
}
// callback
onInitTemplate() {
// Handlebars templates
Handlebars.registerPartial(
'history-rent-row-template',
$('#history-rent-row-template').html()
);
this.templateHistoryRents = Handlebars.compile(
$('#history-rents-template').html()
);
Handlebars.registerPartial(
'occupant-invoice-links-template',
$('#occupant-invoice-links-template').html()
);
this.templateInvoices = Handlebars.compile(
$('#occupant-invoices-template').html()
);
const $occupantsSelected = $('#view-occupant-selected-list-template');
if ($occupantsSelected.length > 0) {
this.templateSelectedRow = Handlebars.compile($occupantsSelected.html());
}
}
_loadPropertyList(callback) {
application.httpGet('/api/properties', (req, res) => {
if (callback) {
const properties = JSON.parse(res.responseText);
callback(properties);
}
});
}
onUserAction($action, actionId) {
const selection = this.list.getSelectedData();
if (actionId === 'list-action-view-occupant') {
this._loadPropertyList((properties) => {
this.form.setData(selection[0], properties);
$('#occupant-form select')
.attr('readonly', true)
.attr('disabled', true)
.addClass('uneditable-input');
$('#occupant-form input')
.attr('readonly', true)
.addClass('uneditable-input');
$('#occupant-form .btn').addClass('hidden');
this.openForm('occupant-form', 'occupant-view-menu');
});
} else if (actionId === 'list-action-edit-occupant') {
$('#occupant-form select')
.attr('readonly', false)
.attr('disabled', false)
.removeClass('uneditable-input');
$('#occupant-form input')
.attr('readonly', false)
.removeClass('uneditable-input');
$('#occupant-form .btn').removeClass('hidden');
this.showMenu('occupant-edit-menu');
} else if (actionId === 'list-action-add-occupant') {
this.list.unselectAll();
this._loadPropertyList((properties) => {
this.form.setData(null, properties);
$('#occupant-form select')
.attr('readonly', false)
.attr('disabled', false)
.removeClass('uneditable-input');
$('#occupant-form input')
.attr('readonly', false)
.removeClass('uneditable-input');
$('#occupant-form .btn').removeClass('hidden');
this.openForm('occupant-form', 'occupant-edit-menu');
});
} else if (actionId === 'list-action-remove-occupant') {
bootbox.confirm(
i18next.t('Are you sure to remove this tenant?'),
(result) => {
if (!result) {
return;
}
const selectionIds = [];
for (let index = 0; index < selection.length; ++index) {
selectionIds.push(selection[index]._id);
}
application.httpDelete(
`/api/occupants/${selectionIds.join()}`,
(req, res) => {
const response = JSON.parse(res.responseText);
if (!response.errors || response.errors.length === 0) {
this.list.unselectAll();
this.loadList(() => {
this.closeForm();
});
} else {
bootbox.alert({ message: response.errors });
}
}
);
}
);
} else if (actionId === 'list-action-save-form') {
this.form.submit((data) => {
this.closeForm(() => {
this.loadList(() => {
this.list.select($('.js-list-row#' + data._id), true);
});
});
});
} else if (actionId === 'list-action-invoices') {
$('#occupant-invoices').html('');
this.openForm('invoices');
application.httpGet(
`/api/rents/occupant/${selection[0]._id}`,
(req, res) => {
const rentsHistory = JSON.parse(res.responseText);
const current = moment();
let count = 0;
const rents = rentsHistory.rents
.reverse()
.filter((rent) => {
if (
moment(`${rent.year}-${rent.month}-01`).isSameOrBefore(current)
) {
count++;
return count <= 48; // view last 48 months
}
return false;
})
.reduce(
(result, rent) => {
let foundYears = result.years.filter(
(year) => year.year === rent.year
);
if (!foundYears || foundYears.length === 0) {
const yearObject = {
occupantId: selection[0]._id,
year: rent.year,
months: [],
};
result.years.push(yearObject);
foundYears = [yearObject];
}
foundYears[0].months.push({
occupantId: selection[0]._id,
year: Number(rent.year),
month: Number(rent.month),
totalToPay: rent.totalToPay,
payment: rent.payment,
});
return result;
},
{ years: [] }
);
$('#occupant-invoices').html(this.templateInvoices(rents));
}
);
} else if (actionId === 'invoice-link') {
const month = $action.data('month');
const year = $action.data('year');
const occupantId = $action.data('occupantId');
let url = `/print/invoice/occupants/${occupantId}/${year}`;
if (month) {
url += `/${month}`;
}
application.openPrintPreview(url);
} else if (actionId === 'list-action-manage-documents') {
this.documentsForm.setData(selection[0]);
this.openForm('contract-documents-form');
} else if (actionId === 'list-action-save-contract-documents') {
this.documentsForm.submit((data) => {
this.closeForm(() => {
if (data._id) {
application.httpGet('/api/occupants/overview', (req, res) => {
const occupantsOverview = JSON.parse(res.responseText);
const countAll = occupantsOverview.countAll;
const countActive = occupantsOverview.countActive;
const countInactive = occupantsOverview.countInactive;
$('#view-occupant .js-all-filter-label').html(
'(' + countAll + ')'
);
$('#view-occupant .all-active-filter-label').html(
'(' + countActive + ')'
);
$('#view-occupant .all-inactive-filter-label').html(
'(' + countInactive + ')'
);
this.list.update(data);
this.list.showAllRows();
});
}
});
});
} else if (actionId === 'list-action-rents-history') {
$('#history-rents-table').html('');
this.openForm('rents-history', null, () => {
application.httpGet(
`/api/rents/occupant/${selection[0]._id}`,
(req, res) => {
const rentsHistory = JSON.parse(res.responseText);
$('#history-rents-table').html(
this.templateHistoryRents(rentsHistory)
);
this.scrollToElement('#history-rents-table .active');
}
);
});
} else if (actionId === 'list-action-print') {
this.openForm('print-doc-selector');
}
}
onInitListener() {
$(document).on('click', '#view-occupant #printofficechecklist', () => {
const selection = this.getSelectedIds();
application.openPrintPreview(`/print/checklist/occupants/${selection}`);
return false;
});
$(document).on('click', '#view-occupant #printcontract', () => {
const selection = this.getSelectedIds();
application.openPrintPreview(
`/print/contract/occupants/${selection}/${LOCA.currentYear}/${LOCA.currentMonth}`
);
return false;
});
$(document).on('click', '#view-occupant #printcustomcontract', () => {
const selection = this.getSelectedIds();
application.openPrintPreview(
`/print/customcontract/occupants/${selection}/${LOCA.currentYear}/${LOCA.currentMonth}`
);
return false;
});
$(document).on('click', '#view-occupant #printdomcontract', () => {
const selection = this.getSelectedIds();
application.openPrintPreview(
`/print/domcontract/occupants/${selection}/${LOCA.currentYear}/${LOCA.currentMonth}`
);
return false;
});
$(document).on('click', '#view-occupant #printguarantycertificate', () => {
const selection = this.getSelectedIds();
application.openPrintPreview(
`/print/guarantycertificate/occupants/${selection}/${LOCA.currentYear}/${LOCA.currentMonth}`
);
return false;
});
$(document).on('click', '#view-occupant #printguarantypayback', () => {
const selection = this.getSelectedIds();
application.openPrintPreview(
`/print/guarantypaybackcertificate/occupants/${selection}/${LOCA.currentYear}/${LOCA.currentMonth}`
);
return false;
});
$(document).on('click', '#view-occupant #printguarantyrequest', () => {
const selection = this.getSelectedIds();
application.openPrintPreview(
`/print/guarantyrequest/occupants/${selection}/${LOCA.currentYear}/${LOCA.currentMonth}`
);
return false;
});
$(document).on('click', '#view-occupant #printinsurancerequest', () => {
const selection = this.getSelectedIds();
application.openPrintPreview(
`/print/insurance/occupants/${selection}/${LOCA.currentYear}/${LOCA.currentMonth}`
);
return false;
});
}
onDataChanged(callback) {
this.form.bindForm();
this.documentsForm.bindForm();
if (callback) {
callback();
}
}
// overriden
exited() {
this.form.unbindForm();
this.documentsForm.unbindForm();
}
}
export default OccupantMiddelware;
|
'use strict';
// Init the application configuration module for AngularJS application
var ApplicationConfiguration = (function() {
// Init module configuration options
var applicationModuleName = 'todogenius';
var applicationModuleVendorDependencies = ['ngResource', 'ui.router', 'ui.bootstrap', 'ui.utils'];
// Add a new vertical module
var registerModule = function(moduleName, dependencies) {
// Create angular module
angular.module(moduleName, dependencies || []);
// Add the module to the AngularJS configuration file
angular.module(applicationModuleName).requires.push(moduleName);
};
return {
applicationModuleName: applicationModuleName,
applicationModuleVendorDependencies: applicationModuleVendorDependencies,
registerModule: registerModule
};
})();
|
// Configuration is hack for testing. If you have a bunch of code that depends
// on probing the environment it might be hard to test that code if there is
// nothing variable passed into `configure`.
//
// Of course, the environment is variable, so you could set `process.env` in
// testing and read it in the function, but I don't like to use the environment
// if I don't have to. It invites abuse.
//
// Also you could make life a little easier by having some static properties
// here that the user could set without poking into the `configure` function
// below at all.
exports.configure = function (configuration) {
return {
socket: configuration.socket,
constituents: {
run: {
path: './test/run.bin.js',
workers: 1,
properties: {}
},
serve: {
path: './test/serve.bin.js',
workers: 1,
properties: {}
}
}
}
}
|
var later = require('../../index'),
runner = require('./runner')(later, later.minute),
should = require('should');
describe('Later.minute', function() {
var tests = [
{
// first second of year
date: new Date(2008, 0, 1),
val: 0,
extent: [0, 59],
start: new Date(2008, 0, 1),
end: new Date(2008, 0, 1, 0, 0, 59)
},
{
// last second of year
date: new Date(2009, 11, 31, 23, 59, 59),
val: 59,
extent: [0, 59],
start: new Date(2009, 11, 31, 23, 59),
end: new Date(2009, 11, 31, 23, 59, 59)
},
{
// first second of month starting on Sunday
date: new Date(2010, 7, 1),
val: 0,
extent: [0, 59],
start: new Date(2010, 7, 1),
end: new Date(2010, 7, 1, 0, 0, 59)
},
{
// last second of month ending on Saturday
date: new Date(2011, 3, 30, 23, 59, 59),
val: 59,
extent: [0, 59],
start: new Date(2011, 3, 30, 23, 59),
end: new Date(2011, 3, 30, 23, 59, 59)
},
{
// first second of day
date: new Date(2012, 1, 28),
val: 0,
extent: [0, 59],
start: new Date(2012, 1, 28),
end: new Date(2012, 1, 28, 0, 0, 59)
},
{
// last second of day on leap day
date: new Date(2012, 1, 29, 23, 59, 59),
val: 59,
extent: [0, 59],
start: new Date(2012, 1, 29, 23, 59),
end: new Date(2012, 1, 29, 23, 59, 59)
},
{
// first second of hour
date: new Date(2012, 10, 8, 14),
val: 0,
extent: [0, 59],
start: new Date(2012, 10, 8, 14),
end: new Date(2012, 10, 8, 14, 0, 59)
},
{
// last second of hour (start DST)
date: new Date(2013, 2, 10, 1, 59, 59),
val: 59,
extent: [0, 59],
start: new Date(2013, 2, 10, 1, 59),
end: new Date(2013, 2, 10, 1, 59, 59)
},
{
// first second of hour (end DST)
date: new Date(2013, 10, 3, 2),
val: 0,
extent: [0, 59],
start: new Date(2013, 10, 3, 2),
end: new Date(2013, 10, 3, 2, 0, 59)
},
{
// last second of hour
date: new Date(2014, 1, 22, 6, 59, 59),
val: 59,
extent: [0, 59],
start: new Date(2014, 1, 22, 6, 59),
end: new Date(2014, 1, 22, 6, 59, 59)
},
{
// first second of minute
date: new Date(2015, 5, 19, 18, 22),
val: 22,
extent: [0, 59],
start: new Date(2015, 5, 19, 18, 22),
end: new Date(2015, 5, 19, 18, 22, 59)
},
{
// last second of minute
date: new Date(2016, 7, 29, 2, 56, 59),
val: 56,
extent: [0, 59],
start: new Date(2016, 7, 29, 2, 56),
end: new Date(2016, 7, 29, 2, 56, 59)
},
{
// second
date: new Date(2017, 8, 4, 10, 31, 22),
val: 31,
extent: [0, 59],
start: new Date(2017, 8, 4, 10, 31),
end: new Date(2017, 8, 4, 10, 31, 59)
}
];
runner.run(tests);
});
|
import React from 'react';
import { Link } from 'react-router-dom';
import GalleryContainer from '../containers/GalleryContainer';
import '../styles/Intro.css';
const Intro = () =>
<div className="Intro">
<div className="Intro__information">
<p>
Are you a college student? Use your printing allowance to promote social
change!
</p>
<p>
Print to Resist helps activist organizations and concerned citizens
spread key information related to the anti-Trump movement. This site
aims to break the internet bubble to help unite the wide movement, to
help instruct people of their rights, and to help promote effective
methods of resistance.
</p>
<p>
Want to help?{' '}
<a className="button_link" href="#gallery">Print and post</a> or{' '}
<Link className="button_link" to="/create">
Add a poster worth spreading
</Link>
</p>
</div>
<GalleryContainer />
</div>;
export default Intro;
|
/* jshint -W053 */
var R = require('..');
var eq = require('./shared/eq');
describe('is', function() {
it('works with built-in types', function() {
eq(R.is(Array, []), true);
eq(R.is(Boolean, new Boolean(false)), true);
eq(R.is(Date, new Date()), true);
eq(R.is(Function, function() {}), true);
eq(R.is(Number, new Number(0)), true);
eq(R.is(Object, {}), true);
eq(R.is(RegExp, /(?:)/), true);
eq(R.is(String, new String('')), true);
});
it('works with user-defined types', function() {
function Foo() {}
function Bar() {}
Bar.prototype = new Foo();
var foo = new Foo();
var bar = new Bar();
eq(R.is(Foo, foo), true);
eq(R.is(Bar, bar), true);
eq(R.is(Foo, bar), true);
eq(R.is(Bar, foo), false);
});
it('is curried', function() {
var isArray = R.is(Array);
eq(isArray([]), true);
eq(isArray({}), false);
});
it('considers almost everything an object', function() {
function Foo() {}
var foo = new Foo();
var isObject = R.is(Object);
eq(isObject(foo), true);
eq(isObject(function() { return arguments; }()), true);
eq(isObject([]), true);
eq(isObject(new Boolean(false)), true);
eq(isObject(new Date()), true);
eq(isObject(function() {}), true);
eq(isObject(new Number(0)), true);
eq(isObject(/(?:)/), true);
eq(isObject(new String('')), true);
eq(isObject(null), false);
eq(isObject(undefined), false);
});
it('does not coerce', function() {
eq(R.is(Boolean, 1), false);
eq(R.is(Number, '1'), false);
eq(R.is(Number, false), false);
});
it('recognizes primitives as their object equivalents', function() {
eq(R.is(Boolean, false), true);
eq(R.is(Number, 0), true);
eq(R.is(String, ''), true);
});
it('does not consider primitives to be instances of Object', function() {
eq(R.is(Object, false), false);
eq(R.is(Object, 0), false);
eq(R.is(Object, ''), false);
});
it('is curried', function() {
eq(typeof R.is(String), 'function');
eq(R.is(String)('s'), true);
});
});
|
import rule from "../../src/rules/new-cap";
import RuleTester from "../helpers/RuleTester";
const ruleTester = new RuleTester();
ruleTester.run("@babel/new-cap", rule, {
valid: [
{
code: "@MyDecorator(123) class MyClass{}",
},
],
invalid: [],
});
|
/**
* Created by I312934 on 9/8/2015.
*/
var fs = require('fs'),
harFile = process.argv[2];
fs.readFile(harFile, 'utf8', function (err,data) {
if (err) {
return console.log(err);
} else {
var sum = 0;
data = JSON.parse(data);
data.log.entries.forEach(function (entry) {
sum += entry.timings.wait;
});
console.log("TTFB sum:", sum);
console.log("TTFB AVG:", sum / data.log.entries.length );
}
});
|
const fs = require('fs');
const { resolve } = require('path');
const resolvePath = path => resolve(__dirname, '../../', path);
const loadModules = (path, ignoreFiles) =>
fs.readdirSync(resolvePath(path))
.filter(path => ignoreFiles.every(ignoredPath => !path.includes(ignoredPath)))
.map(fileName => fs.readFileSync(resolvePath(`${path}/${fileName}`)))
.join(';');
const loadModule = path => {
const content = fs.readFileSync(resolvePath(path)).toString().trim();
return content.endsWith(';')
? content.slice(0, content.length - 1)
: content;
};
module.exports = {
loadModule,
loadModules,
}
|
var helpers = {
id : function(id){
return document.getElementById(id);
},
show : function(e){
e.style.display="block";
},
hide : function(e){
e.style.display = "none";
//use apply with this
},
hideM : function(e){
var length = e.length;
var i = 0;
for(i;i<length;i++){
e[i].style.display = "none";
}
},
clearHtml :function(e){
e.innerHTML = '';
},
serializeTextFields : function(form){
var i=0;
var length= form.elements.length -1;
var data = "";
for(i;i<length;i++){
var name = form.elements[i].name;
var value = form.elements[i].value;
var pair = name+'='+value+'&';
data = data+encodeURI(pair);
}
return data;
},
buildAjaxPostObject :function(form,formData){
var ajaxObject = {
data : formData,
method:"POST"
};
if(form.id==='loginForm'){
ajaxObject.url = '/login';
ajaxObject.successCallback =logincallback.successCallback;
ajaxObject.errorCallback = logincallback.errorCallback;
}
if(form.id==='signUpForm'){
ajaxObject.url = '/createuser';
ajaxObject.successCallback = createcallback.successCallback;
ajaxObject.errorCallback = createcallback.errorCallback;
}
return ajaxObject;
},
ajax: function(options){
var request = new XMLHttpRequest();
request.open(options.method,options.url,true);
request.onreadystatechange = function(){
if(request.status===404)options.errorCallback();
if(request.status!=200||request.readyState!=4)return;
options.successCallback(request.responseText);
};
request.send(options.data);
},
successCallback : function(responseText){
var parsed = JSON.parse(responseText);
var key = Object.keys(parsed)[0];
var storeObject = addToStore({"session":key},"sess","application");
storeObject.transaction.oncomplete = function(){
localStorage.setItem("user",parsed[key]);
checkSession();
};
},
output: function(input){
var newline = /(\n{2}|\r{2})/g;
var urlRegex = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?*=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
var output= input.replace(newline,"<br>").replace(urlRegex,function(url){
if (( url.indexOf(".jpg") > 0 )||(url.indexOf(".jpeg") > 0 ) || (url.indexOf(".png") > 0) || (url.indexOf(".gif") > 0)) return '<br/><img src="' + url + '"><br/>';
return '<a href="' + url + '">' + url + '</a>';
});
return output;
},
saveMessage : function(message,to){
if(to)message.f = to;
var request = addToStore(message,null,'messages');
return message;
},
addProfile: function(message){
if(message.hasOwnProperty("m")){
if(!message.m.p){
message.m.p = {};
message.m.p.u = message.f;
return message;
}
if(message.m.p && !message.m.p.u){
message.m.p.u = message.f;
}
return message;
}
return message;
},
buildMessages: function(){
var messageStore = getStore('messages','readonly');
var count = 0;
var mStr ='';
messageStore.openCursor(null,'prev').onsuccess = function(e){
var cursor = e.target.result;
if(count===20||!cursor){
if(!count){
return;
}
if(count){
var needMore = count===20?'<p style="text-align:center" class="details" onclick="morePagesIndex('+cursor.key+',this)">more</p>':'';
messages.innerHTML = mStr+needMore;
showActivity();
return;
}
}
if(cursor){
mStr = mStr+domElements.incomingMessage(cursor.value);
cursor.continue();
count++;
}
};
},
humanDate : function(date){
var seconds = Math.floor((new Date() - date) / 1000);
var interval = Math.floor(seconds / 31536000);
if (interval > 1) {
return interval + "y";
}
interval = Math.floor(seconds / 2592000);
if (interval > 1) {
return interval + "m";
}
interval = Math.floor(seconds / 86400);
if (interval > 1) {
return interval + "d";
}
interval = Math.floor(seconds / 3600);
if (interval > 1) {
return interval + "h";
}
interval = Math.floor(seconds / 60);
if (interval > 1) {
return interval + " min";
}
return Math.floor(seconds) + "s";
}
};
var signUp= helpers.id("signup");
var login= helpers.id("login");
var splashDiv = helpers.id("splash");
var formDiv = helpers.id("formDiv");
var app = helpers.id("app");
var appBody = helpers.id("appBody");
var appMessage = helpers.id("appMessage");
var messages = helpers.id("messages");
var sendMessage = helpers.id("sendMessage");
var sendBtn = helpers.id("sendBtn");
var btnReply = helpers.id("btnReply");
var messageDiv = helpers.id("messageDiv");
var conversation = helpers.id("conversation");
var sIn = helpers.id("search");
var menu = helpers.id("menu");
var contactDiv = helpers.id("contact");
var openRequest = indexedDB.open("wrinq", 1);
var prf;
var database;
var socket;
openRequest.onupgradeneeded = function(e){
database = e.target.result;
createObjectStore(database,"profile",false);
var ms= createObjectStore(database,"messages",false);
ms.createIndex("between",'f');
ms.createIndex("profile",'m.p.u');
createObjectStore(database,"application",true);
};
openRequest.onsuccess = function(e){
database = e.target.result;
checkSession();
};
openRequest.onerror = function(e){
console.log(e);
};
function getStore(objectStore,permission){
var tran = database.transaction([objectStore],permission);
var store = tran.objectStore(objectStore);
return store;
};
function addToStore(item,key,store){
var storeObject = getStore(store,"readwrite");
if(key){
storeObject.put(item,key);
}
if(!key){
storeObject.put(item);
}
return storeObject;
};
function createObjectStore(database,name,key){
if(database.objectStoreNames.contains(name))return null;
if(key){
return database.createObjectStore(name);
}
if(!key){
return database.createObjectStore(name,{autoIncrement:true});
}
return null;
};
var checkSession = function(){
var appStore = getStore('application','readonly');
var result = appStore.get("sess");
result.onsuccess = function(e){
if(!e.target.result) {
helpers.show(splashDiv);
return;
}
helpers.hide(splashDiv);
helpers.hide(formDiv);
var profileStore = getStore("profile",'readonly');
var profile = profileStore.get("master");
var user = localStorage.getItem("user");
profile.onsuccess = function(e){
if(!e.target.result){
messageDiv.innerHTML = '<a href="/editprofile.html">create a profile '+user+'</a>';
return;
}
messageDiv.innerHTML = '<a href="/editprofile.html">'+user+'</a>';
prf = e.target.result;
};
helpers.buildMessages();
socket= socketManager(e.target.result.session);
};
};
var socketManager = function(sess){
var socket = new WebSocket('ws://localhost:3000/websocket/'+sess);
socket.onopen = function(data){
socket.send(JSON.stringify({"ret":1}));
helpers.show(app);
};
socket.onmessage = function(e){
var message = JSON.parse(e.data);
if(message.hasOwnProperty("msgs") && message.msgs.length>0){
var messageArray = message.msgs;
var length = messageArray.length;
var i =0;
for(i;i<length;i++){
var parsed = JSON.parse(messageArray[i]);
var m = helpers.addProfile(parsed);
helpers.saveMessage(m);
}
var info = length>1?" messages were sent while you were offline":" message was sent while you were offline";
helpers.id("unread").innerHTML = length + info;
socket.send(JSON.stringify({"delmsg":1}));
return;
}
if(message.hasOwnProperty("m")){
helpers.addProfile(message);
helpers.saveMessage(message);
messages.innerHTML = domElements.incomingMessage(message)+ messages.innerHTML;
return;
}
};
socket.onerror = function(e){
messageDiv.innerHTML +='<p id="error-message">Could not connect to the server.Try refreshing.</p>';
helpers.show(app);
};
return socket;
};
var logincallback = {
successCallback: helpers.successCallback,
errorCallback : function(){
var message = helpers.id("message");
message.innerHTML = "Login failed.";
}
};
var createcallback = {
successCallback: helpers.successCallback,
errorCallback : function(){
var message = helpers.id("message");
message.innerHTML = "This action could not be completed";
}
};
var domElements = {
'signUpForm' :'<form id ="signUpForm" onsubmit="submitAjax(event,this)"><p><input type="text" name="username" value="" placeholder= "username" onblur="checkUser(this)" onfocus = "clearMessages()" required/></p><p><input type="password" name="password" value="" placeholder="password" required/></p><p><input type="submit" id="submitButton" value="sign up" disabled/></p></form><p id ="message"></p><p><span class ="underline-spans" onclick = "loginClick()">or login<span></p>',
'loginForm': '<form method="POST" id="loginForm" onsubmit="submitAjax(event,this)"><p><input type="text" name="username" value="" placeholder="username" required/></p><p><input type="password" name="password" value="" placeholder="password" required/></p><p><input type="submit" id="submitButton" name="" value="login"/></p></form><p id= "message"></p><p ><span class ="underline-spans" onclick ="signUpClick()">or sign-up<span></p>',
'commentBox':'<div class="box"><p><textarea rows="5" name="reply" placeholder="your message" onkeyup="autoGrow(this)"></textarea></p></div> <span><button type="button" onclick="reply(this)" id="btnReply disabled">post</button></span><span><button type="button" onclick="removeCommentBox(this)">cancel</button>',
'contact' : function(o){
var temp = '<div class="contacts"><h1 style="text-align:center;">contacts</h1></div>';
return temp;
},
'sendMessage' : '<div class="box"><p><input type="text" name="to" placeholder="to" onblur="check(this)"/></p><p><textarea rows="5" placeholder="your message" onkeyup="autoGrow(this)" name="message"></textarea></p></div> <span><button type="button" onclick="send(this)" id="btnSend" disabled>post</button></span>',
'incomingMessage' : function(m){
// var mDate = m.day+'-'+m.month+'-'+m.year+" ";
// var min = m.min>10?m.min:'0'+m.min;
// var mSec = m.sec>10?m.sec:'0'+m.sec;
// var mTime = (m.hour>=12)?m.hour-12+':'+min+'PM':m.hour+':'+min+' AM';
// var hDate = helpers.humanDate(new Date(m.year,m.month-1,m.day,m.hour,parseInt(m.min),parseInt(m.sec)));
var det =function(){
var name = m.hasOwnProperty("to")?"<span onclick='showConversation(this)'>me, <em class='details'>"+m.to+"</em></span>":"<span onclick='showConversation(this)' class='details'><em>"+m.f+"</em></span>";
if(!m.m.p) return name;
if(!m.m.p.hasOwnProperty("pic")) return name;
if(m.m.p.hasOwnProperty("pic")){
if(m.hasOwnProperty("to"))return '<a href="/editprofile.html"><img class="img-span" src="'+m.m.p.pic+'"/></a>' + name;
return '<img onclick="showContact(this)" class="img-span" src="'+m.m.p.pic+'"/>' + name;
}
return '';
};
var msg = helpers.output(m.m.m);
save(m.f,"sent");
var ms = '<div class="messageBody" data-to="'+m.f+'"><hr style="border-color:#fff; margin-bottom:0px;"/><p><span>'+det()+'</span></p><span>'+msg+'</span><p><button onclick="addCommentBox(this)">reply</button></p></div></div>';
return ms;
}
};
var signUpClick = function(){
helpers.hide(splashDiv);
formDiv.innerHTML = domElements.signUpForm;
helpers.show(formDiv);
};
var loginClick = function(){
helpers.hide(splashDiv);
formDiv.innerHTML= domElements.loginForm;
helpers.show(formDiv);
};
var submitAjax = function(e,f){
e.preventDefault();
var fData = helpers.serializeTextFields(f);
helpers.ajax(helpers.buildAjaxPostObject(f,fData));
};
var checkUser = function(e){
var submitButton = helpers.id("submitButton");
var message = helpers.id("message");
submitButton.disabled = true;
if(!e.value) return;
var ajaxObject = {
url: '/checkuser?name='+e.value,
method: 'GET',
successCallback:function(response){
if(JSON.parse(response).available){
submitButton.disabled = false;
return;
}
else{
submitButton.disabled = true;
message.innerHTML = "The username is taken";
}
}
};
helpers.ajax(ajaxObject);
};
function check(e){
btnSend.disabled = true;
if(!e.value) return;
var ajaxObject = {
url: '/checkuser?name='+e.value,
method: 'GET',
successCallback:function(response){
if(JSON.parse(response).available){
return;
}
else{
btnSend.disabled = false;
}
}
};
helpers.ajax(ajaxObject);
}
var clearMessages = function(){
var message = helpers.id("message");
message.innerHTML = '';
};
var showUnread = function(e){
helpers.hide(e);
helpers.buildMessages();
};
var search = function(e){
var term = e.value;
var searchResult = helpers.id("searchResult");
searchResult.innerHTML = '';
if(term.length>=2){
var res = searchTerm("sent",term.slice(1,term.length).trim());
searchResult.innerHTML = '<ul style="list-style:none">'+res+'</ul>';
}
};
function searchTerm(key,term){
var items = JSON.parse(localStorage.getItem(key));
var length = items.length;
var i = 0;
var li = '';
for(i;i<length;i++){
if(items[i].indexOf(term)!=-1) li+='<li class="details" data-to="'+items[i]+'"onclick="showConversation(this)">'+items[i]+'</li>';
}
return li;
}
function autoGrow (oField) {
if (oField.scrollHeight > oField.clientHeight) {
oField.style.height = oField.scrollHeight + "px";
}
};
function addCommentBox(e){
e.parentNode.innerHTML = domElements.commentBox;
};
function removeCommentBox(e){
e.parentNode.parentNode.innerHTML = '<button onclick = "addCommentBox(this)">reply</button>';
};
function send(e){
var to = document.getElementsByName("to")[0].value;
var temp = document.createElement("div");
temp.innerHTML = document.getElementsByName("message")[0].value;
var message = temp.innerText||temp.textContent;
if(!message){
e.parentNode.parentNode.innerHTML += '<p>The message can not be empty</p>';
return;
}
var messagePacket = {"to":to, "m":{m:message}};
var messageProfile = buildProfile(to,messagePacket);
socket.send(JSON.stringify(messageProfile));
var packet = helpers.saveMessage(buildDate(messagePacket),to);
save(to,"sent");
messages.innerHTML = domElements.incomingMessage(packet)+messages.innerHTML;
showActivity();
return;
};
function reply(e){
var parent = e.parentNode.parentNode.parentNode;
var to = parent.getAttribute("data-to");
var sendError = helpers.id("sendError");
if(sendError)helpers.hide(sendError);
var temp = document.createElement("div");
temp.innerHTML = document.getElementsByName("reply")[0].value;
var message = temp.innerText||temp.textContent;
if(!message){
e.parentNode.parentNode.innerHTML += '<p>The message can not be empty</p>';
return;
}
var messagePacket = {"to":to, "m":{m:message}};
var messageProfile = buildProfile(to,messagePacket);
socket.send(JSON.stringify(messageProfile));
e.parentNode.parentNode.innerHTML = '<button onclick = "addCommentBox(this)">reply</button>';
var packet= helpers.saveMessage(buildDate(messagePacket),to);
messages.innerHTML = domElements.incomingMessage(packet)+messages.innerHTML;
showActivity();
menu.scrollIntoView();
return;
};
function buildProfile(to,messagePacket){
if(!prf){
messagePacket.m.p = null;
return messagePacket;
}
var p = {"n":prf.name,"pic":prf.pic,"a":prf.about};
messagePacket.m.p = p;
return messagePacket;
return messagePacket;
};
function save(item,key){
var exists = localStorage.getItem(key);
if(!exists && item){
var a = [];
a.push(item);
exists = JSON.stringify(a);
localStorage.setItem(key,exists);
return;
}
if(exists && item){
var parsed = JSON.parse(exists);
if(parsed.indexOf(item)<0){
parsed.push(item);
localStorage.setItem(key,JSON.stringify(parsed));
}
return;
}
}
function buildDate(messagePacket){
var date = new Date();
messagePacket.month = date.getMonth()+1;
messagePacket.day = date.getDate();
messagePacket.year = date.getFullYear();
messagePacket.min = date.getMinutes();
messagePacket.hour = date.getHours();
messagePacket.sec = date.getSeconds();
return messagePacket;
}
function showConversation(e){
var to = e.getAttribute("data-to")
||e.parentNode.parentNode.parentNode.getAttribute("data-to")
||e.parentNode.parentNode.getAttribute("data-to");
sIn.value='';
helpers.id("searchResult").innerHTML='';
helpers.hideM([sendMessage,messages,contactDiv]);
helpers.show(conversation);
buildMessages(to);
};
function buildMessages(to){
var mStore = getStore('messages','readonly');
var mIndex = mStore.index("between");
var keyRange = IDBKeyRange.only(to);
var cursor = mIndex.openCursor(keyRange,'prev');
var count = 0;
var mStr='';
cursor.onsuccess = function(e){
var item = e.target.result;
if(item && count!=20){
item.continue();
mStr = mStr + domElements.incomingMessage(item.value);
count++;
}
if(!item||count===20){
var pSpan = '<span class="details" data-to="'+to+'" onclick=showContact(this)>'+to+'</span>';
var heading = '<h1 class="center-div">Your conversation with '+pSpan+'</h1>';
var needMore = count===20?'<p style="text-align:center" class="details" onclick="moreBIndex('+1+",'"+to+"',this)"+'">more</p>':'';
conversation.innerHTML = heading+mStr+needMore;
menu.scrollIntoView();
}
};
}
function moreBIndex(end,to,e){
helpers.hide(e);
var messageStore = getStore('messages','readonly');
var mIndex = messageStore.index("between");
var count = 0;
var mStr =[];
var keyRange = IDBKeyRange.only(to);
var cursor = mIndex.openCursor(keyRange,'prev');
var skip = (end*20);
var nextCount = 20*(end+1);
cursor.onsuccess = function(e){
var cursor = e.target.result;
if(count===nextCount||!cursor){
console.log(cursor);
var needMore = count>=nextCount?function(){
end++;
return '<p style="text-align:center" class="details" onclick="moreBIndex('+end+",'"+to+"',this)"+'">more</p>';
}():'';
conversation.innerHTML = conversation.innerHTML+ mStr.join('')+needMore;
return;
}
if(cursor){
if(count>=skip) mStr.push(domElements.incomingMessage(cursor.value));
cursor.continue();
count++;
}
};
}
function showContact(e){
helpers.hideM([sendMessage,messages,conversation]);
helpers.show(contactDiv);
var of = e.parentNode.parentNode.parentNode.getAttribute("data-to")
||e.getAttribute("data-to");
buildContactProfile(of,e);
}
function buildContactProfile(of,e){
var mStore = getStore('messages','readonly');
var mIndex = mStore.index("profile");
var keyRange = IDBKeyRange.only(of);
var cursor = mIndex.openCursor(keyRange,'prev');
cursor.onsuccess = function(e){
var item = e.target.result.value;
contactDiv.innerHTML='';
if(item.m.p.hasOwnProperty("pic"))contactDiv.innerHTML = contactDiv.innerHTML+ "<img src = '"+item.m.p.pic+"'/>";
contactDiv.innerHTML = contactDiv.innerHTML+ '<p class="details" onclick="showConversation(this)" data-to="'+of+'">user: ' +of+'</p>';
if(item.m.p.hasOwnProperty("n")) contactDiv.innerHTML = contactDiv.innerHTML + '<p>Name: ' +item.m.p.n+'</p>';
if(item.m.p.hasOwnProperty("a")){
var about = item.m.p.a;
var temp = document.createElement("div");
temp.innerHTML = about;
var sanatized = temp.innerText||temp.textContent;
contactDiv.innerHTML = contactDiv.innerHTML + '<p>about: '+helpers.output(sanatized)+'</p><hr>';
}
};
}
function messageBox(){
helpers.hideM([messages,conversation,contactDiv]);
sendMessage.innerHTML = domElements.sendMessage;
helpers.show(sendMessage);
};
function showActivity(){
helpers.hideM([sendMessage,conversation,contactDiv]);
helpers.show(messages);
menu.scrollIntoView();
};
function morePagesIndex(end,e){
helpers.hide(e);
var messageStore = getStore('messages','readonly');
var count = 0;
var mStr =[];
console.log(typeof mStr);
messageStore.openCursor().onsuccess = function(e){
var cursor = e.target.result;
if(end>20)cursor.skip(20-end);
console.log(cursor.key);
if(count===end-1||!cursor){
if(!count){
return;
}
if(count){
var needMore = count===20?'<p style="text-align:center" class="details" onclick="morePagesIndex('+cursor.key+',this)">more</p>':'';
messages.innerHTML = messages.innerHTML+ mStr.reverse().join('')+needMore;
return;
}
}
if(cursor){
mStr.push(domElements.incomingMessage(cursor.value));
cursor.continue();
count++;
}
};
}
|
(function() {
function keywords(str) {
var obj = {}, words = str.split(" ");
for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
return obj;
}
function heredoc(delim) {
return function(stream, state) {
if (stream.match(delim)) state.tokenize = null;
else stream.skipToEnd();
return "string";
}
}
var phpConfig = {
name: "clike",
keywords: keywords("abstract and array as break case catch class clone const continue declare default " +
"do else elseif enddeclare endfor endforeach endif endswitch endwhile extends final " +
"for foreach function global goto if implements interface instanceof namespace " +
"new or private protected public static switch throw trait try use var while xor " +
"die echo empty exit eval include include_once isset list require require_once return " +
"print unset __halt_compiler self static parent"),
blockKeywords: keywords("catch do else elseif for foreach if switch try while"),
atoms: keywords("true false null TRUE FALSE NULL"),
multiLineStrings: true,
hooks: {
"$": function(stream, state) {
stream.eatWhile(/[\w\$_]/);
return "variable-2";
},
"<": function(stream, state) {
if (stream.match(/<</)) {
stream.eatWhile(/[\w\.]/);
state.tokenize = heredoc(stream.current().slice(3));
return state.tokenize(stream, state);
}
return false;
},
"#": function(stream, state) {
while (!stream.eol() && !stream.match("?>", false)) stream.next();
return "comment";
},
"/": function(stream, state) {
if (stream.eat("/")) {
while (!stream.eol() && !stream.match("?>", false)) stream.next();
return "comment";
}
return false;
}
}
};
CodeMirror.defineMode("php", function(config, parserConfig) {
var htmlMode = CodeMirror.getMode(config, {name: "xml", htmlMode: true});
var jsMode = CodeMirror.getMode(config, "javascript");
var cssMode = CodeMirror.getMode(config, "css");
var phpMode = CodeMirror.getMode(config, phpConfig);
function dispatch(stream, state) { // TODO open PHP inside text/css
var isPHP = state.mode == "php";
if (stream.sol() && state.pending != '"') state.pending = null;
if (state.curMode == htmlMode) {
if (stream.match(/^<\?\w*/)) {
state.curMode = phpMode;
state.curState = state.php;
state.curClose = "?>";
state.mode = "php";
return "meta";
}
if (state.pending == '"') {
while (!stream.eol() && stream.next() != '"') {}
var style = "string";
} else if (state.pending && stream.pos < state.pending.end) {
stream.pos = state.pending.end;
var style = state.pending.style;
} else {
var style = htmlMode.token(stream, state.curState);
}
state.pending = null;
var cur = stream.current(), openPHP = cur.search(/<\?/);
if (openPHP != -1) {
if (style == "string" && /\"$/.test(cur) && !/\?>/.test(cur)) state.pending = '"';
else state.pending = {end: stream.pos, style: style};
stream.backUp(cur.length - openPHP);
} else if (style == "tag" && stream.current() == ">" && state.curState.context) {
if (/^script$/i.test(state.curState.context.tagName)) {
state.curMode = jsMode;
state.curState = jsMode.startState(htmlMode.indent(state.curState, ""));
state.curClose = /^<\/\s*script\s*>/i;
state.mode = "javascript";
}
else if (/^style$/i.test(state.curState.context.tagName)) {
state.curMode = cssMode;
state.curState = cssMode.startState(htmlMode.indent(state.curState, ""));
state.curClose = /^<\/\s*style\s*>/i;
state.mode = "css";
}
}
return style;
} else if ((!isPHP || state.php.tokenize == null) &&
stream.match(state.curClose, isPHP)) {
state.curMode = htmlMode;
state.curState = state.html;
state.curClose = null;
state.mode = "html";
if (isPHP) return "meta";
else return dispatch(stream, state);
} else {
return state.curMode.token(stream, state.curState);
}
}
return {
startState: function() {
var html = htmlMode.startState();
return {html: html,
php: phpMode.startState(),
curMode: parserConfig.startOpen ? phpMode : htmlMode,
curState: parserConfig.startOpen ? phpMode.startState() : html,
curClose: parserConfig.startOpen ? /^\?>/ : null,
mode: parserConfig.startOpen ? "php" : "html",
pending: null}
},
copyState: function(state) {
var html = state.html, htmlNew = CodeMirror.copyState(htmlMode, html),
php = state.php, phpNew = CodeMirror.copyState(phpMode, php), cur;
if (state.curState == html) cur = htmlNew;
else if (state.curState == php) cur = phpNew;
else cur = CodeMirror.copyState(state.curMode, state.curState);
return {html: htmlNew, php: phpNew, curMode: state.curMode, curState: cur,
curClose: state.curClose, mode: state.mode,
pending: state.pending};
},
token: dispatch,
indent: function(state, textAfter) {
if ((state.curMode != phpMode && /^\s*<\//.test(textAfter)) ||
(state.curMode == phpMode && /^\?>/.test(textAfter)))
return htmlMode.indent(state.html, textAfter);
return state.curMode.indent(state.curState, textAfter);
},
electricChars: "/{}:"
}
}, "xml", "clike", "javascript", "css");
CodeMirror.defineMIME("application/x-httpd-php", "php");
CodeMirror.defineMIME("application/x-httpd-php-open", {name: "php", startOpen: true});
CodeMirror.defineMIME("text/x-php", phpConfig);
})();
|
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v25.0.1
* @link http://www.ag-grid.com/
* @license MIT
*/
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
import { Bean } from "../context/context";
import { BeanStub } from "../context/beanStub";
var CellPositionUtils = /** @class */ (function (_super) {
__extends(CellPositionUtils, _super);
function CellPositionUtils() {
return _super !== null && _super.apply(this, arguments) || this;
}
CellPositionUtils.prototype.createId = function (cellPosition) {
var rowIndex = cellPosition.rowIndex, rowPinned = cellPosition.rowPinned, column = cellPosition.column;
return this.createIdFromValues(rowIndex, column, rowPinned);
};
CellPositionUtils.prototype.createIdFromValues = function (rowIndex, column, rowPinned) {
return rowIndex + "." + (rowPinned == null ? 'null' : rowPinned) + "." + column.getId();
};
CellPositionUtils.prototype.equals = function (cellA, cellB) {
var colsMatch = cellA.column === cellB.column;
var floatingMatch = cellA.rowPinned === cellB.rowPinned;
var indexMatch = cellA.rowIndex === cellB.rowIndex;
return colsMatch && floatingMatch && indexMatch;
};
CellPositionUtils = __decorate([
Bean('cellPositionUtils')
], CellPositionUtils);
return CellPositionUtils;
}(BeanStub));
export { CellPositionUtils };
|
'use strict';
var express = require('express'),
router = express.Router(),
authenticateClientToken = require('../middlewares/authenticateClientToken'),
getClientId = require('../middlewares/getClientId'),
ClientAccount = require('models').ClientAccount,
HttpApiError = require('error').HttpApiError;
router.get('/', authenticateClientToken, function(req, res, next) {
var offset = +req.query.offset || 0,
limit = +req.query.limit || 50;
ClientAccount
.findAll({ offset: offset, limit: limit })
.then(function(clientAccounts) {
res.json({
clientAccounts: clientAccounts
});
})
.catch(function(error) {
next(error);
});
});
router.get('/:clientId', authenticateClientToken, getClientId, function(req, res, next) {
ClientAccount
.findOne({
where: { client_id: req.clientId }
})
.then(function(clientAccount) {
if (!clientAccount) {
return res.json({
message: 'No client account has been found with given client id'
});
}
res.json({
clientAccount: clientAccount
});
})
.catch(function(error) {
next(error);
});
});
router.post('/:clientId/deposit', authenticateClientToken, getClientId, function(req, res, next) {
var sum = +req.body.sum;
if (!sum || sum <= 0) {
return next(new HttpApiError(400, 'Invalid sum'));
}
ClientAccount
.findOne({
where: { client_id: req.clientId }
})
.then(function(clientAccount) {
if (!clientAccount) {
return res.json({
message: 'No client account has been found with given client id'
});
}
clientAccount.deposit(sum, function(error, amount) {
if (error) {
return next(error);
}
res.json({
amount: amount
});
});
});
});
router.post('/:clientId/withdraw', authenticateClientToken, getClientId, function(req, res, next) {
var sum = +req.body.sum;
if (!sum || sum <= 0) {
return next(new HttpApiError(400, 'Invalid sum'));
}
ClientAccount
.findOne({
where: { client_id: req.clientId }
})
.then(function(clientAccount) {
if (!clientAccount) {
return res.json({
message: 'No client account has been found with given client id'
});
}
clientAccount.withdraw(sum, function(error, amount) {
if (error) {
return next(error);
}
res.json({
amount: amount
});
});
});
});
module.exports = router;
|
function StopWatchDirective() {
'use strict';
return {
restrict: 'E',
scope: {
startTime: '=',
active: '='
},
template: '{{ vm.timePassed }}',
controller: StopWatchController,
controllerAs: 'vm'
};
}
|
'use strict';
angular.module('mean.users').factory('MeanUser', [ '$rootScope', '$http', '$location', '$stateParams', '$cookies', '$q', '$timeout',
function($rootScope, $http, $location, $stateParams, $cookies, $q, $timeout) {
var self;
function escape(html) {
return String(html)
.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/'/g, ''')
.replace(/</g, '<')
.replace(/>/g, '>');
}
function b64_to_utf8( str ) {
return decodeURIComponent(escape(window.atob( str )));
}
/*function url_base64_decode(str) {
var output = str.replace('-', '+').replace('_', '/');
switch (output.length % 4) {
case 0:
break;
case 2:
output += '==';
break;
case 3:
output += '=';
break;
default:
throw 'Illegal base64url string!';
}
return window.atob(output); //polifyll https://github.com/davidchambers/Base64.js
}*/
function MeanUserKlass(){
this.aclDefer = $q.defer();
this.name = 'users';
this.user = {};
this.acl = this.aclDefer.promise;
this.registerForm = false;
this.loggedin = false;
this.isAdmin = false;
this.loginError = 0;
this.usernameError = null;
this.registerError = null;
this.resetpassworderror = null;
this.validationError = null;
self = this;
$http.get('/api/users/me').success(function(response) {
if(!response && $cookies.get('token') && $cookies.get('redirect')) {
self.onIdentity.bind(self)({
token: $cookies.get('token'),
redirect: $cookies.get('redirect').replace(/^"|"$/g, '')
});
$cookies.remove('token');
$cookies.remove('redirect');
} else {
self.onIdentity.bind(self)(response);
}
});
this.acl.then(function(response) {
self.acl = response;
delete self.aclDefer;
});
}
MeanUserKlass.prototype.onIdentity = function(response) {
if (!response) return;
var encodedUser, user, destination;
if (angular.isDefined(response.token)) {
localStorage.setItem('JWT', response.token);
encodedUser = decodeURI(b64_to_utf8(response.token.split('.')[1]));
user = JSON.parse(encodedUser);
}
destination = angular.isDefined(response.redirect) ? response.redirect : destination;
$cookies.remove('redirect');
this.user = user || response;
this.loggedin = true;
this.loginError = 0;
this.registerError = 0;
this.isAdmin = this.user.roles.indexOf('admin') > -1;
var self = this;
// Add circles info to user
$http.get('/api/circles/mine').success(function(acl) {
if(self.aclDefer) {
self.aclDefer.resolve(acl);
} else {
self.acl = acl;
}
if (destination) {
$location.path(destination);
}
$rootScope.$emit('loggedin');
});
};
MeanUserKlass.prototype.onIdFail = function (response) {
$location.path(response.redirect);
this.loginError = 'Authentication failed.';
this.registerError = response;
this.validationError = response.msg;
this.resetpassworderror = response.msg;
$rootScope.$emit('loginfailed');
$rootScope.$emit('registerfailed');
};
var MeanUser = new MeanUserKlass();
MeanUserKlass.prototype.login = function (user) {
// this is an ugly hack due to mean-admin needs
var destination = $location.path().indexOf('/login') === -1 ? $location.absUrl() : false;
$http.post('/api/login', {
email: user.email,
password: user.password,
redirect: $cookies.get('redirect') || destination
})
.success(this.onIdentity.bind(this))
.error(this.onIdFail.bind(this));
};
MeanUserKlass.prototype.register = function(user) {
$http.post('/api/register', {
email: user.email,
password: user.password,
confirmPassword: user.confirmPassword,
username: user.username,
name: user.name
})
.success(this.onIdentity.bind(this))
.error(this.onIdFail.bind(this));
};
MeanUserKlass.prototype.resetpassword = function(user) {
$http.post('/api/reset/' + $stateParams.tokenId, {
password: user.password,
confirmPassword: user.confirmPassword
})
.success(this.onIdentity.bind(this))
.error(this.onIdFail.bind(this));
};
MeanUserKlass.prototype.forgotpassword = function(user) {
$http.post('/api/forgot-password', {
text: user.email
})
.success(function(response) {
$rootScope.$emit('forgotmailsent', response);
})
.error(this.onIdFail.bind(this));
};
MeanUserKlass.prototype.logout = function(){
this.user = {};
this.loggedin = false;
this.isAdmin = false;
$http.get('/api/logout').success(function(data) {
localStorage.removeItem('JWT');
$rootScope.$emit('logout');
});
};
MeanUserKlass.prototype.checkLoggedin = function() {
var deferred = $q.defer();
// Make an AJAX call to check if the user is logged in
$http.get('/api/loggedin').success(function(user) {
// Authenticated
if (user !== '0') $timeout(deferred.resolve);
// Not Authenticated
else {
$cookies.put('redirect', $location.path());
$timeout(deferred.reject);
$location.url('/auth/login');
}
});
return deferred.promise;
};
MeanUserKlass.prototype.checkLoggedOut = function() {
// Check if the user is not connected
// Initialize a new promise
var deferred = $q.defer();
// Make an AJAX call to check if the user is logged in
$http.get('/api/loggedin').success(function(user) {
// Authenticated
if (user !== '0') {
$timeout(deferred.reject);
$location.url('/');
}
// Not Authenticated
else $timeout(deferred.resolve);
});
return deferred.promise;
};
MeanUserKlass.prototype.checkAdmin = function() {
var deferred = $q.defer();
// Make an AJAX call to check if the user is logged in
$http.get('/api/loggedin').success(function(user) {
// Authenticated
if (user !== '0' && user.roles.indexOf('admin') !== -1) $timeout(deferred.resolve);
// Not Authenticated or not Admin
else {
$timeout(deferred.reject);
$location.url('/');
}
});
return deferred.promise;
};
return MeanUser;
}
]);
|
(function() {
angular
.module('app.services')
.factory('AlertService', AlertService);
AlertService.$inject = ['$ionicPopup'];
// <ion-spinner icon="spiral"></ion-spinner>
function AlertService($ionicPopup) {
service = {
spinner: {
start: start,
stop: stop
}
};
return service;
/*
$ionicPopup.show({
title: 'Enter Wi-Fi Password',
subTitle: 'Please use normal things'
});
var alertPopup = $ionicPopup.alert({
title: 'Don\'t eat that!',
template: 'It might taste good'
});
alertPopup.then(function(res) {
console.log('Thank you for not eating my delicious ice cream cone');
});
*/
function start() {
}
function stop() {
}
}
})();
|
define(["jquery","Hammer","hammerify","Velocity","easing"],function($,Hammer,hammerify,velocity){
// Hardcoded .staggered-list scrollFire
// var staggeredListOptions = [];
// $('ul.staggered-list').each(function (i) {
// var label = 'scrollFire-' + i;
// $(this).addClass(label);
// staggeredListOptions.push({ selector: 'ul.staggered-list.' + label, offset: 200, callback: 'showStaggeredList("ul.staggered-list.' + label + '")'});
// });
// scrollFire(staggeredListOptions);
var swipeLeft = false;
var swipeRight = false;
// Dismissible Collections
$('.dismissable').each(function() {
$(this).hammer({
prevent_default: false
}).bind('pan', function(e) {
if (e.gesture.pointerType === "touch") {
var $this = $(this);
var direction = e.gesture.direction;
var x = e.gesture.deltaX;
var velocityX = e.gesture.velocityX;
$this.velocity({ translateX: x }, {duration: 50, queue: false, easing: 'easeOutQuad'});
if (direction === 4 && (x > ($this.innerWidth() / 2) || velocityX < -0.75)) swipeLeft = true;
if (direction === 2 && (x < (-1 * $this.innerWidth() / 2) || velocityX > 0.75)) swipeRight = true;
}
}).bind('panend', function(e) {
if (Math.abs(e.gesture.deltaX) < ($(this).innerWidth() / 2)) {
swipeRight = false;
swipeLeft = false;
}
if (e.gesture.pointerType === "touch") {
var $this = $(this);
if (swipeLeft || swipeRight) {
var fullWidth;
if (swipeLeft) { fullWidth = $this.innerWidth(); } else { fullWidth = -1 * $this.innerWidth(); }
$this.velocity({ translateX: fullWidth }, {duration: 100, queue: false, easing: 'easeOutQuad', complete: function() {
$this.css('border', 'none');
$this.velocity({height: 0, padding: 0}, {duration: 200, queue: false, easing: 'easeOutQuad', complete: function(){ $this.remove();}});
}});
} else $this.velocity({ translateX: 0}, {duration: 100, queue: false, easing: 'easeOutQuad'});
swipeLeft = false;
swipeRight = false;
}
});
// time = 0
// // Vertical Staggered list
// $('ul.staggered-list.vertical li').velocity(
// { translateY: "100px"},
// { duration: 0 });
// $('ul.staggered-list.vertical li').each(function() {
// $(this).velocity(
// { opacity: "1", translateY: "0"},
// { duration: 800, delay: time, easing: [60, 25] });
// time += 120;
// });
// // Fade in and Scale
// $('.fade-in.scale').velocity(
// { scaleX: .4, scaleY: .4, translateX: -600},
// { duration: 0});
// $('.fade-in').each(function() {
// $(this).velocity(
// { opacity: "1", scaleX: 1, scaleY: 1, translateX: 0},
// { duration: 800, easing: [60, 10] });
// });
});
});
|
import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M20.49 3.51c-.56-.56-2.15-.97-4.16-.97-3.08 0-7.15.96-9.98 3.79-4.69 4.7-4.25 12.74-2.84 14.16.56.56 2.15.97 4.16.97 3.08 0 7.15-.96 9.98-3.79 4.69-4.7 4.25-12.74 2.84-14.16zM7.76 7.76c2.64-2.64 6.35-3.12 8.03-3.19-2.05.94-4.46 2.45-6.61 4.61-2.16 2.16-3.67 4.58-4.61 6.63.09-2.48.87-5.74 3.19-8.05zm8.48 8.48c-2.64 2.64-6.35 3.12-8.03 3.19 2.05-.94 4.46-2.45 6.61-4.61 2.16-2.16 3.67-4.58 4.62-6.63-.1 2.48-.88 5.74-3.2 8.05z" />
, 'SportsRugbyRounded');
|
/*
* This file is part of gorilla-repl. Copyright (C) 2014-, Jony Hudson.
*
* gorilla-repl is licenced to you under the MIT licence. See the file LICENCE.txt for full details.
*/
var clojureCompleter = function (cm, options) {
// The gist of this is lifted from the auto-completion modes included with CodeMirror.
var cur = cm.getCursor();
var token = cm.getTokenAt(cur);
var word = token.string;
var start = token.start;
var end = token.end;
// we need to know what namespace the user is currently working in, which we get from the evaluator module
var ns = evaluator.currentNamespace;
// This call must be synchronous as CodeMirror expects a reply right now. This stops us from just sending an
// nREPL message, which is always async, hence the HTTP API endpoint.
var completions = [];
$.ajax({
type: "GET",
url: "/completions",
data: {stub: word, ns: ns},
async: false,
success: function (data) {
completions = data.completions;
}
});
return {
list: completions,
from: CodeMirror.Pos(cur.line, start),
to: CodeMirror.Pos(cur.line, end)
};
};
|
export const initialState = {
kategorieFilter: '',
textFilter: '',
};
export const createFilterableReducer = (actionPrefix) => (state = initialState, action) => {
switch (action.type) {
case `${actionPrefix}_KATEGORIE_FILTER_CHANGE`:
if (state.kategorieFilter === action.typKategorie) {
return { ...state, kategorieFilter: '' };
}
return { ...state, kategorieFilter: action.typKategorie };
case `${actionPrefix}_TEXT_FILTER_CHANGE`:
return { ...state, textFilter: action.textFilter.toLowerCase() };
default:
return state;
}
};
|
export const VALIDATE_JWT = 'VALIDATE_JWT'
export const SESSIONSTORAGE_JWT = 'fluxo.jwt'
|
var RelationChart = function(selector,options) {
var me = this;
this.options = {
selector:null,
canvasWith:600,
canvasHeight:800,
// canvas style
style:'',
drawStyle:{}
};
this.characters = [];
this.relations = [];
if(typeof selector === 'string') {
this.options.selector = selector;
}
this.setOptions(options);
me.canvas = document.querySelector(this.options.selector);
me.canvas.setAttribute('width',parseInt(this.options.canvasWidth, 10)||800);
me.canvas.setAttribute('height',parseInt(this.options.canvasWidth, 10)||600);
me.canvas.style = this.options.style;
me.ctx = me.canvas.getContext('2d');
me.ctx.font = '18px SimSun';
me.ctx.textAlign = 'center';
me.ctx.textBaseline = 'middle';
me.ctx.strokeStyle = '#333';
me.ctx.lineWidth = 4;
me.ctx.fillStyle = '#333';
this.setBehavior(new CircleBehavior(this.options.drawStyle));
me._animationID = -1;
// canvas event handle
me.isMouseDown = false;
me.mouse = {};
me.canvas.onmousedown = function(event) {
me.isMouseDown = true;
for (let i in me.characters) {
let pos = me.windowToCanvas(me.canvas,event.clientX,event.clientY);
if (me.behavior.isIn(pos.x,pos.y,me.characters[i])) {
console.log(me.characters[i].name+" be clicked.");
me.selectedCharacter = me.characters[i];
me.mouse.pos={x:event.clientX,y:event.clientY};
break;
}
}
event.preventDefault();
}
me.canvas.onmousemove = function(event) {
if(me.isMouseDown) {
if(me.selectedCharacter) {
me.selectedCharacter.x += (event.clientX-me.mouse.pos.x);
me.selectedCharacter.y += (event.clientY-me.mouse.pos.y);
me.mouse.pos={x:event.clientX,y:event.clientY};
me.isUpdated = true;
}
}
event.preventDefault();
}
me.canvas.onmouseup = function(event) {
console.log('onmouseup');
me.isMouseDown = false;
console.log('cancel name='+(me.selectedCharacter?me.selectedCharacter.name:'none'));
me.selectedCharacter = null;
event.preventDefault();
}
return me;
}
RelationChart.prototype = {
setOptions : function (options) {
if(!options) return;
for (var i in options) {
if (this.options[i] !== undefined) {
this.options[i] = options[i];
}
}
},
addCharacter: function (character) {
if (!character) {
return;
}
let x = this.canvas.width/2;
let y = this.canvas.height/2;
let xw = this.ctx.measureText("X").width;
if (character.constructor == Array) {
let count = character.length;
let stepAngle = 2*Math.PI/count;
// console.log('w='+x+' y='+y);
let radius = Math.min(this.canvas.width,this.canvas.height)*0.3;
let t = 0;
for (var i in character) {
if (character[i].name) {
let angle = t*stepAngle-Math.PI/2;
t++;
character[i].x=x+radius*Math.cos(angle);
character[i].y=y+radius*Math.sin(angle);
character[i].radius=this.ctx.measureText(character[i].name).width/2+xw;
this.characters.push(character[i]);
}
}
} else if (character && character.name) {
character.x=x;
character.y=y;
character.radius=this.ctx.measureText(character.name).width/2+xw;
this.characters.push(character);
}
this.isUpdated = true;
if(this._animationID === -1) {
var self = this;
requestAnimationFrame(function(t){self.draw.call(self,t)});
}
},
addRelation: function (character,target,desc) {
var isExist = false;
for (var i = this.relations.length - 1; i >= 0; i--) {
if(this.relations[i].src.name==character && this.relations[i].dst.name == target) {
this.relations[i].desc = desc;
isExist = true;
break;
}
}
if(!isExist) {
var src = this.characters.find(function(elt){return elt.name == character;});
var dst = this.characters.find(function(elt){return elt.name == target;});
src && dst ? this.relations.push({src:src, dst:dst, desc:desc}) : null;
}
this.isUpdated = true;
},
windowToCanvas: function (canvas,x,y) {
var bbox = canvas.getBoundingClientRect();
return {x:(x-bbox.left)*(canvas.width/bbox.width),y:(y-bbox.top)*(canvas.height/bbox.height)};
},
setBehavior : function (behavior) {
this.behavior = behavior;
},
draw: function (time) {
if(this.isUpdated) {
this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height);
let pos1 = {}, pos2={};
for(var k in this.relations) {
pos1 = {x:this.relations[k].src.x, y:this.relations[k].src.y};
pos2 = {x:this.relations[k].dst.x, y:this.relations[k].dst.y};
this.behavior.drawRelation(this.ctx, pos1, pos2, this.relations[k].desc);
}
for (let j in this.characters) {
this.behavior.drawCharacter(this.ctx, this.characters[j]);
}
this.isUpdated = false;
}
var self = this;
requestAnimationFrame(function(t){self.draw.call(self,t)});
}
}
RelationChart.Theme = {
}
RelationChart.defaultTheme = {
categorys : []
}
var CircleBehavior = function (style) {
// context style
this.style = {
characterFont : '18px SimSun',
characterFontColor : '#FFFFFF',
characterBackgroupColor : '18px SimSun',
characterStrokeStyle : '#2d78f4',
characterFillStyle : '#3385ff',
characterLineWidth : 4,
relationTextBaseline : 'middle',
relationStrokeStyle : '#376956',
relationFillStyle : '#DEA681',
relationLineWidth : 4,
}
for (var i in this.style) {
if(style[i] != undefined) {
this.style[i] = style[i];
}
}
};
CircleBehavior.prototype = {
drawCharacter : function (context,character) {
context.strokeStyle = this.style.characterStrokeStyle;
context.fillStyle = this.style.characterFillStyle;
context.lineWidth = this.style.characterLineWidth;
context.beginPath();
context.arc(character.x,character.y,character.radius,0,2*Math.PI);
context.fill();
context.stroke();
context.fillStyle = this.style.characterFontColor;
context.textBaseline = 'middle';
context.fillText(character.name,character.x,character.y);
},
drawRelation : function (context,pos1,pos2,desc) {
context.beginPath();
context.strokeStyle = this.style.relationStrokeStyle;
context.moveTo(pos1.x,pos1.y);
context.lineTo(pos2.x,pos2.y);
context.stroke();
context.fillStyle = this.style.relationFillStyle;
context.textBaseline = this.style.relationTextBaseline;
context.fillText(desc,(pos1.x+pos2.x)/2,(pos1.y+pos2.y)/2);
},
isIn : function (x,y,character) {
var x = character.x-x;
var y = character.y-y;
return (x*x+y*y) < character.radius*character.radius;
}
}
|
import assert from 'assert';
import { editAndSaveLinkInstance } from '../utils';
describe('Edit link instance', () => {
it('Can create and edit link instance', () => {
browser.url('/login');
browser.waitForExist('#login-email');
browser
.setValue('#login-email', 'edit@test.ing')
.setValue('#login-password input', 'test1')
.click('form button');
browser.waitForExist('#logout-link');
browser.url('/link-instance');
browser.pause(1000);
editAndSaveLinkInstance('train', 'research', '321', '120.5', 'RUB', 'general desc', []);
const url = browser.getUrl();
const urlParts = url.split('/');
const uuid = urlParts[urlParts.length - 1];
browser.url(`/link-instance/${uuid}/edit`);
browser.pause(1000);
editAndSaveLinkInstance('bus', 'experience', '123', '110', 'EUR', 'other desc');
});
it('Can delete link instance', () => {
browser.url('/login');
browser.waitForExist('#login-email');
browser
.setValue('#login-email', 'edit@test.ing')
.setValue('#login-password input', 'test1')
.click('form button');
browser.waitForExist('#logout-link');
browser.url('/link-instance');
browser.pause(1000);
editAndSaveLinkInstance('train', 'research', '321', '120.5', 'RUB', 'general desc', []);
const url = browser.getUrl();
const urlParts = url.split('/');
const uuid = urlParts[urlParts.length - 1];
browser.url(`/link-instance/${uuid}/edit`);
browser.pause(1000);
browser.click('#delete-button');
browser.waitForExist('div.deleted');
});
});
|
/**
* details-shim.js
* A pure JavaScript (no dependencies) solution to make HTML5
* Details/Summary tags work in unsupportive browsers
*
* Copyright (c) 2013 Tyler Uebele
* Released under the MIT license. See included LICENSE.txt
* or http://opensource.org/licenses/MIT
*
* latest version available at https://github.com/tyleruebele/details-shim
*/
/**
* Enable proper operation of <details> tags in unsupportive browsers
*/
/**
* Modified for require js
**/
define ([], function () {
function details_shim() {
//Because <details> must include a <summary>,
// collecting <summary> tags collects *valid* <details> tags
var Summaries = document.getElementsByTagName('summary');
for (var i = 0; i < Summaries.length; i++) {
if (!Summaries[i].parentNode
//sanity check, parent node should be a <details> tag
|| 'details' != Summaries[i].parentNode.tagName.toLowerCase()
//only run in browsers that don't support <details> natively
|| 'boolean' == typeof Summaries[i].parentNode.open
) {
continue;
}
var Details = Summaries[i].parentNode;
// Prevent repeat processing
if (Details.hasAttribute('data-open')) {
continue;
}
//Set initial class according to `open` attribute
var state = Details.outerHTML
// OR older firefox doesn't have .outerHTML
|| new XMLSerializer().serializeToString(Details);
state = state.substring(0, state.indexOf('>'));
//Read: There is an open attribute, and it's not explicitly empty
state = (-1 != state.indexOf('open') && -1 == state.indexOf('open=""'))
? 'open'
: 'closed'
;
Details.setAttribute('data-open', state);
Details.className += ' ' + state;
//Add onclick handler to toggle visibility class
Summaries[i].addEventListener('click', function () {
//current state
var state = this.parentNode.getAttribute('data-open');
//new state
state = state == 'open' ? 'closed' : 'open';
this.parentNode.setAttribute('data-open', state);
//replace previous open/close class
this.parentNode.className = this.parentNode.className
.replace(/\bopen\b|\bclosed\b/g, ' ') + ' ' + state;
});
//wrap text nodes in span to expose them to css
for (var j = 0; j < Details.childNodes.length; j++) {
if (Details.childNodes[j].nodeType == 3
&& /[^\s]/.test(Details.childNodes[j].data)
) {
var span = document.createElement('span');
var text = Details.childNodes[j];
Details.insertBefore(span, text);
Details.removeChild(text);
span.appendChild(text);
}
}
} // for(Summaries)
} // details_shim()
//Run details_shim() when the page loads
details_shim();
/*window.addEventListener
? window.addEventListener('load', details_shim, false)
: window.attachEvent && window.attachEvent('onload', details_shim);*/
});
|
/*
This script depends on Node.js and Express
Install node.js form www.node.org
Install Express by Windows Command Prompt
Type "npm install Express"
*/
var express = require('express');
var app = express();
port = process.argv[2] || 8000;
app.configure(function () {
app.use(
"/", //the URL throught which you want to access to you static content
express.static(__dirname) //where your static content is located in your filesystem
);
});
app.listen(port); //the port you want to use
console.log("Express server running at => http://localhost:" + port + "/\nCTRL + C to shutdown");
|
//stock_prices_archive table Schema
//--------------------------------
module.exports = function (knex) {
return knex.schema.createTableIfNotExists('stock_prices_archive', function (table) {
table.increments('archive_id').primary();
table.integer('stock_id')
.references('s_id')
.inTable('stocks');
table.string('symbol');
table.string('bid');
table.string('ask');
table.string('change');
table.string('days_low');
table.string('days_high');
table.string('year_low');
table.string('year_high');
table.string('earnings_share');
table.string('eps_estimate_current_year');
table.string('eps_estimate_next_year');
table.string('market_capitalization');
table.string('ebitda');
table.string('days_range');
table.string('open');
table.string('previous_close');
table.string('pe_ratio');
table.string('peg_ratio');
table.string('percent_change');
table.string('volume');
table.string('timestamp');
});
};
|
// This is the base server file. All our modules are loaded here and all the different routes are defined.
// Actual page logic happens in the controllers
/*
* -------- SET UP MODULES/VARS
*/
"use strict";
// Set up express
var express = require('express');
var app = express();
// Set up websockets
var expressWs = require('express-ws')(app);
// Set up session handler
var session = require('express-session');
app.use(session({
secret: 'NotSoSecretKey',
maxAge: 3600000, // 1 hour
resave: false,
saveUninitialized: false
}));
// Set up connect-flash (for flash messages)
var flash = require('connect-flash');
app.use(flash());
// Set up csurf (for csrf protection)
var csrf = require('csurf');
var csrfProtection = csrf({ cookie: false });
// Set up nunjucks (templating engine)
var nunjucks = require('nunjucks');
var env = nunjucks.configure({
autoescape: true,
express: app,
//watch: true // Watch templates for changes. Useful for dev, remove for production though
});
env.addFilter('empty', function(object) { // Needed a way to check if an object was empty
return Object.keys(object).length === 0;
});
// Set up mongojs (like mongodb but cleaner code)
var mongojs = require('mongojs');
var db = mongojs('localhost:27017/GoPro');
// Set up body-parser (for form data reading)
var bodyParser = require('body-parser');
var parseForm = bodyParser.urlencoded({extended: false});
// Load all our controllers
var controllers = require('auto-loader').load(__dirname + '/controllers');
// Load our routes
var routes = require('./routes.js');
// Access control
var access = require('./access.js');
function requiresUser(url) {
for (var pattern of access.user)
if (url.match(pattern))
return true;
}
function requiresAdmin(url) {
for (var pattern of access.admin)
if (url.match(pattern))
return true;
}
// The port we will run on
var port = 30092;
/*
* -------- GLOBAL REQUEST LOGIC
*/
app.use(function(request, response, next) {
// Handle access control
var url = request.url;
if (!request.session.userType && (requiresUser(url) || requiresAdmin(url))) {
if (request.ws) { // if this is a websocket request, just send a 403
response.status(403).send('You don\'t have permission to access that page');
return;
}
// Otherwise, redirect to login
request.session.redirectOnLogin = url;
request.flash('info', 'Please log in to access that page');
response.redirect(routes.login);
return;
} else if (request.session.userType < 2 && requiresAdmin(url)) {
response.status(403).send('You don\'t have permission to access that page');
return;
}
env.addGlobal('url', request.url);
env.addGlobal('flashes', request.flash());
env.addGlobal('routes', routes);
env.addGlobal('session', request.session);
next();
});
// Our express-ws package interfere with routes that have params due to the fact that it adds .websocket to the end of
// URLs. This causes matches on URLs that shouldn't match, so we want to avoid this.
//
// !!!!! Make sure you add this as the first middle-ware function to any routes that have params (including ws routes).
function hasParams(req, res, next) {
for (var param in req.params) {
if (!req.params.hasOwnProperty(param))
continue; // skip loop if the property is from prototype
if (req.params[param] === '.websocket') {
next('route');
return;
}
}
next();
}
/*
* -------- SET UP TASKS THAT RUN PERIODICALLY
*/
// Cleanup lobbies & games every 60 seconds
setInterval(function () {
controllers.LobbyController.cleanupLobbies();
}, 60000);
/*
* -------- SET UP ROUTES
*/
// Serve the static content (libraries, etc.)
app.use(express.static('public'));
// Base route. Right now this is just the base page
app.get(routes.home, csrfProtection, function(request, response) {
response.render('views/base.html.njk');
});
///////////////// Admin pages disabled since they're outdated and we never bothered to update them
//// Admin page.
//app.get(routes.admin, csrfProtection, function(request, response) {
// controllers.AdminController.indexAction(request, response, db);
//});
//
//// Admin page.
//app.post(routes.adminCreateAccount, csrfProtection, function(request, response) {
// controllers.AdminController.createAccountAction(request, response, db);
//});
//
//// Remove all users POST request
//app.post(routes.removeAllAccounts, parseForm, csrfProtection, function(request, response) {
// controllers.AdminController.removeUsersAction(request, response, db);
//});
// Login page
app.get(routes.login, csrfProtection, function(request, response) {
controllers.LoginController.indexAction(request, response, db);
});
// Login POST request
app.post(routes.login, parseForm, csrfProtection, function(request, response) {
controllers.LoginController.loginAction(request, response, db);
});
// Logout GET request
app.get(routes.logout, function(request, response) {
controllers.LoginController.logoutAction(request, response);
});
// Add user POST request
app.post(routes.createAccount, parseForm, csrfProtection, function(request, response) {
controllers.LoginController.addAccountAction(request, response, db);
});
// Account page
app.get(routes.account, csrfProtection, function(request,response){
controllers.AccountController.indexAction(request, response, db);
});
// Update account details
app.post(routes.updateAccount, parseForm, csrfProtection, function(request, response) {
controllers.AccountController.updateAction(request, response, db);
});
// Lobbies
app.get(routes.lobbies, csrfProtection, function(request, response) {
controllers.LobbyController.indexAction(request, response);
});
// Create lobby
app.post(routes.createLobby, parseForm, csrfProtection, function(request, response) {
controllers.LobbyController.addAction(request, response);
});
// Join lobby
app.get(routes.joinLobby, hasParams, csrfProtection, function(request, response) {
controllers.LobbyController.joinAction(request, response);
});
// Lobby websocket request
app.ws(routes.joinLobby, hasParams, function(ws, request) {
controllers.LobbyController.wsAction(ws, request, db);
});
// Quick Game
app.get(routes.quickGame, csrfProtection, function(request, response) {
controllers.QuickGameController.indexAction(request, response);
});
// Hotseat game start
app.post(routes.hotseatGame, parseForm, csrfProtection, function(request, response) {
controllers.GameController.hotseatGameAction(request, response);
});
// Hotseat game websocket request
app.ws(routes.joinHotseatGame, hasParams, function(ws, request) {
controllers.GameController.hotseatWsAction(ws, request);
});
// AI game start
app.post(routes.aiGame, parseForm, csrfProtection, function(request, response) {
controllers.GameController.aiGameAction(request, response);
});
// AI game websocket request
app.ws(routes.joinAiGame, hasParams, function(ws, request) {
controllers.GameController.wsAction(ws, request, db);
});
// Lobby game start
app.get(routes.joinGame, hasParams, function (request, response) {
controllers.GameController.lobbyGameAction(request, response);
});
// Lobby game websocket
app.ws(routes.joinGame, hasParams, function (ws, request) {
controllers.GameController.wsAction(ws, request, db);
});
// Rules
app.get(routes.rules, function(request, response) {
response.render('views/rules.html.njk');
});
// The leaderboards controller
app.get(routes.leaderboards, function(request, response) {
controllers.LeaderboardController.indexAction(request, response, db);
});
/*
* -------- ERROR HANDLING
*/
// Handle bad CSRF token
app.use(function (err, req, res, next) {
if (err.code !== 'EBADCSRFTOKEN')
return next(err);
res.status(403).send('Invalid form submission attempted! You aren\'t allowed to do whatever you just tried doing!');
});
/*
* -------- FINALLY WE CAN ACTUALLY LISTEN
*/
// And now that everything is set up, start listening
app.listen(port);
console.log('Listening on port ' + port);
|
/*
* Paper.js - The Swiss Army Knife of Vector Graphics Scripting.
* http://paperjs.org/
*
* Copyright (c) 2011 - 2013, Juerg Lehni & Jonathan Puckey
* http://lehni.org/ & http://jonathanpuckey.com/
*
* Distributed under the MIT license. See LICENSE file for details.
*
* All rights reserved.
*/
/**
* @name Tool
*
* @class The Tool object refers to a script that the user can interact with
* by using the mouse and keyboard and can be accessed through the global
* {@code tool} variable. All its properties are also available in the paper
* scope.
*
* The global {@code tool} variable only exists in scripts that contain mouse
* handler functions ({@link #onMouseMove}, {@link #onMouseDown},
* {@link #onMouseDrag}, {@link #onMouseUp}) or a keyboard handler
* function ({@link #onKeyDown}, {@link #onKeyUp}).
*
* @classexample
* var path;
*
* // Only execute onMouseDrag when the mouse
* // has moved at least 10 points:
* tool.distanceThreshold = 10;
*
* function onMouseDown(event) {
* // Create a new path every time the mouse is clicked
* path = new Path();
* path.add(event.point);
* path.strokeColor = 'black';
* }
*
* function onMouseDrag(event) {
* // Add a point to the path every time the mouse is dragged
* path.add(event.point);
* }
*/
var Tool = PaperScopeItem.extend(/** @lends Tool# */{
_class: 'Tool',
_list: 'tools',
_reference: '_tool', // PaperScope has accessor for #tool
_events: [ 'onActivate', 'onDeactivate', 'onEditOptions',
'onMouseDown', 'onMouseUp', 'onMouseDrag', 'onMouseMove',
'onKeyDown', 'onKeyUp' ],
// DOCS: rewrite Tool constructor explanation
initialize: function Tool(props) {
PaperScopeItem.call(this);
this._firstMove = true;
this._count = 0;
this._downCount = 0;
this._set(props);
},
/**
* Activates this tool, meaning {@link PaperScope#tool} will
* point to it and it will be the one that recieves mouse events.
*
* @name Tool#activate
* @function
*/
/**
* Removes this tool from the {@link PaperScope#tools} list.
*
* @name Tool#remove
* @function
*/
/**
* The minimum distance the mouse has to drag before firing the onMouseDrag
* event, since the last onMouseDrag event.
*
* @type Number
* @bean
*/
getMinDistance: function() {
return this._minDistance;
},
setMinDistance: function(minDistance) {
this._minDistance = minDistance;
if (this._minDistance != null && this._maxDistance != null
&& this._minDistance > this._maxDistance) {
this._maxDistance = this._minDistance;
}
},
/**
* The maximum distance the mouse has to drag before firing the onMouseDrag
* event, since the last onMouseDrag event.
*
* @type Number
* @bean
*/
getMaxDistance: function() {
return this._maxDistance;
},
setMaxDistance: function(maxDistance) {
this._maxDistance = maxDistance;
if (this._minDistance != null && this._maxDistance != null
&& this._maxDistance < this._minDistance) {
this._minDistance = maxDistance;
}
},
// DOCS: document Tool#fixedDistance
/**
* @type Number
* @bean
*/
getFixedDistance: function() {
return this._minDistance == this._maxDistance
? this._minDistance : null;
},
setFixedDistance: function(distance) {
this._minDistance = distance;
this._maxDistance = distance;
},
/**
* {@grouptitle Mouse Event Handlers}
*
* The function to be called when the mouse button is pushed down. The
* function receives a {@link ToolEvent} object which contains information
* about the mouse event.
*
* @name Tool#onMouseDown
* @property
* @type Function
*
* @example {@paperscript}
* // Creating circle shaped paths where the user presses the mouse button:
* function onMouseDown(event) {
* // Create a new circle shaped path with a radius of 10
* // at the position of the mouse (event.point):
* var path = new Path.Circle({
* center: event.point,
* radius: 10,
* fillColor: 'black'
* });
* }
*/
/**
* The function to be called when the mouse position changes while the mouse
* is being dragged. The function receives a {@link ToolEvent} object which
* contains information about the mouse event.
*
* @name Tool#onMouseDrag
* @property
* @type Function
*
* @example {@paperscript}
* // Draw a line by adding a segment to a path on every mouse drag event:
*
* // Create an empty path:
* var path = new Path({
* strokeColor: 'black'
* });
*
* function onMouseDrag(event) {
* // Add a segment to the path at the position of the mouse:
* path.add(event.point);
* }
*/
/**
* The function to be called the mouse moves within the project view. The
* function receives a {@link ToolEvent} object which contains information
* about the mouse event.
*
* @name Tool#onMouseMove
* @property
* @type Function
*
* @example {@paperscript}
* // Moving a path to the position of the mouse:
*
* // Create a circle shaped path with a radius of 10 at {x: 0, y: 0}:
* var path = new Path.Circle({
* center: [0, 0],
* radius: 10,
* fillColor: 'black'
* });
*
* function onMouseMove(event) {
* // Whenever the user moves the mouse, move the path
* // to that position:
* path.position = event.point;
* }
*/
/**
* The function to be called when the mouse button is released. The function
* receives a {@link ToolEvent} object which contains information about the
* mouse event.
*
* @name Tool#onMouseUp
* @property
* @type Function
*
* @example {@paperscript}
* // Creating circle shaped paths where the user releases the mouse:
* function onMouseUp(event) {
* // Create a new circle shaped path with a radius of 10
* // at the position of the mouse (event.point):
* var path = new Path.Circle({
* center: event.point,
* radius: 10,
* fillColor: 'black'
* });
* }
*/
/**
* {@grouptitle Keyboard Event Handlers}
*
* The function to be called when the user presses a key on the keyboard.
* The function receives a {@link KeyEvent} object which contains
* information about the keyboard event.
* If the function returns {@code false}, the keyboard event will be
* prevented from bubbling up. This can be used for example to stop the
* window from scrolling, when you need the user to interact with arrow
* keys.
*
* @name Tool#onKeyDown
* @property
* @type Function
*
* @example {@paperscript}
* // Scaling a path whenever the user presses the space bar:
*
* // Create a circle shaped path:
* var path = new Path.Circle({
* center: new Point(50, 50),
* radius: 30,
* fillColor: 'red'
* });
*
* function onKeyDown(event) {
* if (event.key == 'space') {
* // Scale the path by 110%:
* path.scale(1.1);
*
* // Prevent the key event from bubbling
* return false;
* }
* }
*/
/**
* The function to be called when the user releases a key on the keyboard.
* The function receives a {@link KeyEvent} object which contains
* information about the keyboard event.
* If the function returns {@code false}, the keyboard event will be
* prevented from bubbling up. This can be used for example to stop the
* window from scrolling, when you need the user to interact with arrow
* keys.
*
* @name Tool#onKeyUp
* @property
* @type Function
*
* @example
* function onKeyUp(event) {
* if (event.key == 'space') {
* console.log('The spacebar was released!');
* }
* }
*/
_updateEvent: function(type, point, minDistance, maxDistance, start,
needsChange, matchMaxDistance) {
if (!start) {
if (minDistance != null || maxDistance != null) {
var minDist = minDistance != null ? minDistance : 0,
vector = point.subtract(this._point),
distance = vector.getLength();
if (distance < minDist)
return false;
// Produce a new point on the way to point if point is further
// away than maxDistance
var maxDist = maxDistance != null ? maxDistance : 0;
if (maxDist != 0) {
if (distance > maxDist) {
point = this._point.add(vector.normalize(maxDist));
} else if (matchMaxDistance) {
return false;
}
}
}
if (needsChange && point.equals(this._point))
return false;
}
// Make sure mousemove events have lastPoint set even for the first move
// so event.delta is always defined for them.
// TODO: Decide whether mousedown also should always have delta set.
this._lastPoint = start && type == 'mousemove' ? point : this._point;
this._point = point;
switch (type) {
case 'mousedown':
this._lastPoint = this._downPoint;
this._downPoint = this._point;
this._downCount++;
break;
case 'mouseup':
// Mouse up events return the down point for last point, so delta is
// spanning over the whole drag.
this._lastPoint = this._downPoint;
break;
}
this._count = start ? 0 : this._count + 1;
return true;
},
_fireEvent: function(type, event) {
// Handle items marked in removeOn*() calls first,.
var sets = paper.project._removeSets;
if (sets) {
// Always clear the drag set on mouseup
if (type === 'mouseup')
sets.mousedrag = null;
var set = sets[type];
if (set) {
for (var id in set) {
var item = set[id];
// If we remove this item, we also need to erase it from all
// other sets.
for (var key in sets) {
var other = sets[key];
if (other && other != set)
delete other[item._id];
}
item.remove();
}
sets[type] = null;
}
}
return this.responds(type)
&& this.fire(type, new ToolEvent(this, type, event));
},
_onHandleEvent: function(type, point, event) {
// Update global reference to this scope.
paper = this._scope;
// Now handle event callbacks
var called = false;
switch (type) {
case 'mousedown':
this._updateEvent(type, point, null, null, true, false, false);
called = this._fireEvent(type, event);
break;
case 'mousedrag':
// In order for idleInterval drag events to work, we need to not
// check the first call for a change of position. Subsequent calls
// required by min/maxDistance functionality will require it,
// otherwise this might loop endlessly.
var needsChange = false,
// If the mouse is moving faster than maxDistance, do not produce
// events for what is left after the first event is generated in
// case it is shorter than maxDistance, as this would produce weird
// results. matchMaxDistance controls this.
matchMaxDistance = false;
while (this._updateEvent(type, point, this.minDistance,
this.maxDistance, false, needsChange, matchMaxDistance)) {
called = this._fireEvent(type, event) || called;
needsChange = true;
matchMaxDistance = true;
}
break;
case 'mouseup':
// If the last mouse drag happened in a different place, call mouse
// drag first, then mouse up.
if (!point.equals(this._point)
&& this._updateEvent('mousedrag', point, this.minDistance,
this.maxDistance, false, false, false)) {
called = this._fireEvent('mousedrag', event);
}
this._updateEvent(type, point, null, this.maxDistance, false,
false, false);
called = this._fireEvent(type, event) || called;
// Start with new values for 'mousemove'
this._updateEvent(type, point, null, null, true, false, false);
this._firstMove = true;
break;
case 'mousemove':
while (this._updateEvent(type, point, this.minDistance,
this.maxDistance, this._firstMove, true, false)) {
called = this._fireEvent(type, event) || called;
this._firstMove = false;
}
break;
}
// Return if a callback was called or not.
return called;
}
/**
* {@grouptitle Event Handling}
*
* Attach an event handler to the tool.
*
* @name Tool#on
* @function
* @param {String('mousedown', 'mouseup', 'mousedrag', 'mousemove',
* 'keydown', 'keyup')} type the event type
* @param {Function} function The function to be called when the event
* occurs
*/
/**
* Attach one or more event handlers to the tool.
*
* @name Tool#on^2
* @function
* @param {Object} param An object literal containing one or more of the
* following properties: {@code mousedown, mouseup, mousedrag, mousemove,
* keydown, keyup}.
*/
/**
* Detach an event handler from the tool.
*
* @name Tool#detach
* @function
* @param {String('mousedown', 'mouseup', 'mousedrag', 'mousemove',
* 'keydown', 'keyup')} type the event type
* @param {Function} function The function to be detached
*/
/**
* Detach one or more event handlers from the tool.
*
* @name Tool#detach^2
* @function
* @param {Object} param An object literal containing one or more of the
* following properties: {@code mousedown, mouseup, mousedrag, mousemove,
* keydown, keyup}
*/
/**
* Fire an event on the tool.
*
* @name Tool#fire
* @function
* @param {String('mousedown', 'mouseup', 'mousedrag', 'mousemove',
* 'keydown', 'keyup')} type the event type
* @param {Object} event An object literal containing properties describing
* the event.
*/
/**
* Check if the tool has one or more event handlers of the specified type.
*
* @name Tool#responds
* @function
* @param {String('mousedown', 'mouseup', 'mousedrag', 'mousemove',
* 'keydown', 'keyup')} type the event type
* @return {Boolean} {@true if the tool has one or more event handlers of
* the specified type}
*/
});
|
/**
* Persistent storage.
* @note we should use local storage
* or indexdb.
*/
var storage = {};
/**
* Predictive analytics.
*
* Examples:
*
* intuit('glasses', 'view');
* intuit('glasses', 'sun');
* intuit('glasses', 'sun');
*
* intuit('glasses');
* //=> sun
*
* @param {String} key
* @param {Atring} value
* @return {String}
* @api public
*/
module.exports = function(key, value) {
if(!value) return storage[key].entity
setter(key, value);
};
/**
* Setter.
*
* Increment the number of times a value
* has been set and also calculate the preferred
* value.
*
* @param {String} key
* @param {String} value
* @api private
*/
function setter(key, value) {
var model = storage[key] || factory(key, value);
var nb = (model.values[value] || 0) + 1;
model.values[value] = nb;
if(nb > model.values[model.entity]) storage[key].entity = value;
}
/**
* Create data representation of
* and unknown key.
*
* @param {String} key
* @param {String} value
* @return {Object}
* @api private
*/
function factory(key, value) {
var model = {
entity: value,
values: {}
};
storage[key] = model;
return model;
}
|
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by CodeZu.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
var Client = require('../../../../client'), constants = Client.constants;
module.exports = Client.sub({
getAuditEntries: Client.method({
method: constants.verbs.GET,
url: '{+tenantPod}api/commerce/customer/credits/{code}/auditentries?startIndex={startIndex}&pageSize={pageSize}&sortBy={sortBy}&filter={filter}&responseFields={responseFields}'
})
});
|
/*
Copyright (c) 2003-2022, CKSource Holding sp. z o.o. All rights reserved.
For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
CKEDITOR.plugins.setLang("devtools","fa",{title:"اطلاعات عنصر",dialogName:"نام پنجره محاورهای",tabName:"نام برگه",elementId:"ID عنصر",elementType:"نوع عنصر"});
|
angular.module('NetPlanningApp').directive('ionCalendar', function($compile) {
function appendHeader(html) {
var header = angular.element('<ion-header-bar></<ion-header-bar>').addClass('bar-subheader');
html.append(header);
var table = angular.element('<table></table>').attr('width', '100%').addClass('header').addClass('stable-bg');
header.append(table);
var tr = angular.element('<tr></tr>');
table.append(tr);
for( var i=0; i<7; i++ ) {
var label = moment().day(i).format('dd');
var td = angular.element('<td></td>').html(label);
if(i === 0 || i === 6 ) {
td.addClass('assertive');
}
tr.append(td);
}
}
return {
restrict: 'E',
replace: true,
scope: {
calendarItems: '=items',
calendarItemClick: '=click',
},
compile: function($html, $attrs) {
$html.empty();
var root = angular.element('<div></div>').addClass('calendar');
appendHeader(root);
var content = angular.element('<ion-content></ion-content>').addClass('has-subheader');
root.append(content);
$html.append(root);
var startDate = moment();
for( var g=0; g<3; g++) {
var monthObj = [];
var today = startDate.clone().add(g,'month');
var startOfMonth = today.clone().startOf('month');
var endOfMonth = today.clone().endOf('month');
for( var day = startOfMonth.clone().subtract(startOfMonth.day(), 'day'); day.isBefore(startOfMonth, 'day'); day.add(1,'day') ) {
monthObj.push({
type: 'past',
m: day.clone()
});
}
for( var day = startOfMonth.clone(); day.isBefore(endOfMonth, 'day') || day.isSame(endOfMonth, 'day'); day.add(1,'day') ) {
monthObj.push({
type: 'current',
m: day.clone()
});
}
for( var day = endOfMonth.clone().add(1,'day'); day.isBefore( endOfMonth.clone().subtract(1, 'day').add(endOfMonth.day(), 'day') ); day.add(1,'day') ) {
monthObj.push({
type: 'next',
m: day.clone()
});
}
var table = angular.element('<table></table>').attr('width', '100%').addClass('month')
content.append(table);
tr = angular.element('<tr></tr>');
table.append(tr);
for( var i=0; i<7; i++ ) {
var monthEl = monthObj[i];
var className = monthEl.type+'-month';
var td = angular.element('<td></td>').addClass(className);
if(today.startOf('month').day() === i) {
td.addClass('assertive').html(today.format('MMM').toUpperCase());
}
tr.append(td);
}
var table = angular.element('<table></table>').attr('width', '100%').addClass('content')
content.append(table);
for( var i=0; i<monthObj.length; i++) {
var monthEl = monthObj[i];
var key = monthEl.m.format('YYYY-MM-DD');
var tr;
if( i % 7 === 0 ) {
tr = angular.element('<tr></tr>');
table.append(tr);
}
var className = monthEl.type+'-month';
var td = angular.element('<td></td>')
.addClass(className)
.attr('ng-click','calendarItemClick(calendarItems[\''+key+'\'] ? calendarItems[\''+key+'\'].items : [])');
if( i % 7 === 0 || i % 7 === 6 ) {
td.addClass('weekend');
}
var htmlDay = angular.element('<span></span>')
.html(monthEl.m.format('D'))
.addClass(monthEl.m.isSame(moment(), 'day') ? 'badge badge-assertive': '')
.wrap('<div></div>')
.parent();
td.append(htmlDay);
var htmlData = angular.element('<span></span>')
.attr('ng-class', '{ \'positive\': calendarItems[\''+key+'\'].items.length }')
.html(' {{calendarItems[\''+key+'\'] ? calendarItems[\''+key+'\'].items.length : \'\'}} ')
.wrap('<div></div>')
.parent();
td.append(htmlData);
tr.append(td);
}
}
return function($scope, $element, $attrs) {
$compile($element.contents())($scope);
};
}
};
});
|
import React, { Component } from 'react';
import { reduxForm, Field } from 'redux-form';
import { connect } from 'react-redux';
import * as actions from '../../actions';
class Signin extends Component {
handleFormSubmit({ email, password }) {
this.props.signinUser({ email, password });
}
renderAllert() {
if (this.props.errorMessage) {
return (
<div className="alert alert-danger">
<strong>Oops, </strong>{this.props.errorMessage}
</div>
);
}
return '';
}
render() {
const { handleSubmit } = this.props;
return (
<form onSubmit={handleSubmit(this.handleFormSubmit.bind(this))}>
<fieldset className="form-group">
<label>Email:</label>
<Field name="email" component="input" type="text" className="form-control" />
</fieldset>
<fieldset className="form-group">
<label>Password:</label>
<Field name="password" component="input" type="password" className="form-control" />
</fieldset>
{this.renderAllert()}
<button action="submit" className="btn btn-primary">Sign in</button>
</form>
);
}
}
function mapStateToProps(state) {
return { errorMessage: state.auth.error };
}
Signin = reduxForm({
form: 'signin',
fields: ['email', 'password']
})(Signin);
export default connect(mapStateToProps, actions)(Signin);
|
$(function() {
chrome.storage.sync.get("disable_render", function(items) {
if (!chrome.runtime.error) {
var disable_render = items.disable_render;
if (disable_render === undefined) {
disable_render = false;
chrome.storage.sync.set({"disable_render" : false}, function() {
console.log("disable_render initialize failed.");
});
}
$('#disable_render').prop('checked', disable_render);
}
});
chrome.storage.sync.get("reload_enable", function(items) {
if (!chrome.runtime.error) {
var reload_enable = items.reload_enable;
if (reload_enable === undefined) {
reload_enable = true;
chrome.storage.sync.set({"reload_enable" : true}, function() {
console.log("reload_enable initialize failed.");
});
}
$('#reload_enable').prop('checked', reload_enable);
}
});
chrome.storage.sync.get("reload_interval", function(items) {
if (!chrome.runtime.error) {
var reload_interval = items.reload_interval;
if (reload_interval === undefined) {
reload_interval = 1000;
chrome.storage.sync.set({"reload_interval" : 1000}, function() {
console.log("reload_interval initialize failed.");
});
}
$('#reload_interval').val(reload_interval);
}
});
$('#disable_render').change(function() {
chrome.storage.sync.set({"disable_render" : $('#disable_render').prop('checked')}, function() {
if (chrome.runtime.error) {
console.log("Storage save runtime error.(disable_render)");
}
});
});
$('#reload_enable').change(function() {
chrome.storage.sync.set({"reload_enable" : $('#reload_enable').prop('checked')}, function() {
if (chrome.runtime.error) {
console.log("Storage save runtime error.(reload_enable)");
}
});
});
$('#reload_interval').change(function() {
chrome.storage.sync.set({"reload_interval" : $('#reload_interval').val()}, function() {
if (chrome.runtime.error) {
console.log("Storage save runtime error.(reload_interval)");
}
});
});
var download_dot_graph = function(diag_code) {
diag_code = diag_code.replace(/<("[^"]*"|'[^']*'|[^'">])*>/g,'');
diag_code = diag_code.replace(/\r/g, "");
var ast = SeqdiagParser.parse(diag_code);
var diagram = Seqdiag.DiagramBuilder.build(ast);
var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute("width", "1024");
svg.setAttribute("height", "600");
var drawer = new Seqdiag.Drawer.SVG(diagram, svg, document);
drawer.draw();
var serializer = new XMLSerializer();
var serialized_svg = serializer.serializeToString(svg);
var dl_blob = new Blob([serialized_svg], {"type" : "image/svg+xml"});
var dl_url = URL.createObjectURL(dl_blob);
chrome.downloads.download({
url: dl_url,
filename: 'export.svg'
});
};
$('#download_svg').click(function() {
chrome.tabs.getSelected(null, function(tab) {
$.ajax({
url: tab.url,
cache: false,
success: function(txt) {
download_dot_graph(txt);
}
});
});
});
});
|
import DOMPurify from 'dompurify'
export const renderIntroText = (config) => {
if (config['intro-text'].length > 0) {
return {
__html: DOMPurify.sanitize(config['intro-text'])
}
}
}
export const renderTitleRight = (config) => {
if (config['header-right-text'].length > 0) {
return (config['header-right-text'])
}
}
export const renderFooterRight = (config) => {
if (config['footer-right-text'].length > 0) {
return (config['footer-right-text'])
}
}
|
require('cloud/app.js');
|
// This is a simple *viewmodel* - JavaScript that defines the data and
// behavior of our UI via KnockoutJS. For more about knockout see
// http://knockoutjs.com/
function AppViewModel()
{
var self = this;
self.endpoints = ko.observableArray([new Endpoint()]);
self.addEndpoint = function()
{
self.endpoints.push(new Endpoint());
}
self.deleteEndpoint = function( item, event )
{
endpointId = $(event.target).attr('array-loc');
self.endpoints.splice(endpointId,1);
}
}
function Endpoint(koData)
{
var self = this;
self.id = ko.observable(Math.floor(Math.random()*10000000));
self.name = ko.observable("Endpoint Name");
self.methods = ko.observableArray([ new Method() ]);
self.supportedHTTPMethods = ['GET','POST','PUT','DELETE'];
ko.mapping.fromJS(koData, knockoutMapping, this);
self.addMethod = function() {
self.methods.push(new Method());
};
self.deleteMethod = function( item, event )
{
methodId = $(event.target).attr('array-loc');
self.methods.splice(methodId,1);
}
self.duplicateMethod = function( item, event )
{
methodId = $(event.target).attr('array-loc');
method = self.methods()[methodId].clone();
self.methods.push(method);
}
}
function Method(koData)
{
var self = this;
self.id = ko.observable(Math.floor(Math.random()*10000000));
self.MethodName = ko.observable("Method Name");
self.Synopsis = ko.observable('');
self.HTTPMethod = ko.observable('');
self.URI = ko.observable('');
self.RequiresOAuth = ko.observable(false);
self.content = ko.observable();
self.parameters = ko.observableArray();
ko.mapping.fromJS(koData, knockoutMapping, this);
self.addParameter = function() {
self.parameters.push(new Parameter());
};
self.deleteParameter = function( item, event )
{
parameterId = $(event.target).attr('array-loc');
self.parameters.splice(parameterId,1);
}
self.addContentSection = function()
{
self.content(new ContentSection());
};
self.deleteContentSection = function()
{
self.content(null);
}
/**
* I am somewhat novice/intermediate when it comes to Javascript so the
* whole prototype / referencing modle somewhat baffles me. I tried a
* couple of more elegent ways to implement the clone function but in the
* end I always wound up with unwanted references to the original objects.
* So I brute forced it... if anybody wants to school me I'm all ears.
*/
self.clone = function()
{
var method = new Method()
method.MethodName = ko.observable( self.MethodName() );
method.Synopsis = ko.observable( self.Synopsis() );
method.HTTPMethod = ko.observable( self.HTTPMethod() );
method.URI = ko.observable( self.URI() );
method.RequiresOAuth = ko.observable( self.RequiresOAuth() );
method.content = ko.observable();
method.parameters = ko.observableArray();
if( self.content() instanceof ContentSection )
{
method.content( self.content().clone() );
}
if( self.parameters() instanceof Array )
{
for (var i=0; i<self.parameters().length; i++)
{
parameter = new Parameter();
method.parameters()[i] = self.parameters()[i].clone();
}
}
return method;
}
}
function Parameter(koData)
{
var self = this;
self.id = ko.observable(Math.floor(Math.random()*10000000));
self.Name = ko.observable('Name');
self.Description = ko.observable('');
self.Default = ko.observable('');
self.Required = ko.observable(true);
self.Type = ko.observable('string');
self.Location = ko.observable('query');
self.availableTypes = ['bool','integer','string','other'];
self.availableLocations = ['query', 'header'];
ko.mapping.fromJS(koData, knockoutMapping, this);
self.typeInput = ko.computed( function()
{
if ( self.Type() == 'other' ||
jQuery.inArray(self.Type(), self.availableTypes) == -1 )
{
return 'freeform-parameter-type-input';
}
return 'list-parameter-type-input';
});
self.clone = function()
{
var parameter = new Parameter();
parameter.Name = ko.observable( self.Name() );
parameter.Description = ko.observable( self.Description() );
parameter.Default = ko.observable( self.Default() );
parameter.Required = ko.observable( self.Required() );
parameter.Type = ko.observable( self.Type() );
parameter.Location = ko.observable( self.Location() );
return parameter;
}
}
function SchemaParameter(koData)
{
var self = this;
self.id = ko.observable(Math.floor(Math.random()*10000000));
self.Name = ko.observable("Name");
self.Description = ko.observable("");
self.Default = ko.observable("");
self.Required = ko.observable(true);
self.Type = ko.observable("integer");
self.parameters = ko.observableArray();
self.availableTypes = ['bool','integer','string','object','collection','list','other'];
ko.mapping.fromJS(koData, knockoutSchemaParameterMapping, this);
self.addParameter = function() {
self.parameters.push(new SchemaParameter());
};
self.deleteParameter = function( item, event )
{
id = $(event.target).attr('array-loc');
self.parameters.splice(id,1);
}
self.displayTemplate = function()
{
if( self.Type() == 'object' || self.Type() == 'collection' || self.Type() == 'list' )
{
return "complex-schema";
}
return "simple-schema";
}
self.typeInput = ko.computed( function()
{
if ( self.Type() == 'other' ||
jQuery.inArray(self.Type(), self.availableTypes) == -1 )
{
return 'freeform-parameter-type-input';
}
return 'list-parameter-type-input';
});
self.clone = function()
{
var parameter = new SchemaParameter();
parameter.Name = ko.observable( self.Name() );
parameter.Description = ko.observable( self.Description() );
parameter.Default = ko.observable( self.Default() );
parameter.Required = ko.observable ( self.Required() );
parameter.Type = ko.observable( self.Type() );
parameter.parameters = ko.observableArray();
if( self.parameters() instanceof Array )
{
for( var i=0; i<self.parameters().length; i++ )
{
parameter.parameters()[i] = self.parameters()[i].clone();
}
}
return parameter;
}
}
function ContentSection(koData)
{
var self = this;
self.id = ko.observable(Math.floor(Math.random()*10000000));
self.schema = {"type":"string"};
self.contentType = ko.observableArray(["application/json"]);
self.parameters = ko.observableArray();
ko.mapping.fromJS(koData, knockoutSchemaParameterMapping, this);
self.addParameter = function() {
parameter = new SchemaParameter();
self.parameters.push(parameter);
};
self.deleteParameter = function( item, event )
{
id = $(event.target).attr('array-loc');
self.parameters.splice(id,1);
}
self.clone = function()
{
var section = new ContentSection();
section.contentType = ko.observableArray( self.contentType() );
section.parameters = ko.observableArray();
if( self.parameters() instanceof Array )
{
for (var i=0; i<self.parameters().length; i++)
{
section.parameters()[i] = self.parameters()[i].clone();
}
}
return section;
}
}
// This mapping object allows us to specify the kind of object create when
// building a view model from a simple object represntation (as we do when
// loading in JSON data). These mapping definitions are referenced throughout
// the object definitions up above
// For more see http://knockoutjs.com/documentation/plugins-mapping.html#customizing_object_construction_using_create
var knockoutMapping = {
'endpoints': {
create: function(options) {
return new Endpoint(options.data);
}
},
'methods': {
create: function(options) {
return new Method(options.data);
}
},
'parameters': {
create: function(options) {
return new Parameter(options.data);
}
},
'schemaParameters': {
create: function(options) {
return new SchemaParameter(options.data);
}
},
'content': {
create: function(options) {
return new ContentSection(options.data);
}
}
}
// We need a distinct definition of what a 'parameter' is because inside the
// Section Content and SchemaParameter objects a parameter is a slightly
// different object. Obviously I could change the name of the array in those
// objects so that they don't collide however the name is significant in that
// I/O Docs looks for that element by name so the output must have the name
// 'parameters'. There are a couple of ways to skin this cat, I chose this way.
var knockoutSchemaParameterMapping = {
'parameters': {
create: function(options) {
return new SchemaParameter(options.data);
}
}
}
/**
* This is a simple helper method to recursivly prune away named variables from
* an object and its children. We do this because we're doing a 'dump' of the
* javascript object to JSON and there are several bits of data that we use
* during the construction and management of the endpoint that we don't want
* translated into the output.
*/
function cleanUp(obj)
{
delete obj.__ko_mapping__;
for( var i in obj )
{
if( typeof(obj[i]) == "object" && obj[i] != null)
{
delete obj[i].id;
delete obj[i].availableTypes;
delete obj[i].__ko_mapping__;
delete obj[i].supportedHTTPMethods;
delete obj[i].availableLocations;
delete obj[i].typeInput;
cleanUp(obj[i]);
}
}
}
|
/*
* node-klass
* https://github.com/ayecue/node-klass
*
* Copyright (c) 2015 "AyeCue" Sören Wehmeier, contributors
* Licensed under the MIT license.
*/
'use strict';
module.exports = (function(
extend,
bind,
from,
CONSTANTS,
Argmap,
Listener
){
function ProcessorBatch(options){
var me = this;
extend(me,{
scope: null,
collection: null,
argMap: new Argmap(),
hooks: new Listener()
},options);
me.argMap.set('hooks',me.hooks);
}
extend(ProcessorBatch.prototype,{
self: ProcessorBatch,
process: function(){
var me = this,
done = bind(me.process,me),
callback;
while (callback = me.collection.shift()) {
if (callback.apply(me.scope,me.argMap.inject([done],true)) === false) {
return;
}
}
me.hooks.fire('processed',me.scope,me.argMap.collect());
}
});
return ProcessorBatch;
})(
require('../common/extend'),
require('../common/bind'),
require('../common/from'),
require('../Constants'),
require('../Argmap'),
require('../Listener')
);
|
define([
'modules/room/module'
], function (module) {
'use strict';
module.controller('modules.room.controllers.test', [
'$scope',
'$state',
'$appEnvironment',
'$element',
function ($scope, $state, $appEnvironment, $element) {
var me = this;
}
]);
});
|
import Text from './Text';
import Registry from '@ui-autotools/registry';
const metadata = Registry.getComponentMetadata(Text);
metadata.exportInfo = {
path: 'src/Text/Text.js',
};
|
function DashboardIndex(){
loadPage('../dashboard/index.html');
/*var _url = 'http://localhost:49822/api/AnaliseDebito';
$.ajax({
url: _url,
type: 'GET',
contentType: "application/json;charset=UTF-8"
}).done(function(data){
listarPendentes('anual',data);
});*/
}
|
let prefix = '';
// load from CloudFront if the app isn't served from a dev/staging environment
// is there a better way to do this?
if (document.location.hostname != 'localhost' &&
document.location.hostname != '10.0.2.2' &&
document.location.hostname != 'iw-files.s3.amazonaws.com' &&
document.location.hostname.indexOf('apps.fivetwentyseven.com') === -1) {
prefix = '//cloudfront-files-1.publicintegrity.org/apps/2017/03/refinery-graphics/';
}
try {
// removes this one annoying error in some marketing code currently deployed in the CMS
window.show_social_links_footer = () => {
// no-op
};
// attempt to get the container div/iframe
const el = document.getElementById('refineryGraphics');
let view = el.getAttribute('data-view');
const queryArray = [];
if (typeof view === 'undefined' || !view) {
view = '';
}
const queryString = `?${queryArray.join('&')}`;
const url = `${prefix}index.html#${view}${queryString}`;
let iframe = null;
// insert the iframe if it doesn't exist
if (el.tagName.toLowerCase() == 'div') {
iframe = document.createElement('iframe');
iframe.setAttribute('src',url);
iframe.setAttribute('id','refineryGraphics');
iframe.setAttribute('style','width:100%;height:900px;');
iframe.setAttribute('frameBorder','0');
iframe.setAttribute('scrolling','no');
el.appendChild(iframe);
}
else if (el.tagName.toLowerCase() == 'iframe') {
iframe = el;
}
// hmmmm revisit all this
// adapted from some USAT embed code
function oembedResizeIframe(els, data) {
for (let i = 0; i < els.length; i++) {
if (data.height) {
els[i].style.height = `${data.height}px`;
}
/*
if (typeof data.scrollTo !== 'undefined' && data.scrollTo !== null) {
var elPos = els[i].getBoundingClientRect().top + window.pageYOffset;
var totalOffset = elPos + parseInt(data.scrollTo);
window.scrollTo(0, totalOffset);
}*/
}
}
function receiveMessage(event) {
if (typeof iframe !== 'undefined' && iframe) {
oembedResizeIframe([iframe], event.data);
}
}
window.addEventListener('message', receiveMessage, false);
} catch (e) {
document.getElementById('refineryGraphics').innerHTML = `<img src="${prefix}${PKG_VERSION}/img/graphic-940.png"/>`;
}
|
module.exports = {
files: [
'js/ionic.filter.bar.js',
'js/ionic.filter.bar.directive.js',
'js/ionic.filter.bar.config.js',
'js/ionic.filter.bar.service.js',
'js/ionic.filter.bar.modal.js',
'test/unit/*.js'
],
frameworks: ['jasmine'],
reporters: ['progress'],
port: 9876,
colors: true,
// possible values: 'OFF', 'ERROR', 'WARN', 'INFO', 'DEBUG'
logLevel: 'INFO',
autoWatch: true,
captureTimeout: 60000,
singleRun: false,
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera (has to be installed with `npm install karma-opera-launcher`)
// - Safari (only Mac; has to be installed with `npm install karma-safari-launcher`)
// - PhantomJS
// - IE (only Windows; has to be installed with `npm install karma-ie-launcher`)
browsers: ['PhantomJS']
};
|
(function () {
var Class = Hilo3d.Class;
var BasicLoader = Hilo3d.BasicLoader;
var DataTexture = Hilo3d.DataTexture;
var TGALoader = Class.create({
Extends: BasicLoader,
constructor: function () {
TGALoader.superclass.constructor.call(this);
},
load: function (params) {
var that = this;
return this.loadRes(params.src, 'buffer')
.then(function (buffer) {
console.time('parse tga image');
var header = that.readHeader(buffer);
that.check(header);
var pixels = that.readPixels(header, buffer);
console.timeEnd('parse tga image');
return that.createTexture(header, pixels);
});
},
readHeader: function(buffer) {
var dv = new DataView(buffer, 0, 18);
var header = {};
header.idlength = dv.getInt8(0);
header.colourMapType = dv.getInt8(1);
header.dataTypeCode = dv.getInt8(2);
header.colourMapOrigin = dv.getInt16(3, true);
header.colourMapLength = dv.getInt16(5, true);
header.colourMapDepth = dv.getInt8(7);
header.xOrigin = dv.getInt16(8, true);
header.yOrigin = dv.getInt16(10, true);
header.width = dv.getInt16(12, true);
header.height = dv.getInt16(14, true);
header.bitsPerPixel = dv.getInt8(16);
header.bytesPerPixel = header.bitsPerPixel / 8;
header.imageDescriptor = dv.getInt8(17);
return header;
},
check(header) {
/* What can we handle */
if (header.dataTypeCode != 2 && header.dataTypeCode != 10) {
throw new Error('TGALoader Can only handle image type 2 and 10');
}
if (header.bitsPerPixel != 16 &&
header.bitsPerPixel != 24 && header.bitsPerPixel != 32) {
throw new Error('TGALoader Can only handle pixel depths of 16, 24, and 32');
}
if (header.colourMapType != 0 && header.colourMapType != 1) {
throw new Error('TGALoader Can only handle colour map types of 0 and 1');
}
},
addPixel: function(arr, offset, count, pixels, idx) {
idx *= 4;
var r = 255;
var g = 255;
var b = 255;
var a = 255;
if (count === 3 || count === 4) {
r = arr[offset + 2];
g = arr[offset + 1];
b = arr[offset];
a = count === 4 ? arr[offset + 3] : 255;
} else if (count === 2) {
r = (arr[offset + 1] & 0x7c) << 1;
g = ((arr[offset + 1] & 0x03) << 6) | ((arr[offset] & 0xe0) >> 2);
b = (arr[offset] & 0x1f) << 3;
a = (arr[offset + 1] & 0x80);
} else {
console.error('cant transform to Pixel');
}
pixels[idx] = r;
pixels[idx + 1] = g;
pixels[idx + 2] = b;
pixels[idx + 3] = a;
},
readPixels: function (header, buffer) {
var bytesPerPixel = header.bytesPerPixel;
var pixelCount = header.width * header.height;
var data = new Uint8Array(buffer);
var pixels = new Uint8Array(pixelCount * 4);
var offset = 18;
for (var i = 0; i < pixelCount; i++) {
if (header.dataTypeCode === 2) {
this.addPixel(data, offset, bytesPerPixel, pixels, i);
} else if (header.dataTypeCode === 10) {
var flag = data[offset++];
var count = flag & 0x7f;
var isRLEChunk = flag & 0x80;
this.addPixel(data, offset, bytesPerPixel, pixels, i);
for (var j = 0; j < count; j++) {
if (!isRLEChunk) {
offset += bytesPerPixel;
}
this.addPixel(data, offset, bytesPerPixel, pixels, ++i);
}
}
offset += bytesPerPixel;
}
return pixels;
},
createTexture(header, pixels) {
return new DataTexture({
width: header.width,
height: header.height,
flipY: true,
image: pixels,
type: Hilo3d.constants.UNSIGNED_BYTE
});
}
});
Hilo3d.TGALoader = TGALoader;
Hilo3d.Loader.addLoader('tga', TGALoader);
})();
|
import convict from 'convict'
const LEGAL_BOOLEAN = {
'1': true,
'0': false,
'true': true,
'false': false
}
convict.addFormat({
name: 'boolean',
validate: val => {
if (LEGAL_BOOLEAN[val] === undefined) {
throw new Error('must be on of ' + Object.keys(LEGAL_BOOLEAN))
}
},
coerce: val => LEGAL_BOOLEAN[val]
})
convict.addFormat({
name: 'json-array',
validate: val => {
if (!Array.isArray(val)) {
throw new Error('must be a JSON array')
}
},
coerce: val => {
try {
return JSON.parse(val)
} catch (err) {
return
}
}
})
var conf = convict({
ice: {
useDefaultServers: {
doc: 'Enable default ICE servers (default true)',
format: 'boolean',
default: true,
env: 'ICE_USE_DEFAULT_SERVERS'
},
servers: {
doc: 'Additional static servers in JSON array format (default [])',
format: 'json-array',
default: [],
env: 'ICE_SERVERS'
}
}
})
conf.validate({strict: true})
export default conf
|
(function(){
'use strict';
angular.module('iTravelApp')
.directive('hideWhenScroll', [function(){
return {
restrict: 'A',
link:link
};
}]);
function link(scope, elem) {
var lastScrollTop = 0;
angular.element(window).on('scroll', scrollHandler);
var isTrans = true;
function scrollHandler() {
var currScrollTop = $(this).scrollTop();
var allowHide = elem.hasClass('allow-hide');
//console.log('allowHide', allowHide);
//scroll when hide code
//if (allowHide && currScrollTop > lastScrollTop){
// elem.addClass('rd-top-n100');
//} else {
// elem.removeClass('rd-top-n100');
//}
//lastScrollTop = currScrollTop;
//nontransparent when scroll
//when scroll over the landing image, change navbar from transparent to nontransparent
//fix navbar to top
//console.log(currScrollTop);
if (allowHide && currScrollTop > 580) {
elem.removeClass('top-nav-collapse');
isTrans = false;
}
//console.log(isTrans);
if (allowHide && !isTrans && currScrollTop <= 580) {
elem.addClass('top-nav-collapse');
}
}
}
})();
|
'use strict';
var _ = require('lodash');
var path = require('path');
var assert = require('assert');
var fs = require('fs');
var async = require('async');
var hbase = require('hbase');
var moment = require('moment');
var settings = require('./config/app/settings');
var db = require('./db/scripts/db');
var turnstileModel = require('./db/models/model-turnstile').Model;
var daywiseAvModel = require('./db/models/model-peakDay-av').Model;
var client = new hbase({
host: '127.0.0.1',
port: 8080
});
var log;
var stationDataPath = path.join(__dirname, './data/stations.json');
var stations = JSON.parse(fs.readFileSync(stationDataPath));
/**
* Function to load the config
*/
var loadConfig = function() {
var env = process.env.NODE_ENV || 'development',
configPath = path.resolve(__dirname, '../config'),
configFile = path.join(configPath + '/', env + '.json'),
config = fs.readFileSync(configFile, 'utf8');
settings.setConfig(config);
};
async.series([
function(done) {
loadConfig();
done();
},
function(done) {
settings.log = log;
done();
},
function(done) {
console.log('Connecting to mongoDb');
db.connect(settings.getConfig().dbURL, done, done);
},
function(done) {
_fetchAndSaveDataForAllStations(done, done);
}
], function(error) {
if(error) {
console.log(error);
} else {
process.exit(0);
}
});
function _fetchAndSaveDataForAllStations(success, failure) {
async.eachSeries(stations, function(station, next) {
var stationCode = _.findKey(station);
_fetchAllForStation(stationCode, function(error, docs) {
if(error) {
next(error);
} else {
console.log('Saving to mongo for', stationCode);
_saveToMongo(docs, next, next);
}
});
}, function(error) {
if(error) {
failure(error);
} else {
success();
}
});
}
function _fetchAllForStation(code, callback) {
console.log('Fetching from turnstileDatas for', code);
var res = [],
years = [2010, 2011, 2012, 2013, 2014, 2015];
async.eachSeries(years, function(y, next) {
_fetchForYear(code, y, function(err, docs) {
if(err) {
next(err);
} else {
res = _.union(res, docs);
setImmediate(next);
}
});
}, function(error) {
if(error) {
callback(error);
} else {
callback(null, res);
}
});
}
function _fetchForYear(code, year, callback) {
var months = [1,2,3,4,5,6,7,8,9,10,11,12],
res = [];
async.eachSeries(months, function(m, next) {
new turnstileModel().retrieve({remote: code, date: {"$gte": new Date(year, m, 1), "$lt": new Date(year, m+1, 1)}}, function(docs) {
_consolidateForOneMonthByDay(code, m, year, docs, function(ans) {
res = _.union(res, ans);
setImmediate(next);
});
}, next);
}, function(error) {
if(error) {
callback(error);
} else {
callback(null, res);
}
});
}
function _consolidateForOneMonthByDay(code, month, year, arr, callback) {
var ans = [];
if(arr.length > 1) {
var x = {
remote: code,
month: month,
year: year,
entries: 0,
exits: 0
};
for(var i=0;i<7;i++) {
var z = _.assign({},x);
z.day = i;
ans.push(z);
}
async.eachSeries(arr, function(a, next) {
if(a.toObject().time >=7 && a.toObject().time<=10) {
var day = new Date(a.toObject().date).getDay();
ans[day].entries = Number(ans[day].entries) + Number(_.get(a, 'entries'));
ans[day].exits = Number(ans[day].exits) + Number(_.get(a, 'exits'));
}
setImmediate(next);
}, function(err) {
if(err) {
callback(err);
} else {
callback(ans);
}
});
} else {
callback(arr);
}
}
function _saveToMongo(docs, success, failure) {
//console.log(docs);
new daywiseAvModel().bulkInsert(docs, success, function(error) {
console.log(error);
success();
});
}
|
ngapp.service('viewFactory', function(randomService) {
let viewConstructors = {},
accessibleViews = {};
this.link = function(view, otherView) {
if (!view || !otherView) return;
view.linkTo(otherView);
otherView.linkTo(view);
};
this.unlink = function(linkedView, linkKey) {
if (!linkedView) return;
delete linkedView[linkKey];
};
this.registerView = function(viewName, constructor, accessibleName) {
viewConstructors[viewName] = constructor;
if (accessibleName) accessibleViews[accessibleName] = viewName;
};
this.newView = function(viewName, active = false) {
let view = viewConstructors[viewName]();
view.id = randomService.generateUniqueId();
view.active = active;
return view;
};
this.getAccessibleViews = function() {
return angular.copy(accessibleViews);
};
this.new = function(viewName) {
return {
templateUrl: `partials/${viewName}.html`,
controller: `${viewName}Controller`,
class: viewName.underscore('-'),
label: viewName.humanize(),
destroy: () => {}
};
}
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.