code
stringlengths
2
1.05M
repo_name
stringlengths
5
114
path
stringlengths
4
991
language
stringclasses
1 value
license
stringclasses
15 values
size
int32
2
1.05M
(function (global, factory) { if (typeof define === 'function' && define.amd) { define(['exports', 'module', 'skatejs'], factory); } else if (typeof exports !== 'undefined' && typeof module !== 'undefined') { factory(exports, module, require('skatejs')); } else { var mod = { exports: {} }; factory(mod.exports, mod, global.skate); global.skate = mod.exports; } })(this, function (exports, module, _skatejs) { 'use strict'; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _skate = _interopRequireDefault(_skatejs); var auiSkate = _skate['default'].noConflict(); module.exports = auiSkate; }); //# sourceMappingURL=../../../js/aui/internal/skate.js.map
parambirs/aui-demos
node_modules/@atlassian/aui/lib/js/aui/internal/skate.js
JavaScript
mit
757
/* * author: Lisa * Info: Base64 / UTF8 * 编码 & 解码 */ function base64Encode(input) { var keyStr = "ABCDEFGHIJKLMNOP" + "QRSTUVWXYZabcdef" + "ghijklmnopqrstuv" + "wxyz0123456789+/" + "="; var output = ""; var chr1, chr2, chr3 = ""; var enc1, enc2, enc3, enc4 = ""; var i = 0; do { chr1 = input[i++]; chr2 = input[i++]; chr3 = input[i++]; enc1 = chr1 >> 2; enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); enc4 = chr3 & 63; if (isNaN(chr2)) { enc3 = enc4 = 64; } else if (isNaN(chr3)) { enc4 = 64; } output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4); chr1 = chr2 = chr3 = ""; enc1 = enc2 = enc3 = enc4 = ""; } while (i < input.length); return output; } function base64Decode(input) { var output = ""; var chr1, chr2, chr3 = ""; var enc1, enc2, enc3, enc4 = ""; var i = 0; var base64test = /[^A-Za-z0-9/+///=]/g; if (base64test.exec(input)) { alert("There were invalid base64 characters in the input text./n" + "Valid base64 characters are A-Z, a-z, 0-9, '+', '/', and '='/n" + "Expect errors in decoding."); } input = input.replace(/[^A-Za-z0-9/+///=]/g, ""); output=new Array(); do { enc1 = keyStr.indexOf(input.charAt(i++)); enc2 = keyStr.indexOf(input.charAt(i++)); enc3 = keyStr.indexOf(input.charAt(i++)); enc4 = keyStr.indexOf(input.charAt(i++)); chr1 = (enc1 << 2) | (enc2 >> 4); chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); chr3 = ((enc3 & 3) << 6) | enc4; output.push(chr1); if (enc3 != 64) { output.push(chr2); } if (enc4 != 64) { output.push(chr3); } chr1 = chr2 = chr3 = ""; enc1 = enc2 = enc3 = enc4 = ""; } while (i < input.length); return output; } function UTF8Encode(str){ var temp = "",rs = ""; for( var i=0 , len = str.length; i < len; i++ ){ temp = str.charCodeAt(i).toString(16); rs += "\\u"+ new Array(5-temp.length).join("0") + temp; } return rs; } function UTF8Decode(str){ return str.replace(/(\\u)(\w{4}|\w{2})/gi, function($0,$1,$2){ return String.fromCharCode(parseInt($2,16)); }); } exports.base64Encode = base64Encode; exports.base64Decode = base64Decode; exports.UTF8Encode = UTF8Encode; exports.UTF8Decode = UTF8Decode;
jrcjing/cbg-log
lib/Tool/base64.js
JavaScript
mit
2,332
const path = require('path'), fs = require('fs'), glob = require('glob'), pug = require('pug'), stylus = require('stylus'), nib = require('nib'), autoprefixer = require('autoprefixer-stylus'), {rollup} = require('rollup'), rollupPluginPug = require('rollup-plugin-pug'), rollupPluginResolve = require('rollup-plugin-node-resolve'), rollupPluginReplace = require('rollup-plugin-replace'), rollupPluginCommonjs = require('rollup-plugin-commonjs'), rollupPluginGlobImport = require('rollup-plugin-glob-import'), rollupPluginAlias = require('rollup-plugin-alias'), rollupPluginBabel = require('rollup-plugin-babel'), sgUtil = require('./util'); class AppBuilder { constructor(conf, CollectorStore) { this.conf = conf; this.CollectorStore = CollectorStore; this.name = this.conf.get('package.name'); this.viewerDest = this.conf.get('viewerDest'); this.source = path.resolve(__dirname, '..', 'app'); this.sections = []; this.generateViewerPages = this.generateViewerPages.bind(this); this.generateViewerStyles = this.generateViewerStyles.bind(this); this.rollupViewerScripts = this.rollupViewerScripts.bind(this); this.getViewerPagesLocals = this.getViewerPagesLocals.bind(this); this.onEnd = this.onEnd.bind(this); } renderCollected() { if (!this.watcher) { this.CollectorStore.getFiles() .forEach(async (file) => { if (!file.exclude) { await file.render; } }); } return this; } saveCollectedData() { if (!this.watcher) { const {viewerDest, CollectorStore: {getCollectedData}} = this; sgUtil.writeJsonFile(path.join(viewerDest, 'structure.json'), getCollectedData()); } } getViewerPagesLocals() { return { description: this.conf.get('package.description', 'No description'), version: this.conf.get('version', this.conf.get('package.version') || 'dev') }; } onEnd(message) { return (error) => { if (error) { throw error; } sgUtil.log(`[✓] ${this.name} ${message}`, 'info'); }; } async generateViewerPages() { const {source, viewerDest, getViewerPagesLocals} = this, onEnd = this.onEnd('viewer html generated.'), templateFile = path.join(source, 'templates', 'viewer', 'index.pug'), renderOptions = Object.assign({ pretty: true, cache: false }, getViewerPagesLocals()); sgUtil.writeFile(path.join(viewerDest, 'index.html'), pug.renderFile(templateFile, renderOptions), onEnd); } async generateViewerStyles() { const {source, viewerDest} = this, onEnd = this.onEnd('viewer css generated.'), stylusStr = glob.sync(`${source}/style/**/!(_)*.styl`) .map((file) => fs.readFileSync(file, 'utf8')) .join('\n'); stylus(stylusStr) .set('include css', true) .set('prefix', 'dsc-') .use(nib()) .use(autoprefixer({ browsers: ['> 5%', 'last 1 versions'], cascade: false })) .include(path.join(source, 'style')) .import('_reset') .import('_mixins') .import('_variables') .render((err, css) => { if (err) { onEnd(err); } else { sgUtil.writeFile(path.join(viewerDest, 'css', 'app.css'), css, onEnd); } }); } async rollupViewerScripts() { const {source, viewerDest} = this, destFile = path.join(viewerDest, 'scripts', 'app.js'); sgUtil.createPath(destFile); try { const bundle = await rollup({ input: path.join(source, 'scripts', 'index.js'), plugins: [ rollupPluginGlobImport({ rename(name, id) { if (path.basename(id) !== 'index.js') { return null; } return path.basename(path.dirname(id)); } }), rollupPluginAlias({ vue: 'node_modules/vue/dist/vue.esm.js' }), rollupPluginResolve({ jsnext: true, main: true, module: true }), rollupPluginPug(), rollupPluginReplace({ 'process.env.NODE_ENV': JSON.stringify('development') }), rollupPluginCommonjs(), rollupPluginBabel() ] }); await bundle.write({ file: destFile, format: 'iife', sourcemap: false }); } catch (error) { throw error; } this.onEnd('viewer js bundle generated.'); } } module.exports = AppBuilder;
stefan-lehmann/atomatic
lib/AppBuilder.js
JavaScript
mit
4,620
'use strict'; const Hoek = require('hoek'); exports.plugin = { register: async (plugin, options) => { plugin.ext('onPreResponse', (request, h) => { try { var internals = { devEnv: (process.env.NODE_ENV === 'development'), meta: options.meta, credentials: request.auth.isAuthenticated ? request.auth.credentials : null }; var response = request.response; if (response.variety && response.variety === 'view') { response.source.context = Hoek.merge(internals, request.response.source.context); } return h.continue; } catch (error) { throw error; } }); }, pkg: require('../package.json'), name: 'context' };
SystangoTechnologies/Hapiness
lib/context.js
JavaScript
mit
672
'use strict'; //Customers service used to communicate Customers REST endpoints angular.module('customers') .factory('Customers', ['$resource', function($resource) { return $resource('customers/:customerId', { customerId: '@_id' }, { update: { method: 'PUT' } }); } ]) .factory('Notify', ['$rootScope', function($rootScope) { var notify = {}; notify.sendMsg = function(msg, data) { data = data || {}; $rootScope.$emit(msg, data); console.log('message sent!'); }; notify.getMsg = function(msg, func, scope) { var unbind = $rootScope.$on(msg, func); if (scope) { scope.$on('destroy', unbind); } }; return notify; } ]);
armackey/spa_practice
public/modules/customers/services/customers.client.service.js
JavaScript
mit
724
/* some devices call home before accepting a wifi access point. Spoof those responses. */ var path = require('path'); exports.load = function(server, boatData, settings) { var endpointMap = [ {'route': '/kindle-wifi/wifiredirect.html', 'responseFile': 'kindle.html'} , {'route': '/kindle-wifi/wifistub.html', 'responseFile': 'kindle.html'} //http://spectrum.s3.amazonaws.com ]; _.each(endpointMap, function(endpoint) { server.get(endpoint.route, function(req, res) { res.sendFile(path.join(__dirname + endpoint.responseFile)); }); }); };
HomegrownMarine/boat_computer
apps/wifi_allow/app.js
JavaScript
mit
603
// フォーマット var koyomi = require('../..').create(); var format = koyomi.format.bind(koyomi); var eq = require('assert').equal; koyomi.startMonth = 1; // 序数 (CC:経過日数) eq(format(20150101, 'CC'), '1'); eq(format(20150101, 'CC>0'), '1st'); eq(format(20150102, 'CC>0'), '2nd'); eq(format(20150103, 'CC>0'), '3rd'); eq(format(20150104, 'CC>0'), '4th'); eq(format(20150105, 'CC>0'), '5th'); eq(format(20150106, 'CC>0'), '6th'); eq(format(20150107, 'CC>0'), '7th'); eq(format(20150108, 'CC>0'), '8th'); eq(format(20150109, 'CC>0'), '9th'); eq(format(20150110, 'CC>0'), '10th'); eq(format(20150111, 'CC>0'), '11th'); eq(format(20150112, 'CC>0'), '12th'); eq(format(20150113, 'CC>0'), '13th'); eq(format(20150114, 'CC>0'), '14th'); eq(format(20150115, 'CC>0'), '15th'); eq(format(20150116, 'CC>0'), '16th'); eq(format(20150117, 'CC>0'), '17th'); eq(format(20150118, 'CC>0'), '18th'); eq(format(20150119, 'CC>0'), '19th'); eq(format(20150120, 'CC>0'), '20th'); eq(format(20150121, 'CC>0'), '21st'); eq(format(20150122, 'CC>0'), '22nd'); eq(format(20150123, 'CC>0'), '23rd'); eq(format(20150124, 'CC>0'), '24th'); eq(format(20150125, 'CC>0'), '25th'); eq(format(20150126, 'CC>0'), '26th'); eq(format(20150127, 'CC>0'), '27th'); eq(format(20150128, 'CC>0'), '28th'); eq(format(20150129, 'CC>0'), '29th'); eq(format(20150130, 'CC>0'), '30th'); eq(format(20150131, 'CC>0'), '31st'); eq(format(20150201, 'CC>0'), '32nd'); eq(format(20150202, 'CC>0'), '33rd'); eq(format(20150203, 'CC>0'), '34th'); eq(format(20150204, 'CC>0'), '35th'); eq(format(20150205, 'CC>0'), '36th'); eq(format(20150206, 'CC>0'), '37th'); eq(format(20150207, 'CC>0'), '38th'); eq(format(20150208, 'CC>0'), '39th'); eq(format(20150209, 'CC>0'), '40th'); eq(format(20150210, 'CC>0'), '41st'); eq(format(20150211, 'CC>0'), '42nd'); eq(format(20150212, 'CC>0'), '43rd'); eq(format(20150213, 'CC>0'), '44th'); eq(format(20150214, 'CC>0'), '45th'); eq(format(20150215, 'CC>0'), '46th'); eq(format(20150216, 'CC>0'), '47th'); eq(format(20150217, 'CC>0'), '48th'); eq(format(20150218, 'CC>0'), '49th'); eq(format(20150219, 'CC>0'), '50th'); eq(format(20150220, 'CC>0'), '51st'); eq(format(20150221, 'CC>0'), '52nd'); eq(format(20150222, 'CC>0'), '53rd'); eq(format(20150223, 'CC>0'), '54th'); eq(format(20150224, 'CC>0'), '55th'); eq(format(20150225, 'CC>0'), '56th'); eq(format(20150226, 'CC>0'), '57th'); eq(format(20150227, 'CC>0'), '58th'); eq(format(20150228, 'CC>0'), '59th'); eq(format(20150301, 'CC>0'), '60th'); eq(format(20150302, 'CC>0'), '61st'); eq(format(20150303, 'CC>0'), '62nd'); eq(format(20150304, 'CC>0'), '63rd'); eq(format(20150305, 'CC>0'), '64th'); eq(format(20150306, 'CC>0'), '65th'); eq(format(20150307, 'CC>0'), '66th'); eq(format(20150308, 'CC>0'), '67th'); eq(format(20150309, 'CC>0'), '68th'); eq(format(20150310, 'CC>0'), '69th'); eq(format(20150311, 'CC>0'), '70th'); eq(format(20150312, 'CC>0'), '71st'); eq(format(20150313, 'CC>0'), '72nd'); eq(format(20150314, 'CC>0'), '73rd'); eq(format(20150315, 'CC>0'), '74th'); eq(format(20150316, 'CC>0'), '75th'); eq(format(20150317, 'CC>0'), '76th'); eq(format(20150318, 'CC>0'), '77th'); eq(format(20150319, 'CC>0'), '78th'); eq(format(20150320, 'CC>0'), '79th'); eq(format(20150321, 'CC>0'), '80th'); eq(format(20150322, 'CC>0'), '81st'); eq(format(20150323, 'CC>0'), '82nd'); eq(format(20150324, 'CC>0'), '83rd'); eq(format(20150325, 'CC>0'), '84th'); eq(format(20150326, 'CC>0'), '85th'); eq(format(20150327, 'CC>0'), '86th'); eq(format(20150328, 'CC>0'), '87th'); eq(format(20150329, 'CC>0'), '88th'); eq(format(20150330, 'CC>0'), '89th'); eq(format(20150331, 'CC>0'), '90th'); eq(format(20150401, 'CC>0'), '91st'); eq(format(20150402, 'CC>0'), '92nd'); eq(format(20150403, 'CC>0'), '93rd'); eq(format(20150404, 'CC>0'), '94th'); eq(format(20150405, 'CC>0'), '95th'); eq(format(20150406, 'CC>0'), '96th'); eq(format(20150407, 'CC>0'), '97th'); eq(format(20150408, 'CC>0'), '98th'); eq(format(20150409, 'CC>0'), '99th'); eq(format(20150410, 'CC>0'), '100th'); eq(format(20150411, 'CC>0'), '101st'); eq(format(20150412, 'CC>0'), '102nd'); eq(format(20150413, 'CC>0'), '103rd'); eq(format(20150414, 'CC>0'), '104th'); eq(format(20150415, 'CC>0'), '105th'); eq(format(20150416, 'CC>0'), '106th'); eq(format(20150417, 'CC>0'), '107th'); eq(format(20150418, 'CC>0'), '108th'); eq(format(20150419, 'CC>0'), '109th'); eq(format(20150420, 'CC>0'), '110th'); eq(format(20150421, 'CC>0'), '111th'); eq(format(20150422, 'CC>0'), '112th'); eq(format(20150423, 'CC>0'), '113th'); eq(format(20150424, 'CC>0'), '114th'); eq(format(20150425, 'CC>0'), '115th'); eq(format(20150426, 'CC>0'), '116th'); eq(format(20150427, 'CC>0'), '117th'); eq(format(20150428, 'CC>0'), '118th'); eq(format(20150429, 'CC>0'), '119th'); eq(format(20150430, 'CC>0'), '120th'); eq(format(20150501, 'CC>0'), '121st'); eq(format(20150502, 'CC>0'), '122nd'); eq(format(20150503, 'CC>0'), '123rd'); eq(format(20150504, 'CC>0'), '124th'); eq(format(20150505, 'CC>0'), '125th'); eq(format(20150506, 'CC>0'), '126th'); eq(format(20150507, 'CC>0'), '127th'); eq(format(20150508, 'CC>0'), '128th'); eq(format(20150509, 'CC>0'), '129th'); eq(format(20150510, 'CC>0'), '130th'); eq(format(20150511, 'CC>0'), '131st'); eq(format(20150512, 'CC>0'), '132nd'); eq(format(20150513, 'CC>0'), '133rd'); eq(format(20150514, 'CC>0'), '134th'); eq(format(20150515, 'CC>0'), '135th'); eq(format(20150516, 'CC>0'), '136th'); eq(format(20150517, 'CC>0'), '137th'); eq(format(20150518, 'CC>0'), '138th'); eq(format(20150519, 'CC>0'), '139th'); eq(format(20150520, 'CC>0'), '140th'); eq(format(20150521, 'CC>0'), '141st'); eq(format(20150522, 'CC>0'), '142nd'); eq(format(20150523, 'CC>0'), '143rd'); eq(format(20150524, 'CC>0'), '144th'); eq(format(20150525, 'CC>0'), '145th'); eq(format(20150526, 'CC>0'), '146th'); eq(format(20150527, 'CC>0'), '147th'); eq(format(20150528, 'CC>0'), '148th'); eq(format(20150529, 'CC>0'), '149th'); eq(format(20150530, 'CC>0'), '150th'); eq(format(20150531, 'CC>0'), '151st'); eq(format(20150601, 'CC>0'), '152nd'); eq(format(20150602, 'CC>0'), '153rd'); eq(format(20150603, 'CC>0'), '154th'); eq(format(20150604, 'CC>0'), '155th'); eq(format(20150605, 'CC>0'), '156th'); eq(format(20150606, 'CC>0'), '157th'); eq(format(20150607, 'CC>0'), '158th'); eq(format(20150608, 'CC>0'), '159th'); eq(format(20150609, 'CC>0'), '160th'); eq(format(20150610, 'CC>0'), '161st'); eq(format(20150611, 'CC>0'), '162nd'); eq(format(20150612, 'CC>0'), '163rd'); eq(format(20150613, 'CC>0'), '164th'); eq(format(20150614, 'CC>0'), '165th'); eq(format(20150615, 'CC>0'), '166th'); eq(format(20150616, 'CC>0'), '167th'); eq(format(20150617, 'CC>0'), '168th'); eq(format(20150618, 'CC>0'), '169th'); eq(format(20150619, 'CC>0'), '170th'); eq(format(20150620, 'CC>0'), '171st'); eq(format(20150621, 'CC>0'), '172nd'); eq(format(20150622, 'CC>0'), '173rd'); eq(format(20150623, 'CC>0'), '174th'); eq(format(20150624, 'CC>0'), '175th'); eq(format(20150625, 'CC>0'), '176th'); eq(format(20150626, 'CC>0'), '177th'); eq(format(20150627, 'CC>0'), '178th'); eq(format(20150628, 'CC>0'), '179th'); eq(format(20150629, 'CC>0'), '180th'); eq(format(20150630, 'CC>0'), '181st'); eq(format(20150701, 'CC>0'), '182nd'); eq(format(20150702, 'CC>0'), '183rd'); eq(format(20150703, 'CC>0'), '184th'); eq(format(20150704, 'CC>0'), '185th'); eq(format(20150705, 'CC>0'), '186th'); eq(format(20150706, 'CC>0'), '187th'); eq(format(20150707, 'CC>0'), '188th'); eq(format(20150708, 'CC>0'), '189th'); eq(format(20150709, 'CC>0'), '190th'); eq(format(20150710, 'CC>0'), '191st'); eq(format(20150711, 'CC>0'), '192nd'); eq(format(20150712, 'CC>0'), '193rd'); eq(format(20150713, 'CC>0'), '194th'); eq(format(20150714, 'CC>0'), '195th'); eq(format(20150715, 'CC>0'), '196th'); eq(format(20150716, 'CC>0'), '197th'); eq(format(20150717, 'CC>0'), '198th'); eq(format(20150718, 'CC>0'), '199th'); eq(format(20150719, 'CC>0'), '200th'); eq(format(20150720, 'CC>0'), '201st'); eq(format(20150721, 'CC>0'), '202nd'); eq(format(20150722, 'CC>0'), '203rd'); eq(format(20150723, 'CC>0'), '204th'); eq(format(20150724, 'CC>0'), '205th'); eq(format(20150725, 'CC>0'), '206th'); eq(format(20150726, 'CC>0'), '207th'); eq(format(20150727, 'CC>0'), '208th'); eq(format(20150728, 'CC>0'), '209th'); eq(format(20150729, 'CC>0'), '210th'); eq(format(20150730, 'CC>0'), '211th'); eq(format(20150731, 'CC>0'), '212th'); eq(format(20150801, 'CC>0'), '213th'); eq(format(20150802, 'CC>0'), '214th'); eq(format(20150803, 'CC>0'), '215th'); eq(format(20150804, 'CC>0'), '216th'); eq(format(20150805, 'CC>0'), '217th'); eq(format(20150806, 'CC>0'), '218th'); eq(format(20150807, 'CC>0'), '219th'); eq(format(20150808, 'CC>0'), '220th'); eq(format(20150809, 'CC>0'), '221st'); eq(format(20150810, 'CC>0'), '222nd'); eq(format(20150811, 'CC>0'), '223rd'); eq(format(20150812, 'CC>0'), '224th'); eq(format(20150813, 'CC>0'), '225th'); eq(format(20150814, 'CC>0'), '226th'); eq(format(20150815, 'CC>0'), '227th'); eq(format(20150816, 'CC>0'), '228th'); eq(format(20150817, 'CC>0'), '229th'); eq(format(20150818, 'CC>0'), '230th'); eq(format(20150819, 'CC>0'), '231st'); eq(format(20150820, 'CC>0'), '232nd'); eq(format(20150821, 'CC>0'), '233rd'); eq(format(20150822, 'CC>0'), '234th'); eq(format(20150823, 'CC>0'), '235th'); eq(format(20150824, 'CC>0'), '236th'); eq(format(20150825, 'CC>0'), '237th'); eq(format(20150826, 'CC>0'), '238th'); eq(format(20150827, 'CC>0'), '239th'); eq(format(20150828, 'CC>0'), '240th'); eq(format(20150829, 'CC>0'), '241st'); eq(format(20150830, 'CC>0'), '242nd'); eq(format(20150831, 'CC>0'), '243rd'); eq(format(20150901, 'CC>0'), '244th'); eq(format(20150902, 'CC>0'), '245th'); eq(format(20150903, 'CC>0'), '246th'); eq(format(20150904, 'CC>0'), '247th'); eq(format(20150905, 'CC>0'), '248th'); eq(format(20150906, 'CC>0'), '249th'); eq(format(20150907, 'CC>0'), '250th'); eq(format(20150908, 'CC>0'), '251st'); eq(format(20150909, 'CC>0'), '252nd'); eq(format(20150910, 'CC>0'), '253rd'); eq(format(20150911, 'CC>0'), '254th'); eq(format(20150912, 'CC>0'), '255th'); eq(format(20150913, 'CC>0'), '256th'); eq(format(20150914, 'CC>0'), '257th'); eq(format(20150915, 'CC>0'), '258th'); eq(format(20150916, 'CC>0'), '259th'); eq(format(20150917, 'CC>0'), '260th'); eq(format(20150918, 'CC>0'), '261st'); eq(format(20150919, 'CC>0'), '262nd'); eq(format(20150920, 'CC>0'), '263rd'); eq(format(20150921, 'CC>0'), '264th'); eq(format(20150922, 'CC>0'), '265th'); eq(format(20150923, 'CC>0'), '266th'); eq(format(20150924, 'CC>0'), '267th'); eq(format(20150925, 'CC>0'), '268th'); eq(format(20150926, 'CC>0'), '269th'); eq(format(20150927, 'CC>0'), '270th'); eq(format(20150928, 'CC>0'), '271st'); eq(format(20150929, 'CC>0'), '272nd'); eq(format(20150930, 'CC>0'), '273rd'); eq(format(20151001, 'CC>0'), '274th'); eq(format(20151002, 'CC>0'), '275th'); eq(format(20151003, 'CC>0'), '276th'); eq(format(20151004, 'CC>0'), '277th'); eq(format(20151005, 'CC>0'), '278th'); eq(format(20151006, 'CC>0'), '279th'); eq(format(20151007, 'CC>0'), '280th'); eq(format(20151008, 'CC>0'), '281st'); eq(format(20151009, 'CC>0'), '282nd'); eq(format(20151010, 'CC>0'), '283rd'); eq(format(20151011, 'CC>0'), '284th'); eq(format(20151012, 'CC>0'), '285th'); eq(format(20151013, 'CC>0'), '286th'); eq(format(20151014, 'CC>0'), '287th'); eq(format(20151015, 'CC>0'), '288th'); eq(format(20151016, 'CC>0'), '289th'); eq(format(20151017, 'CC>0'), '290th'); eq(format(20151018, 'CC>0'), '291st'); eq(format(20151019, 'CC>0'), '292nd'); eq(format(20151020, 'CC>0'), '293rd'); eq(format(20151021, 'CC>0'), '294th'); eq(format(20151022, 'CC>0'), '295th'); eq(format(20151023, 'CC>0'), '296th'); eq(format(20151024, 'CC>0'), '297th'); eq(format(20151025, 'CC>0'), '298th'); eq(format(20151026, 'CC>0'), '299th'); eq(format(20151027, 'CC>0'), '300th'); eq(format(20151028, 'CC>0'), '301st'); eq(format(20151029, 'CC>0'), '302nd'); eq(format(20151030, 'CC>0'), '303rd'); eq(format(20151031, 'CC>0'), '304th'); eq(format(20151101, 'CC>0'), '305th'); eq(format(20151102, 'CC>0'), '306th'); eq(format(20151103, 'CC>0'), '307th'); eq(format(20151104, 'CC>0'), '308th'); eq(format(20151105, 'CC>0'), '309th'); eq(format(20151106, 'CC>0'), '310th'); eq(format(20151107, 'CC>0'), '311th'); eq(format(20151108, 'CC>0'), '312th'); eq(format(20151109, 'CC>0'), '313th'); eq(format(20151110, 'CC>0'), '314th'); eq(format(20151111, 'CC>0'), '315th'); eq(format(20151112, 'CC>0'), '316th'); eq(format(20151113, 'CC>0'), '317th'); eq(format(20151114, 'CC>0'), '318th'); eq(format(20151115, 'CC>0'), '319th'); eq(format(20151116, 'CC>0'), '320th'); eq(format(20151117, 'CC>0'), '321st'); eq(format(20151118, 'CC>0'), '322nd'); eq(format(20151119, 'CC>0'), '323rd'); eq(format(20151120, 'CC>0'), '324th'); eq(format(20151121, 'CC>0'), '325th'); eq(format(20151122, 'CC>0'), '326th'); eq(format(20151123, 'CC>0'), '327th'); eq(format(20151124, 'CC>0'), '328th'); eq(format(20151125, 'CC>0'), '329th'); eq(format(20151126, 'CC>0'), '330th'); eq(format(20151127, 'CC>0'), '331st'); eq(format(20151128, 'CC>0'), '332nd'); eq(format(20151129, 'CC>0'), '333rd'); eq(format(20151130, 'CC>0'), '334th'); eq(format(20151201, 'CC>0'), '335th'); eq(format(20151202, 'CC>0'), '336th'); eq(format(20151203, 'CC>0'), '337th'); eq(format(20151204, 'CC>0'), '338th'); eq(format(20151205, 'CC>0'), '339th'); eq(format(20151206, 'CC>0'), '340th'); eq(format(20151207, 'CC>0'), '341st'); eq(format(20151208, 'CC>0'), '342nd'); eq(format(20151209, 'CC>0'), '343rd'); eq(format(20151210, 'CC>0'), '344th'); eq(format(20151211, 'CC>0'), '345th'); eq(format(20151212, 'CC>0'), '346th'); eq(format(20151213, 'CC>0'), '347th'); eq(format(20151214, 'CC>0'), '348th'); eq(format(20151215, 'CC>0'), '349th'); eq(format(20151216, 'CC>0'), '350th'); eq(format(20151217, 'CC>0'), '351st'); eq(format(20151218, 'CC>0'), '352nd'); eq(format(20151219, 'CC>0'), '353rd'); eq(format(20151220, 'CC>0'), '354th'); eq(format(20151221, 'CC>0'), '355th'); eq(format(20151222, 'CC>0'), '356th'); eq(format(20151223, 'CC>0'), '357th'); eq(format(20151224, 'CC>0'), '358th'); eq(format(20151225, 'CC>0'), '359th'); eq(format(20151226, 'CC>0'), '360th'); eq(format(20151227, 'CC>0'), '361st'); eq(format(20151228, 'CC>0'), '362nd'); eq(format(20151229, 'CC>0'), '363rd'); eq(format(20151230, 'CC>0'), '364th'); eq(format(20151231, 'CC>0'), '365th'); // 文字列の序数 eq(format(20150101, 'GG>0'), '平成'); eq(format(20000101, 'y>0'), '00th'); eq(format(20010101, 'y>0'), '01st');
yukik/koyomi
test/format/josu.js
JavaScript
mit
14,614
import { apiGet, apiPut, apiDelete } from 'utils/api' import { flashError, flashSuccess } from 'utils/flash' import { takeLatest, takeEvery, call, put, select } from 'redux-saga/effects' import { filter, find, without, omit } from 'lodash' import { filesUrlSelector } from 'ducks/app' import { makeUploadsSelector } from 'ducks/uploads' import { makeFiltersQuerySelector } from 'ducks/filters' import { makeSelectedFileIdsSelector } from 'ducks/filePlacements' // Constants const GET_FILES = 'files/GET_FILES' const GET_FILES_SUCCESS = 'files/GET_FILES_SUCCESS' const UPLOADED_FILE = 'files/UPLOADED_FILE' const THUMBNAIL_GENERATED = 'files/THUMBNAIL_GENERATED' const DELETE_FILE = 'files/DELETE_FILE' const DELETE_FILE_FAILURE = 'files/DELETE_FILE_FAILURE' const UPDATE_FILE = 'files/UPDATE_FILE' export const UPDATE_FILE_SUCCESS = 'files/UPDATE_FILE_SUCCESS' export const UPDATE_FILE_FAILURE = 'files/UPDATE_FILE_FAILURE' const UPDATED_FILES = 'files/UPDATED_FILES' const REMOVED_FILES = 'files/REMOVED_FILES' const CHANGE_FILES_PAGE = 'files/CHANGE_FILES_PAGE' const MASS_SELECT = 'files/MASS_SELECT' const MASS_DELETE = 'files/MASS_DELETE' const MASS_CANCEL = 'files/MASS_CANCEL' // Actions export function getFiles (fileType, filesUrl, query = '') { return { type: GET_FILES, fileType, filesUrl, query } } export function getFilesSuccess (fileType, records, meta) { return { type: GET_FILES_SUCCESS, fileType, records, meta } } export function uploadedFile (fileType, file) { return { type: UPLOADED_FILE, fileType, file } } export function thumbnailGenerated (fileType, temporaryUrl, url) { return { type: THUMBNAIL_GENERATED, fileType, temporaryUrl, url } } export function updatedFiles (fileType, files) { return { type: UPDATED_FILES, fileType, files } } export function updateFile (fileType, filesUrl, file, attributes) { return { type: UPDATE_FILE, fileType, filesUrl, file, attributes } } export function deleteFile (fileType, filesUrl, file) { return { type: DELETE_FILE, fileType, filesUrl, file } } export function deleteFileFailure (fileType, file) { return { type: DELETE_FILE_FAILURE, fileType, file } } export function removedFiles (fileType, ids) { return { type: REMOVED_FILES, fileType, ids } } export function updateFileSuccess (fileType, file, response) { return { type: UPDATE_FILE_SUCCESS, fileType, file, response } } export function updateFileFailure (fileType, file) { return { type: UPDATE_FILE_FAILURE, fileType, file } } export function changeFilesPage (fileType, filesUrl, page) { return { type: CHANGE_FILES_PAGE, fileType, filesUrl, page } } export function massSelect (fileType, file, select) { return { type: MASS_SELECT, fileType, file, select } } export function massDelete (fileType) { return { type: MASS_DELETE, fileType } } export function massCancel (fileType) { return { type: MASS_CANCEL, fileType } } // Sagas function * getFilesPerform (action) { try { const filesUrl = `${action.filesUrl}?${action.query}` const response = yield call(apiGet, filesUrl) yield put(getFilesSuccess(action.fileType, response.data, response.meta)) } catch (e) { flashError(e.message) } } function * getFilesSaga () { // takeLatest automatically cancels any saga task started previously if it's still running yield takeLatest(GET_FILES, getFilesPerform) } function * updateFilePerform (action) { try { const { file, filesUrl, attributes } = action const fullUrl = `${filesUrl}/${file.id}` const data = { file: { id: file.id, attributes } } const response = yield call(apiPut, fullUrl, data) yield put(updateFileSuccess(action.fileType, action.file, response.data)) } catch (e) { flashError(e.message) yield put(updateFileFailure(action.fileType, action.file)) } } function * updateFileSaga () { yield takeEvery(UPDATE_FILE, updateFilePerform) } function * changeFilesPagePerform (action) { try { const filtersQuery = yield select(makeFiltersQuerySelector(action.fileType)) let query = `page=${action.page}` if (filtersQuery) { query = `${query}&${filtersQuery}` } yield put(getFiles(action.fileType, action.filesUrl, query)) } catch (e) { flashError(e.message) } } function * changeFilesPageSaga () { yield takeLatest(CHANGE_FILES_PAGE, changeFilesPagePerform) } function * massDeletePerform (action) { try { const { massSelectedIds } = yield select(makeMassSelectedIdsSelector(action.fileType)) const filesUrl = yield select(filesUrlSelector) const fullUrl = `${filesUrl}/mass_destroy?ids=${massSelectedIds.join(',')}` const res = yield call(apiDelete, fullUrl) if (res.error) { flashError(res.error) } else { flashSuccess(res.data.message) yield put(removedFiles(action.fileType, massSelectedIds)) yield put(massCancel(action.fileType)) } } catch (e) { flashError(e.message) } } function * massDeleteSaga () { yield takeLatest(MASS_DELETE, massDeletePerform) } function * deleteFilePerform (action) { try { const res = yield call(apiDelete, `${action.filesUrl}/${action.file.id}`) if (res.error) { flashError(res.error) } else { yield put(removedFiles(action.fileType, [action.file.id])) } } catch (e) { flashError(e.message) } } function * deleteFileSaga () { yield takeLatest(DELETE_FILE, deleteFilePerform) } export const filesSagas = [ getFilesSaga, updateFileSaga, changeFilesPageSaga, massDeleteSaga, deleteFileSaga ] // Selectors export const makeFilesStatusSelector = (fileType) => (state) => { return { loading: state.files[fileType] && state.files[fileType].loading, loaded: state.files[fileType] && state.files[fileType].loaded, massSelecting: state.files[fileType].massSelectedIds.length > 0 } } export const makeFilesLoadedSelector = (fileType) => (state) => { return state.files[fileType] && state.files[fileType].loaded } export const makeMassSelectedIdsSelector = (fileType) => (state) => { const base = state.files[fileType] || defaultFilesKeyState return { massSelectedIds: base.massSelectedIds, massSelectedIndestructibleIds: base.massSelectedIndestructibleIds } } export const makeFilesSelector = (fileType) => (state) => { const base = state.files[fileType] || defaultFilesKeyState const selected = base.massSelectedIds return base.records.map((file) => { if (file.id && selected.indexOf(file.id) !== -1) { return { ...file, massSelected: true } } else { return file } }) } export const makeFilesForListSelector = (fileType) => (state) => { const uploads = makeUploadsSelector(fileType)(state) let files if (uploads.uploadedIds.length) { files = makeFilesSelector(fileType)(state).map((file) => { if (uploads.uploadedIds.indexOf(file.id) === -1) { return file } else { return { ...file, attributes: { ...file.attributes, freshlyUploaded: true } } } }) } else { files = makeFilesSelector(fileType)(state) } return [ ...Object.values(uploads.records).map((upload) => ({ ...upload, attributes: { ...upload.attributes, uploading: true } })), ...files ] } export const makeRawUnselectedFilesForListSelector = (fileType, selectedIds) => (state) => { const all = makeFilesForListSelector(fileType)(state) return filter(all, (file) => selectedIds.indexOf(String(file.id)) === -1) } export const makeUnselectedFilesForListSelector = (fileType) => (state) => { const all = makeFilesForListSelector(fileType)(state) const selectedIds = makeSelectedFileIdsSelector(fileType)(state) return filter(all, (file) => selectedIds.indexOf(String(file.id)) === -1) } export const makeFilesPaginationSelector = (fileType) => (state) => { const base = state.files[fileType] || defaultFilesKeyState return base.pagination } export const makeFilesReactTypeSelector = (fileType) => (state) => { const base = state.files[fileType] || defaultFilesKeyState return base.reactType } export const makeFilesReactTypeIsImageSelector = (fileType) => (state) => { return makeFilesReactTypeSelector(fileType)(state) === 'image' } // State const defaultFilesKeyState = { loading: false, loaded: false, records: [], massSelectedIds: [], massSelectedIndestructibleIds: [], reactType: 'document', pagination: { page: null, pages: null } } const initialState = {} // Reducer function filesReducer (rawState = initialState, action) { const state = rawState if (action.fileType && !state[action.fileType]) { state[action.fileType] = { ...defaultFilesKeyState } } switch (action.type) { case GET_FILES: return { ...state, [action.fileType]: { ...state[action.fileType], loading: true } } case GET_FILES_SUCCESS: return { ...state, [action.fileType]: { ...state[action.fileType], records: action.records, loading: false, loaded: true, pagination: omit(action.meta, ['react_type']), reactType: action.meta.react_type } } case UPLOADED_FILE: return { ...state, [action.fileType]: { ...state[action.fileType], records: [action.file, ...state[action.fileType].records] } } case THUMBNAIL_GENERATED: { return { ...state, [action.fileType]: { ...state[action.fileType], records: state[action.fileType].records.map((record) => { if (record.attributes.thumb !== action.temporaryUrl) return record return { ...record, attributes: { ...record.attributes, thumb: action.url } } }) } } } case UPDATE_FILE: return { ...state, [action.fileType]: { ...state[action.fileType], records: state[action.fileType].records.map((record) => { if (record.id === action.file.id) { return { ...record, attributes: { ...record.attributes, ...action.attributes, updating: true } } } else { return record } }) } } case UPDATE_FILE_SUCCESS: return { ...state, [action.fileType]: { ...state[action.fileType], records: state[action.fileType].records.map((record) => { if (record.id === action.response.id) { return action.response } else { return record } }) } } case UPDATE_FILE_FAILURE: return { ...state, [action.fileType]: { ...state[action.fileType], records: state[action.fileType].records.map((record) => { if (record.id === action.file.id) { return { ...action.file } } else { return record } }) } } case UPDATED_FILES: return { ...state, [action.fileType]: { ...state[action.fileType], records: state[action.fileType].records.map((record) => { const found = find(action.files, { id: record.id }) return found || record }) } } case MASS_SELECT: { if (!action.file.id) return state let massSelectedIds = state[action.fileType].massSelectedIds let massSelectedIndestructibleIds = state[action.fileType].massSelectedIndestructibleIds if (action.select) { massSelectedIds = [...massSelectedIds, action.file.id] if (action.file.attributes.file_placements_size) { massSelectedIndestructibleIds = [...massSelectedIndestructibleIds, action.file.id] } } else { massSelectedIds = without(massSelectedIds, action.file.id) if (action.file.attributes.file_placements_size) { massSelectedIndestructibleIds = without(massSelectedIndestructibleIds, action.file.id) } } return { ...state, [action.fileType]: { ...state[action.fileType], massSelectedIds, massSelectedIndestructibleIds } } } case MASS_CANCEL: return { ...state, [action.fileType]: { ...state[action.fileType], massSelectedIds: [] } } case REMOVED_FILES: { const originalLength = state[action.fileType].records.length const records = state[action.fileType].records.filter((record) => action.ids.indexOf(record.id) === -1) return { ...state, [action.fileType]: { ...state[action.fileType], records, pagination: { ...state[action.fileType].pagination, to: records.length, count: state[action.fileType].pagination.count - (originalLength - records.length) } } } } case DELETE_FILE: return { ...state, [action.fileType]: { ...state[action.fileType], records: state[action.fileType].records.map((record) => { if (record.id === action.file.id) { return { ...record, _destroying: true } } else { return record } }) } } case DELETE_FILE_FAILURE: return { ...state, [action.fileType]: { ...state[action.fileType], records: state[action.fileType].records.map((record) => { if (record.id === action.file.id) { return { ...action.file } } else { return record } }) } } default: return state } } export default filesReducer
sinfin/folio
react/src/ducks/files.js
JavaScript
mit
14,083
var self = module.exports; self = (function(){ self.debug = true; self.prefix = '/kaskade'; self.ssl = false; /*{ key: {PEM}, cert: {PEM} }*/ self.port = 80; self.host = '0.0.0.0'; self.onConnectionClose = new Function(); self.redis = false; /*{ host: {String}, port: {Number}, options: {Object} }*/ self.init = function(cfg){ for(var c in cfg){ if(c in this) this[c] = cfg[c]; } }; })();
Aldlevine/Kaskade.js-node
lib/cfg.js
JavaScript
mit
577
/* eslint-disable no-undef */ const cukeBtnSubmit = '//button[@data-cuke="save-item"]'; const cukeInpSize = '//input[@data-cuke="size"]'; const cukeInpTitle = '//input[@data-cuke="title"]'; const cukeInpContent = '//textarea[@data-cuke="content"]'; const cukeSize = '//x-cuke[@id="size"]'; const cukeTitle = '//x-cuke[@id="title"]'; const cukeContent = '//x-cuke[@id="content"]'; /* const cukeHrefEdit = '//a[@data-cuke="edit-ite"]'; const cukeHrefDelete = '//a[@data-cuke="delete-item"]'; */ const cukeInvalidSize = '//span[@class="help-block error-block"]'; let size = ''; let title = ''; let content = ''; module.exports = function () { // Scenario: Create a new widget // ------------------------------------------------------------------------ this.Given(/^I have opened the 'add widgets' page : "([^"]*)"$/, function (_url) { browser.setViewportSize({ width: 1024, height: 480 }); browser.timeouts('implicit', 60000); browser.timeouts('page load', 60000); browser.url(_url); server.call('_widgets.wipe'); }); this.When(/^I create a "([^"]*)" millimetre "([^"]*)" item with text "([^"]*)",$/, function (_size, _title, _content) { size = _size; title = _title; content = _content; browser.waitForEnabled( cukeBtnSubmit ); browser.setValue(cukeInpTitle, title); browser.setValue(cukeInpSize, size); browser.setValue(cukeInpContent, content); browser.click(cukeBtnSubmit); }); this.Then(/^I see a new record with the same title, size and contents\.$/, function () { expect(browser.getText(cukeSize)).toEqual(size + ' millimetres.'); expect(browser.getText(cukeTitle)).toEqual(title); expect(browser.getText(cukeContent)).toEqual(content); }); // ======================================================================= // Scenario: Verify field validation // ------------------------------------------------------------------------ this.Given(/^I have opened the widgets list page : "([^"]*)"$/, function (_url) { browser.setViewportSize({ width: 1024, height: 480 }); browser.timeoutsImplicitWait(1000); browser.url(_url); }); /* let link = ''; this.Given(/^I choose to edit the "([^"]*)" item,$/, function (_widget) { link = '//a[@data-cuke="' + _widget + '"]'; browser.waitForExist( link ); browser.click(link); browser.waitForEnabled( cukeHrefEdit ); browser.click(cukeHrefEdit); }); */ this.When(/^I set 'Size' to "([^"]*)"$/, function (_size) { browser.setValue(cukeInpSize, _size); }); this.Then(/^I see the size validation hint "([^"]*)"\.$/, function (_message) { expect(browser.getText(cukeInvalidSize)).toEqual(_message); }); // ======================================================================= // Scenario: Fail to delete widget // ------------------------------------------------------------------------ let widget = ''; this.Given(/^I choose to view the "([^"]*)" item,$/, function (_widget) { widget = _widget; const cukeHrefWidget = `//a[@data-cuke="${widget}"]`; browser.waitForEnabled( cukeHrefWidget ); browser.click( cukeHrefWidget ); }); /* let href = null; this.When(/^I decide to delete the item,$/, function () { href = cukeHrefDelete; browser.waitForExist( href ); }); this.Then(/^I see it is disabled\.$/, function () { expect(browser.isEnabled( href )).toBe(true); }); */ // ======================================================================= // Scenario: Unable to update widget // ------------------------------------------------------------------------ /* this.When(/^I attempt to edit the item,$/, function () { href = cukeHrefEdit; browser.waitForExist( href ); }); */ // ======================================================================= // Scenario: Prohibited from add and from update // ------------------------------------------------------------------------ this.Given(/^I have opened the widgets editor page : "([^"]*)"$/, function (_url) { browser.setViewportSize({ width: 1024, height: 480 }); browser.timeouts('implicit', 60000); browser.timeouts('page load', 60000); browser.url(_url); }); /* this.Then(/^I see the warning "([^"]*)"$/, function (_warning) { expect(_warning).toEqual(browser.getText(cukeWarning)); }); */ // ======================================================================= // Scenario: Hide widget // ------------------------------------------------------------------------ /* this.Given(/^I have elected to "([^"]*)" the "([^"]*)" item\.$/, function (_cmd, _widget) { link = '//a[@data-cuke="' + _widget + '"]'; browser.waitForEnabled( link ); browser.click(link); let cukeHrefCmd = '//a[@data-cuke="' + _cmd + '-widget"]'; browser.waitForEnabled( cukeHrefCmd ); browser.click( cukeHrefCmd ); }); */ /* this.Then(/^I no longer see that widget record\.$/, function () { browser.waitForEnabled( cukeWidgetsList ); let item = browser.elements(link); expect(item.value.length).toEqual(0); }); */ };
warehouseman/meteor-mantra-kickstarter
.pkgs/mmks_widget/.e2e_tests/features/widgets/step_defs.js
JavaScript
mit
5,126
function EditMovieCtrl(MovieService,$stateParams) { // ViewModel const edit = this; edit.title = 'Edit Movies' + $stateParams.id; edit.back = function(){ window.history.back() } edit.checker = function(bool){ if(bool=='true') return true; if(bool=='false') return false; } edit.click = function(bool,key){ edit.data[key] = !bool } MovieService.getID($stateParams.id).then(function(results){ if(results.status===404) edit.data.movies='not found' edit.data = results }) // MovieService.get().then(function(results){ // edit.movies = results // }) edit.processForm = function(){ MovieService.put(edit.data).then(function(res){ console.log(res) }) } } EditMovieCtrl.$inject=['MovieService','$stateParams'] export default { name: 'EditMovieCtrl', fn: EditMovieCtrl };
johndoechang888/popcorn
fe/app/js/controllers/EditMovieCtrl.js
JavaScript
mit
882
/** * @fileoverview Rule to require or disallow line breaks inside braces. * @author Toru Nagashima */ "use strict"; //------------------------------------------------------------------------------ // Requirements //------------------------------------------------------------------------------ let astUtils = require("../ast-utils"); //------------------------------------------------------------------------------ // Helpers //------------------------------------------------------------------------------ // Schema objects. let OPTION_VALUE = { oneOf: [ { enum: ["always", "never"] }, { type: "object", properties: { multiline: { type: "boolean" }, minProperties: { type: "integer", minimum: 0 } }, additionalProperties: false, minProperties: 1 } ] }; /** * Normalizes a given option value. * * @param {string|Object|undefined} value - An option value to parse. * @returns {{multiline: boolean, minProperties: number}} Normalized option object. */ function normalizeOptionValue(value) { let multiline = false; let minProperties = Number.POSITIVE_INFINITY; if (value) { if (value === "always") { minProperties = 0; } else if (value === "never") { minProperties = Number.POSITIVE_INFINITY; } else { multiline = Boolean(value.multiline); minProperties = value.minProperties || Number.POSITIVE_INFINITY; } } else { multiline = true; } return {multiline: multiline, minProperties: minProperties}; } /** * Normalizes a given option value. * * @param {string|Object|undefined} options - An option value to parse. * @returns {{ObjectExpression: {multiline: boolean, minProperties: number}, ObjectPattern: {multiline: boolean, minProperties: number}}} Normalized option object. */ function normalizeOptions(options) { if (options && (options.ObjectExpression || options.ObjectPattern)) { return { ObjectExpression: normalizeOptionValue(options.ObjectExpression), ObjectPattern: normalizeOptionValue(options.ObjectPattern) }; } let value = normalizeOptionValue(options); return {ObjectExpression: value, ObjectPattern: value}; } //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ module.exports = { meta: { docs: { description: "enforce consistent line breaks inside braces", category: "Stylistic Issues", recommended: false }, fixable: "whitespace", schema: [ { oneOf: [ OPTION_VALUE, { type: "object", properties: { ObjectExpression: OPTION_VALUE, ObjectPattern: OPTION_VALUE }, additionalProperties: false, minProperties: 1 } ] } ] }, create: function(context) { let sourceCode = context.getSourceCode(); let normalizedOptions = normalizeOptions(context.options[0]); /** * Reports a given node if it violated this rule. * * @param {ASTNode} node - A node to check. This is an ObjectExpression node or an ObjectPattern node. * @param {{multiline: boolean, minProperties: number}} options - An option object. * @returns {void} */ function check(node) { let options = normalizedOptions[node.type]; let openBrace = sourceCode.getFirstToken(node); let closeBrace = sourceCode.getLastToken(node); let first = sourceCode.getTokenOrCommentAfter(openBrace); let last = sourceCode.getTokenOrCommentBefore(closeBrace); let needsLinebreaks = ( node.properties.length >= options.minProperties || ( options.multiline && node.properties.length > 0 && first.loc.start.line !== last.loc.end.line ) ); /* * Use tokens or comments to check multiline or not. * But use only tokens to check whether line breaks are needed. * This allows: * var obj = { // eslint-disable-line foo * a: 1 * } */ first = sourceCode.getTokenAfter(openBrace); last = sourceCode.getTokenBefore(closeBrace); if (needsLinebreaks) { if (astUtils.isTokenOnSameLine(openBrace, first)) { context.report({ message: "Expected a line break after this opening brace.", node: node, loc: openBrace.loc.start, fix: function(fixer) { return fixer.insertTextAfter(openBrace, "\n"); } }); } if (astUtils.isTokenOnSameLine(last, closeBrace)) { context.report({ message: "Expected a line break before this closing brace.", node: node, loc: closeBrace.loc.start, fix: function(fixer) { return fixer.insertTextBefore(closeBrace, "\n"); } }); } } else { if (!astUtils.isTokenOnSameLine(openBrace, first)) { context.report({ message: "Unexpected line break after this opening brace.", node: node, loc: openBrace.loc.start, fix: function(fixer) { return fixer.removeRange([ openBrace.range[1], first.range[0] ]); } }); } if (!astUtils.isTokenOnSameLine(last, closeBrace)) { context.report({ message: "Unexpected line break before this closing brace.", node: node, loc: closeBrace.loc.start, fix: function(fixer) { return fixer.removeRange([ last.range[1], closeBrace.range[0] ]); } }); } } } return { ObjectExpression: check, ObjectPattern: check }; } };
lauracurley/2016-08-ps-react
node_modules/eslint/lib/rules/object-curly-newline.js
JavaScript
mit
7,202
"use strict"; var GLOBAL_MOUNT_POINT_MAX = Math.pow(2, 53); var util = { uuid: function(){ return Math.ceil(Math.random() * GLOBAL_MOUNT_POINT_MAX); } }; module.exports = util;
Ovaldi/node-cqrs
src/util.js
JavaScript
mit
194
/** * @author Mat Groves http://matgroves.com/ @Doormat23 */ /** * A DisplayObjectContainer represents a collection of display objects. * It is the base class of all display objects that act as a container for other objects. * * @class DisplayObjectContainer * @extends DisplayObject * @constructor */ PIXI.DisplayObjectContainer = function() { PIXI.DisplayObject.call( this ); /** * [read-only] The of children of this container. * * @property children * @type Array<DisplayObject> * @readOnly */ this.children = []; } // constructor PIXI.DisplayObjectContainer.prototype = Object.create( PIXI.DisplayObject.prototype ); PIXI.DisplayObjectContainer.prototype.constructor = PIXI.DisplayObjectContainer; /** * Adds a child to the container. * * @method addChild * @param child {DisplayObject} The DisplayObject to add to the container */ PIXI.DisplayObjectContainer.prototype.addChild = function(child) { if(child.parent != undefined) { //// COULD BE THIS??? child.parent.removeChild(child); // return; } child.parent = this; this.children.push(child); // update the stage refference.. if(this.stage) { var tmpChild = child; do { if(tmpChild.interactive)this.stage.dirty = true; tmpChild.stage = this.stage; tmpChild = tmpChild._iNext; } while(tmpChild) } // LINKED LIST // // modify the list.. var childFirst = child.first var childLast = child.last; var nextObject; var previousObject; // this could be wrong if there is a filter?? if(this._filters || this._mask) { previousObject = this.last._iPrev; } else { previousObject = this.last; } nextObject = previousObject._iNext; // always true in this case // need to make sure the parents last is updated too var updateLast = this; var prevLast = previousObject; while(updateLast) { if(updateLast.last == prevLast) { updateLast.last = child.last; } updateLast = updateLast.parent; } if(nextObject) { nextObject._iPrev = childLast; childLast._iNext = nextObject; } childFirst._iPrev = previousObject; previousObject._iNext = childFirst; // need to remove any render groups.. if(this.__renderGroup) { // being used by a renderTexture.. if it exists then it must be from a render texture; if(child.__renderGroup)child.__renderGroup.removeDisplayObjectAndChildren(child); // add them to the new render group.. this.__renderGroup.addDisplayObjectAndChildren(child); } } /** * Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown * * @method addChildAt * @param child {DisplayObject} The child to add * @param index {Number} The index to place the child in */ PIXI.DisplayObjectContainer.prototype.addChildAt = function(child, index) { if(index >= 0 && index <= this.children.length) { if(child.parent != undefined) { child.parent.removeChild(child); } child.parent = this; if(this.stage) { var tmpChild = child; do { if(tmpChild.interactive)this.stage.dirty = true; tmpChild.stage = this.stage; tmpChild = tmpChild._iNext; } while(tmpChild) } // modify the list.. var childFirst = child.first; var childLast = child.last; var nextObject; var previousObject; if(index == this.children.length) { previousObject = this.last; var updateLast = this; var prevLast = this.last; while(updateLast) { if(updateLast.last == prevLast) { updateLast.last = child.last; } updateLast = updateLast.parent; } } else if(index == 0) { previousObject = this; } else { previousObject = this.children[index-1].last; } nextObject = previousObject._iNext; // always true in this case if(nextObject) { nextObject._iPrev = childLast; childLast._iNext = nextObject; } childFirst._iPrev = previousObject; previousObject._iNext = childFirst; this.children.splice(index, 0, child); // need to remove any render groups.. if(this.__renderGroup) { // being used by a renderTexture.. if it exists then it must be from a render texture; if(child.__renderGroup)child.__renderGroup.removeDisplayObjectAndChildren(child); // add them to the new render group.. this.__renderGroup.addDisplayObjectAndChildren(child); } } else { throw new Error(child + " The index "+ index +" supplied is out of bounds " + this.children.length); } } /** * [NYI] Swaps the depth of 2 displayObjects * * @method swapChildren * @param child {DisplayObject} * @param child2 {DisplayObject} * @private */ PIXI.DisplayObjectContainer.prototype.swapChildren = function(child, child2) { if(child === child2) { return; } var index1 = this.children.indexOf(child); var index2 = this.children.indexOf(child2); if(index1 < 0 || index2 < 0) { throw new Error("swapChildren: Both the supplied DisplayObjects must be a child of the caller."); } this.removeChild(child); this.removeChild(child2); if(index1 < index2) { this.addChildAt(child2, index1); this.addChildAt(child, index2); } else { this.addChildAt(child, index2); this.addChildAt(child2, index1); } } /** * Returns the Child at the specified index * * @method getChildAt * @param index {Number} The index to get the child from */ PIXI.DisplayObjectContainer.prototype.getChildAt = function(index) { if(index >= 0 && index < this.children.length) { return this.children[index]; } else { throw new Error(child + " Both the supplied DisplayObjects must be a child of the caller " + this); } } /** * Removes a child from the container. * * @method removeChild * @param child {DisplayObject} The DisplayObject to remove */ PIXI.DisplayObjectContainer.prototype.removeChild = function(child) { var index = this.children.indexOf( child ); if ( index !== -1 ) { // unlink // // modify the list.. var childFirst = child.first; var childLast = child.last; var nextObject = childLast._iNext; var previousObject = childFirst._iPrev; if(nextObject)nextObject._iPrev = previousObject; previousObject._iNext = nextObject; if(this.last == childLast) { var tempLast = childFirst._iPrev; // need to make sure the parents last is updated too var updateLast = this; while(updateLast.last == childLast) { updateLast.last = tempLast; updateLast = updateLast.parent; if(!updateLast)break; } } childLast._iNext = null; childFirst._iPrev = null; // update the stage reference.. if(this.stage) { var tmpChild = child; do { if(tmpChild.interactive)this.stage.dirty = true; tmpChild.stage = null; tmpChild = tmpChild._iNext; } while(tmpChild) } // webGL trim if(child.__renderGroup) { child.__renderGroup.removeDisplayObjectAndChildren(child); } child.parent = undefined; this.children.splice( index, 1 ); } else { throw new Error(child + " The supplied DisplayObject must be a child of the caller " + this); } } /* * Updates the container's children's transform for rendering * * @method updateTransform * @private */ PIXI.DisplayObjectContainer.prototype.updateTransform = function() { if(!this.visible)return; PIXI.DisplayObject.prototype.updateTransform.call( this ); for(var i=0,j=this.children.length; i<j; i++) { this.children[i].updateTransform(); } }
MKelm/pixi.js
src/pixi/display/DisplayObjectContainer.js
JavaScript
mit
7,407
function ga() {} var _gaq = []
NonLogicalDev/ucsd_cat125
client/scripts/ga.js
JavaScript
mit
31
export { default } from 'ember-stripe-elements/components/stripe-card';
code-corps/ember-stripe-elements
app/components/stripe-card.js
JavaScript
mit
72
version https://git-lfs.github.com/spec/v1 oid sha256:a2aca9cd81f31f3e9e83559fdcfa84d3ee900090ee4baeb2bae129e9d06473eb size 1264
yogeshsaroya/new-cdnjs
ajax/libs/foundation/5.4.1/js/foundation/foundation.equalizer.min.js
JavaScript
mit
129
const exec = require('child_process').exec const path = require('path') const fs = require('fs') const execPath = process.execPath const binPath = path.dirname(execPath) const dep = path.join(execPath, '../../lib/node_modules/dep') const repository = 'https://github.com/depjs/dep.git' const bin = path.join(dep, 'bin/dep.js') process.stdout.write( 'exec: git' + [' clone', repository, dep].join(' ') + '\n' ) exec('git clone ' + repository + ' ' + dep, (e) => { if (e) throw e process.stdout.write('link: ' + bin + '\n') process.stdout.write(' => ' + path.join(binPath, 'dep') + '\n') fs.symlink(bin, path.join(binPath, 'dep'), (e) => { if (e) throw e }) })
depjs/dep
scripts/install.js
JavaScript
mit
676
"use strict"; ace.define("ace/snippets/matlab", ["require", "exports", "module"], function (e, t, n) { "use strict"; t.snippetText = undefined, t.scope = "matlab"; });
IonicaBizau/arc-assembler
clients/ace-builds/src-min-noconflict/snippets/matlab.js
JavaScript
mit
172
(function(){ /** * PubSub implementation (fast) */ var PubSub = function PubSub( defaultScope ){ if (!(this instanceof PubSub)){ return new PubSub( defaultScope ); } this._topics = {}; this.defaultScope = defaultScope || this; }; PubSub.prototype = { /** * Subscribe a callback (or callbacks) to a topic (topics). * * @param {String|Object} topic The topic name, or a config with key/value pairs of { topic: callbackFn, ... } * @param {Function} fn The callback function (if not using Object as previous argument) * @param {Object} scope (optional) The scope to bind callback to * @param {Number} priority (optional) The priority of the callback (higher = earlier) * @return {this} */ subscribe: function( topic, fn, scope, priority ){ var listeners = this._topics[ topic ] || (this._topics[ topic ] = []) ,orig = fn ,idx ; // check if we're subscribing to multiple topics // with an object if ( Physics.util.isObject( topic ) ){ for ( var t in topic ){ this.subscribe( t, topic[ t ], fn, scope ); } return this; } if ( Physics.util.isObject( scope ) ){ fn = Physics.util.bind( fn, scope ); fn._bindfn_ = orig; } else if (!priority) { priority = scope; } fn._priority_ = priority; idx = Physics.util.sortedIndex( listeners, fn, '_priority_' ); listeners.splice( idx, 0, fn ); return this; }, /** * Unsubscribe function from topic * @param {String} topic Topic name * @param {Function} fn The original callback function * @return {this} */ unsubscribe: function( topic, fn ){ var listeners = this._topics[ topic ] ,listn ; if (!listeners){ return this; } for ( var i = 0, l = listeners.length; i < l; i++ ){ listn = listeners[ i ]; if ( listn._bindfn_ === fn || listn === fn ){ listeners.splice(i, 1); break; } } return this; }, /** * Publish data to a topic * @param {Object|String} data * @param {Object} scope The scope to be included in the data argument passed to callbacks * @return {this} */ publish: function( data, scope ){ if (typeof data !== 'object'){ data = { topic: data }; } var topic = data.topic ,listeners = this._topics[ topic ] ,l = listeners && listeners.length ; if ( !topic ){ throw 'Error: No topic specified in call to world.publish()'; } if ( !l ){ return this; } data.scope = data.scope || this.defaultScope; while ( l-- ){ data.handler = listeners[ l ]; data.handler( data ); } return this; } }; Physics.util.pubsub = PubSub; })();
lejoying/ibrainstroms
web/PhysicsJS/src/util/pubsub.js
JavaScript
mit
3,581
function fixPosition() { console.log($(window).scrollTop()); // if its anywhee but at the very top of the screen, fix it if ($(window).scrollTop() >= headerHeight) { // magic number offset that just feels right to prevent the 'bounce' // if (headPosition.top > 0){ $('body').addClass('js-fix-positions'); } // otherwise, make sure its not fixed else { $('body').removeClass('js-fix-positions'); } }; //Generate the weight guide meter with JS as its pretty useless without it, without some server side intervention function createBasketWeightGuide(){ // create the element for the guide $('.af__basket__weight-guide--label').after('<div class="js-af__weight-guide__wrapper"></div>'); $('.js-af__weight-guide__wrapper').append('<div class="js-af__weight-guide__meter"></div>'); $('.af__product__add-to-basket').submit(function(e){ e.preventDefault(); //var $multiplier= weightGuideListener(); }) } function weightGuideListener(){ var $bar = $('.js-af__weight-guide__meter'); //Didnt work as expected, so used this for speed: http://stackoverflow.com/questions/12945352/change-width-on-click-using-jquery var $percentage = (100 * parseFloat($bar.css('width')) / parseFloat($bar.parent().css('width')) +10 + '%'); $bar.css("width", $percentage); var $message = $('.af__basket__weight-guide--cta'); currentWidth=parseInt($percentage); console.log(currentWidth); // cannot use switch for less than if (currentWidth <= 21 ){ $message.text('Plenty of room'); } else if (currentWidth <= 45){ $bar.css('background-color', '#ee0'); } else if (currentWidth <= 65){ $bar.css('background-color', '#c1ea39'); $message.text('Getting there...') } else if (currentWidth <= 80){ $message.text('Room for a little one?'); } else if (currentWidth <= 89){ $message.text('Almost full!'); } else if (currentWidth >= 95 && currentWidth <= 99){ $message.text('Lookin\' good!'); } else if (currentWidth <= 99.9){ $bar.css('background-color', '#3ece38'); } else { $bar.css('background-color', '#d00'); $bar.css("width", "100%"); $message.text('(Delivery band 2 logic)'); } } function selectOnFocus(){ $('.af__product__add-to-basket input').focus(function(){ this.select(); }) }; $(document).ready(function(){ headerHeight=$('.af__header').outerHeight(); // icnludes padding and margins scrollIntervalID = setInterval(fixPosition, 16); // = 60 FPS createBasketWeightGuide(); selectOnFocus(); });
brtdesign/brtdesign.github.io
work/af-december2016/assets/js/_default.js
JavaScript
mit
2,769
import React from 'react'; import ReactDOM from 'react-dom'; import _ from 'underscore'; import babel from 'babel-core/browser'; import esprima from 'esprima'; import escodegen from 'escodegen'; import estraverse from 'estraverse'; import Codemirror from 'react-codemirror'; import classNames from 'classnames'; import { iff, default as globalUtils } from 'app/utils/globalUtils'; import './styles/app.less'; import 'react-codemirror/node_modules/codemirror/lib/codemirror.css'; import 'react-codemirror/node_modules/codemirror/theme/material.css'; import 'app/modules/JsxMode'; const localStorage = window.localStorage; const TAB_SOURCE = 'SOURCE'; const TAB_TRANSCODE = 'TRANSCODE'; const LiveDemoApp = React.createClass({ getInitialState() { return { sourceCode: '', transCode: '', transError: '', tab: TAB_SOURCE, func: function() { } }; }, componentWillMount() { this._setSource(localStorage.getItem('sourceCode') || ''); }, componentDidMount() { this._renderPreview(); }, componentDidUpdate() { this._renderPreview(); }, render() { const { sourceCode, transCode, tab, transError } = this.state; const showSource = (tab === TAB_SOURCE); const cmOptions = { lineNumbers: true, readOnly: !showSource, mode: 'jsx', theme: 'material', tabSize: 2, smartIndent: true, indentWithTabs: false }; const srcTabClassName = classNames({ 'otsLiveDemoApp-tab': true, 'otsLiveDemoApp-active': showSource }); const transTabClassName = classNames({ 'otsLiveDemoApp-tab': true, 'otsLiveDemoApp-active': !showSource }); console.log((transCode || transError)); return ( <div className='otsLiveDemoApp'> <div className='otsLiveDemoApp-tabs'> <button className={srcTabClassName} onClick={this._onSrcClick}>Source</button> <button className={transTabClassName} onClick={this._onTransClick}>Transcode</button> </div> <div className='otsLiveDemoApp-src'> <Codemirror value={showSource ? sourceCode : (transCode || transError)} onChange={this._onChangeEditor} options={cmOptions} /> </div> </div> ); }, _onChangeEditor(value) { const { tab } = this.state; if (tab === TAB_SOURCE) { this._setSource(value); } }, _onSrcClick() { this.setState({ tab: TAB_SOURCE }); }, _onTransClick() { this.setState({ tab: TAB_TRANSCODE }); }, _setSource(sourceCode) { localStorage.setItem('sourceCode', sourceCode); const dependencies = []; let transCode; let transError; try { const es5trans = babel.transform(sourceCode); let uniqueId = 0; estraverse.replace(es5trans.ast.program, { enter(node, parent) { if ( node.type === 'CallExpression' && node.callee.type === 'Identifier' && node.callee.name === 'require' && node.arguments.length === 1 && node.arguments[0].type === 'Literal' ) { const dep = { identifier: '__DEPENDENCY_'+ (uniqueId++) , depName: node.arguments[0].value }; dependencies.push(dep); return { name: dep.identifier, type: 'Identifier' }; } else if ( node.type === 'AssignmentExpression' && node.left.type === 'MemberExpression' && node.left.object.type === 'Identifier' && node.left.object.name === 'module' && node.left.property.type === 'Identifier' && node.left.property.name === 'exports' ) { return { type: 'ReturnStatement', argument: node.right } } } }); transCode = escodegen.generate(es5trans.ast.program); } catch (e) { const msg = 'Error transpiling source code: '; transError = msg + e.toString(); globalUtils.error(msg, e); } this.setState({ sourceCode, transCode, transError }); if (transCode) { try { const fnConstArgs = [{ what: 'aaa'}].concat(dependencies.map((dep) => { return dep.identifier; })); fnConstArgs.push('exports'); fnConstArgs.push(transCode); this.setState({ func: new (Function.prototype.bind.apply(Function, fnConstArgs)) }); } catch(e) { console.error('Runtime Error', e); } } }, _renderPreview() { const { func } = this.state; const { Component, error } = (() => { try { return { Component: func(React, {}) }; } catch(e) { return { error: e }; } })(); try { if (Component) { ReactDOM.render(<Component />, document.getElementById('preview')); } else if (error) { ReactDOM.render(<div className='otsLiveDemoApp-error'>{error.toString()}</div>, document.getElementById('preview')); } } catch (e) { globalUtils.error('Fatal error rendering preview: ', e); } } }); ReactDOM.render(<LiveDemoApp />, document.getElementById('editor')); // const newProgram = { // type: 'Program', // body: [ // { // type: 'CallExpression', // callee: { // type: 'FunctionExpression', // id: null, // params: dependencies.map((dep) => { // return { // type: 'Identifier', // name: dep.identifier // } // }), // body: { // type: 'BlockStatement', // body: es5trans.ast.program.body // } // }, // arguments: [] // } // ] // };
frank-weindel/react-live-demo
app/index.js
JavaScript
mit
5,927
/** @babel */ /* eslint-env jasmine, atomtest */ /* This file contains verifying specs for: https://github.com/sindresorhus/atom-editorconfig/issues/118 */ import fs from 'fs'; import path from 'path'; const testPrefix = path.basename(__filename).split('-').shift(); const projectRoot = path.join(__dirname, 'fixtures'); const filePath = path.join(projectRoot, `test.${testPrefix}`); describe('editorconfig', () => { let textEditor; const textWithoutTrailingWhitespaces = 'I\nam\nProvidence.'; const textWithManyTrailingWhitespaces = 'I \t \nam \t \nProvidence.'; beforeEach(() => { waitsForPromise(() => Promise.all([ atom.packages.activatePackage('editorconfig'), atom.workspace.open(filePath) ]).then(results => { textEditor = results[1]; }) ); }); afterEach(() => { // remove the created fixture, if it exists runs(() => { fs.stat(filePath, (err, stats) => { if (!err && stats.isFile()) { fs.unlink(filePath); } }); }); waitsFor(() => { try { return fs.statSync(filePath).isFile() === false; } catch (err) { return true; } }, 5000, `removed ${filePath}`); }); describe('Atom being set to remove trailing whitespaces', () => { beforeEach(() => { // eslint-disable-next-line camelcase textEditor.getBuffer().editorconfig.settings.trim_trailing_whitespace = true; // eslint-disable-next-line camelcase textEditor.getBuffer().editorconfig.settings.insert_final_newline = false; }); it('should strip trailing whitespaces on save.', () => { textEditor.setText(textWithManyTrailingWhitespaces); textEditor.save(); expect(textEditor.getText().length).toEqual(textWithoutTrailingWhitespaces.length); }); }); });
florianb/atom-editorconfig
spec/iss118-spec.js
JavaScript
mit
1,733
import React from "react" import { injectIntl } from "react-intl" import { NavLink } from "react-router-dom" import PropTypes from "prop-types" import Styles from "./Navigation.css" function Navigation({ intl }) { return ( <ul className={Styles.list}> <li><NavLink exact to="/" activeClassName={Styles.activeLink}>Home</NavLink></li> <li><NavLink to="/redux" activeClassName={Styles.activeLink}>Redux</NavLink></li> <li><NavLink to="/localization" activeClassName={Styles.activeLink}>Localization</NavLink></li> <li><NavLink to="/markdown" activeClassName={Styles.activeLink}>Markdown</NavLink></li> <li><NavLink to="/missing" activeClassName={Styles.activeLink}>Missing</NavLink></li> </ul> ) } Navigation.propTypes = { intl: PropTypes.object } export default injectIntl(Navigation)
sebastian-software/edgeapp
src/components/Navigation.js
JavaScript
mit
832
const Marionette = require('backbone.marionette'); const MeterValuesView = require('./MeterValuesView.js'); module.exports = class EnergyMetersView extends Marionette.View { template = Templates['capabilities/energy/meters']; className() { return 'energy-meters'; } regions() { return { metersByPeriod: '.metersByPeriod' }; } modelEvents() { return {change: 'render'}; } onRender() { const metersView = new Marionette.CollectionView({ collection: this.model.metersByPeriod(), childView: MeterValuesView }); this.showChildView('metersByPeriod', metersView); } }
monitron/jarvis-ha
lib/web/scripts/capabilities/energy/EnergyMetersView.js
JavaScript
mit
625
const _ = require('lodash'); const en = { modifiers: require('../../res/en').modifiers }; const Types = require('../../lib/types'); const optional = { optional: true }; const repeatable = { repeatable: true }; const nullableNumber = { type: Types.NameExpression, name: 'number', nullable: true }; const nullableNumberOptional = _.extend({}, nullableNumber, optional); const nullableNumberOptionalRepeatable = _.extend({}, nullableNumber, optional, repeatable); const nullableNumberRepeatable = _.extend({}, nullableNumber, repeatable); const nonNullableObject = { type: Types.NameExpression, name: 'Object', nullable: false }; const nonNullableObjectOptional = _.extend({}, nonNullableObject, optional); const nonNullableObjectOptionalRepeatable = _.extend({}, nonNullableObject, optional, repeatable); const nonNullableObjectRepeatable = _.extend({}, nonNullableObject, repeatable); module.exports = [ { description: 'nullable number', expression: '?number', parsed: nullableNumber, described: { en: { simple: 'nullable number', extended: { description: 'number', modifiers: { nullable: en.modifiers.extended.nullable }, returns: '' } } } }, { description: 'postfix nullable number', expression: 'number?', newExpression: '?number', parsed: nullableNumber, described: { en: { simple: 'nullable number', extended: { description: 'number', modifiers: { nullable: en.modifiers.extended.nullable }, returns: '' } } } }, { description: 'non-nullable object', expression: '!Object', parsed: nonNullableObject, described: { en: { simple: 'non-null Object', extended: { description: 'Object', modifiers: { nullable: en.modifiers.extended.nonNullable }, returns: '' } } } }, { description: 'postfix non-nullable object', expression: 'Object!', newExpression: '!Object', parsed: nonNullableObject, described: { en: { simple: 'non-null Object', extended: { description: 'Object', modifiers: { nullable: en.modifiers.extended.nonNullable }, returns: '' } } } }, { description: 'repeatable nullable number', expression: '...?number', parsed: nullableNumberRepeatable, described: { en: { simple: 'nullable repeatable number', extended: { description: 'number', modifiers: { nullable: en.modifiers.extended.nullable, repeatable: en.modifiers.extended.repeatable }, returns: '' } } } }, { description: 'postfix repeatable nullable number', expression: '...number?', newExpression: '...?number', parsed: nullableNumberRepeatable, described: { en: { simple: 'nullable repeatable number', extended: { description: 'number', modifiers: { nullable: en.modifiers.extended.nullable, repeatable: en.modifiers.extended.repeatable }, returns: '' } } } }, { description: 'repeatable non-nullable object', expression: '...!Object', parsed: nonNullableObjectRepeatable, described: { en: { simple: 'non-null repeatable Object', extended: { description: 'Object', modifiers: { nullable: en.modifiers.extended.nonNullable, repeatable: en.modifiers.extended.repeatable }, returns: '' } } } }, { description: 'postfix repeatable non-nullable object', expression: '...Object!', newExpression: '...!Object', parsed: nonNullableObjectRepeatable, described: { en: { simple: 'non-null repeatable Object', extended: { description: 'Object', modifiers: { nullable: en.modifiers.extended.nonNullable, repeatable: en.modifiers.extended.repeatable }, returns: '' } } } }, { description: 'postfix optional nullable number', expression: 'number=?', newExpression: '?number=', parsed: nullableNumberOptional, described: { en: { simple: 'optional nullable number', extended: { description: 'number', modifiers: { nullable: en.modifiers.extended.nullable, optional: en.modifiers.extended.optional }, returns: '' } } } }, { description: 'postfix nullable optional number', expression: 'number?=', newExpression: '?number=', parsed: nullableNumberOptional, described: { en: { simple: 'optional nullable number', extended: { description: 'number', modifiers: { nullable: en.modifiers.extended.nullable, optional: en.modifiers.extended.optional }, returns: '' } } } }, { description: 'postfix repeatable nullable optional number', expression: '...number?=', newExpression: '...?number=', parsed: nullableNumberOptionalRepeatable, described: { en: { simple: 'optional nullable repeatable number', extended: { description: 'number', modifiers: { nullable: en.modifiers.extended.nullable, optional: en.modifiers.extended.optional, repeatable: en.modifiers.extended.repeatable }, returns: '' } } } }, { description: 'postfix optional non-nullable object', expression: 'Object=!', newExpression: '!Object=', parsed: nonNullableObjectOptional, described: { en: { simple: 'optional non-null Object', extended: { description: 'Object', modifiers: { nullable: en.modifiers.extended.nonNullable, optional: en.modifiers.extended.optional }, returns: '' } } } }, { description: 'postfix non-nullable optional object', expression: 'Object!=', newExpression: '!Object=', parsed: nonNullableObjectOptional, described: { en: { simple: 'optional non-null Object', extended: { description: 'Object', modifiers: { nullable: en.modifiers.extended.nonNullable, optional: en.modifiers.extended.optional }, returns: '' } } } }, { description: 'postfix repeatable non-nullable optional object', expression: '...Object!=', newExpression: '...!Object=', parsed: nonNullableObjectOptionalRepeatable, described: { en: { simple: 'optional non-null repeatable Object', extended: { description: 'Object', modifiers: { nullable: en.modifiers.extended.nonNullable, optional: en.modifiers.extended.optional, repeatable: en.modifiers.extended.repeatable }, returns: '' } } } } ];
hegemonic/catharsis
test/specs/nullable.js
JavaScript
mit
9,138
angular.module('Reader.services.options', []) .factory('options', function($rootScope, $q) { var controllerObj = {}; options.onChange(function (changes) { $rootScope.$apply(function () { for (var property in changes) { controllerObj[property] = changes[property].newValue; } }); }); return { get: function (callback) { options.get(function (values) { $rootScope.$apply(function () { angular.copy(values, controllerObj); if (callback instanceof Function) { callback(controllerObj); } }); }); return controllerObj; }, set: function (values) { options.set(values); }, enableSync: options.enableSync, isSyncEnabled: options.isSyncEnabled }; });
Janpot/google-reader-notifier
app/js/services/options.js
JavaScript
mit
858
import Ember from 'ember'; import DS from 'ember-data'; import DataAdapterMixin from 'ember-simple-auth/mixins/data-adapter-mixin'; export default DS.RESTAdapter.extend(DataAdapterMixin, { authorizer: 'authorizer:dspace', initENVProperties: Ember.on('init', function() { let ENV = this.container.lookupFactory('config:environment'); if (Ember.isPresent(ENV.namespace)) { this.set('namespace', ENV.namespace); } if (Ember.isPresent(ENV.host)) { this.set('host', ENV.host); } }), //coalesceFindRequests: true, -> commented out, because it only works for some endpoints (e.g. items) and not others (e.g. communities) ajax(url, type, hash) { if (Ember.isEmpty(hash)) { hash = {}; } if (Ember.isEmpty(hash.data)) { hash.data = {}; } if (type === "GET") { hash.data.expand = 'all'; //add ?expand=all to all GET calls } return this._super(url, type, hash); } });
atmire/dsember-core
addon/adapters/application.js
JavaScript
mit
949
function alertThanks (post) { alert("Thanks for submitting a post!"); return post; } Telescope.callbacks.add("postSubmitClient", alertThanks);
mxchelle/PhillyAIMSApp
packages/custom/lib/callbacks.js
JavaScript
mit
148
"use strict"; var async = require('async'); var fs = require('fs'); var util = require('util'); var prompt = require('prompt'); var httpRequest = require('emsoap').subsystems.httpRequest; var common = require('./common'); var mms = require('./mms'); var mmscmd = require('./mmscmd'); var deploy = require('./deploy'); var session; // MMS session var modelFile = "sfmodel.json"; var externalSystemType = 'NODEX'; var externalSystem; var accessAddress; var credentials; var mappedObjects; var verboseLoggingForExternalSystem; function afterAuth(cb) { // munge mappedObjects as required for (var name in mappedObjects) { var map = mappedObjects[name]; if (!map.typeBindingProperties) { map.typeBindingProperties = {}; for (var propName in map) { switch(propName) { case "target": case "properties": ; default: map.typeBindingProperties[name] = map[name]; } } } } // invoke op to create model session.directive( { op : "INVOKE", targetType: "CdmExternalSystem", name: "invokeExternal", params: { externalSystem: externalSystem, opName : "createSfModel", params : { sfVersion : credentials.sfVersion, externalSystem : externalSystem, typeDescs : mappedObjects } } }, function (err, result) { if (err) { return cb(err); } fs.writeFileSync(modelFile, JSON.stringify(result.results, null, 2)); mmscmd.execFile(modelFile,session, deploy.outputWriter, cb); } ); } exports.deployModel = function deployModel(externalSystemName,mmsSession,cb) { session = mmsSession; externalSystem = externalSystemName; var text; if(!session.creds.externalCredentials) { console.log("Profile must include externalCredentials"); process.exit(1); } credentials = session.creds.externalCredentials[externalSystemName]; if(!credentials) { console.log("Profile does not provide externalCredentials for " + externalSystemName); process.exit(1); } if(!credentials.oauthKey || !credentials.oauthSecret) { console.log("externalSystemName for " + externalSystemName + " must contain the oAuth key and secret."); } accessAddress = credentials.host; try { text = fs.readFileSync("salesforce.json"); } catch(err) { console.log('Error reading file salesforce.json:' + err); process.exit(1); } try { mappedObjects = JSON.parse(text); } catch(err) { console.log('Error parsing JSON in salesforce.json:' + err); process.exit(1); } if(mappedObjects._verbose_logging_) { verboseLoggingForExternalSystem = mappedObjects._verbose_logging_; } delete mappedObjects._verbose_logging_; createExternalSystem(function(err) { if (err) { return cb(err); } var addr = common.global.session.creds.server + "/oauth/" + externalSystem + "/authenticate"; if (common.global.argv.nonInteractive) { console.log("Note: what follows will fail unless Emotive has been authorized at " + addr); afterAuth(cb); } else { console.log("Please navigate to " + addr.underline + " with your browser"); prompt.start(); prompt.colors = false; prompt.message = 'Press Enter when done'; prompt.delimiter = ''; var props = { properties: { q: { description : ":" } } } prompt.get(props, function (err, result) { if (err) { return cb(err); } afterAuth(cb); }); } }); } function createExternalSystem(cb) { if (!session.creds.username) { console.log("session.creds.username was null"); process.exit(1); } if(verboseLoggingForExternalSystem) console.log('VERBOSE LOGGING IS ON FOR ' + externalSystem); session.directive({ op: 'INVOKE', targetType: 'CdmExternalSystem', name: "updateOAuthExternalSystem", params: { name: externalSystem, typeName: externalSystemType, "oauthCredentials" : { "oauthType": "salesforce", "oauthKey": credentials.oauthKey, "oauthSecret": credentials.oauthSecret }, properties: { proxyConfiguration: {verbose: verboseLoggingForExternalSystem, sfVersion: credentials.sfVersion}, globalPackageName : "sfProxy" } } }, cb); }
emote/tools
lib/sfsetup.js
JavaScript
mit
5,142
/** * 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 React from 'react'; // import Layout from '../../components/Layout'; const title = 'Admin Page'; const isAdmin = false; export default { path: '/admin', children : [ require('./dashboard').default, require('./library').default, require('./setting').default, // require('./editor').default, require('./news').default, require('./monngon').default, require('./product').default, require('./seo').default, ], async action({store, next}) { let user = store.getState().user const route = await next(); // Provide default values for title, description etc. route.title = `${route.title || 'Amdmin Page'}`; return route; }, };
luanlv/comhoavang
src/routes/admin/index.js
JavaScript
mit
959
// flow-typed signature: 267f077135db8f8ca8e152b4b262406e // flow-typed version: <<STUB>>/react-redux_v^5.0.4/flow_v0.46.0 /** * This is an autogenerated libdef stub for: * * 'react-redux' * * Fill this stub out by replacing all the `any` types. * * Once filled out, we encourage you to share your work with the * community by sending a pull request to: * https://github.com/flowtype/flow-typed */ declare module 'react-redux' { declare module.exports: any; } /** * We include stubs for each file inside this npm package in case you need to * require those files directly. Feel free to delete any files that aren't * needed. */ declare module 'react-redux/dist/react-redux' { declare module.exports: any; } declare module 'react-redux/dist/react-redux.min' { declare module.exports: any; } declare module 'react-redux/es/components/connectAdvanced' { declare module.exports: any; } declare module 'react-redux/es/components/Provider' { declare module.exports: any; } declare module 'react-redux/es/connect/connect' { declare module.exports: any; } declare module 'react-redux/es/connect/mapDispatchToProps' { declare module.exports: any; } declare module 'react-redux/es/connect/mapStateToProps' { declare module.exports: any; } declare module 'react-redux/es/connect/mergeProps' { declare module.exports: any; } declare module 'react-redux/es/connect/selectorFactory' { declare module.exports: any; } declare module 'react-redux/es/connect/verifySubselectors' { declare module.exports: any; } declare module 'react-redux/es/connect/wrapMapToProps' { declare module.exports: any; } declare module 'react-redux/es/index' { declare module.exports: any; } declare module 'react-redux/es/utils/PropTypes' { declare module.exports: any; } declare module 'react-redux/es/utils/shallowEqual' { declare module.exports: any; } declare module 'react-redux/es/utils/Subscription' { declare module.exports: any; } declare module 'react-redux/es/utils/verifyPlainObject' { declare module.exports: any; } declare module 'react-redux/es/utils/warning' { declare module.exports: any; } declare module 'react-redux/es/utils/wrapActionCreators' { declare module.exports: any; } declare module 'react-redux/lib/components/connectAdvanced' { declare module.exports: any; } declare module 'react-redux/lib/components/Provider' { declare module.exports: any; } declare module 'react-redux/lib/connect/connect' { declare module.exports: any; } declare module 'react-redux/lib/connect/mapDispatchToProps' { declare module.exports: any; } declare module 'react-redux/lib/connect/mapStateToProps' { declare module.exports: any; } declare module 'react-redux/lib/connect/mergeProps' { declare module.exports: any; } declare module 'react-redux/lib/connect/selectorFactory' { declare module.exports: any; } declare module 'react-redux/lib/connect/verifySubselectors' { declare module.exports: any; } declare module 'react-redux/lib/connect/wrapMapToProps' { declare module.exports: any; } declare module 'react-redux/lib/index' { declare module.exports: any; } declare module 'react-redux/lib/utils/PropTypes' { declare module.exports: any; } declare module 'react-redux/lib/utils/shallowEqual' { declare module.exports: any; } declare module 'react-redux/lib/utils/Subscription' { declare module.exports: any; } declare module 'react-redux/lib/utils/verifyPlainObject' { declare module.exports: any; } declare module 'react-redux/lib/utils/warning' { declare module.exports: any; } declare module 'react-redux/lib/utils/wrapActionCreators' { declare module.exports: any; } declare module 'react-redux/src/components/connectAdvanced' { declare module.exports: any; } declare module 'react-redux/src/components/Provider' { declare module.exports: any; } declare module 'react-redux/src/connect/connect' { declare module.exports: any; } declare module 'react-redux/src/connect/mapDispatchToProps' { declare module.exports: any; } declare module 'react-redux/src/connect/mapStateToProps' { declare module.exports: any; } declare module 'react-redux/src/connect/mergeProps' { declare module.exports: any; } declare module 'react-redux/src/connect/selectorFactory' { declare module.exports: any; } declare module 'react-redux/src/connect/verifySubselectors' { declare module.exports: any; } declare module 'react-redux/src/connect/wrapMapToProps' { declare module.exports: any; } declare module 'react-redux/src/index' { declare module.exports: any; } declare module 'react-redux/src/utils/PropTypes' { declare module.exports: any; } declare module 'react-redux/src/utils/shallowEqual' { declare module.exports: any; } declare module 'react-redux/src/utils/Subscription' { declare module.exports: any; } declare module 'react-redux/src/utils/verifyPlainObject' { declare module.exports: any; } declare module 'react-redux/src/utils/warning' { declare module.exports: any; } declare module 'react-redux/src/utils/wrapActionCreators' { declare module.exports: any; } // Filename aliases declare module 'react-redux/dist/react-redux.js' { declare module.exports: $Exports<'react-redux/dist/react-redux'>; } declare module 'react-redux/dist/react-redux.min.js' { declare module.exports: $Exports<'react-redux/dist/react-redux.min'>; } declare module 'react-redux/es/components/connectAdvanced.js' { declare module.exports: $Exports<'react-redux/es/components/connectAdvanced'>; } declare module 'react-redux/es/components/Provider.js' { declare module.exports: $Exports<'react-redux/es/components/Provider'>; } declare module 'react-redux/es/connect/connect.js' { declare module.exports: $Exports<'react-redux/es/connect/connect'>; } declare module 'react-redux/es/connect/mapDispatchToProps.js' { declare module.exports: $Exports<'react-redux/es/connect/mapDispatchToProps'>; } declare module 'react-redux/es/connect/mapStateToProps.js' { declare module.exports: $Exports<'react-redux/es/connect/mapStateToProps'>; } declare module 'react-redux/es/connect/mergeProps.js' { declare module.exports: $Exports<'react-redux/es/connect/mergeProps'>; } declare module 'react-redux/es/connect/selectorFactory.js' { declare module.exports: $Exports<'react-redux/es/connect/selectorFactory'>; } declare module 'react-redux/es/connect/verifySubselectors.js' { declare module.exports: $Exports<'react-redux/es/connect/verifySubselectors'>; } declare module 'react-redux/es/connect/wrapMapToProps.js' { declare module.exports: $Exports<'react-redux/es/connect/wrapMapToProps'>; } declare module 'react-redux/es/index.js' { declare module.exports: $Exports<'react-redux/es/index'>; } declare module 'react-redux/es/utils/PropTypes.js' { declare module.exports: $Exports<'react-redux/es/utils/PropTypes'>; } declare module 'react-redux/es/utils/shallowEqual.js' { declare module.exports: $Exports<'react-redux/es/utils/shallowEqual'>; } declare module 'react-redux/es/utils/Subscription.js' { declare module.exports: $Exports<'react-redux/es/utils/Subscription'>; } declare module 'react-redux/es/utils/verifyPlainObject.js' { declare module.exports: $Exports<'react-redux/es/utils/verifyPlainObject'>; } declare module 'react-redux/es/utils/warning.js' { declare module.exports: $Exports<'react-redux/es/utils/warning'>; } declare module 'react-redux/es/utils/wrapActionCreators.js' { declare module.exports: $Exports<'react-redux/es/utils/wrapActionCreators'>; } declare module 'react-redux/lib/components/connectAdvanced.js' { declare module.exports: $Exports<'react-redux/lib/components/connectAdvanced'>; } declare module 'react-redux/lib/components/Provider.js' { declare module.exports: $Exports<'react-redux/lib/components/Provider'>; } declare module 'react-redux/lib/connect/connect.js' { declare module.exports: $Exports<'react-redux/lib/connect/connect'>; } declare module 'react-redux/lib/connect/mapDispatchToProps.js' { declare module.exports: $Exports<'react-redux/lib/connect/mapDispatchToProps'>; } declare module 'react-redux/lib/connect/mapStateToProps.js' { declare module.exports: $Exports<'react-redux/lib/connect/mapStateToProps'>; } declare module 'react-redux/lib/connect/mergeProps.js' { declare module.exports: $Exports<'react-redux/lib/connect/mergeProps'>; } declare module 'react-redux/lib/connect/selectorFactory.js' { declare module.exports: $Exports<'react-redux/lib/connect/selectorFactory'>; } declare module 'react-redux/lib/connect/verifySubselectors.js' { declare module.exports: $Exports<'react-redux/lib/connect/verifySubselectors'>; } declare module 'react-redux/lib/connect/wrapMapToProps.js' { declare module.exports: $Exports<'react-redux/lib/connect/wrapMapToProps'>; } declare module 'react-redux/lib/index.js' { declare module.exports: $Exports<'react-redux/lib/index'>; } declare module 'react-redux/lib/utils/PropTypes.js' { declare module.exports: $Exports<'react-redux/lib/utils/PropTypes'>; } declare module 'react-redux/lib/utils/shallowEqual.js' { declare module.exports: $Exports<'react-redux/lib/utils/shallowEqual'>; } declare module 'react-redux/lib/utils/Subscription.js' { declare module.exports: $Exports<'react-redux/lib/utils/Subscription'>; } declare module 'react-redux/lib/utils/verifyPlainObject.js' { declare module.exports: $Exports<'react-redux/lib/utils/verifyPlainObject'>; } declare module 'react-redux/lib/utils/warning.js' { declare module.exports: $Exports<'react-redux/lib/utils/warning'>; } declare module 'react-redux/lib/utils/wrapActionCreators.js' { declare module.exports: $Exports<'react-redux/lib/utils/wrapActionCreators'>; } declare module 'react-redux/src/components/connectAdvanced.js' { declare module.exports: $Exports<'react-redux/src/components/connectAdvanced'>; } declare module 'react-redux/src/components/Provider.js' { declare module.exports: $Exports<'react-redux/src/components/Provider'>; } declare module 'react-redux/src/connect/connect.js' { declare module.exports: $Exports<'react-redux/src/connect/connect'>; } declare module 'react-redux/src/connect/mapDispatchToProps.js' { declare module.exports: $Exports<'react-redux/src/connect/mapDispatchToProps'>; } declare module 'react-redux/src/connect/mapStateToProps.js' { declare module.exports: $Exports<'react-redux/src/connect/mapStateToProps'>; } declare module 'react-redux/src/connect/mergeProps.js' { declare module.exports: $Exports<'react-redux/src/connect/mergeProps'>; } declare module 'react-redux/src/connect/selectorFactory.js' { declare module.exports: $Exports<'react-redux/src/connect/selectorFactory'>; } declare module 'react-redux/src/connect/verifySubselectors.js' { declare module.exports: $Exports<'react-redux/src/connect/verifySubselectors'>; } declare module 'react-redux/src/connect/wrapMapToProps.js' { declare module.exports: $Exports<'react-redux/src/connect/wrapMapToProps'>; } declare module 'react-redux/src/index.js' { declare module.exports: $Exports<'react-redux/src/index'>; } declare module 'react-redux/src/utils/PropTypes.js' { declare module.exports: $Exports<'react-redux/src/utils/PropTypes'>; } declare module 'react-redux/src/utils/shallowEqual.js' { declare module.exports: $Exports<'react-redux/src/utils/shallowEqual'>; } declare module 'react-redux/src/utils/Subscription.js' { declare module.exports: $Exports<'react-redux/src/utils/Subscription'>; } declare module 'react-redux/src/utils/verifyPlainObject.js' { declare module.exports: $Exports<'react-redux/src/utils/verifyPlainObject'>; } declare module 'react-redux/src/utils/warning.js' { declare module.exports: $Exports<'react-redux/src/utils/warning'>; } declare module 'react-redux/src/utils/wrapActionCreators.js' { declare module.exports: $Exports<'react-redux/src/utils/wrapActionCreators'>; }
danielsneijers/markslide
flow-typed/npm/react-redux_vx.x.x.js
JavaScript
mit
11,881
import * as riot from 'riot' import { init, compile } from '../../helpers/' import TargetComponent from '../../../dist/tags/popup/su-popup.js' describe('su-popup', function () { let element, component let spyOnMouseover, spyOnMouseout init(riot) const mount = opts => { const option = Object.assign({ 'onmouseover': spyOnMouseover, 'onmouseout': spyOnMouseout, }, opts) element = document.createElement('app') riot.register('su-popup', TargetComponent) const AppComponent = compile(` <app> <su-popup tooltip="{ props.tooltip }" data-title="{ props.dataTitle }" data-variation="{ props.dataVariation }" onmouseover="{ () => dispatch('mouseover') }" onmouseout="{ () => dispatch('mouseout') }" ><i class="add icon"></i></su-popup> </app>`) riot.register('app', AppComponent) component = riot.mount(element, option)[0] } beforeEach(function () { spyOnMouseover = sinon.spy() spyOnMouseout = sinon.spy() }) afterEach(function () { riot.unregister('su-popup') riot.unregister('app') }) it('is mounted', function () { mount() expect(component).to.be.ok }) it('show and hide popup', function () { mount({ tooltip: 'Add users to your feed' }) expect(component.$('.content').innerHTML).to.equal('Add users to your feed') expect(component.$('su-popup .ui.popup').classList.contains('nowrap')).to.equal(true) fireEvent(component.$('su-popup .ui.popup'), 'mouseover') expect(spyOnMouseover).to.have.been.calledOnce expect(component.$('su-popup .ui.popup').classList.contains('visible')).to.equal(true) expect(component.$('su-popup .ui.popup').classList.contains('hidden')).to.equal(false) fireEvent(component.$('su-popup .ui.popup'), 'mouseout') expect(spyOnMouseout).to.have.been.calledOnce expect(component.$('su-popup .ui.popup').classList.contains('visible')).to.equal(false) expect(component.$('su-popup .ui.popup').classList.contains('hidden')).to.equal(true) }) it('header', function () { mount({ tooltip: 'Add users to your feed', dataTitle: 'Title' }) expect(component.$('.header').innerHTML).to.equal('Title') expect(component.$('.content').innerHTML).to.equal('Add users to your feed') }) it('wide', function () { mount({ tooltip: 'Add users to your feed', dataVariation: 'wide' }) expect(component.$('su-popup .ui.popup').classList.contains('wide')).to.equal(true) expect(component.$('su-popup .ui.popup').classList.contains('nowrap')).to.equal(false) }) })
black-trooper/semantic-ui-riot
test/spec/popup/su-popup.spec.js
JavaScript
mit
2,656
const jwt = require('jsonwebtoken'); const User = require('../models/User'); // import { port, auth } from '../../config'; /** * The Auth Checker middleware function. */ module.exports = (req, res, next) => { if (!req.headers.authorization) { return res.status(401).end(); } // get the last part from a authorization header string like "bearer token-value" const token = req.headers.authorization.split(' ')[1]; // decode the token using a secret key-phrase return jwt.verify(token, "React Starter Kit", (err, decoded) => { // the 401 code is for unauthorized status if (err) { return res.status(401).end(); } const userId = decoded.sub; // check if a user exists return User.findById(userId, (userErr, user) => { if (userErr || !user) { return res.status(401).end(); } return next(); }); }); };
ziedAb/PVMourakiboun
src/data/middleware/auth-check.js
JavaScript
mit
874
var Ringpop = require('ringpop'); var TChannel = require('TChannel'); var express = require('express'); var NodeCache = require('node-cache'); var cache = new NodeCache(); var host = '127.0.0.1'; // not recommended for production var httpPort = process.env.PORT || 8080; var port = httpPort - 5080; var bootstrapNodes = ['127.0.0.1:3000']; var tchannel = new TChannel(); var subChannel = tchannel.makeSubChannel({ serviceName: 'ringpop', trace: false }); var ringpop = new Ringpop({ app: 'yourapp', hostPort: host + ':' + port, channel: subChannel }); ringpop.setupChannel(); ringpop.channel.listen(port, host, function onListen() { console.log('TChannel is listening on ' + port); ringpop.bootstrap(bootstrapNodes, function onBootstrap(err) { if (err) { console.log('Error: Could not bootstrap ' + ringpop.whoami()); process.exit(1); } console.log('Ringpop ' + ringpop.whoami() + ' has bootstrapped!'); }); // This is how you wire up a handler for forwarded requests ringpop.on('request', handleReq); }); var server = express(); server.get('/*', onReq); server.listen(httpPort, function onListen() { console.log('Server is listening on ' + httpPort); }); function extractKey(req) { var urlParts = req.url.split('/'); if (urlParts.length < 3) return ''; // URL does not have 2 parts... return urlParts[1]; } function onReq(req, res) { var key = extractKey(req); if (ringpop.handleOrProxy(key, req, res)) { handleReq(req, res); } } function handleReq(req, res) { cache.get(req.url, function(err, value) { if (value == undefined) { var key = extractKey(req); var result = host + ':' + port + ' is responsible for ' + key; cache.set(req.url, result, function(err, success) { if (!err && success) { res.end(result + ' NOT CACHED'); } }); } else { res.end(value + ' CACHED'); } }); }
Andras-Simon/nodebp
second.js
JavaScript
mit
1,982
Element.prototype.remove = function() { this.parentElement.removeChild(this); } const addIcon = (icon) => `<i class="fa fa-${icon}"></i>` const headerTxt = (type) => { switch (type) { case 'error': return `${addIcon('ban')} Error` case 'warning': return `${addIcon('exclamation')} Warning` case 'success': return `${addIcon('check')} Success` default: return `${addIcon('ban')} Error` } } const createModal = (texto, type) => { let modal = document.createElement('div') modal.classList = 'modal-background' let headertxt = 'Error' let content = ` <div class="modal-frame"> <header class="modal-${type} modal-header"> <h4> ${headerTxt(type)} </h4> <span id="closeModal">&times;</span> </header> <div class="modal-mssg"> ${texto} </div> <button id="btnAcceptModal" class="btn modal-btn modal-${type}">Aceptar</button> </div> ` modal.innerHTML = content document.body.appendChild(modal) document.getElementById('btnAcceptModal').addEventListener('click', () => modal.remove()) document.getElementById('closeModal').addEventListener('click', () => modal.remove()) } export const errorModal = (message) => createModal(message, 'error') export const successModal = (message) => createModal(message, 'success') export const warningModal = (message) => createModal(message, 'warning')
jcarral/Subsub
build/script/lib/modals.js
JavaScript
mit
1,439
import React from 'react'; import { View, ScrollView } from 'react-native'; import ConcensusButton from '../components/ConcensusButton'; import axios from 'axios'; const t = require('tcomb-form-native'); const Form = t.form.Form; const NewPollScreen = ({ navigation }) => { function onProposePress() { navigation.navigate('QRCodeShower'); axios.post('http://4d23f078.ngrok.io/createPoll'); } return ( <View style={{ padding: 20 }}> <ScrollView> <Form type={Poll} /> </ScrollView> <ConcensusButton label="Propose Motion" onPress={onProposePress} /> </View> ); }; NewPollScreen.navigationOptions = ({ navigation }) => ({ title: 'Propose a Motion', }); export default NewPollScreen; const Poll = t.struct({ subject: t.String, proposal: t.String, endsInMinutes: t.Number, consensusPercentage: t.Number, });
concensus/react-native-ios-concensus
screens/NewPollScreen.js
JavaScript
mit
929
define(["ace/ace"], function(ace) { return function(element) { var editor = ace.edit(element); editor.setTheme("ace/theme/eclipse"); editor.getSession().setMode("ace/mode/python"); editor.getSession().setUseSoftTabs(true); editor.getSession().setTabSize(4); editor.setShowPrintMargin(false); return editor; }; })
nachovizzo/AUTONAVx
simulator/autonavx_demo/js/init/editor.js
JavaScript
mit
330
/** * React components for kanna projects. * @module kanna-lib-components */ "use strict"; module.exports = { /** * @name KnAccordionArrow */ get KnAccordionArrow() { return require('./kn_accordion_arrow'); }, /** * @name KnAccordionBody */ get KnAccordionBody() { return require('./kn_accordion_body'); }, /** * @name KnAccordionHeader */ get KnAccordionHeader() { return require('./kn_accordion_header'); }, /** * @name KnAccordion */ get KnAccordion() { return require('./kn_accordion'); }, /** * @name KnAnalogClock */ get KnAnalogClock() { return require('./kn_analog_clock'); }, /** * @name KnBody */ get KnBody() { return require('./kn_body'); }, /** * @name KnButton */ get KnButton() { return require('./kn_button'); }, /** * @name KnCheckbox */ get KnCheckbox() { return require('./kn_checkbox'); }, /** * @name KnClock */ get KnClock() { return require('./kn_clock'); }, /** * @name KnContainer */ get KnContainer() { return require('./kn_container'); }, /** * @name KnDesktopShowcase */ get KnDesktopShowcase() { return require('./kn_desktop_showcase'); }, /** * @name KnDigitalClock */ get KnDigitalClock() { return require('./kn_digital_clock'); }, /** * @name KnFaIcon */ get KnFaIcon() { return require('./kn_fa_icon'); }, /** * @name KnFooter */ get KnFooter() { return require('./kn_footer'); }, /** * @name KnHead */ get KnHead() { return require('./kn_head'); }, /** * @name KnHeaderLogo */ get KnHeaderLogo() { return require('./kn_header_logo'); }, /** * @name KnHeaderTabItem */ get KnHeaderTabItem() { return require('./kn_header_tab_item'); }, /** * @name KnHeaderTab */ get KnHeaderTab() { return require('./kn_header_tab'); }, /** * @name KnHeader */ get KnHeader() { return require('./kn_header'); }, /** * @name KnHtml */ get KnHtml() { return require('./kn_html'); }, /** * @name KnIcon */ get KnIcon() { return require('./kn_icon'); }, /** * @name KnImage */ get KnImage() { return require('./kn_image'); }, /** * @name KnIonIcon */ get KnIonIcon() { return require('./kn_ion_icon'); }, /** * @name KnLabel */ get KnLabel() { return require('./kn_label'); }, /** * @name KnLinks */ get KnLinks() { return require('./kn_links'); }, /** * @name KnListItemArrowIcon */ get KnListItemArrowIcon() { return require('./kn_list_item_arrow_icon'); }, /** * @name KnListItemIcon */ get KnListItemIcon() { return require('./kn_list_item_icon'); }, /** * @name KnListItemText */ get KnListItemText() { return require('./kn_list_item_text'); }, /** * @name KnListItem */ get KnListItem() { return require('./kn_list_item'); }, /** * @name KnList */ get KnList() { return require('./kn_list'); }, /** * @name KnMain */ get KnMain() { return require('./kn_main'); }, /** * @name KnMobileShowcase */ get KnMobileShowcase() { return require('./kn_mobile_showcase'); }, /** * @name KnNote */ get KnNote() { return require('./kn_note'); }, /** * @name KnPassword */ get KnPassword() { return require('./kn_password'); }, /** * @name KnRadio */ get KnRadio() { return require('./kn_radio'); }, /** * @name KnRange */ get KnRange() { return require('./kn_range'); }, /** * @name KnShowcase */ get KnShowcase() { return require('./kn_showcase'); }, /** * @name KnSlider */ get KnSlider() { return require('./kn_slider'); }, /** * @name KnSlideshow */ get KnSlideshow() { return require('./kn_slideshow'); }, /** * @name KnSpinner */ get KnSpinner() { return require('./kn_spinner'); }, /** * @name KnTabItem */ get KnTabItem() { return require('./kn_tab_item'); }, /** * @name KnTab */ get KnTab() { return require('./kn_tab'); }, /** * @name KnText */ get KnText() { return require('./kn_text'); }, /** * @name KnThemeStyle */ get KnThemeStyle() { return require('./kn_theme_style'); } };
kanna-lab/kanna-lib-components
lib/index.js
JavaScript
mit
4,495
function countBs(string) { return countChar(string, "B"); } function countChar(string, ch) { var counted = 0; for (var i = 0; i < string.length; i++) { if (string.charAt(i) == ch) counted += 1; } return counted; } console.log(countBs("BBC")); // -> 2 console.log(countChar("kakkerlak", "k")); // -> 4
jdhunterae/eloquent_js
ch03/su03-bean_counting.js
JavaScript
mit
343
/* * Copyright (c) André Bargull * Alle Rechte vorbehalten / All Rights Reserved. Use is subject to license terms. * * <https://github.com/anba/es6draft> */ /*--- id: sec-function-calls-runtime-semantics-evaluation info: Check TypeError is thrown from correct realm with tco-call to class constructor from class [[Construct]] invocation. description: > 12.3.4.3 Runtime Semantics: EvaluateDirectCall( func, thisValue, arguments, tailPosition ) ... 4. If tailPosition is true, perform PrepareForTailCall(). 5. Let result be Call(func, thisValue, argList). 6. Assert: If tailPosition is true, the above call will not return here, but instead evaluation will continue as if the following return has already occurred. 7. Assert: If result is not an abrupt completion, then Type(result) is an ECMAScript language type. 8. Return result. 9.2.1 [[Call]] ( thisArgument, argumentsList) ... 2. If F.[[FunctionKind]] is "classConstructor", throw a TypeError exception. 3. Let callerContext be the running execution context. 4. Let calleeContext be PrepareForOrdinaryCall(F, undefined). 5. Assert: calleeContext is now the running execution context. ... features: [tail-call-optimization, class] ---*/ // - The class constructor call is in a valid tail-call position, which means PrepareForTailCall is performed. // - The function call returns from `otherRealm` and proceeds the tail-call in this realm. // - Calling the class constructor throws a TypeError from the current realm, that means this realm and not `otherRealm`. var code = "(class { constructor() { return (class {})(); } });"; var otherRealm = $262.createRealm(); var tco = otherRealm.evalScript(code); assert.throws(TypeError, function() { new tco(); });
anba/es6draft
src/test/scripts/suite262/language/expressions/call/tco-cross-realm-class-construct.js
JavaScript
mit
1,776
/** * getRoles - get all roles * * @api {get} /roles Get all roles * @apiName GetRoles * @apiGroup Role * * * @apiSuccess {Array[Role]} raw Return table of roles * @apiSuccessExample {json} Success-Response: * HTTP/1.1 200 OK * [ * { * "id": 1, * "name": "Administrator", * "slug": "administrator" * } * ] * * @apiUse InternalServerError */ /** * createRole - create new role * * @api {post} /roles Create a role * @apiName CreateRole * @apiGroup Role * @apiPermission admin * * @apiParam {String} name Name of new role * @apiParam {String} slug Slug from name of new role * * @apiSuccess (Created 201) {Number} id Id of new role * @apiSuccess (Created 201) {String} name Name of new role * @apiSuccess (Created 201) {String} slug Slug of new role * @apiSuccessExample {json} Success-Response: * HTTP/1.1 201 Created * { * "id": 3, * "name": "Custom", * "slug": "custom" * } * * @apiUse BadRequest * @apiUse InternalServerError */ /** * getRole - get role by id * * @api {get} /roles/:id Get role by id * @apiName GetRole * @apiGroup Role * * @apiSuccess {Number} id Id of role * @apiSuccess {String} name Name of role * @apiSuccess {String} slug Slug of role * @apiSuccessExample {json} Success-Response: * HTTP/1.1 200 OK * { * "id": 2, * "name": "User", * "slug": "user" * } * * @apiUse NotFound * @apiUse InternalServerError */ /** * updateRole - update role * * @api {put} /roles/:id Update role from id * @apiName UpdateRole * @apiGroup Role * @apiPermission admin * * * @apiParam {String} name New role name * @apiParam {String} slug New role slug * * @apiSuccess {Number} id Id of role * @apiSuccess {String} name Name of role * @apiSuccess {String} slug Slug of role * @apiSuccessExample {json} Success-Response: * HTTP/1.1 200 OK * { * "id": 3, * "name": "Customer", * "slug": "customer" * } * * @apiUse NotFound * @apiUse BadRequest * @apiUse InternalServerError */ /** * deleteRole - delete role * * @api {delete} /roles/:id Delete role from id * @apiName DeleteRole * @apiGroup Role * @apiPermission admin * * * @apiSuccessExample Success-Response: * HTTP/1.1 204 No Content * * @apiUse NotFound * @apiUse BadRequest * @apiUse InternalServerError */
MadDeveloper/easy.js
src/bundles/role/doc/role.doc.js
JavaScript
mit
2,414
import { Component } from 'react'; import format from '../components/format'; import parse from 'date-fns/parse'; import getDay from 'date-fns/get_day'; import Media from 'react-media'; import Page from '../layouts/Page'; import TimelineView from '../components/TimelineView'; import ListView from '../components/ListView'; import db from '../events'; export default class extends Component { static async getInitialProps({ query }) { const response = db .map((event, id) => ({ ...event, id })) .filter((event) => { if (!query.day) { return true; } return getDay(event.startsAt) === parseInt(query.day, 10); }); const events = await Promise.resolve(response); return { events: events.reduce((groupedByDay, event) => { const day = format(event.startsAt, 'dddd'); groupedByDay[day] = [...(groupedByDay[day] || []), event]; return groupedByDay; }, {}) }; } render() { return ( <Page title="Arrangementer"> <Media query="(max-width: 799px)" > {(matches) => { const Component = matches ? ListView : TimelineView; return <Component events={this.props.events} />; }} </Media> </Page> ); } }
webkom/jubileum.abakus.no
pages/index.js
JavaScript
mit
1,320
module.exports = (req, res, next) => { req.context = req.context || {}; next(); };
thedavisproject/davis-web
src/middleware/initContext.js
JavaScript
mit
87
'use strict'; angular.module('achan.previewer').service('imagePreviewService', function () { var source; var ImagePreviewService = { render: function (scope, element) { element.html('<img src="' + source + '" class="img-responsive" />'); }, forSource: function (src) { source = src; return ImagePreviewService; } }; return ImagePreviewService; });
achan/angular-previewer
app/scripts/services/imagePreviewService.js
JavaScript
mit
392
var test = require('./tape') var mongojs = require('../index') test('should export bson types', function (t) { t.ok(mongojs.Binary) t.ok(mongojs.Code) t.ok(mongojs.DBRef) t.ok(mongojs.Double) t.ok(mongojs.Long) t.ok(mongojs.MinKey) t.ok(mongojs.MaxKey) t.ok(mongojs.ObjectID) t.ok(mongojs.ObjectId) t.ok(mongojs.Symbol) t.ok(mongojs.Timestamp) t.ok(mongojs.Decimal128) t.end() })
mafintosh/mongojs
test/test-expose-bson-types.js
JavaScript
mit
408
/* Misojs Codemirror component */ var m = require('mithril'), basePath = "external/codemirror/", pjson = require("./package.json"); // Here we have a few fixes to make CM work in node - we only setup each, // if they don't already exist, otherwise we would override the browser global.document = global.document || {}; global.document.createElement = global.document.createElement || function(){ return { setAttribute: function(){} }; }; global.window = global.window || {}; global.window.getSelection = global.window.getSelection || function(){ return false; }; global.navigator = global.navigator || {}; global.navigator.userAgent = global.navigator.userAgent || "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.130 Safari/537.36"; // Grab code mirror and the javascript language // Note: you cannot dynamically require with browserify, // so we must get whatever modes we need here. // If you need other languages, simply equire them statically in your program. var CodeMirror = require('codemirror'); require("codemirror/mode/javascript/javascript.js"); require("codemirror/mode/htmlmixed/htmlmixed.js"); require("codemirror/mode/css/css.js"); // Our component var CodemirrorComponent = { // Returns a textarea view: function(ctrl, attrs) { return m("div", [ // It is ok to include CSS here - the browser will cache it, // though a more ideal setup would be the ability to load only // once when required. m("LINK", { href: basePath + "lib/codemirror.css", rel: "stylesheet"}), m("textarea", {config: CodemirrorComponent.config(attrs)}, attrs.value()) ]); }, config: function(attrs) { return function(element, isInitialized) { if(typeof CodeMirror !== 'undefined') { if (!isInitialized) { var editor = CodeMirror.fromTextArea(element, { lineNumbers: true }); editor.on("change", function(instance, object) { m.startComputation(); attrs.value(editor.doc.getValue()); if (typeof attrs.onchange == "function"){ attrs.onchange(instance, object); } m.endComputation(); }); } } else { console.warn('ERROR: You need Codemirror in the page'); } }; } }; // Allow the user to pass in arguments when loading. module.exports = function(args){ if(args && args.basePath) { basePath = args.basePath; } return CodemirrorComponent; };
jsguy/misojs-codemirror-component
codemirror.component.js
JavaScript
mit
2,410
import { observable, action } from 'mobx'; import Fuse from 'fuse.js'; import Activity from './../utils/Activity'; import noop from 'lodash/noop'; import uniqBy from 'lodash/uniqBy'; const inactive = Activity(500); export default class Story { @observable keyword = ''; @observable allStories = []; @observable stories = []; @action search(keyword) { this.keyword = keyword; inactive().then(() => { this.stories = this.searchStories(this.allStories, this.keyword); }, noop); } @action addStories(stories){ this.allStories = uniqBy(this.allStories.concat(stories), story => story.key); this.stories = this.searchStories(this.allStories, this.keyword); } searchStories(stories, keyword) { /** * threshold is the correctness of the search * @type {{threshold: number, keys: string[]}} */ const options = { threshold: 0.2, keys: ['text'] }; const google = new Fuse(stories, options); return google.search(keyword) || []; } }
nadimtuhin/facebook-activity-monitor
src/content/store/Story.js
JavaScript
mit
1,020
'use strict'; const Schemas = require('../server/schemas'); const Code = require('code'); const Lab = require('lab'); const expect = Code.expect; const lab = exports.lab = Lab.script(); const describe = lab.describe; const it = lab.it; describe('server/schemas.todoSchema', () => { it('validates object', (done) => { expect(Schemas.todoSchema.validate({ test: 'val' }).error).to.exist(); return done(); }); it('allows id as string, done as boolean, and content as string', (done) => { expect(Schemas.todoSchema.validate({ id: 1 }).error).to.exist(); expect(Schemas.todoSchema.validate({ id: 'id' }).error).to.not.exist(); expect(Schemas.todoSchema.validate({ done: false}).error).to.not.exist(); expect(Schemas.todoSchema.validate({ done: 'somtest'}).error).to.exist(); expect(Schemas.todoSchema.validate({ done: 'false'}).error).to.not.exist(); expect(Schemas.todoSchema.validate({ content: 1234567 }).error).to.exist(); expect(Schemas.todoSchema.validate({ content: 'test' }).error).to.not.exist(); return done(); }); it('exposes a todoObject', (done) => { expect(Schemas.todoObject).to.be.an.object(); return done(); }); });
genediazjr/hapitodo
test/schemasTest.js
JavaScript
mit
1,261
/** * @module popoff/overlay * * Because overlay-component is hopelessly out of date. * This is modern rewrite. */ const Emitter = require('events').EventEmitter; const inherits = require('inherits'); const extend = require('xtend/mutable'); module.exports = Overlay; /** * Initialize a new `Overlay`. * * @param {Object} options * @api public */ function Overlay(options) { if (!(this instanceof Overlay)) return new Overlay(options); Emitter.call(this); extend(this, options); if (!this.container) { this.container = document.body || document.documentElement; } //create overlay element this.element = document.createElement('div'); this.element.classList.add('popoff-overlay'); if (this.closable) { this.element.addEventListener('click', e => { this.hide(); }); this.element.classList.add('popoff-closable'); } } inherits(Overlay, Emitter); //close overlay by click Overlay.prototype.closable = true; /** * Show the overlay. * * Emits "show" event. * * @return {Overlay} * @api public */ Overlay.prototype.show = function () { this.emit('show'); this.container.appendChild(this.element); //class removed in a timeout to save animation setTimeout( () => { this.element.classList.add('popoff-visible'); this.emit('afterShow'); }, 10); return this; }; /** * Hide the overlay. * * Emits "hide" event. * * @return {Overlay} * @api public */ Overlay.prototype.hide = function () { this.emit('hide'); this.element.classList.remove('popoff-visible'); this.element.addEventListener('transitionend', end); this.element.addEventListener('webkitTransitionEnd', end); this.element.addEventListener('otransitionend', end); this.element.addEventListener('oTransitionEnd', end); this.element.addEventListener('msTransitionEnd', end); var to = setTimeout(end, 1000); var that = this; function end () { that.element.removeEventListener('transitionend', end); that.element.removeEventListener('webkitTransitionEnd', end); that.element.removeEventListener('otransitionend', end); that.element.removeEventListener('oTransitionEnd', end); that.element.removeEventListener('msTransitionEnd', end); clearInterval(to); that.container.removeChild(that.element); that.emit('afterHide'); } return this; };
dfcreative/popoff
overlay.js
JavaScript
mit
2,294
/* Copyright (c) 2011 Andrei Mackenzie Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // Compute the edit distance between the two given strings exports.getEditDistance = function(a, b){ if(a.length == 0) return b.length; if(b.length == 0) return a.length; var matrix = []; // increment along the first column of each row var i; for(i = 0; i <= b.length; i++){ matrix[i] = [i]; } // increment each column in the first row var j; for(j = 0; j <= a.length; j++){ matrix[0][j] = j; } // Fill in the rest of the matrix for(i = 1; i <= b.length; i++){ for(j = 1; j <= a.length; j++){ if(b.charAt(i-1) == a.charAt(j-1)){ matrix[i][j] = matrix[i-1][j-1]; } else { matrix[i][j] = Math.min(matrix[i-1][j-1] + 1, // substitution Math.min(matrix[i][j-1] + 1, // insertion matrix[i-1][j] + 1)); // deletion } } } return matrix[b.length][a.length]; };
crazyfacka/text2meo
data/lib/levenshtein.js
JavaScript
mit
1,980
import React, { PropTypes } from 'react'; import { connect } from 'react-redux'; import GroupPage from './GroupPage.js'; import GroupNotFoundPage from './GroupNotFoundPage.js'; const Group = ({ isValid, groupId }) => (isValid ? <GroupPage groupId={groupId} /> : <GroupNotFoundPage groupId={groupId} />); Group.propTypes = { groupId: PropTypes.string, isValid: PropTypes.bool.isRequired }; export default connect(state => ({ groupId: state.router.params.groupId, isValid: !!state.groups.data[state.router.params.groupId] }))(Group);
logger-app/logger-app
src/containers/Group/Group.js
JavaScript
mit
545
'use strict' let ugly = require('gulp-uglify') ,gulp = require('gulp') ,watch = require('gulp-watch') ,plumber = require('gulp-plumber') ,newer = require('gulp-newer') ,stylus = require('gulp-stylus') ,jade = require('gulp-jade') ,concat = require('gulp-concat') ,rename = require('gulp-rename') ,runSequence = require('run-sequence') ,_ = require('lodash') ,path = require('path') ,fs = require('fs') ,spawn = require('cross-spawn') let cssFolder = __dirname + '/public/css' ,jsFolder = __dirname + '/public/js' ,views = __dirname + '/views' ,stylusOptions = { compress: true } ,uglyOptions = { } gulp.task('stylus', function() { gulp.src(cssFolder + '/*.styl') /* .pipe(newer({ dest: cssFolder ,map: function(path) { return path.replace(/\.styl$/, '.css') } })) */ .pipe(plumber()) .pipe(stylus(stylusOptions)) .pipe(gulp.dest(cssFolder)) }) gulp.task('ugly', function() { gulp.src(jsFolder + '/*.js') .pipe(newer({ dest: jsFolder ,map: function(path) { return path.replace(/\.dev.js$/, '.min.js') } })) .pipe(plumber()) .pipe(rename(function (path) { path.basename = path.basename.replace('.dev', '.min') })) .pipe(gulp.dest(jsFolder)) .pipe(ugly(uglyOptions)) .pipe(gulp.dest(jsFolder)) }) let config = require('./config') let pack = require('./package.json') let packj = require('./node_modules/jade-press/package.json') config.version = pack.version config.siteDesc = packj.description gulp.task('jade', function() { gulp.src(views + '/*.jade') .pipe(plumber()) .pipe(jade({ locals: config })) .pipe(gulp.dest(__dirname)) }) gulp.task('server', function (cb) { var runner = spawn( 'node' ,['server'] ,{ stdio: 'inherit' } ) runner.on('exit', function (code) { process.exit(code) }) runner.on('error', function (err) { cb(err) }) }) gulp.task('watch', function () { runSequence('server') watch([cssFolder + '/*.styl', cssFolder + '/parts/*.styl'], function() { runSequence('stylus') }) watch(jsFolder, function() { runSequence('ugly') }) watch([ views + '/*.jade' ,views + '/parts/*.jade' ], function() { runSequence('jade') } ) }) gulp.task('default', ['watch']) gulp.task('dist', function() { runSequence('stylus', 'ugly', 'jade') })
jade-press/jade-press.org
gulpfile.js
JavaScript
mit
2,290
const Lib = require("../src/main"); const assert = require("assert"); describe("plain object output", function () { context("for `JSON.stringify` serializable objects", function () { it("should have resembling structure", function () { const obj1 = { a: 1, b: "b", c: true }; const res = Lib.write(obj1); const exp1 = { f: [ ["a", 1], ["b", "b"], ["c", true] ] }; assert.deepStrictEqual(res, exp1); assert.equal(Lib.stringify(obj1), JSON.stringify(res)); const obj2 = { obj1 }; const exp2 = { f: [["obj1", exp1]] }; assert.deepStrictEqual(Lib.write(obj2), exp2); assert.equal(Lib.stringify(obj2), JSON.stringify(exp2)); }); context("with `alwaysByRef: true`", function () { it("should use references environment", function () { const obj1 = { a: { a: 1 }, b: { b: "b" }, c: { c: true } }; const res = Lib.write(obj1, { alwaysByRef: true }); const exp1 = { r: 3, x: [ { f: [["c", true]] }, { f: [["b", "b"]] }, { f: [["a", 1]] }, { f: [ ["a", { r: 2 }], ["b", { r: 1 }], ["c", { r: 0 }] ] } ] }; assert.deepStrictEqual(res, exp1); const obj2 = Lib.read(res); assert.notStrictEqual(obj1, obj2); assert.deepStrictEqual(obj1, obj2); }); }); }); it("should have correct format for shared values", function () { const root = { val: "hi" }; root.rec1 = { obj1: root, obj2: root, obj3: { obj: root } }; root.rec2 = root; assert.deepStrictEqual(Lib.write(root), { r: 0, x: [ { f: [ ["val", "hi"], [ "rec1", { f: [ ["obj1", { r: 0 }], ["obj2", { r: 0 }], ["obj3", { f: [["obj", { r: 0 }]] }] ] } ], ["rec2", { r: 0 }] ] } ] }); }); }); describe("special values", function () { it("should correctly restore them", function () { const root = { undef: undefined, nul: null, nan: NaN }; const res = Lib.write(root); assert.deepStrictEqual(res, { f: [ ["undef", { $: "undefined" }], ["nul", null], ["nan", { $: "NaN" }] ] }); const { undef, nul, nan } = Lib.read(res); assert.strictEqual(undef, undefined); assert.strictEqual(nul, null); assert.ok(typeof nan === "number" && Number.isNaN(nan)); }); }); describe("reading plain object", function () { it("should correctly assign shared values", function () { const obj = Lib.read({ r: 0, x: [ { f: [ ["val", "hi"], [ "rec1", { f: [ ["obj1", { r: 0 }], ["obj2", { r: 0 }], ["obj3", { f: [["obj", { r: 0 }]] }] ] } ], ["rec2", { r: 0 }] ] } ] }); assert.strictEqual(Object.keys(obj).sort().join(), "rec1,rec2,val"); assert.strictEqual(obj.val, "hi"); assert.strictEqual(Object.keys(obj.rec1).sort().join(), "obj1,obj2,obj3"); assert.strictEqual(Object.keys(obj.rec1.obj3).sort().join(), "obj"); assert.strictEqual(obj.rec2, obj); assert.strictEqual(obj.rec1.obj1, obj); assert.strictEqual(obj.rec1.obj2, obj); assert.strictEqual(obj.rec1.obj3.obj, obj); }); }); describe("object with parent", function () { function MyObj() { this.a = 1; this.b = "b"; this.c = true; } Lib.regConstructor(MyObj); it("should output `$` attribute", function () { const obj1 = new MyObj(); assert.deepEqual(Lib.write(obj1), { $: "MyObj", f: [ ["a", 1], ["b", "b"], ["c", true] ] }); function Object() { this.a = obj1; } Lib.regConstructor(Object); assert.deepEqual(Lib.write(new Object()), { $: "Object_1", f: [ [ "a", { f: [ ["a", 1], ["b", "b"], ["c", true] ], $: "MyObj" } ] ] }); }); it("should use `$` attribute to resolve a type on read", function () { const obj1 = Lib.read({ $: "MyObj", f: [ ["a", 1], ["b", "b"], ["c", true] ] }); assert.strictEqual(obj1.constructor, MyObj); assert.equal(Object.keys(obj1).sort().join(), "a,b,c"); assert.strictEqual(obj1.a, 1); assert.strictEqual(obj1.b, "b"); assert.strictEqual(obj1.c, true); }); context("for shared values", function () { function Obj2() {} Lib.regConstructor(Obj2); it("should write shared values in `shared` map", function () { const root = new Obj2(); root.l1 = new Obj2(); root.l1.back = root.l1; assert.deepStrictEqual(Lib.write(root), { f: [["l1", { r: 0 }]], $: "Obj2", x: [{ f: [["back", { r: 0 }]], $: "Obj2" }] }); }); it("should use `#shared` keys to resolve prototypes on read", function () { const obj1 = Lib.read({ f: [["l1", { r: 0 }]], $: "Obj2", x: [{ f: [["back", { r: 0 }]], $: "Obj2" }] }); assert.strictEqual(obj1.constructor, Obj2); assert.deepEqual(Object.keys(obj1), ["l1"]); assert.deepEqual(Object.keys(obj1.l1), ["back"]); assert.strictEqual(obj1.l1.constructor, Obj2); assert.strictEqual(obj1.l1.back, obj1.l1); }); }); }); describe("prototypes chain", function () { it("should correctly store and recover all references", function () { class C1 { constructor(p) { this.p1 = p; } } class C2 extends C1 { constructor() { super("A"); this.c1 = new C1(this); } } Lib.regOpaqueObject(C1.prototype, "C1"); Lib.regOpaqueObject(C2.prototype, "C2"); const obj = new C2(); C1.prototype.p_prop_1 = "prop_1"; const res = Lib.write(obj); C1.prototype.p_prop_1 = "changed"; assert.deepEqual(res, { r: 0, x: [ { p: { $: "C2" }, f: [ ["p1", "A"], [ "c1", { p: { $: "C1", f: [["p_prop_1", "prop_1"]] }, f: [["p1", { r: 0 }]] } ] ] } ] }); const r2 = Lib.read(res); assert.ok(r2 instanceof C1); assert.ok(r2 instanceof C2); assert.strictEqual(r2.constructor, C2); assert.strictEqual(Object.getPrototypeOf(r2).constructor, C2); assert.strictEqual(r2.c1.constructor, C1); assert.strictEqual(r2.c1.p1, r2); assert.equal(r2.p1, "A"); assert.strictEqual(C1.prototype.p_prop_1, "prop_1"); class C3 { constructor(val) { this.a = val; } } Lib.regOpaqueObject(C3.prototype, "C3", { props: false }); class C4 extends C3 { constructor() { super("A"); this.b = "B"; } } Lib.regOpaqueObject(C4.prototype, "C4"); const obj2 = new C4(); const res2 = Lib.write(obj2); assert.deepEqual(res2, { p: { $: "C4" }, f: [ ["a", "A"], ["b", "B"] ] }); const obj3 = Lib.read(res2); assert.ok(obj3 instanceof C3); assert.ok(obj3 instanceof C4); assert.equal(obj3.a, "A"); assert.equal(obj3.b, "B"); assert.equal( Object.getPrototypeOf(Object.getPrototypeOf(obj3)), Object.getPrototypeOf(Object.getPrototypeOf(obj2)) ); }); }); describe("property's descriptor", function () { it("should correctly store and recover all settings", function () { const a = {}; let setCalled = 0; let getCalled = 0; let back; let val; const descr = { set(value) { assert.strictEqual(this, back); setCalled++; val = value; }, get() { assert.strictEqual(this, back); getCalled++; return a; } }; Object.defineProperty(a, "prop", descr); const psym1 = Symbol("prop"); const psym2 = Symbol("prop"); Object.defineProperty(a, psym1, { value: "B", enumerable: true }); Object.defineProperty(a, psym2, { value: "C", configurable: true }); Object.defineProperty(a, Symbol.for("prop"), { value: "D", writable: true }); Lib.regOpaqueObject(descr.set, "dset"); Lib.regOpaqueObject(descr.get, "dget"); const opts = { symsByName: new Map() }; const res = Lib.write(a, opts); assert.deepEqual(res, { f: [ ["prop", null, 15, { $: "dget" }, { $: "dset" }], [{ name: "prop" }, "B", 5], [{ name: "prop", id: 1 }, "C", 6], [{ key: "prop" }, "D", 3] ] }); back = Lib.read(res, opts); assert.deepEqual(Object.getOwnPropertySymbols(back), [ psym1, psym2, Symbol.for("prop") ]); assert.strictEqual(setCalled, 0); assert.strictEqual(getCalled, 0); back.prop = "A"; assert.strictEqual(setCalled, 1); assert.strictEqual(getCalled, 0); assert.strictEqual(val, "A"); assert.strictEqual(back.prop, a); assert.strictEqual( Object.getOwnPropertyDescriptor(back, Symbol("prop")), void 0 ); assert.deepEqual(Object.getOwnPropertyDescriptor(back, "prop"), { enumerable: false, configurable: false, ...descr }); assert.deepEqual(Object.getOwnPropertyDescriptor(back, psym1), { value: "B", writable: false, enumerable: true, configurable: false }); assert.deepEqual(Object.getOwnPropertyDescriptor(back, psym2), { value: "C", writable: false, enumerable: false, configurable: true }); assert.deepEqual( Object.getOwnPropertyDescriptor(back, Symbol.for("prop")), { value: "D", writable: true, enumerable: false, configurable: false } ); }); }); describe("arrays serialization", function () { context("without shared references", function () { it("should be similar to `JSON.stringify`/`JSON.parse`", function () { const obj = { arr: [1, "a", [true, [false, null]], undefined] }; const res = Lib.write(obj); assert.deepStrictEqual(res, { f: [["arr", [1, "a", [true, [false, null]], { $: "undefined" }]]] }); const back = Lib.read(res); assert.deepStrictEqual(obj, back); }); it("doesn't support Array as root", function () { assert.throws(() => Lib.write([1, 2]), TypeError); }); }); it("should handle shared references", function () { const obj = { arr: [1, "a", [true, [false, null]], undefined] }; obj.arr.push(obj.arr); const res = Lib.write(obj); assert.notStrictEqual(res, obj); assert.deepStrictEqual(res, { f: [["arr", { r: 0 }]], x: [[1, "a", [true, [false, null]], { $: "undefined" }, { r: 0 }]] }); const back = Lib.read(res); assert.notStrictEqual(res, back); assert.deepStrictEqual(obj, back); }); }); describe("`Set` serialization", function () { context("without shared references", function () { it("should output `JSON.stringify` serializable object", function () { const arr = [1, "a", [true, [false, null]], undefined]; const obj = { set: new Set(arr) }; obj.set.someNum = 100; obj.set.self = obj.set; const res = Lib.write(obj); assert.deepStrictEqual(res, { f: [["set", { r: 0 }]], x: [ { $: "Set", l: [1, "a", [true, [false, null]], { $: "undefined" }], f: [ ["someNum", 100], ["self", { r: 0 }] ] } ] }); const back = Lib.read(res); assert.deepStrictEqual(obj, back); }); }); it("should handle shared references", function () { const obj = new Set([1, "a", [true, [false, null]], undefined]); obj.add(obj); const res = Lib.write(obj); assert.notStrictEqual(res, obj); assert.deepStrictEqual(res, { r: 0, x: [ { $: "Set", l: [1, "a", [true, [false, null]], { $: "undefined" }, { r: 0 }] } ] }); const back = Lib.read(res); assert.notStrictEqual(res, back); assert.deepStrictEqual(obj, back); }); }); describe("`Map` serialization", function () { context("without shared references", function () { it("should output `JSON.stringify` serializable object", function () { const arr = [[1, "a"], [true, [false, null]], [undefined]]; const obj = { map: new Map(arr) }; const res = Lib.write(obj); assert.deepStrictEqual(res, { f: [ [ "map", { $: "Map", k: [1, true, { $: "undefined" }], v: ["a", [false, null], { $: "undefined" }] } ] ] }); const back = Lib.read(res); assert.deepStrictEqual(obj, back); }); }); it("should handle shared references", function () { const obj = new Map([[1, "a"], [true, [false, null]], [undefined]]); obj.set(obj, obj); const res = Lib.write(obj); assert.notStrictEqual(res, obj); assert.deepStrictEqual(res, { r: 0, x: [ { $: "Map", k: [1, true, { $: "undefined" }, { r: 0 }], v: ["a", [false, null], { $: "undefined" }, { r: 0 }] } ] }); const back = Lib.read(res); assert.notStrictEqual(res, back); assert.deepStrictEqual(obj, back); }); }); describe("opaque objects serialization", function () { it("should throw for not registered objects", function () { function a() {} assert.throws(() => Lib.write({ a }), TypeError); }); it("should not throw if `ignore:true`", function () { function a() {} assert.deepStrictEqual(Lib.write({ a }, { ignore: true }), {}); }); it("should output object's name if registered", function () { function a() {} Lib.regOpaqueObject(a); assert.deepStrictEqual(Lib.write({ a }), { f: [["a", { $: "a" }]] }); Lib.regOpaqueObject(a); assert.deepStrictEqual(Lib.read({ f: [["a", { $: "a" }]] }), { a }); (function () { function a() {} Lib.regOpaqueObject(a); assert.deepStrictEqual(Lib.write({ a }), { f: [["a", { $: "a_1" }]] }); assert.deepStrictEqual(Lib.read({ f: [["a", { $: "a_1" }]] }), { a }); })(); }); it("should not serialize properties specified before its registration", function () { const obj = { prop1: "p1", [Symbol.for("sym#a")]: "s1", [Symbol.for("sym#b")]: "s2", prop2: "p2", [3]: "N3", [4]: "N4" }; Lib.regOpaqueObject(obj, "A"); obj.prop1 = "P2"; obj.prop3 = "p3"; obj[Symbol.for("sym#a")] = "S1"; obj[Symbol.for("sym#c")] = "s3"; obj[4] = "n4"; obj[5] = "n5"; assert.deepStrictEqual(Lib.write({ obj }), { f: [ [ "obj", { $: "A", f: [ ["4", "n4"], ["5", "n5"], ["prop1", "P2"], ["prop3", "p3"], [ { key: "sym#a" }, "S1" ], [ { key: "sym#c" }, "s3" ] ] } ] ] }); }); }); describe("opaque primitive value serialization", function () { it("should output object's name if registered", function () { const a = Symbol("a"); Lib.regOpaquePrim(a, "sa"); assert.ok(!a[Lib.descriptorSymbol]); assert.deepStrictEqual(Lib.write({ a }), { f: [["a", { $: "sa" }]] }); Lib.regOpaquePrim(a, "sb"); assert.deepStrictEqual(Lib.read({ f: [["a", { $: "sa" }]] }), { a }); (function () { const a = Symbol("a"); Lib.regOpaquePrim(a, "sa"); assert.deepStrictEqual(Lib.write({ a }), { f: [["a", { $: "sa_1" }]] }); assert.deepStrictEqual(Lib.read({ f: [["a", { $: "sa_1" }]] }), { a }); })(); }); }); describe("Symbols serialization", function () { it("should keep values", function () { const a1 = Symbol("a"); const a2 = Symbol("a"); const b = Symbol("b"); const g = Symbol.for("g"); const opts = { symsByName: new Map() }; const res = Lib.write({ a1, a2, b1: b, b2: b, g }, opts); assert.deepStrictEqual(res, { f: [ ["a1", { name: "a", $: "Symbol" }], ["a2", { name: "a", id: 1, $: "Symbol" }], ["b1", { name: "b", $: "Symbol" }], ["b2", { name: "b", $: "Symbol" }], ["g", { key: "g", $: "Symbol" }] ] }); const { a1: ra1, a2: ra2, b1: rb1, b2: rb2, g: rg } = Lib.read(res, opts); assert.strictEqual(a1, ra1); assert.strictEqual(a2, ra2); assert.strictEqual(b, rb1); assert.strictEqual(b, rb2); assert.strictEqual(rg, g); const { a1: la1, a2: la2, b1: lb1, b2: lb2, g: lg } = Lib.read(res, { ignore: true }); assert.notStrictEqual(a1, la1); assert.notStrictEqual(a2, la2); assert.notStrictEqual(lb1, b); assert.notStrictEqual(lb2, b); assert.strictEqual(lg, g); assert.strictEqual(lb1, lb2); assert.equal(String(la1), "Symbol(a)"); assert.equal(String(la2), "Symbol(a)"); assert.equal(String(lb1), "Symbol(b)"); assert.equal(String(lb2), "Symbol(b)"); }); }); describe("type with `$$typeof` attribute", function () { Lib.regDescriptor({ name: "hundred", typeofTag: 100, read(ctx, json) { return { $$typeof: 100 }; }, write(ctx, value) { return { $: "hundred" }; }, props: false }); it("should use overriden methods", function () { assert.deepStrictEqual(Lib.write({ $$typeof: 100 }), { $: "hundred" }); assert.deepStrictEqual(Lib.read({ $: "hundred" }), { $$typeof: 100 }); }); }); describe("bind function arguments", function () { it("should be serializable", function () { const obj = {}; function f1(a1, a2, a3) { return [this, a1, a2, a3]; } const a1 = {}, a2 = {}, a3 = {}; Lib.regOpaqueObject(obj, "obj"); Lib.regOpaqueObject(f1); Lib.regOpaqueObject(a1, "arg"); Lib.regOpaqueObject(a2, "arg"); const bind = Lib.bind(f1, obj, a1, a2); bind.someNum = 100; bind.rec = bind; const fjson = Lib.write({ f: bind }); assert.deepStrictEqual(fjson, { f: [ [ "f", { r: 0 } ] ], x: [ { f: [ ["someNum", 100], [ "rec", { r: 0 } ], [ { $: "#this" }, { $: "obj" } ], [ { $: "#fun" }, { $: "f1" } ], [ { $: "#args" }, [ { $: "arg" }, { $: "arg_1" } ] ] ], $: "Bind" } ] }); const f2 = Lib.read(fjson).f; assert.notStrictEqual(f1, f2); const res = f2(a3); assert.strictEqual(res.length, 4); const [robj, ra1, ra2, ra3] = res; assert.strictEqual(obj, robj); assert.strictEqual(a1, ra1); assert.strictEqual(a2, ra2); assert.strictEqual(a3, ra3); }); }); describe("RegExp", function () { it("should be serializable", function () { const re1 = /\w+/; const re2 = /ho/g; const s1 = "uho-ho-ho"; re2.test(s1); const res = Lib.write({ re1, re2 }); assert.deepEqual(res, { f: [ ["re1", { src: "\\w+", flags: "", $: "RegExp" }], ["re2", { src: "ho", flags: "g", last: 3, $: "RegExp" }] ] }); const { re1: bre1, re2: bre2 } = Lib.read(res); assert.equal(re1.src, bre1.src); assert.equal(re1.flags, bre1.flags); assert.equal(re1.lastIndex, bre1.lastIndex); assert.equal(re2.src, bre2.src); assert.equal(re2.flags, bre2.flags); assert.equal(re2.lastIndex, bre2.lastIndex); }); }); describe("not serializable values", function () { it("should throw an exception if `ignore:falsy`", function () { function A() {} try { Lib.write({ A }); } catch (e) { assert.equal(e.constructor, TypeError); assert.equal( e.message, `not serializable value "function A() {}" at "1"(A) of "A"` ); return; } assert.fail("should throw"); }); it("should be ignored if `ignore:true`", function () { function A() {} const d = Lib.write({ A }, { ignore: true }); const r = Lib.read(d); assert.deepEqual(r, {}); }); it('should register an opaque descriptor `ignore:"opaque"`', function () { function A() {} const d = Lib.write({ A, b: A }, { ignore: "opaque" }); const r = Lib.read(d); assert.deepEqual(r, { A, b: A }); }); it("should register an opaque descriptor with auto-opaque descriptor", function () { function A() {} Lib.regAutoOpaqueConstr(A, true); const a = new A(); const d = Lib.write({ a, b: a }, { ignore: "opaque" }); const r = Lib.read(d); assert.deepEqual(r, { a, b: a }); }); it('should be converted into a not usable placeholder if `ignore:"placeholder"`', function () { function A() {} const d = Lib.write({ A }, { ignore: "placeholder" }); const r = Lib.read(d); try { r.A(); } catch (e) { assert.equal(e.constructor, TypeError); assert.equal(e.message, "apply in a not restored object"); return; } assert.fail("should throw"); }); }); describe("TypedArray", function () { it("should be serializable", function () { const arr1 = new Int32Array([1, 2, 3, 4, 5]); const arr2 = new Uint32Array(arr1.buffer, 8); const d = Lib.write({ arr1, arr2 }, {}); assert.deepStrictEqual(d, { f: [ [ "arr1", { o: 0, l: 5, b: { r: 0 }, $: "Int32Array" } ], [ "arr2", { o: 8, l: 3, b: { r: 0 }, $: "Uint32Array" } ] ], x: [ { d: "AQAAAAIAAAADAAAABAAAAAUAAAA=", $: "ArrayBuffer" } ] }); const { arr1: rarr1, arr2: rarr2 } = Lib.read(d); assert.equal(rarr1.constructor, Int32Array); assert.equal(rarr2.constructor, Uint32Array); assert.notStrictEqual(arr1, rarr1); assert.notStrictEqual(arr2, rarr2); assert.deepStrictEqual(arr1, rarr1); assert.deepStrictEqual(arr2, rarr2); }); }); describe("WeakSet/WeakMap", function () { it("should be serializable", function () { const set = new WeakSet(); const map = new WeakMap(); const map2 = new WeakMap(); const obj1 = {}; const obj2 = {}; Lib.regOpaqueObject(obj1, "w#obj1"); set.add(obj1).add(obj2); map.set(obj1, "obj1").set(obj2, "obj2"); map2.set(obj1, "2obj1"); assert.ok(set.has(obj1)); assert.ok(map.has(obj1)); assert.strictEqual(map.get(obj1), "obj1"); assert.strictEqual(map.get({}), void 0); const d = Lib.write({ set, map, map2, obj1, obj2 }); assert.deepStrictEqual(d, { x: [{}, { $: "w#obj1" }], f: [ ["set", { v: [{ r: 0 }, { r: 1 }], $: "WeakSet" }], [ "map", { k: [{ r: 1 }, { r: 0 }], v: ["obj1", "obj2"], $: "WeakMap" } ], [ "map2", { k: [{ r: 1 }], v: ["2obj1"], $: "WeakMap" } ], ["obj1", { r: 1 }], ["obj2", { r: 0 }] ] }); const { set: rset, map: rmap, map2: rmap2, obj1: robj1, obj2: robj2 } = Lib.read(d); assert.strictEqual(robj1, obj1); assert.notStrictEqual(robj2, obj2); assert.ok(rset.has(obj1)); assert.ok(set.delete(obj1)); assert.ok(!set.has(obj1)); assert.ok(rset.has(obj1)); assert.ok(rset.has(robj2)); assert.ok(!rset.has(obj2)); assert.ok(!set.has(robj2)); assert.strictEqual(rmap.get(obj1), "obj1"); assert.strictEqual(rmap2.get(obj1), "2obj1"); assert.ok(map.delete(obj1)); assert.strictEqual(rmap.get(obj1), "obj1"); assert.ok(rset.delete(robj2)); assert.ok(!rset.has(robj2)); assert.ok(!rset.delete(robj2)); assert.ok(!rset.has(robj2)); }); }); describe("WeakSet/WeakMap workaround", function () { it("should be serializable", function () { const set = new Lib.WeakSetWorkaround(); const map = new Lib.WeakMapWorkaround(); const map2 = new Lib.WeakMapWorkaround(); const obj1 = {}; const obj2 = {}; Lib.regOpaqueObject(obj1, "w##obj1"); set.add(obj1).add(obj2); map.set(obj1, "obj1").set(obj2, "obj2"); map2.set(obj1, "2obj1"); assert.ok(set.has(obj1)); assert.ok(map.has(obj1)); assert.strictEqual(map.get(obj1), "obj1"); assert.strictEqual(map.get({}), void 0); const d = Lib.write({ set, map, map2, obj1, obj2 }); assert.deepStrictEqual(d, { f: [ [ "set", { f: [["prop", { name: "@effectful/weakset", $: "Symbol" }]], $: "WeakSet#" } ], [ "map", { f: [["prop", { name: "@effectful/weakmap", $: "Symbol" }]], $: "WeakMap#" } ], [ "map2", { f: [["prop", { name: "@effectful/weakmap", id: 1, $: "Symbol" }]], $: "WeakMap#" } ], [ "obj1", { $: "w##obj1", f: [ [{ name: "@effectful/weakset" }, true, 2], [{ name: "@effectful/weakmap" }, "obj1", 2], [{ name: "@effectful/weakmap", id: 1 }, "2obj1", 2] ] } ], [ "obj2", { f: [ [{ name: "@effectful/weakset" }, true, 2], [{ name: "@effectful/weakmap" }, "obj2", 2] ] } ] ] }); const { set: rset, map: rmap, map2: rmap2, obj1: robj1, obj2: robj2 } = Lib.read(d); assert.strictEqual(robj1, obj1); assert.notStrictEqual(robj2, obj2); assert.ok(rset.has(obj1)); assert.ok(set.delete(obj1)); assert.ok(!set.has(obj1)); assert.ok(rset.has(obj1)); assert.ok(rset.has(robj2)); assert.ok(!rset.has(obj2)); assert.ok(!set.has(robj2)); assert.strictEqual(rmap.get(obj1), "obj1"); assert.strictEqual(rmap2.get(obj1), "2obj1"); assert.ok(map.delete(obj1)); assert.strictEqual(rmap.get(obj1), "obj1"); assert.ok(rset.delete(robj2)); assert.ok(!rset.has(robj2)); assert.ok(!rset.delete(robj2)); assert.ok(!rset.has(robj2)); }); }); describe("BigInt", function () { it("should be serializable", function () { const num = 2n ** 10000n; const doc = Lib.write({ num }); assert.equal(doc.f[0][0], "num"); assert.ok(doc.f[0][1].int.substr); assert.equal(doc.f[0][1].int.length, 3011); assert.strictEqual(Lib.read(doc).num, num); }); });
awto/effectfuljs
packages/serialization/test/main.js
JavaScript
mit
27,905
(function () { 'use strict'; angular .module('crimes.routes') .config(routeConfig); routeConfig.$inject = ['$stateProvider']; function routeConfig($stateProvider) { $stateProvider .state('crimes', { abstract: true, url: '/crimes', template: '<ui-view/>' }) .state('crimes.list', { url: '', templateUrl: '/modules/crimes/client/views/list-crimes.client.view.html', controller: 'CrimesListController', controllerAs: 'vm', data: { pageTitle: 'Crimes List' } }) .state('crimes.view', { url: '/:crimeId', templateUrl: '/modules/crimes/client/views/view-crimes.client.view.html', controller: 'CrimesController', controllerAs: 'vm', resolve: { crimeResolve: getCrime }, data: { pageTitle: 'Crimes {{ crimeResolve.title }}' } }); } getCrime.$inject = ['$stateParams', 'CrimesService']; function getCrime($stateParams, CrimesService) { return CrimesService.get({ crimeId: $stateParams.crimeId }).$promise; } }());
ravikumargh/Police
modules/crimes/client/config/crime.client.routes.js
JavaScript
mit
1,154
/** * Compile sass files to css using compass */ module.exports = { dev: { options: { config: 'config.rb', environment: 'development' } }, };
timothytran/ngModular
grunt/compass.js
JavaScript
mit
192
// JSON Object of all of the icons and their tags export default { apple : { name : 'apple', color: '#be0000', image : 'apple67.svg', tags: ['apple', 'fruit', 'food'], categories: ['food', 'supermarket'] }, bread : { name : 'bread', color: '#c26b24', image : 'bread14.svg', tags: ['bread', 'food', 'wheat', 'bake'], categories: ['food', 'supermarket'] }, broccoli : { name : 'broccoli', color: '#16a900', image : 'broccoli.svg', tags: ['broccoli', 'food', 'vegetable'], categories: ['food', 'supermarket'] }, cheese : { name : 'cheese', color: '#ffe625', image : 'cheese7.svg', tags: ['cheese', 'food', 'dairy'], categories: ['food', 'supermarket'] }, shopping : { name : 'shopping', color: '#f32393', image : 'shopping225.svg', tags: ['shopping', 'bag'], categories: ['shopping', 'supermarket'] }, cart : { name : 'cart', color: '#9ba990', image : 'supermarket1.svg', tags: ['cart', 'shopping'], categories: ['shopping', 'supermarket'] }, fish : { name : 'fish', color: '#6d7ca9', image : 'fish52.svg', tags: ['fish', 'food'], categories: ['fish', 'supermarket'] }, giftbox : { name : 'giftbox', color: '#f32393', image : 'giftbox56.svg', tags: ['giftbox', 'gift', 'present'], categories: ['gift', 'shopping', 'supermarket'] } };
una/heiroglyph
app/js/data/iconListInfo.js
JavaScript
mit
1,423
const path = require('path'); const webpack = require('webpack'); const webpackMerge = require('webpack-merge'); const commonConfig = require('./webpack.common.config.js'); module.exports = function () { return webpackMerge(commonConfig, { watch: true, devtool: 'cheap-module-source-map', // plugins: [ // new webpack.optimize.CommonsChunkPlugin({ // name: "common", // }) // ], devServer: { contentBase: __dirname + "/public/", port: 8080, watchContentBase: true } }) };
LilyaSidorenko/jsmp-project2
webpack.dev.config.js
JavaScript
mit
598
const Nodelist = artifacts.require("./Nodelist.sol"); const BiathlonNode = artifacts.require("./BiathlonNode.sol"); const SecondNode = artifacts.require("./SecondNode.sol"); const BiathlonToken = artifacts.require("./BiathlonToken.sol"); const Ownable = artifacts.require('../contracts/ownership/Ownable.sol'); // const MintableToken = artifacts.require('MintableToken.sol'); const SecondBiathlonToken = artifacts.require("./SecondBiathlonToken.sol"); let nl; let bn; let bt; let sn; let st; contract('BiathlonToken', function(accounts) { beforeEach(async function() { bn = await BiathlonNode.deployed(); nl = await Nodelist.deployed(); bt = await BiathlonToken.deployed(); st = await SecondBiathlonToken.deployed(); sn = await SecondNode.deployed(); }); it('should have an owner', async function() { let owner = await bt.owner(); assert.isTrue(owner !== 0); }); it('should belong to the correct node', async function() { let node = await bt.node_address(); let bna = await bn.address; assert.equal(node, bna, "Token was not initialised to correct node"); }); it('should have a storage contract that is separate', async function() { let storage_address = await bt.storage_address(); assert.notEqual(storage_address, bt.address); }); it("should be able to register itself with the Node list of tokens", async function() { let registration = await bt.register_with_node(); let node_token_count = await bn.count_tokens(); assert.equal(node_token_count, 1, "Node array of tokens doesn't have deployed BiathlonToken"); }); it('should mint a given amount of tokens to a given address', async function() { const result = await bt.mint(accounts[0], 100, { from: accounts[0] }); assert.equal(result.logs[0].event, 'Mint'); assert.equal(result.logs[0].args.to.valueOf(), accounts[0]); assert.equal(result.logs[0].args.amount.valueOf(), 100); assert.equal(result.logs[1].event, 'Transfer'); assert.equal(result.logs[1].args.from.valueOf(), 0x0); let balance0 = await bt.balanceOf(accounts[0]); assert(balance0 == 100); let totalSupply = await bt.totalSupply(); assert.equal(totalSupply, 100); }) it('should allow owner to mint 50 to account #2', async function() { let result = await bt.mint(accounts[2], 50); assert.equal(result.logs[0].event, 'Mint'); assert.equal(result.logs[0].args.to.valueOf(), accounts[2]); assert.equal(result.logs[0].args.amount.valueOf(), 50); assert.equal(result.logs[1].event, 'Transfer'); assert.equal(result.logs[1].args.from.valueOf(), 0x0); let new_balance = await bt.balanceOf(accounts[2]); assert.equal(new_balance, 50, 'Owner could not mint 50 to account #2'); }); it('should have account #2 on registry after first token minting', async function() { let check_user = await nl.users(accounts[2]); assert.equal(check_user, bn.address); }); it('should spend 25 of the tokens minted to account #2', async function() { let result = await bt.spend(accounts[2], 25); assert.equal(result.logs[0].event, 'Burn'); let new_balance = await bt.balanceOf(accounts[2]); assert.equal(new_balance, 25); }); it('should have total supply changed by these minting and spending operations', async function() { let result = await bt.totalSupply(); assert.equal(result, 125); }); it('should not allow non-onwers to spend', async function() { try { let spendtask = await bt.spend(accounts[0], 1, {from: accounts[2]}) } catch (error) { const invalidJump = error.message.search('invalid opcode') >= 0; assert(invalidJump, "Expected throw, got '" + error + "' instead"); return; } assert.fail("Expected to reject spending from non-owner"); }); it('should not allow non-owners to mint', async function() { try { let minttask = await bt.mint(accounts[2], 50, {from: accounts[1]}); } catch (error) { const invalidJump = error.message.search('invalid opcode') >= 0; assert(invalidJump, "Expected throw, got '" + error + "' instead"); return; } assert.fail("Expected to reject minting from non-owner"); }); it('should not be able to spend more than it has', async function() { try { let spendtask = await bt.spend(accounts[2], 66) } catch (error) { const invalidJump = error.message.search('invalid opcode') >= 0; assert(invalidJump, "Expected throw, got '" + error + "' instead"); return; } assert.fail("Expected to reject spending more than limit"); }); it('second deployed token should belong to the correct node', async function() { let node = await st.node_address(); let bna = await bn.address; assert.equal(node, bna, "Token was not initialised to correct node"); }); it('second token should be able to upgrade the token with the node', async function() { let name = await st.name(); const upgraded = await bn.upgrade_token(bt.address, st.address, name); assert.equal(upgraded.logs[0].event, 'UpgradeToken'); let count_of_tokens = await bn.count_tokens(); assert.equal(count_of_tokens, 1, 'Should only be one token in tokenlist still'); }); it('should deactivate original token after upgrade', async function () { let tia = await bn.tokens.call(bt.address); assert.isNotTrue(tia[1]); let newtoken = await bn.tokens.call(st.address); assert.isTrue(newtoken[1]); }); it('should carry over the previous balances since storage contract is fixed', async function() { let get_balance = await st.balanceOf(accounts[2]); assert.equal(get_balance, 25); }); it('should not allow the deactivated contract to mint', async function() { try { let newmint = await bt.mint(accounts[2], 10); } catch(error) { const invalidJump = error.message.search('invalid opcode') >= 0; assert(invalidJump, "Expected throw, got '" + error + "' instead"); return; } assert.fail("Expected to reject spending more than limit"); }); it('should allow minting more tokens to accounts', async function() { let newmint = await st.mint(accounts[2], 3); let getbalance = await st.balanceOf(accounts[2]); let totalsupply = await st.totalSupply(); assert.equal(totalsupply, 128); assert.equal(getbalance, 28); }); it('should be able to transfer as contract owner from one account to another', async function() { let thetransfer = await st.biathlon_transfer(accounts[2], accounts[3], 2); let getbalance2 = await st.balanceOf(accounts[2]); let getbalance3 = await st.balanceOf(accounts[3]); assert.equal(getbalance2, 26); assert.equal(getbalance3, 2); }); it('should not be able to transfer as non-owner from one account to another', async function() { try { let thetransfer = await st.biathlon_transfer(accounts[3], accounts[4], 1, {from: accounts[1]}); } catch(error) { const invalidJump = error.message.search('invalid opcode') >= 0; assert(invalidJump, "Expected throw, got '" + error + "' instead"); return; } assert.fail("Expected to reject transfering from non-owner"); }) });
BiathlonHelsinki/BiathlonContract
test/3_biathlontoken.js
JavaScript
mit
7,223
var express = require('express'); var bodyParser = require('body-parser'); var fs = require('fs') var app = express(); var lostStolen = require('mastercard-lost-stolen'); var MasterCardAPI = lostStolen.MasterCardAPI; var dummyData = []; var dummyDataFiles = ['www/data/menu.json', 'www/data/account-number.json']; dummyDataFiles.forEach(function(file) { fs.readFile(file, 'utf8', function(err, data) { if (err) { return console.log(err); } dummyData[file] = JSON.parse(data); }); }); var config = { p12file: process.env.KEY_FILE || null, p12pwd: process.env.KEY_FILE_PWD || 'keystorepassword', p12alias: process.env.KEY_FILE_ALIAS || 'keyalias', apiKey: process.env.API_KEY || null, sandbox: process.env.SANDBOX || 'true', } var useDummyData = null == config.p12file; if (useDummyData) { console.log('p12 file info missing, using dummy data') } else { console.log('has p12 file info, using MasterCardAPI') var authentication = new MasterCardAPI.OAuth(config.apiKey, config.p12file, config.p12alias, config.p12pwd); MasterCardAPI.init({ sandbox: 'true' === config.sandbox, authentication: authentication }); } app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(express.static('www')); app.post('/menu', function(req, res) { res.json(dummyData[dummyDataFiles[0]]); }); app.post('/orders', function(req, res) { res.json({}); }); app.post('/confirm', function(req, res) { res.json({}); }); app.post('/checkAccountNumber', function(req, res) { if (useDummyData) { if (null == dummyData[dummyDataFiles[1]][req.body.accountNumber]) { res.json(dummyData[dummyDataFiles[1]].default); } else { res.json(dummyData[dummyDataFiles[1]][req.body.accountNumber]); } } else { var requestData = { "AccountInquiry": { "AccountNumber": req.body.accountNumber } }; lostStolen.AccountInquiry.update(requestData, function(error, data) { if (error) { res.json({ "type": "APIError", "message": "Error executing API call", "status": 400, "data": { "Errors": { "Error": { "Source": "Unknown", "ReasonCode": "UNKNOWN", "Description": "Unknown error", "Recoverable": "false" } } } }); } else { res.json(data); } }); } }); app.listen(3000, function() { console.log('Example app listening on port 3000!'); });
perusworld/mcdevapi-lostandstolen-refimpl-web
index.js
JavaScript
mit
2,903
var express = require('express'); var router = express.Router(); /* GET home page. */ router.get('/', function(req, res, next) { res.render('index', { title: 'Express' }); }); router.get('/about', function(req, res, next) { res.render('about', { title: 'About' }); }); module.exports = router;
Studio39/node-snapclone
routes/index.js
JavaScript
mit
301
'use strict'; // Projects controller angular.module('about').controller('AboutUsController', ['$scope', '$stateParams', '$state', '$location', 'Authentication', function($scope, $stateParams, $state, $location, Authentication) { $scope.authentication = Authentication; } ]);
spiridonov-oa/people-ma
public/modules/about/controllers/about.client.controller.js
JavaScript
mit
281
import { Dimensions, PixelRatio } from 'react-native'; const Utils = { ratio: PixelRatio.get(), pixel: 1 / PixelRatio.get(), size: { width: Dimensions.get('window').width, height: Dimensions.get('window').height, }, post(url, data, callback) { const fetchOptions = { method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify(data), }; fetch(url, fetchOptions) .then(response => { response.json(); }) .then(responseData => { callback(responseData); }); }, }; export default Utils;
zhiyuanMA/ReactNativeShowcase
components/utils.js
JavaScript
mit
765
#!/usr/bin/env node // // cli.js // // Copyright (c) 2016-2017 Junpei Kawamoto // // This software is released under the MIT License. // // http://opensource.org/licenses/mit-license.php // const { start, crawl } = require("../lib/crawler"); const argv = require("yargs") .option("lang", { describe: "Language to be used to scrape trand pages. Not used in crawl command." }) .default("lang", "EN") .option("dir", { describe: "Path to the directory to store database files" }) .demandOption(["dir"]) .command("*", "Start crawling", () => {}, (argv) => { start(argv.lang, argv.dir); }) .command("crawl", "Crawl comments form a video", () => {}, (argv) => { crawl(argv.dir).catch((err) => { console.error(err); }); }) .help("h") .alias("h", "help") .argv;
itslab-kyushu/youtube-comment-crawler
bin/cli.js
JavaScript
mit
867
const AppError = require('../../../lib/errors/app') const assert = require('assert') function doSomethingBad () { throw new AppError('app error message') } it('Error details', function () { try { doSomethingBad() } catch (err) { assert.strictEqual( err.name, 'AppError', "Name property set to error's name" ) assert( err instanceof AppError, 'Is an instance of its class' ) assert( err instanceof Error, 'Is instance of built-in Error' ) assert( require('util').isError(err), 'Should be recognized by Node.js util#isError' ) assert( err.stack, 'Should have recorded a stack' ) assert.strictEqual( err.toString(), 'AppError: app error message', 'toString should return the default error message formatting' ) assert.strictEqual( err.stack.split('\n')[0], 'AppError: app error message', 'Stack should start with the default error message formatting' ) assert.strictEqual( err.stack.split('\n')[1].indexOf('doSomethingBad'), 7, 'The first stack frame should be the function where the error was thrown' ) } })
notmessenger/poker-analysis
test/lib/errors/app.js
JavaScript
mit
1,211
export default { cache: function (state, payload) { state.apiCache[payload.api_url] = payload.api_response; }, addConfiguredType: function (state, type) { state.configuredTypes.push(type); }, removeConfiguredType: function (state, index) { state.configuredTypes.splice(index, 1); }, updateConfiguredType: function (state, type) { for (var i = 0, len = state.configuredTypes.length; i < len; i++) { if (state.configuredTypes[i].name === type.name) { state.configuredTypes.splice(i, 1); state.configuredTypes.push(type); // Avoid too keep looping over a spliced array return; } } }, setBaseExtraFormTypes: function (state, types) { state.baseTypes = types; }, setConfiguredExtraFormTypes: function (state, types) { state.configuredTypes = types; } };
IDCI-Consulting/ExtraFormBundle
Resources/public/js/editor/src/store/mutations.js
JavaScript
mit
854
var indexController = require('./controllers/cIndex'); var usuarioController = require('./controllers/cUsuario'); var clientesController = require('./controllers/cCliente'); var adminController = require('./controllers/cAdmin'); var umedController = require('./controllers/cUmed'); var matepController = require('./controllers/cMatep'); var empleController = require('./controllers/cEmple'); var accesosController = require('./controllers/cAccesos'); var cargoController = require('./controllers/cCargos'); var reactoController = require('./controllers/cReacto'); var lineasController = require('./controllers/cLineas'); var prodController = require('./controllers/cProd'); var envasesController = require('./controllers/cEnvases'); var tanquesController = require('./controllers/cTanques'); var ubicaController = require('./controllers/cUbica'); var recetaController = require('./controllers/cReceta'); var remitosController = require('./controllers/cRemitos'); var progController = require('./controllers/cProgramacion'); var FormEnReactorController = require('./controllers/cFormEnReactor'); var labController = require('./controllers/cLab'); var formController = require('./controllers/cFormulados'); var mEventos = require('./models/mEventos'); var consuController = require('./controllers/cConsumibles'); var produccionController = require('./controllers/cProduccion'); var fraccionadoController = require('./controllers/cFraccionado'); var aprobacionController = require('./controllers/cAprobacion'); var navesController = require('./controllers/cNaves'); var mapaController = require('./controllers/cMapa'); function logout (req, res) { fecha = new Date(); day = fecha.getDate(); month = fecha.getMonth(); if (day<10) day = "0" + day; if (month<10) month = "0" + month; fecha = fecha.getFullYear() + "/"+month+"/"+day+" "+fecha.getHours()+":"+fecha.getMinutes() mEventos.add(req.session.user.unica, fecha, "Logout", "", function(){ }); req.session = null; return res.redirect('/'); } // Verifica que este logueado function auth (req, res, next) { if (req.session.auth) { return next(); } else { console.log("dentro del else del auth ") return res.redirect('/') } } module.exports = function(app) { app.get('/', adminController.getLogin); app.get('/login', adminController.getLogin) app.post('/login', adminController.postLogin); app.get('/logout', logout); app.get('/inicio', auth, indexController.getInicio); app.get('/error', indexController.getError); //ayuda app.get('/ayuda', indexController.getAyuda); app.get('/ayudaver/:id', indexController.AyudaVer); //novedades app.get('/listanovedades', indexController.getNovedades); //usuarios app.get('/usuarioslista', auth, usuarioController.getUsuarios); app.get('/usuariosalta', auth, usuarioController.getUsuariosAlta); app.post('/usuariosalta', auth, usuarioController.putUsuario); app.get('/usuariosmodificar/:id', auth, usuarioController.getUsuarioModificar); app.post('/usuariosmodificar', auth, usuarioController.postUsuarioModificar); app.get('/usuariosborrar/:id', auth, usuarioController.getDelUsuario); //configurar accesos app.get('/accesoslista/:id', auth, accesosController.getAccesos); app.post('/accesoslista', auth, accesosController.postAccesos); //clientes app.get('/clienteslista', auth, clientesController.getClientes); app.get('/clientesalta', auth, clientesController.getClientesAlta); app.post('/clientesalta', auth, clientesController.putCliente); app.get('/clientesmodificar/:id', auth, clientesController.getClienteModificar); app.post('/clientesmodificar', auth, clientesController.postClienteModificar); app.get('/clientesborrar/:id', auth, clientesController.getDelCliente); app.get('/:cliente/materiasprimas', auth, clientesController.getMatep); //unidades de medida "umed" app.get('/umedlista', auth, umedController.getAllUmed); app.get('/umedalta', auth, umedController.getAlta); app.post('/umedalta', auth, umedController.postAlta); app.get('/umedmodificar/:id', auth, umedController.getModificar); app.post('/umedactualizar', auth, umedController.postModificar); app.get('/umedborrar/:id', auth, umedController.getDelUmed); //materias primas por cliente app.get('/mateplista/:cdcliente', auth, matepController.getAllMatepPorCliente); app.get('/matepalta/:cdcliente', auth, matepController.getAlta); app.post('/matepalta', auth, matepController.postAlta); app.get('/matepmodificar/:id', auth, matepController.getModificar); app.post('/matepmodificar', auth, matepController.postModificar); app.get('/matepborrar/:id', auth, matepController.getDelMatep); //cantidad maxima en tanque por matep app.get('/formenreactor/:id', auth, FormEnReactorController.getFormEnReactor); app.get('/formenreactoralta/:idform', auth, FormEnReactorController.getAlta); app.post('/formenreactoralta', auth, FormEnReactorController.postAlta); app.get('/formenreactormodificar/:id', auth, FormEnReactorController.getModificar); app.post('/formenreactormodificar', auth, FormEnReactorController.postModificar); app.get('/formenreactorborrar/:id', auth, FormEnReactorController.del); //producto por clientereactor app.get('/prodlista/:cdcliente', auth, prodController.getAllProdPorCliente); app.get('/prodalta/:cdcliente', auth, prodController.getAlta); app.post('/prodalta', auth, prodController.postAlta); app.get('/prodmodificar/:id', auth, prodController.getModificar); app.post('/prodmodificar', auth, prodController.postModificar); app.get('/prodborrar/:id', auth, prodController.getDelProd); app.get('/:idprod/ablote', auth, prodController.getAbLote); //empleados app.get('/emplelista', auth, empleController.getEmpleados); app.get('/emplealta', auth, empleController.getAlta); app.post('/emplealta', auth, empleController.postAlta); app.get('/emplemodificar/:codigo', auth, empleController.getModificar); app.post('/emplemodificar', auth, empleController.postModificar); app.get('/empleborrar/:codigo', auth, empleController.getDelEmple); //cargos de empleados app.get('/cargoslista', auth, cargoController.getAllCargos); app.get('/cargosalta', auth, cargoController.getAlta); app.post('/cargosalta', auth, cargoController.postAlta); app.get('/cargosmodificar/:id', auth, cargoController.getModificar); app.post('/cargosmodificar', auth, cargoController.postModificar); app.get('/cargosborrar/:id', auth, cargoController.getDelCargo); //reactores app.get('/reactolista', auth, reactoController.getAll); app.get('/reactoalta', auth, reactoController.getAlta); app.post('/reactoalta', auth, reactoController.postAlta); app.get('/reactomodificar/:id', auth, reactoController.getModificar); app.post('/reactomodificar', auth, reactoController.postModificar); app.get('/reactoborrar/:id', auth, reactoController.getDel); //lineas app.get('/lineaslista', auth, lineasController.getAll); app.get('/lineasalta', auth, lineasController.getAlta); app.post('/lineasalta', auth, lineasController.postAlta); app.get('/lineasmodificar/:id', auth, lineasController.getModificar); app.post('/lineasmodificar', auth, lineasController.postModificar); app.get('/lineasborrar/:id', auth, lineasController.getDel); //envases app.get('/envaseslista', auth, envasesController.getAll); app.get('/envasesalta', auth, envasesController.getAlta); app.post('/envasesalta', auth, envasesController.postAlta); app.get('/envasesmodificar/:id', auth, envasesController.getModificar); app.post('/envasesmodificar', auth, envasesController.postModificar); app.get('/envasesborrar/:id', auth, envasesController.getDel); app.get('/capacidadenvase/:id', auth, envasesController.getCapacidad); //tanques app.get('/tanqueslista', auth, tanquesController.getAll); app.get('/tanquesalta', auth, tanquesController.getAlta); app.post('/tanquesalta', auth, tanquesController.postAlta); app.get('/tanquesmodificar/:id', auth, tanquesController.getModificar); app.post('/tanquesmodificar', auth, tanquesController.postModificar); app.get('/tanquesborrar/:id', auth, tanquesController.getDel); //ubicaciones "ubica" app.get('/ubicalista', auth, ubicaController.getAll); app.get('/ubicaalta', auth, ubicaController.getAlta); app.post('/ubicaalta', auth, ubicaController.postAlta); app.get('/ubicamodificar/:id', auth, ubicaController.getModificar); app.post('/ubicamodificar', auth, ubicaController.postModificar); app.get('/ubicaborrar/:id', auth, ubicaController.getDel); //recetas app.get('/recetalista/:id', auth, recetaController.getRecetaPorFormulado); app.get('/recetaalta/:id', auth, recetaController.getAlta); app.post('/recetaalta', auth, recetaController.postAlta); app.get('/recetaborrar/:id', auth, recetaController.getDel); app.get('/recetamodificar/:id', auth, recetaController.getModificar); app.post('/recetamodificar', auth, recetaController.postModificar); //remitos app.get('/remitoslista', auth, remitosController.getAll); app.get('/remitosalta', auth, remitosController.getAlta); app.post('/remitosalta', auth, remitosController.postAlta); app.get('/remitosmodificar/:id', auth, remitosController.getModificar); app.post('/remitosmodificar', auth, remitosController.postModificar); app.get('/remitosborrar/:id', auth, remitosController.getDel); app.get('/buscarremito/:finicio/:ffin', auth, remitosController.getRemitos); //programacion app.get('/prog1lista', auth, progController.getAll); app.get('/prog1alta', auth, progController.getAlta); app.post('/prog1alta', auth, progController.postAlta); app.get('/prog2lista', auth, progController.getLista); app.get('/prog1alta2/:idprog', auth, progController.getAlta2); app.post('/prog1alta2', auth, progController.postAlta2); app.get('/prog1/:lote/:anio/:clienteid/:prodid', auth, progController.getCodigo); app.get('/prog1borrar/:id', auth, progController.getDel); app.get('/refrescaremito/:idcliente/:idmatep', auth, progController.getRemitos); app.get('/traerpa/:idform', auth, progController.getPA); app.get('/buscarprogramaciones/:fecha', auth, progController.getProgramaciones); app.get('/produccionborrarprogram/:id', auth, progController.getDelProgram); //laboratorio app.get('/lab/:idremito', auth, labController.getLab); app.post('/lab', auth, labController.postLab); //formulados app.get('/formuladoalta/:cdcliente', auth, formController.getAlta); app.post('/formuladoalta', auth, formController.postAlta); app.get('/formuladolista/:cdcliente', auth, formController.getAllFormuladoPorCliente); app.get('/formuladomodificar/:id', auth, formController.getModificar); app.post('/formuladomodificar', auth, formController.postModificar); app.get('/formuladoborrar/:id', auth, formController.getDelFormulado); app.get('/:id/formulados', auth, formController.getForms); app.get('/:idform/ablotee', auth, formController.getAbLote); //consumibles app.get('/consumibleslista/:idprod', auth, consuController.getAll); app.get('/consumiblesalta/:idprod', auth, consuController.getAlta); app.post('/consumiblesalta', auth, consuController.postAlta); app.get('/consumiblesborrar/:id', auth, consuController.getDel); //produccion app.get('/produccionlista', auth, produccionController.getLista); app.get('/buscarprogramaciones2/:fi/:ff', auth, produccionController.getProgramaciones); app.get('/produccionver/:id', auth, produccionController.getVerFormulado); app.post('/produccionver', auth, produccionController.postDatosFormulado); app.get('/produccionimprimir/:id', auth, produccionController.getImprimir); //borrar //fraccionado app.get('/fraccionadolista', auth, fraccionadoController.getLista); app.get('/fraccionadoalta/:id', auth, fraccionadoController.getAlta); app.post('/fraccionadoalta', auth, fraccionadoController.postAlta); app.get('/fraccionadomodificar/:id', auth, fraccionadoController.getModificar); app.post('/fraccionadomodificar', auth, fraccionadoController.postModificar); //borrar? //aprobacion app.get('/aprobacionlista', auth, aprobacionController.getLista); app.get('/aprobacionver/:id', auth, aprobacionController.getVer); app.post('/aprobacionver', auth, aprobacionController.postVer); app.get('/aprobacionimprimir/:id', auth, aprobacionController.getImprimir); //naves app.get('/naveslista', auth, navesController.getLista); //mapa app.get('/mapaver', auth, mapaController.getMapa); };
IsaacMiguel/ProchemBio
routes.js
JavaScript
mit
12,314
'use strict'; const buildType = process.config.target_defaults.default_configuration; const assert = require('assert'); if (process.argv[2] === 'fatal') { const binding = require(process.argv[3]); binding.error.throwFatalError(); return; } test(`./build/${buildType}/binding.node`); test(`./build/${buildType}/binding_noexcept.node`); function test(bindingPath) { const binding = require(bindingPath); assert.throws(() => binding.error.throwApiError('test'), function(err) { return err instanceof Error && err.message.includes('Invalid'); }); assert.throws(() => binding.error.throwJSError('test'), function(err) { return err instanceof Error && err.message === 'test'; }); assert.throws(() => binding.error.throwTypeError('test'), function(err) { return err instanceof TypeError && err.message === 'test'; }); assert.throws(() => binding.error.throwRangeError('test'), function(err) { return err instanceof RangeError && err.message === 'test'; }); assert.throws( () => binding.error.doNotCatch( () => { throw new TypeError('test'); }), function(err) { return err instanceof TypeError && err.message === 'test' && !err.caught; }); assert.throws( () => binding.error.catchAndRethrowError( () => { throw new TypeError('test'); }), function(err) { return err instanceof TypeError && err.message === 'test' && err.caught; }); const err = binding.error.catchError( () => { throw new TypeError('test'); }); assert(err instanceof TypeError); assert.strictEqual(err.message, 'test'); const msg = binding.error.catchErrorMessage( () => { throw new TypeError('test'); }); assert.strictEqual(msg, 'test'); assert.throws(() => binding.error.throwErrorThatEscapesScope('test'), function(err) { return err instanceof Error && err.message === 'test'; }); assert.throws(() => binding.error.catchAndRethrowErrorThatEscapesScope('test'), function(err) { return err instanceof Error && err.message === 'test' && err.caught; }); const p = require('./napi_child').spawnSync( process.execPath, [ __filename, 'fatal', bindingPath ]); assert.ifError(p.error); assert.ok(p.stderr.toString().includes( 'FATAL ERROR: Error::ThrowFatalError This is a fatal error')); }
MTASZTAKI/ApertusVR
plugins/languageAPI/jsAPI/3rdParty/node-addon-api/test/error.js
JavaScript
mit
2,328
var express = require('express'), compression = require('compression'), path = require('path'), favicon = require('serve-favicon'), logger = require('morgan'), cookieParser = require('cookie-parser'), bodyParser = require('body-parser'), session = require('express-session'), session = require('express-session'), flash = require('connect-flash'), moment = require('moment'), mongoose = require('mongoose'), MongoStore = require('connect-mongo')(session), Pclog = require('./models/pclog.js'), configDB = require('./config/database.js'); mongoose.Promise = global.Promise = require('bluebird'); mongoose.connect(configDB.uri); var routes = require('./routes/index'), reports = require('./routes/reports'), statistics = require('./routes/statistics'), charts = require('./routes/charts'), logs = require('./routes/logs'), organization = require('./routes/organization'), users = require('./routes/users'); var app = express(); //var rootFolder = __dirname; // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); app.use(compression()); // uncomment after placing your favicon in /public app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(session({ secret: 'safe_session_cat', resave: true, rolling: true, saveUninitialized: false, cookie: {secure: false, maxAge: 900000}, store: new MongoStore({ url: configDB.uri }) })); app.use(flash()); app.use(express.static(path.join(__dirname, 'public'))); app.use('/', function(req,res,next){ app.locals.currentUrl = req.path; app.locals.moment = moment; res.locals.messages = require('express-messages')(req, res); if(req.session & req.session.user){ app.locals.user = req.session.user; } console.log(app.locals.user); next(); }); app.use('/', routes); app.use('/reports', reports); app.use('/statistics', statistics); app.use('/charts', charts); app.use('/logs', logs); app.use('/organization', organization); app.use('/users', users); // catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error('Page Not Found.'); err.status = 404; next(err); }); // error handlers // development error handler // will print stacktrace // if (app.get('env') === 'development') { // app.use(function(err, req, res, next) { // res.status(err.status || 500); // res.render('error', { // message: err.message, // error: err // }); // }); // } // production error handler // no stacktraces leaked to user app.use(function(err, req, res, next) { if(err.status){ res.status(err.status); }else{ err.status = 500; err.message = "Internal Server Error." res.status(500); } res.render('404', {error: err}); }); module.exports = app;
EdmonJiang/FA_Inventory
app.js
JavaScript
mit
2,979
const os = require("os"); const fs = require("fs"); const config = { } let libs; switch (os.platform()) { case "darwin": { libs = [ "out/Debug_x64/libpvpkcs11.dylib", "out/Debug/libpvpkcs11.dylib", "out/Release_x64/libpvpkcs11.dylib", "out/Release/libpvpkcs11.dylib", ]; break; } case "win32": { libs = [ "out/Debug_x64/pvpkcs11.dll", "out/Debug/pvpkcs11.dll", "out/Release_x64/pvpkcs11.dll", "out/Release/pvpkcs11.dll", ]; break; } default: throw new Error("Cannot get pvpkcs11 compiled library. Unsupported OS"); } config.lib = libs.find(o => fs.existsSync(o)); if (!config.lib) { throw new Error("config.lib is empty"); } module.exports = config;
PeculiarVentures/pvpkcs11
test/config.js
JavaScript
mit
742
/* * @Author: justinwebb * @Date: 2015-09-24 21:08:23 * @Last Modified by: justinwebb * @Last Modified time: 2015-09-24 22:19:45 */ (function (window) { 'use strict'; window.JWLB = window.JWLB || {}; window.JWLB.View = window.JWLB.View || {}; //-------------------------------------------------------------------- // Event handling //-------------------------------------------------------------------- var wallOnClick = function (event) { if (event.target.tagName.toLowerCase() === 'img') { var id = event.target.parentNode.dataset.id; var selectedPhoto = this.photos.filter(function (photo) { if (photo.id === id) { photo.portrait.id = id; return photo; } })[0]; this.sendEvent('gallery', selectedPhoto.portrait); } }; //-------------------------------------------------------------------- // View overrides //-------------------------------------------------------------------- var addUIListeners = function () { this.ui.wall.addEventListener('click', wallOnClick.bind(this)); }; var initUI = function () { var isUIValid = false; var comp = document.querySelector(this.selector); this.ui.wall = comp; if (this.ui.wall) { this.reset(); isUIValid = true; } return isUIValid; }; //-------------------------------------------------------------------- // Constructor //-------------------------------------------------------------------- var Gallery = function (domId) { // Overriden View class methods this.initUI = initUI; this.addUIListeners = addUIListeners; this.name = 'Gallery'; // Instance properties this.photos = []; // Initialize View JWLB.View.call(this, domId); }; //-------------------------------------------------------------------- // Inheritance //-------------------------------------------------------------------- Gallery.prototype = Object.create(JWLB.View.prototype); Gallery.prototype.constructor = Gallery; //-------------------------------------------------------------------- // Instance methods //-------------------------------------------------------------------- Gallery.prototype.addThumb = function (data, id) { // Store image data for future reference var photo = { id: id, thumb: null, portrait: data.size[0] }; data.size.forEach(function (elem) { if (elem.label === 'Square') { photo.thumb = elem; } if (elem.height > photo.portrait.height) { photo.portrait = elem; } }); this.photos.push(photo); // Build thumbnail UI var node = document.createElement('div'); node.setAttribute('data-id', id); node.setAttribute('class', 'thumb'); var img = document.createElement('img'); img.setAttribute('src', photo.thumb.source); img.setAttribute('title', 'id: '+ id); node.appendChild(img); this.ui.wall.querySelector('article[name=foobar]').appendChild(node); }; Gallery.prototype.reset = function () { if (this.ui.wall.children.length > 0) { var article = this.ui.wall.children.item(0) article.parentElement.removeChild(article); } var article = document.createElement('article'); article.setAttribute('name', 'foobar'); this.ui.wall.appendChild(article); }; window.JWLB.View.Gallery = Gallery; })(window);
JustinWebb/lightbox-demo
app/js/helpers/view/gallery.js
JavaScript
mit
3,410
"use strict"; const readdir = require("../../"); const dir = require("../utils/dir"); const { expect } = require("chai"); const through2 = require("through2"); const fs = require("fs"); let nodeVersion = parseFloat(process.version.substr(1)); describe("Stream API", () => { it("should be able to pipe to other streams as a Buffer", done => { let allData = []; readdir.stream("test/dir") .pipe(through2((data, enc, next) => { try { // By default, the data is streamed as a Buffer expect(data).to.be.an.instanceOf(Buffer); // Buffer.toString() returns the file name allData.push(data.toString()); next(null, data); } catch (e) { next(e); } })) .on("finish", () => { try { expect(allData).to.have.same.members(dir.shallow.data); done(); } catch (e) { done(e); } }) .on("error", err => { done(err); }); }); it('should be able to pipe to other streams in "object mode"', done => { let allData = []; readdir.stream("test/dir") .pipe(through2({ objectMode: true }, (data, enc, next) => { try { // In "object mode", the data is a string expect(data).to.be.a("string"); allData.push(data); next(null, data); } catch (e) { next(e); } })) .on("finish", () => { try { expect(allData).to.have.same.members(dir.shallow.data); done(); } catch (e) { done(e); } }) .on("error", err => { done(err); }); }); it('should be able to pipe fs.Stats to other streams in "object mode"', done => { let allData = []; readdir.stream("test/dir", { stats: true }) .pipe(through2({ objectMode: true }, (data, enc, next) => { try { // The data is an fs.Stats object expect(data).to.be.an("object"); expect(data).to.be.an.instanceOf(fs.Stats); allData.push(data.path); next(null, data); } catch (e) { next(e); } })) .on("finish", () => { try { expect(allData).to.have.same.members(dir.shallow.data); done(); } catch (e) { done(e); } }) .on("error", done); }); it("should be able to pause & resume the stream", done => { let allData = []; let stream = readdir.stream("test/dir") .on("data", data => { allData.push(data); // The stream should not be paused expect(stream.isPaused()).to.equal(false); if (allData.length === 3) { // Pause for one second stream.pause(); setTimeout(() => { try { // The stream should still be paused expect(stream.isPaused()).to.equal(true); // The array should still only contain 3 items expect(allData).to.have.lengthOf(3); // Read the rest of the stream stream.resume(); } catch (e) { done(e); } }, 1000); } }) .on("end", () => { expect(allData).to.have.same.members(dir.shallow.data); done(); }) .on("error", done); }); it('should be able to use "readable" and "read"', done => { let allData = []; let nullCount = 0; let stream = readdir.stream("test/dir") .on("readable", () => { // Manually read the next chunk of data let data = stream.read(); while (true) { // eslint-disable-line if (data === null) { // The stream is done nullCount++; break; } else { // The data should be a string (the file name) expect(data).to.be.a("string").with.length.of.at.least(1); allData.push(data); data = stream.read(); } } }) .on("end", () => { if (nodeVersion >= 12) { // In Node >= 12, the "readable" event fires twice, // and stream.read() returns null twice expect(nullCount).to.equal(2); } else if (nodeVersion >= 10) { // In Node >= 10, the "readable" event only fires once, // and stream.read() only returns null once expect(nullCount).to.equal(1); } else { // In Node < 10, the "readable" event fires 13 times (once per file), // and stream.read() returns null each time expect(nullCount).to.equal(13); } expect(allData).to.have.same.members(dir.shallow.data); done(); }) .on("error", done); }); it('should be able to subscribe to custom events instead of "data"', done => { let allFiles = []; let allSubdirs = []; let stream = readdir.stream("test/dir"); // Calling "resume" is required, since we're not handling the "data" event stream.resume(); stream .on("file", filename => { expect(filename).to.be.a("string").with.length.of.at.least(1); allFiles.push(filename); }) .on("directory", subdir => { expect(subdir).to.be.a("string").with.length.of.at.least(1); allSubdirs.push(subdir); }) .on("end", () => { expect(allFiles).to.have.same.members(dir.shallow.files); expect(allSubdirs).to.have.same.members(dir.shallow.dirs); done(); }) .on("error", done); }); it('should handle errors that occur in the "data" event listener', done => { testErrorHandling("data", dir.shallow.data, 7, done); }); it('should handle errors that occur in the "file" event listener', done => { testErrorHandling("file", dir.shallow.files, 3, done); }); it('should handle errors that occur in the "directory" event listener', done => { testErrorHandling("directory", dir.shallow.dirs, 2, done); }); it('should handle errors that occur in the "symlink" event listener', done => { testErrorHandling("symlink", dir.shallow.symlinks, 5, done); }); function testErrorHandling (eventName, expected, expectedErrors, done) { let errors = [], data = []; let stream = readdir.stream("test/dir"); // Capture all errors stream.on("error", error => { errors.push(error); }); stream.on(eventName, path => { data.push(path); if (path.indexOf(".txt") >= 0 || path.indexOf("dir-") >= 0) { throw new Error("Epic Fail!!!"); } else { return true; } }); stream.on("end", () => { try { // Make sure the correct number of errors were thrown expect(errors).to.have.lengthOf(expectedErrors); for (let error of errors) { expect(error.message).to.equal("Epic Fail!!!"); } // All of the events should have still been emitted, despite the errors expect(data).to.have.same.members(expected); done(); } catch (e) { done(e); } }); stream.resume(); } });
BigstickCarpet/readdir-enhanced
test/specs/stream.spec.js
JavaScript
mit
7,232
// Copyright 2015 Peter Beverloo. All rights reserved. // Use of this source code is governed by the MIT license, a copy of which can // be found in the LICENSE file. // Base class for a module. Stores the environment and handles magic such as route annotations. export class Module { constructor(env) { this.env_ = env; let decoratedRoutes = Object.getPrototypeOf(this).decoratedRoutes_; if (!decoratedRoutes) return; decoratedRoutes.forEach(route => { env.dispatcher.addRoute(route.method, route.route_path, ::this[route.handler]); }); } }; // Annotation that can be used on modules to indicate that the annotated method is the request // handler for a |method| (GET, POST) request for |route_path|. export function route(method, route_path) { return (target, handler) => { if (!target.hasOwnProperty('decoratedRoutes_')) target.decoratedRoutes_ = []; target.decoratedRoutes_.push({ method, route_path, handler }); }; }
beverloo/node-home-server
src/module.js
JavaScript
mit
981
version https://git-lfs.github.com/spec/v1 oid sha256:be847f24aac166b803f1ff5ccc7e4d7bc3fb5d960543e35f779068a754294c94 size 1312
yogeshsaroya/new-cdnjs
ajax/libs/extjs/4.2.1/src/app/domain/Direct.js
JavaScript
mit
129
// Core is a collection of helpers // Nothing specific to the emultor application "use strict"; // all code is defined in this namespace window.te = window.te || {}; // te.provide creates a namespace if not previously defined. // Levels are seperated by a `.` Each level is a generic JS object. // Example: // te.provide("my.name.space"); // my.name.foo = function(){}; // my.name.space.bar = function(){}; te.provide = function(ns /*string*/ , root) { var parts = ns.split('.'); var lastLevel = root || window; for (var i = 0; i < parts.length; i++) { var p = parts[i]; if (!lastLevel[p]) { lastLevel = lastLevel[p] = {}; } else if (typeof lastLevel[p] !== 'object') { throw new Error('Error creating namespace.'); } else { lastLevel = lastLevel[p]; } } }; // A simple UID generator. Returned UIDs are guaranteed to be unique to the page load te.Uid = (function() { var id = 1; function next() { return id++; } return { next: next }; })(); // defaultOptionParse is a helper for functions that expect an options // var passed in. This merges the passed in options with a set of defaults. // Example: // foo function(options) { // tf.defaultOptionParse(options, {bar:true, fizz:"xyz"}); // } te.defaultOptionParse = function(src, defaults) { src = src || {}; var keys = Object.keys(defaults); for (var i = 0; i < keys.length; i++) { var k = keys[i]; if (src[k] === undefined) { src[k] = defaults[k]; } } return src; }; // Simple string replacement, eg: // tf.sprintf('{0} and {1}', 'foo', 'bar'); // outputs: foo and bar te.sprintf = function(str) { for (var i = 1; i < arguments.length; i++) { var re = new RegExp('\\{' + (i - 1) + '\\}', 'gm'); str = str.replace(re, arguments[i]); } return str; };
tyleregeto/8bit-emulator
src/core.js
JavaScript
mit
1,772
import Ember from 'ember'; let __TRANSLATION_MAP__ = {}; export default Ember.Service.extend({ map: __TRANSLATION_MAP__ });
alexBaizeau/ember-fingerprint-translations
app/services/translation-map.js
JavaScript
mit
126
import React from 'react'; <<<<<<< HEAD import { Switch, Route } from 'react-router-dom'; import Home from './Home'; import About from './About'; import Blog from './Blog'; import Resume from './Resume'; import Error404 from './Error404'; ======= // import GithubForm from './forms/github/GithubForm'; import GithubRecent from './forms/github/RecentList'; import './Content.css'; >>>>>>> 23d814bedfd5c07e05ea49d9a90053074a4c829a class Content extends React.Component { render() { return ( <div className="app-content"> <<<<<<< HEAD <Switch> <Route exact path="/" component={Home} /> {/* <Route exact path="/about" component={About} /> */} <Route component={Error404} /> </Switch> ======= <div className="content-description"> <br />College Student. Love Coding. Interested in Web and Machine Learning. </div> <hr /> <div className="content-list"> <div className="list-projects"> <h3>Recent Projects</h3> {/* <GithubRecent userName="slkjse9" standardDate={5259492000} /> */} <GithubRecent userName="hejuby" standardDate={3.154e+10} /> {/* <h2>Activity</h2> */} <h3>Experience</h3> <h3>Education</h3> <ul> <li><h4>Computer Science</h4>Colorado State University, Fort Collins (2017 -)</li> </ul> <br /> </div> </div> {/* <div className="content-home-github-recent-title"> <h2>Recent Works</h2> <h3>updated in 2 months</h3> </div> */} {/* <h3>Recent</h3> <GithubForm contentType="recent"/> */} {/* <h3>Lifetime</h3> {/* <GithubForm contentType="life"/> */} {/* <div className="content-home-blog-recent-title"> <h2>Recent Posts</h2> <h3>written in 2 months</h3> </div> <BlogRecent /> */} >>>>>>> 23d814bedfd5c07e05ea49d9a90053074a4c829a </div> ); } } export default Content;
slkjse9/slkjse9.github.io
src/components/Content.js
JavaScript
mit
2,049
var mongoose = require('mongoose'); var bcrypt = require('bcrypt'); var saltRounds = 10; var userSchema = new mongoose.Schema({ email: { type: String, index: {unique: true} }, password: String, name: String }); //hash password userSchema.methods.generateHash = function(password){ return bcrypt.hashSync(password, bcrypt.genSaltSync(saltRounds)); } userSchema.methods.validPassword = function(password){ return bcrypt.compareSync(password, this.password); } var User = mongoose.model('User',userSchema); module.exports = User;
zymokey/mission-park
models/user/user.js
JavaScript
mit
541
module.exports = { 'throttle': 10, 'hash': true, 'gzip': false, 'baseDir': 'public', 'buildDir': 'build', 'prefix': '' };
wunderlist/bilder-aws
lib/defaults.js
JavaScript
mit
133
var modules = { "success" : [ {id: 1, name:"控制台", code:"console", protocol:"http", domain:"console.ecc.com", port:"18333", created:'2017-03-08 00:00:00', creator:'1', modified:'2017-03-08 00:00:00', modifier:'1'}, {id: 2, name:"服务中心", code:"service-center", protocol:"http", domain:"sc.ecc.com", port:"18222", created:'2017-03-08 00:00:00', creator:'1', modified:'2017-03-08 00:00:00', modifier:'1'} ], "error" : { code : "0200-ERROR", msg : "There are some errors occured." } } module.exports = { "modules": modules }
chinakite/wukong
data/datas/modules.js
JavaScript
mit
545
const { createServer, plugins: { queryParser, serveStatic } } = require('restify'); const { join } = require('path'); const fetch = require('node-fetch'); const proxy = require('http-proxy-middleware'); const { PORT = 5000 } = process.env; const server = createServer(); server.use(queryParser()); server.get('/', async (req, res, next) => { if (!req.query.b) { const tokenRes = await fetch('https://webchat-mockbot.azurewebsites.net/directline/token', { headers: { origin: 'http://localhost:5000' }, method: 'POST' }); if (!tokenRes.ok) { return res.send(500); } const { token } = await tokenRes.json(); return res.send(302, null, { location: `/?b=webchat-mockbot&t=${encodeURIComponent(token)}` }); } return serveStatic({ directory: join(__dirname, 'dist'), file: 'index.html' })(req, res, next); }); server.get('/embed/*/config', proxy({ changeOrigin: true, target: 'https://webchat.botframework.com/' })); server.listen(PORT, () => console.log(`Embed dev server is listening to port ${PORT}`));
billba/botchat
packages/embed/hostDevServer.js
JavaScript
mit
1,094
/** * @author: * @date: 2016/1/21 */ define(["core/js/layout/Panel"], function (Panel) { var view = Panel.extend({ /*Panel的配置项 start*/ title:"表单-", help:"内容", brief:"摘要", /*Panel 配置 End*/ oninitialized:function(triggerEvent){ this._super(); this.mainRegion={ comXtype:$Component.TREE, comConf:{ data:[this.getModuleTree("core/js/base/AbstractView")], } }; var that = this; this.footerRegion = { comXtype: $Component.TOOLSTRIP, comConf: { /*Panel的配置项 start*/ textAlign: $TextAlign.RIGHT, items: [{ text: "展开所有节点", onclick: function (e) { that.getMainRegionRef().getComRef().expandAll(); }, },{ text: "折叠所有节点", onclick: function (e) { that.getMainRegionRef().getComRef().collapseAll(); }, }] /*Panel 配置 End*/ } }; }, getModuleTree:function(moduleName,arr){ var va = window.rtree.tree[moduleName]; var tree = {title: moduleName}; if(!arr){ arr = []; }else{ if(_.contains(arr,moduleName)){ return false; } } arr.push(moduleName); if(va&&va.deps&&va.deps.length>0){ tree.children = []; tree.folder=true; for(var i=0;i<va.deps.length;i++){ var newTree = this.getModuleTree(va.deps[i],arr); if(newTree){ tree.children.push(newTree); }else{ if(!tree.count){ tree.count = 0; } tree.count++; } } } return tree; } }); return view; });
huangfeng19820712/hfast
example/view/tree/treeAndTable.js
JavaScript
mit
2,606
$('#modalUploader').on('show.bs.modal', function (event) { var uploader = new qq.FileUploaderBasic({ element: document.getElementById('file-uploader-demo1'), button: document.getElementById('areaSubir'), action: '/Files/Upload', params: { ruta: $('#RutaActual').val() }, allowedExtensions: ['jpg', 'jpeg', 'png', 'gif', 'doc', 'docx', 'pdf'], multiple: false, onComplete: function (id, fileName, responseJSON) { $.gritter.add({ title: 'Upload file', text: responseJSON.message }); }, onSubmit: function (id, fileName) { var strHtml = "<li>" + fileName + "</li>"; $("#dvxArchivos").append(strHtml); } }); }); $('#modalUploader').on('hidden.bs.modal', function () { RecargarRuta(); }) function AbrirCarpeta(pCarpeta) { $("#RutaSolicitada").val(pCarpeta); $("#frmMain").submit(); } function AbrirRuta(pCarpeta) { $("#RutaSolicitada").val(pCarpeta); $("#frmMain").submit(); } function RecargarRuta() { AbrirCarpeta($("#RutaActual").val()); } function EliminarArchivo(pRuta) { if (confirm("Are you sure that want to delete this file?")) { $.gritter.add({ title: 'Delete file', text: "File deleted" }); $("#ArchivoParaEliminar").val(pRuta); AbrirCarpeta($("#RutaActual").val()); } } function SubirNivel() { if ($("#TieneSuperior").val() == "1") { var strRutaAnterior = $("#RutaSuperior").val(); AbrirRuta(strRutaAnterior); } } function IrInicio() { AbrirRuta($("#RutaRaiz").val()); } function AbrirDialogoArchivo() { $("#modalUploader").modal(); } function getParameterByName(name) { name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]"); var regexS = "[\\?&]" + name + "=([^&#]*)"; var regex = new RegExp(regexS); var results = regex.exec(window.location.search); if (results == null) return ""; else return decodeURIComponent(results[1].replace(/\+/g, " ")); }
walalm/MVC-Azure-Explorer
MVC_Azure_Explorer/MVC_Azure_Explorer/Scripts/UtilsFileManager.js
JavaScript
mit
2,111
// setToken when re-connecting var originalReconnect = Meteor.connection.onReconnect; Meteor.connection.onReconnect = function() { setToken(); if(originalReconnect) { originalReconnect(); } }; if(Meteor.status().connected) { setToken(); } function setToken() { var firewallHumanToken = Cookie.get('sikka-human-token'); Meteor.call('setSikkaHumanToken', firewallHumanToken); } // reloading the page window.sikkaCommands = sikkaCommands = new Mongo.Collection('sikka-commands'); sikkaCommands.find({}).observe({ added: function(command) { if(command._id === "reload") { location.reload(); } } });
meteorhacks/sikka
lib/client/core.js
JavaScript
mit
631
import React from 'react'; import ReactDOM from 'react-dom'; import componentOrElement from 'react-prop-types/lib/componentOrElement'; import ownerDocument from './utils/ownerDocument'; import getContainer from './utils/getContainer'; /** * The `<Portal/>` component renders its children into a new "subtree" outside of current component hierarchy. * You can think of it as a declarative `appendChild()`, or jQuery's `$.fn.appendTo()`. * The children of `<Portal/>` component will be appended to the `container` specified. */ let Portal = React.createClass({ displayName: 'Portal', propTypes: { /** * A Node, Component instance, or function that returns either. The `container` will have the Portal children * appended to it. */ container: React.PropTypes.oneOfType([ componentOrElement, React.PropTypes.func ]), /** * Classname to use for the Portal Component */ className: React.PropTypes.string }, componentDidMount() { this._renderOverlay(); }, componentDidUpdate() { this._renderOverlay(); }, componentWillReceiveProps(nextProps) { if (this._overlayTarget && nextProps.container !== this.props.container) { this._portalContainerNode.removeChild(this._overlayTarget); this._portalContainerNode = getContainer(nextProps.container, ownerDocument(this).body); this._portalContainerNode.appendChild(this._overlayTarget); } }, componentWillUnmount() { this._unrenderOverlay(); this._unmountOverlayTarget(); }, _mountOverlayTarget() { if (!this._overlayTarget) { this._overlayTarget = document.createElement('div'); if (this.props.className) { this._overlayTarget.className = this.props.className; } this._portalContainerNode = getContainer(this.props.container, ownerDocument(this).body); this._portalContainerNode.appendChild(this._overlayTarget); } }, _unmountOverlayTarget() { if (this._overlayTarget) { this._portalContainerNode.removeChild(this._overlayTarget); this._overlayTarget = null; } this._portalContainerNode = null; }, _renderOverlay() { let overlay = !this.props.children ? null : React.Children.only(this.props.children); // Save reference for future access. if (overlay !== null) { this._mountOverlayTarget(); this._overlayInstance = ReactDOM.unstable_renderSubtreeIntoContainer( this, overlay, this._overlayTarget ); } else { // Unrender if the component is null for transitions to null this._unrenderOverlay(); this._unmountOverlayTarget(); } }, _unrenderOverlay() { if (this._overlayTarget) { ReactDOM.unmountComponentAtNode(this._overlayTarget); this._overlayInstance = null; } }, render() { return null; }, getMountNode(){ return this._overlayTarget; }, getOverlayDOMNode() { if (!this.isMounted()) { throw new Error('getOverlayDOMNode(): A component must be mounted to have a DOM node.'); } if (this._overlayInstance) { return ReactDOM.findDOMNode(this._overlayInstance); } return null; } }); export default Portal;
HPate-Riptide/react-overlays
src/Portal.js
JavaScript
mit
3,227
dojo.provide("plugins.dijit.SyncDialog"); // HAS A dojo.require("dijit.Dialog"); dojo.require("dijit.form.Button"); dojo.require("dijit.form.ValidationTextBox"); // INHERITS dojo.require("plugins.core.Common"); dojo.declare( "plugins.dijit.SyncDialog", [ dijit._Widget, dijit._Templated, plugins.core.Common ], { //Path to the template of this widget. templatePath: dojo.moduleUrl("plugins", "dijit/templates/syncdialog.html"), // OR USE @import IN HTML TEMPLATE cssFiles : [ dojo.moduleUrl("plugins", "dijit/css/syncdialog.css") ], // Calls dijit._Templated.widgetsInTemplate widgetsInTemplate : true, // PARENT plugins.workflow.Apps WIDGET parentWidget : null, // DISPLAYED MESSAGE message : null, //////}} constructor : function(args) { console.log("SyncDialog.constructor args:"); console.dir({args:args}); // LOAD CSS this.loadCSS(); }, postCreate : function() { //////console.log("SyncDialog.postCreate plugins.dijit.SyncDialog.postCreate()"); this.startup(); }, startup : function () { ////console.log("SyncDialog.startup plugins.dijit.SyncDialog.startup()"); ////console.log("SyncDialog.startup this.parentWidget: " + this.parentWidget); this.inherited(arguments); // SET UP DIALOG this.setDialogue(); // SET KEY LISTENER this.setKeyListener(); // ADD CSS NAMESPACE CLASS FOR TITLE CSS STYLING this.setNamespaceClass("syncDialog"); }, setKeyListener : function () { dojo.connect(this.dialog, "onkeypress", dojo.hitch(this, "handleOnKeyPress")); }, handleOnKeyPress: function (event) { var key = event.charOrCode; console.log("SyncDialog.handleOnKeyPress key: " + key); if ( key == null ) return; event.stopPropagation(); if ( key == dojo.keys.ESCAPE ) this.hide(); }, setNamespaceClass : function (ccsClass) { // ADD CSS NAMESPACE CLASS dojo.addClass(this.dialog.domNode, ccsClass); dojo.addClass(this.dialog.titleNode, ccsClass); dojo.addClass(this.dialog.closeButtonNode, ccsClass); }, show: function () { // SHOW THE DIALOGUE this.dialog.show(); this.message.focus(); }, hide: function () { // HIDE THE DIALOGUE this.dialog.hide(); }, doEnter : function(type) { // RUN ENTER CALLBACK IF 'ENTER' CLICKED console.log("SyncDialog.doEnter plugins.dijit.SyncDialog.doEnter()"); var inputs = this.validateInputs(["message", "details"]); console.log("SyncDialog.doEnter inputs:"); console.dir({inputs:inputs}); if ( ! inputs ) { console.log("SyncDialog.doEnter inputs is null. Returning"); return; } // RESET this.message.set('value', ""); this.details.value = ""; // HIDE this.hide(); // DO CALLBACK this.dialog.enterCallback(inputs); }, validateInputs : function (keys) { console.log("Hub.validateInputs keys: "); console.dir({keys:keys}); var inputs = new Object; this.isValid = true; for ( var i = 0; i < keys.length; i++ ) { console.log("Hub.validateInputs Doing keys[" + i + "]: " + keys[i]); inputs[keys[i]] = this.verifyInput(keys[i]); } console.log("Hub.validateInputs inputs: "); console.dir({inputs:inputs}); if ( ! this.isValid ) return null; return inputs; }, verifyInput : function (input) { console.log("Aws.verifyInput input: "); console.dir({this_input:this[input]}); var value = this[input].value; console.log("Aws.verifyInput value: " + value); var className = this.getClassName(this[input]); console.log("Aws.verifyInput className: " + className); if ( className ) { console.log("Aws.verifyInput this[input].isValid(): " + this[input].isValid()); if ( ! value || ! this[input].isValid() ) { console.log("Aws.verifyInput input " + input + " value is empty. Adding class 'invalid'"); dojo.addClass(this[input].domNode, 'invalid'); this.isValid = false; } else { console.log("SyncDialog.verifyInput value is NOT empty. Removing class 'invalid'"); dojo.removeClass(this[input].domNode, 'invalid'); return value; } } else { if ( input.match(/;/) || input.match(/`/) ) { console.log("SyncDialog.verifyInput value is INVALID. Adding class 'invalid'"); dojo.addClass(this[input], 'invalid'); this.isValid = false; return null; } else { console.log("SyncDialog.verifyInput value is VALID. Removing class 'invalid'"); dojo.removeClass(this[input], 'invalid'); return value; } } return null; }, doCancel : function() { // RUN CANCEL CALLBACK IF 'CANCEL' CLICKED ////console.log("SyncDialog.doCancel plugins.dijit.SyncDialog.doCancel()"); this.dialog.cancelCallback(); this.dialog.hide(); }, setDialogue : function () { // APPEND DIALOG TO DOCUMENT document.body.appendChild(this.dialog.domNode); this.dialog.parentWidget = this; // AVOID this._fadeOutDeferred NOT DEFINED ERROR this._fadeOutDeferred = function () {}; }, load : function (args) { console.log("SyncDialog.load args:"); console.dir({args:args}); if ( args.title ) { console.log("SyncDialog.load SETTING TITLE: " + args.title); this.dialog.set('title', args.title); } this.headerNode.innerHTML = args.header; if (args.message) this.message.set('value', args.message); if (args.details) this.details.value = args.details; //if (args.details) this.details.innerHTML(args.details); this.dialog.enterCallback = args.enterCallback; this.show(); } });
agua/aguadev
html/plugins/dijit/SyncDialog.js
JavaScript
mit
5,315
angular.module('perCapita.controllers', []) .controller('AppCtrl', ['$scope', '$rootScope', '$ionicModal', '$timeout', '$localStorage', '$ionicPlatform', 'AuthService', function ($scope, $rootScope, $ionicModal, $timeout, $localStorage, $ionicPlatform, AuthService) { $scope.loginData = $localStorage.getObject('userinfo', '{}'); $scope.reservation = {}; $scope.registration = {}; $scope.loggedIn = false; if (AuthService.isAuthenticated()) { $scope.loggedIn = true; $scope.username = AuthService.getUsername(); } // Create the login modal that we will use later $ionicModal.fromTemplateUrl('templates/login.html', { scope: $scope }).then(function (modal) { $scope.modal = modal; }); // Triggered in the login modal to close it $scope.closeLogin = function () { $scope.modal.hide(); }; // Open the login modal $scope.login = function () { $scope.modal.show(); }; // Perform the login action when the user submits the login form $scope.doLogin = function () { console.log('Doing login', $scope.loginData); $localStorage.storeObject('userinfo', $scope.loginData); AuthService.login($scope.loginData); $scope.closeLogin(); }; $scope.logOut = function () { AuthService.logout(); $scope.loggedIn = false; $scope.username = ''; }; $rootScope.$on('login:Successful', function () { $scope.loggedIn = AuthService.isAuthenticated(); $scope.username = AuthService.getUsername(); }); $ionicModal.fromTemplateUrl('templates/register.html', { scope: $scope }).then(function (modal) { $scope.registerform = modal; }); $scope.closeRegister = function () { $scope.registerform.hide(); }; $scope.register = function () { $scope.registerform.show(); }; $scope.doRegister = function () { console.log('Doing registration', $scope.registration); $scope.loginData.username = $scope.registration.username; $scope.loginData.password = $scope.registration.password; AuthService.register($scope.registration); $timeout(function () { $scope.closeRegister(); }, 1000); }; $rootScope.$on('registration:Successful', function () { $localStorage.storeObject('userinfo', $scope.loginData); }); }]) .controller('FavoriteDetailsController', ['$scope', '$rootScope', '$state', '$stateParams', 'Favorites', function ($scope, $rootScope, $state, $stateParams, Favorites) { $scope.showFavButton = false; // Lookup favorites for a given user id Favorites.findById({id: $stateParams.id}) .$promise.then( function (response) { $scope.city = response; }, function (response) { $scope.message = "Error: " + response.status + " " + response.statusText; } ); }]) .controller('HomeController', ['$scope', 'perCapitaService', '$stateParams', '$rootScope', 'Favorites', '$ionicPlatform', '$cordovaLocalNotification', '$cordovaToast', function ($scope, perCapitaService, $stateParams, $rootScope, Favorites, $ionicPlatform, $cordovaLocalNotification, $cordovaToast) { $scope.showFavButton = $rootScope.currentUser; $scope.controlsData = {skills: $rootScope.skills}; // Look up jobs data $scope.doLookup = function () { $rootScope.skills = $scope.controlsData.skills; perCapitaService.lookup($scope.controlsData.skills); }; // Post process the jobs data, by adding Indeeds link and calculating jobsPer1kPeople and jobsRank $scope.updatePerCapitaData = function () { $scope.cities = perCapitaService.response.data.docs; var arrayLength = $scope.cities.length; for (var i = 0; i < arrayLength; i++) { var obj = $scope.cities[i]; obj.jobsPer1kPeople = Math.round(obj.totalResults / obj.population * 1000); obj.url = "https://www.indeed.com/jobs?q=" + $scope.controlsData.skills + "&l=" + obj.city + ", " + obj.state; } // rank jobs var sortedObjs; if (perCapitaService.isSkills) { sortedObjs = _.sortBy($scope.cities, 'totalResults').reverse(); } else { sortedObjs = _.sortBy($scope.cities, 'jobsPer1kPeople').reverse(); } $scope.cities.forEach(function (element) { element.jobsRank = sortedObjs.indexOf(element) + 1; }); if (!$scope.$$phase) { $scope.$apply(); } $rootScope.cities = $scope.cities; console.log("Loaded " + arrayLength + " results.") }; perCapitaService.registerObserverCallback($scope.updatePerCapitaData); $scope.addToFavorites = function () { delete $scope.city._id; delete $scope.city._rev; $scope.city.customerId = $rootScope.currentUser.id Favorites.create($scope.city); $ionicPlatform.ready(function () { $cordovaLocalNotification.schedule({ id: 1, title: "Added Favorite", text: $scope.city.city }).then(function () { console.log('Added Favorite ' + $scope.city.city); }, function () { console.log('Failed to add Favorite '); }); $cordovaToast .show('Added Favorite ' + $scope.city.city, 'long', 'center') .then(function (success) { // success }, function (error) { // error }); }); } if ($stateParams.id) { console.log("param " + $stateParams.id); $scope.city = $rootScope.cities.filter(function (obj) { return obj._id === $stateParams.id; })[0]; console.log($scope.city); } else { $scope.doLookup(); } }]) .controller('AboutController', ['$scope', function ($scope) { }]) .controller('FavoritesController', ['$scope', '$rootScope', '$state', 'Favorites', '$ionicListDelegate', '$ionicPopup', function ($scope, $rootScope, $state, Favorites, $ionicListDelegate, $ionicPopup) { $scope.shouldShowDelete = false; /*$scope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams) { console.log("State changed: ", toState); if(toState.name === "app.favorites") $scope.refreshItems(); });*/ $scope.refreshItems = function () { if ($rootScope.currentUser) { Favorites.find({ filter: { where: { customerId: $rootScope.currentUser.id } } }).$promise.then( function (response) { $scope.favorites = response; console.log("Got favorites"); }, function (response) { console.log(response); }); } else { $scope.message = "You are not logged in" } } $scope.refreshItems(); $scope.toggleDelete = function () { $scope.shouldShowDelete = !$scope.shouldShowDelete; console.log($scope.shouldShowDelete); } $scope.deleteFavorite = function (favoriteid) { var confirmPopup = $ionicPopup.confirm({ title: '<h3>Confirm Delete</h3>', template: '<p>Are you sure you want to delete this item?</p>' }); confirmPopup.then(function (res) { if (res) { console.log('Ok to delete'); Favorites.deleteById({id: favoriteid}).$promise.then( function (response) { $scope.favorites = $scope.favorites.filter(function (el) { return el.id !== favoriteid; }); $state.go($state.current, {}, {reload: false}); // $window.location.reload(); }, function (response) { console.log(response); $state.go($state.current, {}, {reload: false}); }); } else { console.log('Canceled delete'); } }); $scope.shouldShowDelete = false; } }]) ;
vjuylov/percapita-mobile
www/js/controllers/controllers.js
JavaScript
mit
8,105
var http = require("http"); var querystring = require("querystring"); // 核心模块 var SBuffer=require("../tools/SBuffer"); var common=require("../tools/common"); var zlib=require("zlib"); var redis_pool=require("../tools/connection_pool"); var events = require('events'); var util = require('util'); function ProxyAgent(preHeaders,preAnalysisFields,logName){ this.headNeeds = preHeaders||""; this.preAnalysisFields = preAnalysisFields||""; this.AnalysisFields = {}; this.logName=logName||""; this.response=null; this.reqConf={}; this.retData=[]; this.redis =null; // redis {} redis_key events.EventEmitter.call(this); } /** * 获取服务配置信息 * @param 服务名 * @return object */ ProxyAgent.prototype.getReqConfig = function(logName){ var _self=this; var Obj={}; Obj=Config[logName]; Obj.logger=Analysis.getLogger(logName); Obj.name=logName; return Obj; } ProxyAgent.prototype.doRequest=function(_req,_res){ var _self=this; _self.reqConf=_self.getReqConfig(this.logName); logger.debug('进入'+_self.reqConf.desc+"服务"); var header_obj =this.packageHeaders(_req.headers,this.headNeeds); var url_obj = url.parse(request.url, true); var query_obj = url_obj.query; var postData = request.body|| ""; // 获取请求参数 _res.setHeader("Content-Type", config.contentType); _res.setHeader(config.headerkey, config.headerval); var opts=_self.packData(header_obj,query_obj,postData); logger.debug(header_obj.mobileid +_self.reqConf.desc+ '接口参数信息:'+opts[0].path +" data:"+ opts[1]); if(typeof(postData) =="object" && postData.redis_key.length>0){ this.getRedis(opts[0],opts[1]); } else{ this.httpProxy(opts[0],opts[1]); } } /** * 封装get post接口 * @param headers * @param query * @param body * @return [] */ ProxyAgent.prototype.packData=function(headers,query,body){ var _self=this; //resType 解释 ""==>GET,"body"==>POST,"json"==>特殊poi,"raw"==>原始数据 var type=_self.reqConf.resType || ""; body = body || ""; var len=0; var query_str=""; var body_str=""; if(type==""){ query=common.extends(query,headers); query_str = querystring.stringify(query, '&', '='); } else if(type=="body"){ body=common.extends(body,headers); body_str = querystring.stringify(body, '&', '='); len=body_str.length; if(body.redis_key){ this.redis={}; this.redis.redis_key=body.redis_key; } } else if(type=="json"){ query=common.extends(query,headers); query_str = 'json='+querystring.stringify(query, '&', '='); } else if(type=="raw"){ len=body.length; body_str=body; } var actionlocation = headers.actionlocation || ""; if(actionlocation==""){ actionlocation=query.actionlocation||""; } var opts=_self.getRequestOptions(len,actionlocation); opts.path+=((opts.path.indexOf("?")>=0)?"&":"?")+query_str; return [opts,body_str]; } /** * 获取请求头信息 * @param len数据长度 * @param actiontion 通用访问地址 * @return object 头信息 */ ProxyAgent.prototype.getRequestOptions=function(len,actionlocation){ var _self=this; var options = { //http请求参数设置 host: _self.reqConf.host, // 远端服务器域名 port: _self.reqConf.port, // 远端服务器端口号 path: _self.reqConf.path||"", headers : {'Connection' : 'keep-alive'} }; if(actionlocation.length>0){ options.path=actionlocation; } var rtype= _self.reqConf.reqType || ""; if(rtype.length>0){ options.headers['Content-Type']=rtype; } if(len>0){ options.headers['Content-Length']=len; } return options; } ProxyAgent.prototype.getRedisOptions=function(options,actionlocation){ var obj={}; return obj; } /** * 获取头部信息进行封装 * @param request.headers * @param need fields ;split with ',' * @return object headers */ ProxyAgent.prototype.packageHeaders = function(headers) { var fields=arguments[1]||""; var query_obj = {}; var reqip = headers['x-real-ip'] || '0'; // 客户端请求的真实ip地址 var forward = headers['x-forwarded-for'] || '0'; // 客户端请求来源 var osversion = headers['osversion'] || '0';// 客户端系统 var devicemodel = headers['devicemodel'] || '0';// 客户端型号 var manufacturername = headers['manufacturername'] || '0';// 制造厂商 var actionlocation = headers['actionlocation']; // 请求后台地址 var dpi = headers['dpi'] || '2.0';// 密度 var imsi = headers['imsi'] || '0'; // 客户端imsi var mobileid = headers['mobileid'] || '0'; // 客户端mibileid var version = headers['version'] || '0';// 客户端版本version var selflon = headers['selflon'] || '0';// 经度 var selflat = headers['selflat'] || '0';// 维度 var uid = headers['uid'] || '0'; // 犬号 var radius=headers['radius']||'0';//误差半径 var platform=headers['platform']||"";//平台 ios ,android var gender= headers['gender'] || '0'; query_obj.gender = gender; query_obj.reqip = reqip; query_obj.forward = forward; query_obj.osversion = osversion; query_obj.devicemodel = devicemodel; query_obj.manufacturername = manufacturername; query_obj.actionlocation = actionlocation; query_obj.dpi = dpi; query_obj.imsi = imsi; query_obj.mobileid = mobileid; query_obj.version = version; query_obj.selflon = selflon; query_obj.selflat = selflat; query_obj.uid = uid; query_obj.radius=radius; query_obj.platform=platform; if(fields.length > 0){ var afields = fields.split(","); var newObj = {}; for(var i = 0; i < afields.length ; i ++){ newObj[afields[i]] = query_obj[afields[i]] || ""; } return newObj; } else{ return query_obj; } } /** * http 请求代理 * @param options 远程接口信息 * @param reqData 请求内容 req.method== get时一般为空 */ ProxyAgent.prototype.httpProxy = function (options,reqData){ var _self=this; var TongjiObj={}; var req = http.request(options, function(res) { TongjiObj.statusCode = res.statusCode ||500; var tmptime=Date.now(); TongjiObj.restime = tmptime; TongjiObj.resEnd =tmptime; TongjiObj.ends = tmptime; TongjiObj.length = 0; TongjiObj.last = tmptime; var sbuffer=new SBuffer(); res.setEncoding("utf-8"); res.on('data', function (trunk) { sbuffer.append(trunk); }); res.on('end', function () { TongjiObj.resEnd = Date.now(); //doRequestCB(response, {"data":sbuffer.toString(),"status":res.statusCode},TongjiObj,redisOpt); _self.emmit("onDone",sbuffer,TongjiObj); }); }); req.setTimeout(timeout,function(){ req.emit('timeOut',{message:'have been timeout...'}); }); req.on('error', function(e) { TongjiObj.statusCode=500; _self.emmit("onDone","",500,TongjiObj); }); req.on('timeOut', function(e) { req.abort(); TongjiObj.statusCode=500; TongjiObj.last = Date.now(); _self.emmit("onDone","",500,TongjiObj); }); req.end(reqData); } /** * 设置缓存 * @param redis_key * @param redis_time * @param resultBuffer */ ProxyAgent.prototype.setRedis = function (redis_key, redis_time, resultBuffer) { redis_pool.acquire(function(err, client) { if (!err) { client.setex(redis_key, redis_time, resultBuffer, function(err, repliy) { redis_pool.release(client); // 链接使用完毕释放链接 }); logger.debug(redis_key + '设置缓存数据成功!'); } else { writeLogs.logs(Analysis.getLogger('error'), 'error', { msg : 'redis_general保存数据到redis缓存数据库时链接redis数据库异常', err : 14 }); logger.debug(redis_key + '设置缓存数据失败!'); } }); } /** * 从缓存中获取数据,如果获取不到,则请求后台返回的数据返回给客户端 并且将返回的数据设置到redis缓存 * redis_key通过self变量中取 * @param options * @param reqData */ ProxyAgent.prototype.getRedis = function ( options, reqData) { var _self=this; var redis_key=this.redis.redis_key || ""; redis_pool.acquire(function(err, client) { if (!err) { client.get(redis_key, function(err, date) { redis_pool.release(client) // 用完之后释放链接 if (!err && date != null) { var resultBuffer = new Buffer(date); _self.response.statusCode = 200; _self.response.setHeader("Content-Length", resultBuffer.length); _self.response.write(resultBuffer); // 以二进制流的方式输出数据 _self.response.end(); logger.debug(redis_key + '通用接口下行缓存数据:' + date); } else { _self.httpProxy(options, reqData); } }); } else { _self.httpProxy(options, reqData); } }); } /** * 输出gzip数据 * response 内置 * @param resultBuffer */ ProxyAgent.prototype.gzipOutPut = function (resultBuffer){ var _self=this; zlib.gzip(resultBuffer, function(code, buffer){ // 对服务器返回的数据进行压缩 if (code != null) { // 如果正常结束 logger.debug('压缩成功,压缩前:'+resultBuffer.length+',压缩后:'+buffer.length); _self.response.setHeader('Content-Encoding', 'gzip'); //压缩标志 } else { buffer = new Buffer( '{"msg":["服务器返回数据非JSON格式"]}'); _self.response.statusCode=500; } _self.response.setHeader("Content-Length", buffer.length); _self.response.write(buffer); _self.response.end(); }); } /** * 请求完毕处理 * @param buffer type buffer/string * @param status 请求http状态 * @param tongji object统计对象 */ ProxyAgent.prototype.onDone =function(buffer,status){ var tongji=arguments[2] ||""; var _self=this; var resultStr = typeof(buffer)=="object"?buffer.toString():buffer; if(this.reqConf.isjson==1){ var resultObj = common.isJson( resultStr, _self.reqConf.logName); // 判断返回结果是否是json格式 if (resultObj) { // 返回结果是json格式 resultStr = JSON.stringify(resultObj); _self.response.statusCode = status; } else { resultStr = '{"msg":["gis服务器返回数据非JSON格式"]}'; _self.response.statusCode = 500; } } else{ _self.response.statusCode = status; } var resultBuffer = new Buffer(resultStr); if(tongji!=""){ tongji.ends = Date.now(); tongji.length = resultBuffer.length; } if(resultBuffer.length > 500 ){ //压缩输出 _self.gzipOutPut(resultBuffer); }else{ _self.response.setHeader("Content-Length", resultBuffer.length); _self.response.write(resultBuffer); // 以二进制流的方式输出数据 _self.response.end(); } if(tongji!=""){ tongji.last= Date.now(); tongji=common.extends(tongji,_self.preAnalysisFields); logger.debug('耗时:' + (tongji.last - tongji.start)+'ms statusCode='+status); writeLogs.logs(poiDetailServer,'poiDetailServer',obj); } }); ProxyAgent.prototype.onDones =function(buffer,status){ var tongji=arguments[2] ||""; this.retData.push([buffer,status,tongji]; }); ProxyAgent.prototype.dealDones =function(){ var tongji=arguments[2] ||""; this.retData.push([buffer,status,tongji]; }); //ProxyAgent 从event 集成 //utils.inherit(ProxyAgent,event); exports.ProxyAgent=ProxyAgent;
RazarDessun/fastProxy
test/test_timeout2.js
JavaScript
mit
11,087
import React from 'react'; import IconBase from './../components/IconBase/IconBase'; export default class IosHeart extends React.Component { render() { if(this.props.bare) { return <g> <path d="M359.385,80C319.966,80,277.171,97.599,256,132.8C234.83,97.599,192.034,80,152.615,80C83.647,80,32,123.238,32,195.779 c0,31.288,12.562,71.924,40.923,105.657c28.359,33.735,45.229,51.7,100.153,88C228,425.738,256,432,256,432s28-6.262,82.924-42.564 c54.923-36.3,71.794-54.265,100.153-88C467.438,267.703,480,227.067,480,195.779C480,123.238,428.353,80,359.385,80z"></path> </g>; } return <IconBase> <path d="M359.385,80C319.966,80,277.171,97.599,256,132.8C234.83,97.599,192.034,80,152.615,80C83.647,80,32,123.238,32,195.779 c0,31.288,12.562,71.924,40.923,105.657c28.359,33.735,45.229,51.7,100.153,88C228,425.738,256,432,256,432s28-6.262,82.924-42.564 c54.923-36.3,71.794-54.265,100.153-88C467.438,267.703,480,227.067,480,195.779C480,123.238,428.353,80,359.385,80z"></path> </IconBase>; } };IosHeart.defaultProps = {bare: false}
fbfeix/react-icons
src/icons/IosHeart.js
JavaScript
mit
1,031
import React, {PropTypes} from 'react'; import {connect} from 'react-redux'; import {bindActionCreators} from 'redux'; import * as courseActions from '../../actions/courseActions'; import CourseForm from './CourseForm'; import {authorsFormattedForDropdown} from '../../selectors/selectors'; import toastr from 'toastr'; export class ManageCoursePage extends React.Component { constructor(props, context) { super(props, context); this.state = { course: Object.assign({}, props.course), errors: {}, saving: false }; this.updateCourseState = this.updateCourseState.bind(this); this.saveCourse = this.saveCourse.bind(this); } componentWillReceiveProps(nextProps) { if (this.props.course.id != nextProps.course.id) { // Necessary to populate form when existing course is loaded directly. this.setState({course: Object.assign({}, nextProps.course)}); } } updateCourseState(event) { // handler for each form field const field = event.target.name; let course = this.state.course; course[field] = event.target.value; return this.setState({course: course}); } courseFormValid() { let formIsValid = true; let errors = {}; if (this.state.course.title.length < 5) { errors.title = 'Title must be at least 5 characters.'; formIsValid = false; } this.setState({errors: errors}); return formIsValid; } saveCourse(event) { event.preventDefault(); if (!this.courseFormValid()) { return; } this.setState({saving: true}); this.props.actions.saveCourse(this.state.course) .then(() => this.redirect()) .catch(error => { toastr.error(error); this.setState({saving: false}); }); } redirect() { // redirect to courses route this.setState({saving: false}); toastr.success('Course saved!'); this.context.router.push('/courses'); } render() { return ( <CourseForm allAuthors={this.props.authors} onChange={this.updateCourseState} onSave={this.saveCourse} errors={this.state.errors} course={this.state.course} saving={this.state.saving}/> ); } } ManageCoursePage.propTypes = { course: PropTypes.object.isRequired, authors: PropTypes.array.isRequired, actions: PropTypes.object.isRequired }; //Pull in the React Router context so router is available on this.context.router. ManageCoursePage.contextTypes = { router: PropTypes.object }; function getCourseById(courses, id) { const course = courses.filter(course => course.id == id); if (course.length) return course[0]; //since filter returns an array, have to grab the first. return null; } function mapStateToProps(state, ownProps) { let course = { id: "", title: "", watchHref: "", authorId: "", length: "23", category: "" }; const courseId = ownProps.params.id; // from the path `/course/:id` if (courseId && state.courses.length > 0) { course = getCourseById(state.courses, courseId); } return { course: course, authors: authorsFormattedForDropdown(state.authors) } } function mapDispatchToProps(dispatch) { return { actions: bindActionCreators(courseActions, dispatch) }; } export default connect(mapStateToProps, mapDispatchToProps)(ManageCoursePage);
vitaliykrushinsky/react-redux-demo
src/components/course/ManageCoursePage.js
JavaScript
mit
3,176
AmazonTemplateDescriptionCategorySpecificGridRowRenderer = Class.create(AmazonTemplateDescriptionCategorySpecificRenderer, { // --------------------------------------- attributeHandler: null, // --------------------------------------- process: function() { if (this.specificHandler.isSpecificRendered(this.indexedXPath) && !this.isValueForceSet()) { return ''; } if (!this.load()) { return ''; } this.renderParentSpecific(); if (this.specificHandler.isSpecificRendered(this.indexedXPath) && !this.isValueForceSet()) { return ''; } if (this.specificHandler.isSpecificRendered(this.indexedXPath)) { if (this.isValueForceSet()) { this.forceSelectAndDisable(this.getForceSetValue()); this.hideButton($(this.indexedXPath + '_remove_button')); var myEvent = new CustomEvent('undeleteble-specific-appear'); $(this.getParentIndexedXpath()).dispatchEvent(myEvent); } return ''; } this.renderSelf(); if (this.isValueForceSet()) { this.forceSelectAndDisable(this.getForceSetValue()); } this.observeToolTips(this.indexedXPath); this.checkSelection(); this.renderSpecificAttributes(); }, // --------------------------------------- load: function($super) { this.attributeHandler = AttributeHandlerObj; return $super(); }, //######################################## renderParentSpecific: function() { if (this.specific.parent_specific_id == null) { return ''; } if (!this.dictionaryHelper.isSpecificTypeContainer(this.parentSpecific)) { return ''; } var parentBlockRenderer = new AmazonTemplateDescriptionCategorySpecificBlockRenderer(); parentBlockRenderer.setSpecificsHandler(this.specificHandler); parentBlockRenderer.setIndexedXpath(this.getParentIndexedXpath()); parentBlockRenderer.process(); }, renderSelf: function() { this.renderLabel(); this.renderChooseMode(); this.renderValueInputs(); // affects the appearance of the actions buttons this.specificHandler.markSpecificAsRendered(this.indexedXPath); this.renderButtons(); // --------------------------------------- $(this.indexedXPath).observe('my-duplicate-is-rendered', this.onMyDuplicateRendered.bind(this)); // --------------------------------------- // like grid visibility or view of 'Add Specific' container this.throwEventsToParents(); }, renderSpecificAttributes: function() { var self = this; if (!this.specific.params.hasOwnProperty('attributes')) { return ''; } this.specific.params.attributes.each(function(attribute, index) { var renderer = new AmazonTemplateDescriptionCategorySpecificGridRowAttributeRenderer(); renderer.setSpecificsHandler(self.specificHandler); renderer.setIndexedXpath(self.indexedXPath); renderer.attribute = attribute; renderer.attributeIndex = index; renderer.process(); }); }, //######################################## renderLabel: function() { var td = new Element('td'); var title = this.specific.title; if (this.dictionaryHelper.isSpecificRequired(this.specific) || this.isValueForceSet()) { title += ' <span class="required">*</span>'; } else if (this.dictionaryHelper.isSpecificDesired(this.specific)) { title += ' <span style="color: grey; font-style: italic;">(' + M2ePro.translator.translate('Desired') + ')</span>'; } td.appendChild((new Element('span').insert(title))); var note = this.getDefinitionNote(this.specific.data_definition); if (note) { var toolTip = this.getToolTipBlock(this.indexedXPath + '_definition_note', note); toolTip.show(); td.appendChild(toolTip); } var notice = this.getSpecificOverriddenNotice(); if (notice) td.appendChild(notice); notice = this.getSpecificParentageNotice(); if (notice) td.appendChild(notice); this.getRowContainer().appendChild(td); }, // --------------------------------------- renderChooseMode: function() { var select = new Element('select', { 'id' : this.indexedXPath +'_mode', 'indexedxpath': this.indexedXPath, 'class' : 'M2ePro-required-when-visible', 'style' : 'width: 93.2%;' }); select.appendChild(new Element('option', {'style': 'display: none'})); if (this.specific.recommended_values.length > 0) { select.appendChild(new Element('option', {'value': this.MODE_RECOMMENDED_VALUE})) .insert(M2ePro.translator.translate('Recommended Values')); } select.appendChild(new Element('option', {'value': this.MODE_CUSTOM_VALUE})) .insert(M2ePro.translator.translate('Custom Value')); select.appendChild(new Element('option', {'value': this.MODE_CUSTOM_ATTRIBUTE})) .insert(M2ePro.translator.translate('Custom Attribute')); select.observe('change', this.onChangeChooseMode.bind(this)); this.getRowContainer().appendChild(new Element('td')).appendChild(select); }, onChangeChooseMode: function(event) { var customValue = $(this.indexedXPath + '_' + this.MODE_CUSTOM_VALUE), customValueNote = $(this.indexedXPath + '_custom_value_note'), customValueNoteError = $('advice-M2ePro-specifics-validation-' + customValue.id); var customAttribute = $(this.indexedXPath + '_' + this.MODE_CUSTOM_ATTRIBUTE), customAttributeNote = $(this.indexedXPath + '_custom_attribute_note'), customAttributeError = $('advice-M2ePro-required-when-visible-' + customAttribute.id); var recommendedValue = $(this.indexedXPath + '_' + this.MODE_RECOMMENDED_VALUE); customValue && customValue.hide(); customValueNote && customValueNote.hide(); customValueNoteError && customValueNoteError.hide(); customAttribute && customAttribute.hide(); customAttributeNote && customAttributeNote.hide(); customAttributeError && customAttributeError.hide(); recommendedValue && recommendedValue.hide(); if (event.target.value == this.MODE_CUSTOM_VALUE) { customValue && customValue.show(); customValueNote && customValueNote.show(); customValueNoteError && customValueNoteError.show(); } if (event.target.value == this.MODE_CUSTOM_ATTRIBUTE) { customAttribute && customAttribute.show(); customAttributeNote && customAttributeNote.show(); customAttributeError && customAttributeError.show(); } if (event.target.value == this.MODE_RECOMMENDED_VALUE) { recommendedValue && recommendedValue.show(); } }, // --------------------------------------- renderValueInputs: function() { var td = this.getRowContainer().appendChild(new Element('td')); // --------------------------------------- if (this.dictionaryHelper.isSpecificTypeText(this.specific)) { var note = this.getCustomValueTypeNote(); if (note) td.appendChild(this.getToolTipBlock(this.indexedXPath + '_custom_value_note', note)); td.appendChild(this.getTextTypeInput()); } if (this.dictionaryHelper.isSpecificTypeSelect(this.specific)) { td.appendChild(this.getSelectTypeInput()); } // --------------------------------------- // --------------------------------------- note = this.getCustomAttributeTypeNote(); if (note) td.appendChild(this.getToolTipBlock(this.indexedXPath + '_custom_attribute_note', note)); td.appendChild(this.getCustomAttributeSelect()); // --------------------------------------- td.appendChild(this.getRecommendedValuesSelect()); }, // --------------------------------------- getTextTypeInput: function() { if (this.dictionaryHelper.isSpecificTypeTextArea(this.specific)) { var input = new Element('textarea', { 'id' : this.indexedXPath +'_'+ this.MODE_CUSTOM_VALUE, 'indexedxpath' : this.indexedXPath, 'specific_id' : this.specific.specific_id, 'specific_type' : this.specific.params.type, 'mode' : this.MODE_CUSTOM_VALUE, 'class' : 'M2ePro-required-when-visible M2ePro-specifics-validation', 'style' : 'width: 91.4%; display: none;' }); } else { var input = new Element('input', { 'id' : this.indexedXPath +'_'+ this.MODE_CUSTOM_VALUE, 'indexedxpath' : this.indexedXPath, 'specific_id' : this.specific.specific_id, 'mode' : this.MODE_CUSTOM_VALUE, 'specific_type' : this.specific.params.type, 'type' : 'text', 'class' : 'input-text M2ePro-required-when-visible M2ePro-specifics-validation', 'style' : 'display: none; width: 91.4%;' }); this.specific.params.type == 'date_time' && Calendar.setup({ 'inputField': input, 'ifFormat': "%Y-%m-%d %H:%M:%S", 'showsTime': true, 'button': input, 'align': 'Bl', 'singleClick': true }); this.specific.params.type == 'date' && Calendar.setup({ 'inputField': input, 'ifFormat': "%Y-%m-%d", 'showsTime': true, 'button': input, 'align': 'Bl', 'singleClick': true }); } input.observe('change', this.onChangeValue.bind(this)); return input; }, getSelectTypeInput: function() { var self = this; var select = new Element('select', { 'id' : this.indexedXPath +'_'+ this.MODE_CUSTOM_VALUE, 'indexedxpath': this.indexedXPath, 'specific_id' : this.specific.specific_id, 'mode' : this.MODE_CUSTOM_VALUE, 'class' : 'M2ePro-required-when-visible', 'style' : 'display: none; width: 93.2%;' }); select.appendChild(new Element('option', {'style': 'display: none;'})); var specificOptions = this.specific.values; specificOptions.each(function(option) { var label = option == 'true' ? 'Yes' : (option == 'false' ? 'No' : option), tempOption = new Element('option', {'value': option}); select.appendChild(tempOption).insert(label); }); select.observe('change', this.onChangeValue.bind(this)); return select; }, getCustomAttributeSelect: function() { var select = new Element('select', { 'id' : this.indexedXPath +'_'+ this.MODE_CUSTOM_ATTRIBUTE, 'indexedxpath' : this.indexedXPath, 'specific_id' : this.specific.specific_id, 'specific_type' : this.specific.params.type, 'mode' : this.MODE_CUSTOM_ATTRIBUTE, 'class' : 'attributes M2ePro-required-when-visible', 'style' : 'display: none; width: 93.2%;', 'apply_to_all_attribute_sets' : '0' }); select.appendChild(new Element('option', {'style': 'display: none', 'value': ''})); this.attributeHandler.availableAttributes.each(function(el) { select.appendChild(new Element('option', {'value': el.code})).insert(el.label); }); select.value = ''; select.observe('change', this.onChangeValue.bind(this)); var handlerObj = new AttributeCreator(select.id); handlerObj.setSelectObj(select); handlerObj.injectAddOption(); return select; }, getRecommendedValuesSelect: function() { var select = new Element('select', { 'id' : this.indexedXPath +'_'+ this.MODE_RECOMMENDED_VALUE, 'indexedxpath': this.indexedXPath, 'specific_id' : this.specific.specific_id, 'mode' : this.MODE_RECOMMENDED_VALUE, 'class' : 'M2ePro-required-when-visible', 'style' : 'display: none; width: 93.2%;' }); select.appendChild(new Element('option', {'style': 'display: none', 'value': ''})); this.specific.recommended_values.each(function(value) { select.appendChild(new Element('option', {'value': value})).insert(value); }); select.value = ''; select.observe('change', this.onChangeValue.bind(this)); return select; }, onChangeValue: function(event) { var selectedObj = {}; selectedObj['mode'] = event.target.getAttribute('mode'); selectedObj['type'] = event.target.getAttribute('specific_type'); selectedObj['is_required'] = (this.dictionaryHelper.isSpecificRequired(this.specific) || this.isValueForceSet()) ? 1 : 0; selectedObj[selectedObj.mode] = event.target.value; this.specificHandler.markSpecificAsSelected(this.indexedXPath, selectedObj); }, // --------------------------------------- renderButtons: function() { var td = this.getRowContainer().appendChild(new Element('td')); var cloneButton = this.getCloneButton(); if(cloneButton !== null) td.appendChild(cloneButton); var removeButton = this.getRemoveButton(); if(removeButton !== null) td.appendChild(removeButton); }, // --------------------------------------- throwEventsToParents: function() { var myEvent, parentXpath; // --------------------------------------- myEvent = new CustomEvent('child-specific-rendered'); parentXpath = this.getParentIndexedXpath(); $(parentXpath + '_grid').dispatchEvent(myEvent); $(parentXpath + '_add_row').dispatchEvent(myEvent); // --------------------------------------- // my duplicate is already rendered this.touchMyNeighbors(); // --------------------------------------- // --------------------------------------- if (this.isValueForceSet()) { this.hideButton($(this.indexedXPath + '_remove_button')); myEvent = new CustomEvent('undeleteble-specific-appear'); $(this.getParentIndexedXpath()).dispatchEvent(myEvent); } // --------------------------------------- }, //######################################## checkSelection: function() { if (this.specific.values.length == 1) { this.forceSelectAndDisable(this.specific.values[0]); return ''; } if (!this.specificHandler.isMarkedAsSelected(this.indexedXPath) && !this.specificHandler.isInFormData(this.indexedXPath)) { return ''; } var selectionInfo = this.specificHandler.getSelectionInfo(this.indexedXPath); var id = this.indexedXPath + '_mode'; $(id).value = selectionInfo.mode; this.simulateAction($(id), 'change'); if (selectionInfo.mode == this.MODE_CUSTOM_VALUE) { id = this.indexedXPath +'_'+ this.MODE_CUSTOM_VALUE; $(id).value = selectionInfo['custom_value']; this.simulateAction($(id), 'change'); } if (selectionInfo.mode == this.MODE_CUSTOM_ATTRIBUTE) { id = this.indexedXPath +'_'+ this.MODE_CUSTOM_ATTRIBUTE; $(id).value = selectionInfo['custom_attribute']; this.simulateAction($(id), 'change'); } if (selectionInfo.mode == this.MODE_RECOMMENDED_VALUE) { id = this.indexedXPath +'_'+ this.MODE_RECOMMENDED_VALUE; $(id).value = selectionInfo['recommended_value']; this.simulateAction($(id), 'change'); } }, forceSelectAndDisable: function(value) { if (!value) { return; } var modeSelect = $(this.indexedXPath + '_mode'); modeSelect.value = this.MODE_CUSTOM_VALUE; this.simulateAction(modeSelect, 'change'); modeSelect.setAttribute('disabled','disabled'); var valueObj = $(this.indexedXPath +'_'+ this.MODE_CUSTOM_VALUE); valueObj.value = value; this.simulateAction(valueObj, 'change'); valueObj.setAttribute('disabled', 'disabled'); }, //######################################## getToolTipBlock: function(id, messageHtml) { var container = new Element('div', { 'id' : id, 'style': 'float: right; display: none;' }); container.appendChild(new Element('img', { 'src' : M2ePro.url.get('m2epro_skin_url') + '/images/tool-tip-icon.png', 'class' : 'tool-tip-image' })); var htmlCont = container.appendChild(new Element('span', { 'class' : 'tool-tip-message tip-left', 'style' : 'display: none; max-width: 500px;' })); htmlCont.appendChild(new Element('img', { 'src': M2ePro.url.get('m2epro_skin_url') + '/images/help.png' })); htmlCont.appendChild(new Element('span')).insert(messageHtml); return container; }, // --------------------------------------- getCustomValueTypeNote: function() { if (this.specific.data_definition.definition) { return null; } if (this.specific.params.type == 'int') return this.getIntTypeNote(this.specific.params); if (this.specific.params.type == 'float') return this.getFloatTypeNote(this.specific.params); if (this.specific.params.type == 'string') return this.getStringTypeNote(this.specific.params); if (this.specific.params.type == 'date_time') return this.getDatTimeTypeNote(this.specific.params); return this.getAnyTypeNote(this.specific.params); }, getIntTypeNote: function(params) { var notes = []; var handler = { 'type': function() { notes[0] = M2ePro.translator.translate('Type: Numeric.') + ' '; }, 'min_value': function(restriction) { notes[1] = M2ePro.translator.translate('Min:') + ' ' + restriction + '. '; }, 'max_value': function(restriction) { notes[2] = M2ePro.translator.translate('Max:') + ' ' + restriction + '. '; }, 'total_digits': function(restriction) { notes[3] = M2ePro.translator.translate('Total digits (not more):') + ' ' + restriction + '. '; } }; for (var paramName in params) { params.hasOwnProperty(paramName) && handler[paramName] && handler[paramName](params[paramName]); } return notes.join(''); }, getFloatTypeNote: function(params) { var notes = []; var handler = { 'type': function() { notes[0] = M2ePro.translator.translate('Type: Numeric floating point.') + ' '; }, 'min_value': function(restriction) { notes[1] = M2ePro.translator.translate('Min:') + ' ' + restriction + '. '; }, 'max_value': function(restriction) { notes[2] = M2ePro.translator.translate('Max:') + ' ' + restriction + '. '; }, 'decimal_places': function(restriction) { notes[3] = M2ePro.translator.translate('Decimal places (not more):') + ' ' + restriction.value + '. '; }, 'total_digits': function(restriction) { notes[4] = M2ePro.translator.translate('Total digits (not more):') + ' ' + restriction + '. '; } }; for (var paramName in params) { params.hasOwnProperty(paramName) && handler[paramName] && handler[paramName](params[paramName]); } return notes.join(''); }, getStringTypeNote: function(params) { var notes = []; var handler = { 'type': function() { notes[0] = M2ePro.translator.translate('Type: String.') + ' '; }, 'min_length': function(restriction) { notes[1] = restriction != 1 ? M2ePro.translator.translate('Min length:') + ' ' + restriction : ''; }, 'max_length': function(restriction) { notes[2] = M2ePro.translator.translate('Max length:') + ' ' + restriction; }, 'pattern': function(restriction) { if (restriction == '[a-zA-Z][a-zA-Z]|unknown') { notes[3] = M2ePro.translator.translate('Two uppercase letters or "unknown".'); } } }; for (var paramName in params) { params.hasOwnProperty(paramName) && handler[paramName] && handler[paramName](params[paramName]); } return notes.join(''); }, getDatTimeTypeNote: function(params) { var notes = []; var handler = { 'type': function(restriction) { notes.push(M2ePro.translator.translate('Type: Date time. Format: YYYY-MM-DD hh:mm:ss')); } }; for (var paramName in params) { params.hasOwnProperty(paramName) && handler[paramName] && handler[paramName](params[paramName]); } return notes.join(''); }, getAnyTypeNote: function(params) { return M2ePro.translator.translate('Can take any value.'); }, // --------------------------------------- getCustomAttributeTypeNote: function() { if (this.specific.values.length <= 0 && this.specific.recommended_values.length <= 0) { return null; } var span = new Element('span'); var title = this.specific.values.length > 0 ? M2ePro.translator.translate('Allowed Values') : M2ePro.translator.translate('Recommended Values'); span.appendChild(new Element('span')).insert('<b>' + title + ': </b>'); var ul = span.appendChild(new Element('ul')); var noteValues = this.specific.values.length > 0 ? this.specific.values : this.specific.recommended_values; noteValues.each(function(value) { ul.appendChild(new Element('li')).insert(value); }); return span.outerHTML; }, // --------------------------------------- getDefinitionNote: function(definitionPart) { if (!definitionPart.definition) { return; } var div = new Element('div'); div.appendChild(new Element('div', {style: 'padding: 2px 0; margin-top: 5px;'})) .insert('<b>' + M2ePro.translator.translate('Definition:') + '</b>'); div.appendChild(new Element('div')) .insert(definitionPart.definition); if (definitionPart.tips && definitionPart.tips.match(/[a-z0-9]/i)) { div.appendChild(new Element('div', {style: 'padding: 2px 0; margin-top: 5px;'})) .insert('<b>' + M2ePro.translator.translate('Tips:') + '</b>'); div.appendChild(new Element('div')) .insert(definitionPart.tips); } if (definitionPart.example && definitionPart.example.match(/[a-z0-9]/i)) { div.appendChild(new Element('div', {style: 'padding: 2px 0; margin-top: 5px;'})) .insert('<b>' + M2ePro.translator.translate('Examples:') + '</b>'); div.appendChild(new Element('div')) .insert(definitionPart.example); } return div.outerHTML; }, // --------------------------------------- getSpecificOverriddenNotice: function() { if (!this.specificHandler.canSpecificBeOverwrittenByVariationTheme(this.specific)) { return null; } var variationThemesList = this.specificHandler.themeAttributes[this.specific.xml_tag]; var message = '<b>' + M2ePro.translator.translate('Value of this Specific can be automatically overwritten by M2E Pro.') + '</b>'; message += '<br/><br/>' + variationThemesList.join(', '); return this.constructNotice(message); }, getSpecificParentageNotice: function() { if (this.specific.xml_tag != 'Parentage') { return null; } return this.constructNotice(M2ePro.translator.translate('Amazon Parentage Specific will be overridden notice.')); }, constructNotice: function(message) { var container = new Element('div', { 'style': 'float: right; margin-right: 3px; margin-top: 1px;' }); container.appendChild(new Element('img', { 'src' : M2ePro.url.get('m2epro_skin_url') + '/images/warning.png', 'class' : 'tool-tip-image' })); var htmlCont = container.appendChild(new Element('span', { 'class' : 'tool-tip-message tip-left', 'style' : 'display: none; max-width: 500px; border-color: #ffd967; background-color: #fffbf0;' })); htmlCont.appendChild(new Element('img', { 'src' : M2ePro.url.get('m2epro_skin_url') + '/images/i_notice.gif', 'style' : 'margin-top: -21px;' })); htmlCont.appendChild(new Element('span')).insert(message); return container; }, //######################################## observeToolTips: function(indexedXpath) { $$('tr[id="' + indexedXpath + '"] .tool-tip-image').each(function(element) { element.observe('mouseover', MagentoFieldTipObj.showToolTip); element.observe('mouseout', MagentoFieldTipObj.onToolTipIconMouseLeave); }); $$('tr[id="' + indexedXpath + '"] .tool-tip-message').each(function(element) { element.observe('mouseout', MagentoFieldTipObj.onToolTipMouseLeave); element.observe('mouseover', MagentoFieldTipObj.onToolTipMouseEnter); }); }, //######################################## removeAction: function($super, event) { // for attributes removing var myEvent = new CustomEvent('parent-specific-row-is-removed'); $(this.indexedXPath).dispatchEvent(myEvent); // --------------------------------------- var deleteResult = $super(event); this.throwEventsToParents(); return deleteResult; }, cloneAction: function($super, event) { var newIndexedXpath = $super(event); this.observeToolTips(newIndexedXpath); var myEvent = new CustomEvent('parent-specific-row-is-cloned', { 'new_indexed_xpath': newIndexedXpath }); $(this.indexedXPath).dispatchEvent(myEvent); return newIndexedXpath; }, // --------------------------------------- getRowContainer: function() { if ($(this.indexedXPath)) { return $(this.indexedXPath); } var grid = $$('table[id="'+ this.getParentIndexedXpath() +'_grid"] table.border tbody').first(); return grid.appendChild(new Element('tr', {id: this.indexedXPath})); } // --------------------------------------- });
portchris/NaturalRemedyCompany
src/js/M2ePro/Amazon/Template/Description/Category/Specific/Grid/RowRenderer.js
JavaScript
mit
28,752
define([ 'angular' ], function (ng) { 'use strict'; return ng.module('backgroundModule', []); });
lukasz-si/resume
app/components/background-code/module.js
JavaScript
mit
112
const pkg = state => state.pkg const app = state => state.app const device = state => state.app.device const sidebar = state => state.app.sidebar const effect = state => state.app.effect const menuitems = state => state.menu.items const componententry = state => { return state.menu.item.filter(c => c.meta && c.meta.label === 'Components')[0] } export { pkg, app, device, sidebar, effect, menuitems, componententry }
blushft/wespk
client/src/store/getters.js
JavaScript
mit
435
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ angular.module('MetronicApp').controller('UsuariosCtrl', function ($scope, GetSv, $rootScope, PostSv,toaster) { $scope.usuarios = []; $scope.add = false; $scope.edit = false; $scope.a_editar = {}; $scope.usuario = {}; $scope.getUsers = function () { GetSv.getData("usuarios").then(function (data) { if (data.Error) { $scope.error = true; } else { $scope.usuarios = data; $scope.error = false; } }, function (e) { $scope.error = true; }); }; $scope.getUsers(); $scope.closeEdit = function () { $scope.a_editar = {}; $scope.edit = false; }; $scope.openEdit = function (item) { $scope.a_editar = item; $scope.edit = true; }; $scope.closeAdd = function () { $scope.add = false; }; $scope.openAdd = function (item) { $scope.a_editar = {}; $scope.add = true; }; $scope.sendUser = function (servlet, user) { PostSv.postData(servlet, {usuario: JSON.stringify(user)}).then(function (data) { if (data.Error) { toaster.pop('error', "Error", data.Error); } else { toaster.pop('success', "Exito", data.Exito); $scope.a_editar = {}; $scope.usuario = {}; $scope.getUsers(); $scope.add = false; $scope.edit = false; } }, function (e) { toaster.pop('error', "Error", "Error fatal"); } ); }; $scope.roles = $rootScope.roles; });
JoPaRoRo/Fleet
web/js/controllers/usuarios.js
JavaScript
mit
1,854
/* * This file exports the configuration Express.js back to the application * so that it can be used in other parts of the product. */ var path = require('path'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var session = require('express-session'); var RedisStore = require('connect-redis')(session); exports.setup = function(app, express) { app.set('views', path.join(__dirname + '../../public/views')); app.engine('html', require('ejs').renderFile); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(session({ cookie: { maxAge: (24*3600*1000*30) }, store: new RedisStore({ host: 'localhost', port: 6379, db: 1, pass: '' }), secret: 'mylittlesecret', resave: false, saveUninitialized: false })); app.use(express.static(path.join(__dirname + '../../public'))); }
kurtbradd/facebook-music-recommender
config/express-config.js
JavaScript
mit
1,002
(function() { chai.should(); describe("Dropzone", function() { var getMockFile, xhr; getMockFile = function() { return { status: Dropzone.ADDED, accepted: true, name: "test file name", size: 123456, type: "text/html" }; }; xhr = null; beforeEach(function() { return xhr = sinon.useFakeXMLHttpRequest(); }); describe("Emitter", function() { var emitter; emitter = null; beforeEach(function() { return emitter = new Dropzone.prototype.Emitter(); }); it(".on() should return the object itself", function() { return (emitter.on("test", function() {})).should.equal(emitter); }); it(".on() should properly register listeners", function() { var callback, callback2; (emitter._callbacks === void 0).should.be["true"]; callback = function() {}; callback2 = function() {}; emitter.on("test", callback); emitter.on("test", callback2); emitter.on("test2", callback); emitter._callbacks.test.length.should.equal(2); emitter._callbacks.test[0].should.equal(callback); emitter._callbacks.test[1].should.equal(callback2); emitter._callbacks.test2.length.should.equal(1); return emitter._callbacks.test2[0].should.equal(callback); }); it(".emit() should return the object itself", function() { return emitter.emit('test').should.equal(emitter); }); it(".emit() should properly invoke all registered callbacks with arguments", function() { var callCount1, callCount12, callCount2, callback1, callback12, callback2; callCount1 = 0; callCount12 = 0; callCount2 = 0; callback1 = function(var1, var2) { callCount1++; var1.should.equal('callback1 var1'); return var2.should.equal('callback1 var2'); }; callback12 = function(var1, var2) { callCount12++; var1.should.equal('callback1 var1'); return var2.should.equal('callback1 var2'); }; callback2 = function(var1, var2) { callCount2++; var1.should.equal('callback2 var1'); return var2.should.equal('callback2 var2'); }; emitter.on("test1", callback1); emitter.on("test1", callback12); emitter.on("test2", callback2); callCount1.should.equal(0); callCount12.should.equal(0); callCount2.should.equal(0); emitter.emit("test1", "callback1 var1", "callback1 var2"); callCount1.should.equal(1); callCount12.should.equal(1); callCount2.should.equal(0); emitter.emit("test2", "callback2 var1", "callback2 var2"); callCount1.should.equal(1); callCount12.should.equal(1); callCount2.should.equal(1); emitter.emit("test1", "callback1 var1", "callback1 var2"); callCount1.should.equal(2); callCount12.should.equal(2); return callCount2.should.equal(1); }); return describe(".off()", function() { var callback1, callback2, callback3, callback4; callback1 = function() {}; callback2 = function() {}; callback3 = function() {}; callback4 = function() {}; beforeEach(function() { return emitter._callbacks = { 'test1': [callback1, callback2], 'test2': [callback3], 'test3': [callback1, callback4], 'test4': [] }; }); it("should work without any listeners", function() { var emt; emitter._callbacks = void 0; emt = emitter.off(); emitter._callbacks.should.eql({}); return emt.should.equal(emitter); }); it("should properly remove all event listeners", function() { var emt; emt = emitter.off(); emitter._callbacks.should.eql({}); return emt.should.equal(emitter); }); it("should properly remove all event listeners for specific event", function() { var emt; emitter.off("test1"); (emitter._callbacks["test1"] === void 0).should.be["true"]; emitter._callbacks["test2"].length.should.equal(1); emitter._callbacks["test3"].length.should.equal(2); emt = emitter.off("test2"); (emitter._callbacks["test2"] === void 0).should.be["true"]; return emt.should.equal(emitter); }); return it("should properly remove specific event listener", function() { var emt; emitter.off("test1", callback1); emitter._callbacks["test1"].length.should.equal(1); emitter._callbacks["test1"][0].should.equal(callback2); emitter._callbacks["test3"].length.should.equal(2); emt = emitter.off("test3", callback4); emitter._callbacks["test3"].length.should.equal(1); emitter._callbacks["test3"][0].should.equal(callback1); return emt.should.equal(emitter); }); }); }); describe("static functions", function() { describe("Dropzone.createElement()", function() { var element; element = Dropzone.createElement("<div class=\"test\"><span>Hallo</span></div>"); it("should properly create an element from a string", function() { return element.tagName.should.equal("DIV"); }); it("should properly add the correct class", function() { return element.classList.contains("test").should.be.ok; }); it("should properly create child elements", function() { return element.querySelector("span").tagName.should.equal("SPAN"); }); return it("should always return only one element", function() { element = Dropzone.createElement("<div></div><span></span>"); return element.tagName.should.equal("DIV"); }); }); describe("Dropzone.elementInside()", function() { var child1, child2, element; element = Dropzone.createElement("<div id=\"test\"><div class=\"child1\"><div class=\"child2\"></div></div></div>"); document.body.appendChild(element); child1 = element.querySelector(".child1"); child2 = element.querySelector(".child2"); after(function() { return document.body.removeChild(element); }); it("should return yes if elements are the same", function() { return Dropzone.elementInside(element, element).should.be.ok; }); it("should return yes if element is direct child", function() { return Dropzone.elementInside(child1, element).should.be.ok; }); it("should return yes if element is some child", function() { Dropzone.elementInside(child2, element).should.be.ok; return Dropzone.elementInside(child2, document.body).should.be.ok; }); return it("should return no unless element is some child", function() { Dropzone.elementInside(element, child1).should.not.be.ok; return Dropzone.elementInside(document.body, child1).should.not.be.ok; }); }); describe("Dropzone.optionsForElement()", function() { var element, testOptions; testOptions = { url: "/some/url", method: "put" }; before(function() { return Dropzone.options.testElement = testOptions; }); after(function() { return delete Dropzone.options.testElement; }); element = document.createElement("div"); it("should take options set in Dropzone.options from camelized id", function() { element.id = "test-element"; return Dropzone.optionsForElement(element).should.equal(testOptions); }); it("should return undefined if no options set", function() { element.id = "test-element2"; return expect(Dropzone.optionsForElement(element)).to.equal(void 0); }); it("should return undefined and not throw if it's a form with an input element of the name 'id'", function() { element = Dropzone.createElement("<form><input name=\"id\" /</form>"); return expect(Dropzone.optionsForElement(element)).to.equal(void 0); }); return it("should ignore input fields with the name='id'", function() { element = Dropzone.createElement("<form id=\"test-element\"><input type=\"hidden\" name=\"id\" value=\"fooo\" /></form>"); return Dropzone.optionsForElement(element).should.equal(testOptions); }); }); describe("Dropzone.forElement()", function() { var dropzone, element; element = document.createElement("div"); element.id = "some-test-element"; dropzone = null; before(function() { document.body.appendChild(element); return dropzone = new Dropzone(element, { url: "/test" }); }); after(function() { dropzone.disable(); return document.body.removeChild(element); }); it("should throw an exception if no dropzone attached", function() { return expect(function() { return Dropzone.forElement(document.createElement("div")); }).to["throw"]("No Dropzone found for given element. This is probably because you're trying to access it before Dropzone had the time to initialize. Use the `init` option to setup any additional observers on your Dropzone."); }); it("should accept css selectors", function() { return expect(Dropzone.forElement("#some-test-element")).to.equal(dropzone); }); return it("should accept native elements", function() { return expect(Dropzone.forElement(element)).to.equal(dropzone); }); }); describe("Dropzone.discover()", function() { var element1, element2, element3; element1 = document.createElement("div"); element1.className = "dropzone"; element2 = element1.cloneNode(); element3 = element1.cloneNode(); element1.id = "test-element-1"; element2.id = "test-element-2"; element3.id = "test-element-3"; describe("specific options", function() { before(function() { Dropzone.options.testElement1 = { url: "test-url" }; Dropzone.options.testElement2 = false; document.body.appendChild(element1); document.body.appendChild(element2); return Dropzone.discover(); }); after(function() { document.body.removeChild(element1); return document.body.removeChild(element2); }); it("should find elements with a .dropzone class", function() { return element1.dropzone.should.be.ok; }); return it("should not create dropzones with disabled options", function() { return expect(element2.dropzone).to.not.be.ok; }); }); return describe("Dropzone.autoDiscover", function() { before(function() { Dropzone.options.testElement3 = { url: "test-url" }; return document.body.appendChild(element3); }); after(function() { return document.body.removeChild(element3); }); it("should create dropzones even if Dropzone.autoDiscover == false", function() { Dropzone.autoDiscover = false; Dropzone.discover(); return expect(element3.dropzone).to.be.ok; }); return it("should not automatically be called if Dropzone.autoDiscover == false", function() { Dropzone.autoDiscover = false; Dropzone.discover = function() { return expect(false).to.be.ok; }; return Dropzone._autoDiscoverFunction(); }); }); }); describe("Dropzone.isValidFile()", function() { it("should return true if called without acceptedFiles", function() { return Dropzone.isValidFile({ type: "some/type" }, null).should.be.ok; }); it("should properly validate if called with concrete mime types", function() { var acceptedMimeTypes; acceptedMimeTypes = "text/html,image/jpeg,application/json"; Dropzone.isValidFile({ type: "text/html" }, acceptedMimeTypes).should.be.ok; Dropzone.isValidFile({ type: "image/jpeg" }, acceptedMimeTypes).should.be.ok; Dropzone.isValidFile({ type: "application/json" }, acceptedMimeTypes).should.be.ok; return Dropzone.isValidFile({ type: "image/bmp" }, acceptedMimeTypes).should.not.be.ok; }); it("should properly validate if called with base mime types", function() { var acceptedMimeTypes; acceptedMimeTypes = "text/*,image/*,application/*"; Dropzone.isValidFile({ type: "text/html" }, acceptedMimeTypes).should.be.ok; Dropzone.isValidFile({ type: "image/jpeg" }, acceptedMimeTypes).should.be.ok; Dropzone.isValidFile({ type: "application/json" }, acceptedMimeTypes).should.be.ok; Dropzone.isValidFile({ type: "image/bmp" }, acceptedMimeTypes).should.be.ok; return Dropzone.isValidFile({ type: "some/type" }, acceptedMimeTypes).should.not.be.ok; }); it("should properly validate if called with mixed mime types", function() { var acceptedMimeTypes; acceptedMimeTypes = "text/*,image/jpeg,application/*"; Dropzone.isValidFile({ type: "text/html" }, acceptedMimeTypes).should.be.ok; Dropzone.isValidFile({ type: "image/jpeg" }, acceptedMimeTypes).should.be.ok; Dropzone.isValidFile({ type: "image/bmp" }, acceptedMimeTypes).should.not.be.ok; Dropzone.isValidFile({ type: "application/json" }, acceptedMimeTypes).should.be.ok; return Dropzone.isValidFile({ type: "some/type" }, acceptedMimeTypes).should.not.be.ok; }); it("should properly validate even with spaces in between", function() { var acceptedMimeTypes; acceptedMimeTypes = "text/html , image/jpeg, application/json"; Dropzone.isValidFile({ type: "text/html" }, acceptedMimeTypes).should.be.ok; return Dropzone.isValidFile({ type: "image/jpeg" }, acceptedMimeTypes).should.be.ok; }); return it("should properly validate extensions", function() { var acceptedMimeTypes; acceptedMimeTypes = "text/html , image/jpeg, .pdf ,.png"; Dropzone.isValidFile({ name: "somxsfsd", type: "text/html" }, acceptedMimeTypes).should.be.ok; Dropzone.isValidFile({ name: "somesdfsdf", type: "image/jpeg" }, acceptedMimeTypes).should.be.ok; Dropzone.isValidFile({ name: "somesdfadfadf", type: "application/json" }, acceptedMimeTypes).should.not.be.ok; Dropzone.isValidFile({ name: "some-file file.pdf", type: "random/type" }, acceptedMimeTypes).should.be.ok; Dropzone.isValidFile({ name: "some-file.pdf file.gif", type: "random/type" }, acceptedMimeTypes).should.not.be.ok; return Dropzone.isValidFile({ name: "some-file file.png", type: "random/type" }, acceptedMimeTypes).should.be.ok; }); }); return describe("Dropzone.confirm", function() { beforeEach(function() { return sinon.stub(window, "confirm"); }); afterEach(function() { return window.confirm.restore(); }); it("should forward to window.confirm and call the callbacks accordingly", function() { var accepted, rejected; accepted = rejected = false; window.confirm.returns(true); Dropzone.confirm("test question", (function() { return accepted = true; }), (function() { return rejected = true; })); window.confirm.args[0][0].should.equal("test question"); accepted.should.equal(true); rejected.should.equal(false); accepted = rejected = false; window.confirm.returns(false); Dropzone.confirm("test question 2", (function() { return accepted = true; }), (function() { return rejected = true; })); window.confirm.args[1][0].should.equal("test question 2"); accepted.should.equal(false); return rejected.should.equal(true); }); return it("should not error if rejected is not provided", function() { var accepted, rejected; accepted = rejected = false; window.confirm.returns(false); Dropzone.confirm("test question", (function() { return accepted = true; })); window.confirm.args[0][0].should.equal("test question"); accepted.should.equal(false); return rejected.should.equal(false); }); }); }); describe("Dropzone.getElement() / getElements()", function() { var tmpElements; tmpElements = []; beforeEach(function() { tmpElements = []; tmpElements.push(Dropzone.createElement("<div class=\"tmptest\"></div>")); tmpElements.push(Dropzone.createElement("<div id=\"tmptest1\" class=\"random\"></div>")); tmpElements.push(Dropzone.createElement("<div class=\"random div\"></div>")); return tmpElements.forEach(function(el) { return document.body.appendChild(el); }); }); afterEach(function() { return tmpElements.forEach(function(el) { return document.body.removeChild(el); }); }); describe(".getElement()", function() { it("should accept a string", function() { var el; el = Dropzone.getElement(".tmptest"); el.should.equal(tmpElements[0]); el = Dropzone.getElement("#tmptest1"); return el.should.equal(tmpElements[1]); }); it("should accept a node", function() { var el; el = Dropzone.getElement(tmpElements[2]); return el.should.equal(tmpElements[2]); }); return it("should fail if invalid selector", function() { var errorMessage; errorMessage = "Invalid `clickable` option provided. Please provide a CSS selector or a plain HTML element."; expect(function() { return Dropzone.getElement("lblasdlfsfl", "clickable"); }).to["throw"](errorMessage); expect(function() { return Dropzone.getElement({ "lblasdlfsfl": "lblasdlfsfl" }, "clickable"); }).to["throw"](errorMessage); return expect(function() { return Dropzone.getElement(["lblasdlfsfl"], "clickable"); }).to["throw"](errorMessage); }); }); return describe(".getElements()", function() { it("should accept a list of strings", function() { var els; els = Dropzone.getElements([".tmptest", "#tmptest1"]); return els.should.eql([tmpElements[0], tmpElements[1]]); }); it("should accept a list of nodes", function() { var els; els = Dropzone.getElements([tmpElements[0], tmpElements[2]]); return els.should.eql([tmpElements[0], tmpElements[2]]); }); it("should accept a mixed list", function() { var els; els = Dropzone.getElements(["#tmptest1", tmpElements[2]]); return els.should.eql([tmpElements[1], tmpElements[2]]); }); it("should accept a string selector", function() { var els; els = Dropzone.getElements(".random"); return els.should.eql([tmpElements[1], tmpElements[2]]); }); it("should accept a single node", function() { var els; els = Dropzone.getElements(tmpElements[1]); return els.should.eql([tmpElements[1]]); }); return it("should fail if invalid selector", function() { var errorMessage; errorMessage = "Invalid `clickable` option provided. Please provide a CSS selector, a plain HTML element or a list of those."; expect(function() { return Dropzone.getElements("lblasdlfsfl", "clickable"); }).to["throw"](errorMessage); return expect(function() { return Dropzone.getElements(["lblasdlfsfl"], "clickable"); }).to["throw"](errorMessage); }); }); }); describe("constructor()", function() { var dropzone; dropzone = null; afterEach(function() { if (dropzone != null) { return dropzone.destroy(); } }); it("should throw an exception if the element is invalid", function() { return expect(function() { return dropzone = new Dropzone("#invalid-element"); }).to["throw"]("Invalid dropzone element."); }); it("should throw an exception if assigned twice to the same element", function() { var element; element = document.createElement("div"); dropzone = new Dropzone(element, { url: "url" }); return expect(function() { return new Dropzone(element, { url: "url" }); }).to["throw"]("Dropzone already attached."); }); it("should throw an exception if both acceptedFiles and acceptedMimeTypes are specified", function() { var element; element = document.createElement("div"); return expect(function() { return dropzone = new Dropzone(element, { url: "test", acceptedFiles: "param", acceptedMimeTypes: "types" }); }).to["throw"]("You can't provide both 'acceptedFiles' and 'acceptedMimeTypes'. 'acceptedMimeTypes' is deprecated."); }); it("should set itself as element.dropzone", function() { var element; element = document.createElement("div"); dropzone = new Dropzone(element, { url: "url" }); return element.dropzone.should.equal(dropzone); }); it("should add itself to Dropzone.instances", function() { var element; element = document.createElement("div"); dropzone = new Dropzone(element, { url: "url" }); return Dropzone.instances[Dropzone.instances.length - 1].should.equal(dropzone); }); it("should use the action attribute not the element with the name action", function() { var element; element = Dropzone.createElement("<form action=\"real-action\"><input type=\"hidden\" name=\"action\" value=\"wrong-action\" /></form>"); dropzone = new Dropzone(element); return dropzone.options.url.should.equal("real-action"); }); return describe("options", function() { var element, element2; element = null; element2 = null; beforeEach(function() { element = document.createElement("div"); element.id = "test-element"; element2 = document.createElement("div"); element2.id = "test-element2"; return Dropzone.options.testElement = { url: "/some/url", parallelUploads: 10 }; }); afterEach(function() { return delete Dropzone.options.testElement; }); it("should take the options set in Dropzone.options", function() { dropzone = new Dropzone(element); dropzone.options.url.should.equal("/some/url"); return dropzone.options.parallelUploads.should.equal(10); }); it("should prefer passed options over Dropzone.options", function() { dropzone = new Dropzone(element, { url: "/some/other/url" }); return dropzone.options.url.should.equal("/some/other/url"); }); it("should take the default options if nothing set in Dropzone.options", function() { dropzone = new Dropzone(element2, { url: "/some/url" }); return dropzone.options.parallelUploads.should.equal(2); }); it("should call the fallback function if forceFallback == true", function(done) { return dropzone = new Dropzone(element, { url: "/some/other/url", forceFallback: true, fallback: function() { return done(); } }); }); it("should set acceptedFiles if deprecated acceptedMimetypes option has been passed", function() { dropzone = new Dropzone(element, { url: "/some/other/url", acceptedMimeTypes: "my/type" }); return dropzone.options.acceptedFiles.should.equal("my/type"); }); return describe("options.clickable", function() { var clickableElement; clickableElement = null; dropzone = null; beforeEach(function() { clickableElement = document.createElement("div"); clickableElement.className = "some-clickable"; return document.body.appendChild(clickableElement); }); afterEach(function() { document.body.removeChild(clickableElement); if (dropzone != null) { return dropzone.destroy; } }); it("should use the default element if clickable == true", function() { dropzone = new Dropzone(element, { clickable: true }); return dropzone.clickableElements.should.eql([dropzone.element]); }); it("should lookup the element if clickable is a CSS selector", function() { dropzone = new Dropzone(element, { clickable: ".some-clickable" }); return dropzone.clickableElements.should.eql([clickableElement]); }); it("should simply use the provided element", function() { dropzone = new Dropzone(element, { clickable: clickableElement }); return dropzone.clickableElements.should.eql([clickableElement]); }); it("should accept multiple clickable elements", function() { dropzone = new Dropzone(element, { clickable: [document.body, ".some-clickable"] }); return dropzone.clickableElements.should.eql([document.body, clickableElement]); }); return it("should throw an exception if the element is invalid", function() { return expect(function() { return dropzone = new Dropzone(element, { clickable: ".some-invalid-clickable" }); }).to["throw"]("Invalid `clickable` option provided. Please provide a CSS selector, a plain HTML element or a list of those."); }); }); }); }); describe("init()", function() { describe("clickable", function() { var dropzone, dropzones, name, _results; dropzones = { "using acceptedFiles": new Dropzone(Dropzone.createElement("<form action=\"/\"></form>"), { clickable: true, acceptedFiles: "audio/*,video/*" }), "using acceptedMimeTypes": new Dropzone(Dropzone.createElement("<form action=\"/\"></form>"), { clickable: true, acceptedMimeTypes: "audio/*,video/*" }) }; it("should not add an accept attribute if no acceptParameter", function() { var dropzone; dropzone = new Dropzone(Dropzone.createElement("<form action=\"/\"></form>"), { clickable: true, acceptParameter: null, acceptedMimeTypes: null }); return dropzone.hiddenFileInput.hasAttribute("accept").should.be["false"]; }); _results = []; for (name in dropzones) { dropzone = dropzones[name]; _results.push(describe(name, function() { return (function(dropzone) { it("should create a hidden file input if clickable", function() { dropzone.hiddenFileInput.should.be.ok; return dropzone.hiddenFileInput.tagName.should.equal("INPUT"); }); it("should use the acceptParameter", function() { return dropzone.hiddenFileInput.getAttribute("accept").should.equal("audio/*,video/*"); }); return it("should create a new input element when something is selected to reset the input field", function() { var event, hiddenFileInput, i, _i, _results1; _results1 = []; for (i = _i = 0; _i <= 3; i = ++_i) { hiddenFileInput = dropzone.hiddenFileInput; event = document.createEvent("HTMLEvents"); event.initEvent("change", true, true); hiddenFileInput.dispatchEvent(event); dropzone.hiddenFileInput.should.not.equal(hiddenFileInput); _results1.push(Dropzone.elementInside(hiddenFileInput, document).should.not.be.ok); } return _results1; }); })(dropzone); })); } return _results; }); it("should create a .dz-message element", function() { var dropzone, element; element = Dropzone.createElement("<form class=\"dropzone\" action=\"/\"></form>"); dropzone = new Dropzone(element, { clickable: true, acceptParameter: null, acceptedMimeTypes: null }); return element.querySelector(".dz-message").should.be["instanceof"](Element); }); return it("should not create a .dz-message element if there already is one", function() { var dropzone, element, msg; element = Dropzone.createElement("<form class=\"dropzone\" action=\"/\"></form>"); msg = Dropzone.createElement("<div class=\"dz-message\">TEST</div>"); element.appendChild(msg); dropzone = new Dropzone(element, { clickable: true, acceptParameter: null, acceptedMimeTypes: null }); element.querySelector(".dz-message").should.equal(msg); return element.querySelectorAll(".dz-message").length.should.equal(1); }); }); describe("options", function() { var dropzone, element; element = null; dropzone = null; beforeEach(function() { element = Dropzone.createElement("<div></div>"); return dropzone = new Dropzone(element, { maxFilesize: 4, url: "url", acceptedMimeTypes: "audio/*,image/png", maxFiles: 3 }); }); return describe("file specific", function() { var file; file = null; beforeEach(function() { file = { name: "test name", size: 2 * 1024 * 1024, width: 200, height: 100 }; return dropzone.options.addedfile.call(dropzone, file); }); describe(".addedFile()", function() { return it("should properly create the previewElement", function() { file.previewElement.should.be["instanceof"](Element); file.previewElement.querySelector("[data-dz-name]").innerHTML.should.eql("test name"); return file.previewElement.querySelector("[data-dz-size]").innerHTML.should.eql("<strong>2.1</strong> MB"); }); }); describe(".error()", function() { it("should properly insert the error", function() { dropzone.options.error.call(dropzone, file, "test message"); return file.previewElement.querySelector("[data-dz-errormessage]").innerHTML.should.eql("test message"); }); return it("should properly insert the error when provided with an object containing the error", function() { dropzone.options.error.call(dropzone, file, { error: "test message" }); return file.previewElement.querySelector("[data-dz-errormessage]").innerHTML.should.eql("test message"); }); }); describe(".thumbnail()", function() { return it("should properly insert the error", function() { var thumbnail, transparentGif; transparentGif = "data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=="; dropzone.options.thumbnail.call(dropzone, file, transparentGif); thumbnail = file.previewElement.querySelector("[data-dz-thumbnail]"); thumbnail.src.should.eql(transparentGif); return thumbnail.alt.should.eql("test name"); }); }); describe(".uploadprogress()", function() { return it("should properly set the width", function() { dropzone.options.uploadprogress.call(dropzone, file, 0); file.previewElement.querySelector("[data-dz-uploadprogress]").style.width.should.eql("0%"); dropzone.options.uploadprogress.call(dropzone, file, 80); file.previewElement.querySelector("[data-dz-uploadprogress]").style.width.should.eql("80%"); dropzone.options.uploadprogress.call(dropzone, file, 90); file.previewElement.querySelector("[data-dz-uploadprogress]").style.width.should.eql("90%"); dropzone.options.uploadprogress.call(dropzone, file, 100); return file.previewElement.querySelector("[data-dz-uploadprogress]").style.width.should.eql("100%"); }); }); return describe(".resize()", function() { describe("with default thumbnail settings", function() { return it("should properly return target dimensions", function() { var info; info = dropzone.options.resize.call(dropzone, file); info.optWidth.should.eql(120); return info.optHeight.should.eql(120); }); }); return describe("with null thumbnail settings", function() { return it("should properly return target dimensions", function() { var i, info, setting, testSettings, _i, _len, _results; testSettings = [[null, null], [null, 150], [150, null]]; _results = []; for (i = _i = 0, _len = testSettings.length; _i < _len; i = ++_i) { setting = testSettings[i]; dropzone.options.thumbnailWidth = setting[0]; dropzone.options.thumbnailHeight = setting[1]; info = dropzone.options.resize.call(dropzone, file); if (i === 0) { info.optWidth.should.eql(200); info.optHeight.should.eql(100); } if (i === 1) { info.optWidth.should.eql(300); info.optHeight.should.eql(150); } if (i === 2) { info.optWidth.should.eql(150); _results.push(info.optHeight.should.eql(75)); } else { _results.push(void 0); } } return _results; }); }); }); }); }); describe("instance", function() { var dropzone, element, requests; element = null; dropzone = null; requests = null; beforeEach(function() { requests = []; xhr.onCreate = function(xhr) { return requests.push(xhr); }; element = Dropzone.createElement("<div></div>"); document.body.appendChild(element); return dropzone = new Dropzone(element, { maxFilesize: 4, maxFiles: 100, url: "url", acceptedMimeTypes: "audio/*,image/png", uploadprogress: function() {} }); }); afterEach(function() { document.body.removeChild(element); dropzone.destroy(); return xhr.restore(); }); describe(".accept()", function() { it("should pass if the filesize is OK", function() { return dropzone.accept({ size: 2 * 1024 * 1024, type: "audio/mp3" }, function(err) { return expect(err).to.be.undefined; }); }); it("shouldn't pass if the filesize is too big", function() { return dropzone.accept({ size: 10 * 1024 * 1024, type: "audio/mp3" }, function(err) { return err.should.eql("File is too big (10MiB). Max filesize: 4MiB."); }); }); it("should properly accept files which mime types are listed in acceptedFiles", function() { dropzone.accept({ type: "audio/mp3" }, function(err) { return expect(err).to.be.undefined; }); dropzone.accept({ type: "image/png" }, function(err) { return expect(err).to.be.undefined; }); return dropzone.accept({ type: "audio/wav" }, function(err) { return expect(err).to.be.undefined; }); }); it("should properly reject files when the mime type isn't listed in acceptedFiles", function() { return dropzone.accept({ type: "image/jpeg" }, function(err) { return err.should.eql("You can't upload files of this type."); }); }); it("should fail if maxFiles has been exceeded and call the event maxfilesexceeded", function() { var called, file; sinon.stub(dropzone, "getAcceptedFiles"); file = { type: "audio/mp3" }; dropzone.getAcceptedFiles.returns({ length: 99 }); dropzone.options.dictMaxFilesExceeded = "You can only upload {{maxFiles}} files."; called = false; dropzone.on("maxfilesexceeded", function(lfile) { lfile.should.equal(file); return called = true; }); dropzone.accept(file, function(err) { return expect(err).to.be.undefined; }); called.should.not.be.ok; dropzone.getAcceptedFiles.returns({ length: 100 }); dropzone.accept(file, function(err) { return expect(err).to.equal("You can only upload 100 files."); }); called.should.be.ok; return dropzone.getAcceptedFiles.restore(); }); return it("should properly handle if maxFiles is 0", function() { var called, file; file = { type: "audio/mp3" }; dropzone.options.maxFiles = 0; called = false; dropzone.on("maxfilesexceeded", function(lfile) { lfile.should.equal(file); return called = true; }); dropzone.accept(file, function(err) { return expect(err).to.equal("You can not upload any more files."); }); return called.should.be.ok; }); }); describe(".removeFile()", function() { return it("should abort uploading if file is currently being uploaded", function(done) { var mockFile; mockFile = getMockFile(); dropzone.uploadFile = function(file) {}; dropzone.accept = function(file, done) { return done(); }; sinon.stub(dropzone, "cancelUpload"); dropzone.addFile(mockFile); return setTimeout(function() { mockFile.status.should.equal(Dropzone.UPLOADING); dropzone.getUploadingFiles()[0].should.equal(mockFile); dropzone.cancelUpload.callCount.should.equal(0); dropzone.removeFile(mockFile); dropzone.cancelUpload.callCount.should.equal(1); return done(); }, 10); }); }); describe(".cancelUpload()", function() { it("should properly cancel upload if file currently uploading", function(done) { var mockFile; mockFile = getMockFile(); dropzone.accept = function(file, done) { return done(); }; dropzone.addFile(mockFile); return setTimeout(function() { mockFile.status.should.equal(Dropzone.UPLOADING); dropzone.getUploadingFiles()[0].should.equal(mockFile); dropzone.cancelUpload(mockFile); mockFile.status.should.equal(Dropzone.CANCELED); dropzone.getUploadingFiles().length.should.equal(0); dropzone.getQueuedFiles().length.should.equal(0); return done(); }, 10); }); it("should properly cancel the upload if file is not yet uploading", function() { var mockFile; mockFile = getMockFile(); dropzone.accept = function(file, done) { return done(); }; dropzone.options.parallelUploads = 0; dropzone.addFile(mockFile); mockFile.status.should.equal(Dropzone.QUEUED); dropzone.getQueuedFiles()[0].should.equal(mockFile); dropzone.cancelUpload(mockFile); mockFile.status.should.equal(Dropzone.CANCELED); dropzone.getQueuedFiles().length.should.equal(0); return dropzone.getUploadingFiles().length.should.equal(0); }); it("should call processQueue()", function(done) { var mockFile; mockFile = getMockFile(); dropzone.accept = function(file, done) { return done(); }; dropzone.options.parallelUploads = 0; sinon.spy(dropzone, "processQueue"); dropzone.addFile(mockFile); return setTimeout(function() { dropzone.processQueue.callCount.should.equal(1); dropzone.cancelUpload(mockFile); dropzone.processQueue.callCount.should.equal(2); return done(); }, 10); }); return it("should properly cancel all files with the same XHR if uploadMultiple is true", function(done) { var mock1, mock2, mock3; mock1 = getMockFile(); mock2 = getMockFile(); mock3 = getMockFile(); dropzone.accept = function(file, done) { return done(); }; dropzone.options.uploadMultiple = true; dropzone.options.parallelUploads = 3; sinon.spy(dropzone, "processFiles"); dropzone.addFile(mock1); dropzone.addFile(mock2); dropzone.addFile(mock3); return setTimeout(function() { var _ref; dropzone.processFiles.callCount.should.equal(1); sinon.spy(mock1.xhr, "abort"); dropzone.cancelUpload(mock1); expect((mock1.xhr === (_ref = mock2.xhr) && _ref === mock3.xhr)).to.be.ok; mock1.status.should.equal(Dropzone.CANCELED); mock2.status.should.equal(Dropzone.CANCELED); mock3.status.should.equal(Dropzone.CANCELED); mock1.xhr.abort.callCount.should.equal(1); return done(); }, 10); }); }); describe(".disable()", function() { return it("should properly cancel all pending uploads", function(done) { dropzone.accept = function(file, done) { return done(); }; dropzone.options.parallelUploads = 1; dropzone.addFile(getMockFile()); dropzone.addFile(getMockFile()); return setTimeout(function() { dropzone.getUploadingFiles().length.should.equal(1); dropzone.getQueuedFiles().length.should.equal(1); dropzone.files.length.should.equal(2); sinon.spy(requests[0], "abort"); requests[0].abort.callCount.should.equal(0); dropzone.disable(); requests[0].abort.callCount.should.equal(1); dropzone.getUploadingFiles().length.should.equal(0); dropzone.getQueuedFiles().length.should.equal(0); dropzone.files.length.should.equal(2); dropzone.files[0].status.should.equal(Dropzone.CANCELED); dropzone.files[1].status.should.equal(Dropzone.CANCELED); return done(); }, 10); }); }); describe(".destroy()", function() { it("should properly cancel all pending uploads and remove all file references", function(done) { dropzone.accept = function(file, done) { return done(); }; dropzone.options.parallelUploads = 1; dropzone.addFile(getMockFile()); dropzone.addFile(getMockFile()); return setTimeout(function() { dropzone.getUploadingFiles().length.should.equal(1); dropzone.getQueuedFiles().length.should.equal(1); dropzone.files.length.should.equal(2); sinon.spy(dropzone, "disable"); dropzone.destroy(); dropzone.disable.callCount.should.equal(1); element.should.not.have.property("dropzone"); return done(); }, 10); }); it("should be able to create instance of dropzone on the same element after destroy", function() { dropzone.destroy(); return (function() { return new Dropzone(element, { maxFilesize: 4, url: "url", acceptedMimeTypes: "audio/*,image/png", uploadprogress: function() {} }); }).should.not["throw"](Error); }); return it("should remove itself from Dropzone.instances", function() { (Dropzone.instances.indexOf(dropzone) !== -1).should.be.ok; dropzone.destroy(); return (Dropzone.instances.indexOf(dropzone) === -1).should.be.ok; }); }); describe(".filesize()", function() { it("should convert to KiloBytes, etc..", function() { dropzone.options.filesizeBase.should.eql(1000); dropzone.filesize(2 * 1000 * 1000).should.eql("<strong>2</strong> MB"); dropzone.filesize(2 * 1024 * 1024).should.eql("<strong>2.1</strong> MB"); dropzone.filesize(2 * 1000 * 1000 * 1000).should.eql("<strong>2</strong> GB"); dropzone.filesize(2 * 1024 * 1024 * 1024).should.eql("<strong>2.1</strong> GB"); dropzone.filesize(2.5111 * 1000 * 1000 * 1000).should.eql("<strong>2.5</strong> GB"); dropzone.filesize(1.1 * 1000).should.eql("<strong>1.1</strong> KB"); return dropzone.filesize(999 * 1000).should.eql("<strong>1</strong> MB"); }); return it("should convert to KibiBytes, etc.. when the filesizeBase is changed to 1024", function() { dropzone.options.filesizeBase = 1024; dropzone.filesize(2 * 1024 * 1024).should.eql("<strong>2</strong> MB"); return dropzone.filesize(2 * 1000 * 1000).should.eql("<strong>1.9</strong> MB"); }); }); describe("._updateMaxFilesReachedClass()", function() { it("should properly add the dz-max-files-reached class", function() { dropzone.getAcceptedFiles = function() { return { length: 10 }; }; dropzone.options.maxFiles = 10; dropzone.element.classList.contains("dz-max-files-reached").should.not.be.ok; dropzone._updateMaxFilesReachedClass(); return dropzone.element.classList.contains("dz-max-files-reached").should.be.ok; }); it("should fire the 'maxfilesreached' event when appropriate", function() { var spy; spy = sinon.spy(); dropzone.on("maxfilesreached", function() { return spy(); }); dropzone.getAcceptedFiles = function() { return { length: 9 }; }; dropzone.options.maxFiles = 10; dropzone._updateMaxFilesReachedClass(); spy.should.not.have.been.called; dropzone.getAcceptedFiles = function() { return { length: 10 }; }; dropzone._updateMaxFilesReachedClass(); spy.should.have.been.called; dropzone.getAcceptedFiles = function() { return { length: 11 }; }; dropzone._updateMaxFilesReachedClass(); return spy.should.have.been.calledOnce; }); return it("should properly remove the dz-max-files-reached class", function() { dropzone.getAcceptedFiles = function() { return { length: 10 }; }; dropzone.options.maxFiles = 10; dropzone.element.classList.contains("dz-max-files-reached").should.not.be.ok; dropzone._updateMaxFilesReachedClass(); dropzone.element.classList.contains("dz-max-files-reached").should.be.ok; dropzone.getAcceptedFiles = function() { return { length: 9 }; }; dropzone._updateMaxFilesReachedClass(); return dropzone.element.classList.contains("dz-max-files-reached").should.not.be.ok; }); }); return describe("events", function() { return describe("progress updates", function() { return it("should properly emit a totaluploadprogress event", function(done) { var totalProgressExpectation, _called; dropzone.files = [ { size: 1990, accepted: true, status: Dropzone.UPLOADING, upload: { progress: 20, total: 2000, bytesSent: 400 } }, { size: 1990, accepted: true, status: Dropzone.UPLOADING, upload: { progress: 10, total: 2000, bytesSent: 200 } } ]; _called = 0; dropzone.on("totaluploadprogress", function(progress) { progress.should.equal(totalProgressExpectation); if (++_called === 3) { return done(); } }); totalProgressExpectation = 15; dropzone.emit("uploadprogress", {}); totalProgressExpectation = 97.5; dropzone.files[0].upload.bytesSent = 2000; dropzone.files[1].upload.bytesSent = 1900; dropzone.emit("uploadprogress", {}); totalProgressExpectation = 100; dropzone.files[0].upload.bytesSent = 2000; dropzone.files[1].upload.bytesSent = 2000; dropzone.emit("uploadprogress", {}); dropzone.files[0].status = Dropzone.CANCELED; return dropzone.files[1].status = Dropzone.CANCELED; }); }); }); }); describe("helper function", function() { var dropzone, element; element = null; dropzone = null; beforeEach(function() { element = Dropzone.createElement("<div></div>"); return dropzone = new Dropzone(element, { url: "url" }); }); describe("getExistingFallback()", function() { it("should return undefined if no fallback", function() { return expect(dropzone.getExistingFallback()).to.equal(void 0); }); it("should only return the fallback element if it contains exactly fallback", function() { element.appendChild(Dropzone.createElement("<form class=\"fallbacks\"></form>")); element.appendChild(Dropzone.createElement("<form class=\"sfallback\"></form>")); return expect(dropzone.getExistingFallback()).to.equal(void 0); }); it("should return divs as fallback", function() { var fallback; fallback = Dropzone.createElement("<form class=\" abc fallback test \"></form>"); element.appendChild(fallback); return fallback.should.equal(dropzone.getExistingFallback()); }); return it("should return forms as fallback", function() { var fallback; fallback = Dropzone.createElement("<div class=\" abc fallback test \"></div>"); element.appendChild(fallback); return fallback.should.equal(dropzone.getExistingFallback()); }); }); describe("getFallbackForm()", function() { it("should use the paramName without [0] if uploadMultiple is false", function() { var fallback, fileInput; dropzone.options.uploadMultiple = false; dropzone.options.paramName = "myFile"; fallback = dropzone.getFallbackForm(); fileInput = fallback.querySelector("input[type=file]"); return fileInput.name.should.equal("myFile"); }); return it("should properly add [0] to the file name if uploadMultiple is true", function() { var fallback, fileInput; dropzone.options.uploadMultiple = true; dropzone.options.paramName = "myFile"; fallback = dropzone.getFallbackForm(); fileInput = fallback.querySelector("input[type=file]"); return fileInput.name.should.equal("myFile[0]"); }); }); describe("getAcceptedFiles() / getRejectedFiles()", function() { var mock1, mock2, mock3, mock4; mock1 = mock2 = mock3 = mock4 = null; beforeEach(function() { mock1 = getMockFile(); mock2 = getMockFile(); mock3 = getMockFile(); mock4 = getMockFile(); dropzone.options.accept = function(file, done) { if (file === mock1 || file === mock3) { return done(); } else { return done("error"); } }; dropzone.addFile(mock1); dropzone.addFile(mock2); dropzone.addFile(mock3); return dropzone.addFile(mock4); }); it("getAcceptedFiles() should only return accepted files", function() { return dropzone.getAcceptedFiles().should.eql([mock1, mock3]); }); return it("getRejectedFiles() should only return rejected files", function() { return dropzone.getRejectedFiles().should.eql([mock2, mock4]); }); }); describe("getQueuedFiles()", function() { return it("should return all files with the status Dropzone.QUEUED", function() { var mock1, mock2, mock3, mock4; mock1 = getMockFile(); mock2 = getMockFile(); mock3 = getMockFile(); mock4 = getMockFile(); dropzone.options.accept = function(file, done) { return file.done = done; }; dropzone.addFile(mock1); dropzone.addFile(mock2); dropzone.addFile(mock3); dropzone.addFile(mock4); dropzone.getQueuedFiles().should.eql([]); mock1.done(); mock3.done(); dropzone.getQueuedFiles().should.eql([mock1, mock3]); mock1.status.should.equal(Dropzone.QUEUED); mock3.status.should.equal(Dropzone.QUEUED); mock2.status.should.equal(Dropzone.ADDED); return mock4.status.should.equal(Dropzone.ADDED); }); }); describe("getUploadingFiles()", function() { return it("should return all files with the status Dropzone.UPLOADING", function(done) { var mock1, mock2, mock3, mock4; mock1 = getMockFile(); mock2 = getMockFile(); mock3 = getMockFile(); mock4 = getMockFile(); dropzone.options.accept = function(file, _done) { return file.done = _done; }; dropzone.uploadFile = function() {}; dropzone.addFile(mock1); dropzone.addFile(mock2); dropzone.addFile(mock3); dropzone.addFile(mock4); dropzone.getUploadingFiles().should.eql([]); mock1.done(); mock3.done(); return setTimeout((function() { dropzone.getUploadingFiles().should.eql([mock1, mock3]); mock1.status.should.equal(Dropzone.UPLOADING); mock3.status.should.equal(Dropzone.UPLOADING); mock2.status.should.equal(Dropzone.ADDED); mock4.status.should.equal(Dropzone.ADDED); return done(); }), 10); }); }); describe("getActiveFiles()", function() { return it("should return all files with the status Dropzone.UPLOADING or Dropzone.QUEUED", function(done) { var mock1, mock2, mock3, mock4; mock1 = getMockFile(); mock2 = getMockFile(); mock3 = getMockFile(); mock4 = getMockFile(); dropzone.options.accept = function(file, _done) { return file.done = _done; }; dropzone.uploadFile = function() {}; dropzone.options.parallelUploads = 2; dropzone.addFile(mock1); dropzone.addFile(mock2); dropzone.addFile(mock3); dropzone.addFile(mock4); dropzone.getActiveFiles().should.eql([]); mock1.done(); mock3.done(); mock4.done(); return setTimeout((function() { dropzone.getActiveFiles().should.eql([mock1, mock3, mock4]); mock1.status.should.equal(Dropzone.UPLOADING); mock3.status.should.equal(Dropzone.UPLOADING); mock2.status.should.equal(Dropzone.ADDED); mock4.status.should.equal(Dropzone.QUEUED); return done(); }), 10); }); }); return describe("getFilesWithStatus()", function() { return it("should return all files with provided status", function() { var mock1, mock2, mock3, mock4; mock1 = getMockFile(); mock2 = getMockFile(); mock3 = getMockFile(); mock4 = getMockFile(); dropzone.options.accept = function(file, _done) { return file.done = _done; }; dropzone.uploadFile = function() {}; dropzone.addFile(mock1); dropzone.addFile(mock2); dropzone.addFile(mock3); dropzone.addFile(mock4); dropzone.getFilesWithStatus(Dropzone.ADDED).should.eql([mock1, mock2, mock3, mock4]); mock1.status = Dropzone.UPLOADING; mock3.status = Dropzone.QUEUED; mock4.status = Dropzone.QUEUED; dropzone.getFilesWithStatus(Dropzone.ADDED).should.eql([mock2]); dropzone.getFilesWithStatus(Dropzone.UPLOADING).should.eql([mock1]); return dropzone.getFilesWithStatus(Dropzone.QUEUED).should.eql([mock3, mock4]); }); }); }); return describe("file handling", function() { var dropzone, mockFile; mockFile = null; dropzone = null; beforeEach(function() { var element; mockFile = getMockFile(); element = Dropzone.createElement("<div></div>"); return dropzone = new Dropzone(element, { url: "/the/url" }); }); afterEach(function() { return dropzone.destroy(); }); describe("addFile()", function() { it("should properly set the status of the file", function() { var doneFunction; doneFunction = null; dropzone.accept = function(file, done) { return doneFunction = done; }; dropzone.processFile = function() {}; dropzone.uploadFile = function() {}; dropzone.addFile(mockFile); mockFile.status.should.eql(Dropzone.ADDED); doneFunction(); mockFile.status.should.eql(Dropzone.QUEUED); mockFile = getMockFile(); dropzone.addFile(mockFile); mockFile.status.should.eql(Dropzone.ADDED); doneFunction("error"); return mockFile.status.should.eql(Dropzone.ERROR); }); it("should properly set the status of the file if autoProcessQueue is false and not call processQueue", function(done) { var doneFunction; doneFunction = null; dropzone.options.autoProcessQueue = false; dropzone.accept = function(file, done) { return doneFunction = done; }; dropzone.processFile = function() {}; dropzone.uploadFile = function() {}; dropzone.addFile(mockFile); sinon.stub(dropzone, "processQueue"); mockFile.status.should.eql(Dropzone.ADDED); doneFunction(); mockFile.status.should.eql(Dropzone.QUEUED); dropzone.processQueue.callCount.should.equal(0); return setTimeout((function() { dropzone.processQueue.callCount.should.equal(0); return done(); }), 10); }); it("should not add the file to the queue if autoQueue is false", function() { var doneFunction; doneFunction = null; dropzone.options.autoQueue = false; dropzone.accept = function(file, done) { return doneFunction = done; }; dropzone.processFile = function() {}; dropzone.uploadFile = function() {}; dropzone.addFile(mockFile); mockFile.status.should.eql(Dropzone.ADDED); doneFunction(); return mockFile.status.should.eql(Dropzone.ADDED); }); it("should create a remove link if configured to do so", function() { dropzone.options.addRemoveLinks = true; dropzone.processFile = function() {}; dropzone.uploadFile = function() {}; sinon.stub(dropzone, "processQueue"); dropzone.addFile(mockFile); return dropzone.files[0].previewElement.querySelector("a[data-dz-remove].dz-remove").should.be.ok; }); it("should attach an event handler to data-dz-remove links", function() { var event, file, removeLink1, removeLink2; dropzone.options.previewTemplate = "<div class=\"dz-preview dz-file-preview\">\n <div class=\"dz-details\">\n <div class=\"dz-filename\"><span data-dz-name></span></div>\n <div class=\"dz-size\" data-dz-size></div>\n <img data-dz-thumbnail />\n </div>\n <div class=\"dz-progress\"><span class=\"dz-upload\" data-dz-uploadprogress></span></div>\n <div class=\"dz-success-mark\"><span>✔</span></div>\n <div class=\"dz-error-mark\"><span>✘</span></div>\n <div class=\"dz-error-message\"><span data-dz-errormessage></span></div>\n <a class=\"link1\" data-dz-remove></a>\n <a class=\"link2\" data-dz-remove></a>\n</div>"; sinon.stub(dropzone, "processQueue"); dropzone.addFile(mockFile); file = dropzone.files[0]; removeLink1 = file.previewElement.querySelector("a[data-dz-remove].link1"); removeLink2 = file.previewElement.querySelector("a[data-dz-remove].link2"); sinon.stub(dropzone, "removeFile"); event = document.createEvent("HTMLEvents"); event.initEvent("click", true, true); removeLink1.dispatchEvent(event); dropzone.removeFile.callCount.should.eql(1); event = document.createEvent("HTMLEvents"); event.initEvent("click", true, true); removeLink2.dispatchEvent(event); return dropzone.removeFile.callCount.should.eql(2); }); return describe("thumbnails", function() { it("should properly queue the thumbnail creation", function(done) { var ct_callback, ct_file, doneFunction, mock1, mock2, mock3; doneFunction = null; dropzone.accept = function(file, done) { return doneFunction = done; }; dropzone.processFile = function() {}; dropzone.uploadFile = function() {}; mock1 = getMockFile(); mock2 = getMockFile(); mock3 = getMockFile(); mock1.type = "image/jpg"; mock2.type = "image/jpg"; mock3.type = "image/jpg"; dropzone.on("thumbnail", function() { return console.log("HII"); }); ct_file = ct_callback = null; dropzone.createThumbnail = function(file, callback) { ct_file = file; return ct_callback = callback; }; sinon.spy(dropzone, "createThumbnail"); dropzone.addFile(mock1); dropzone.addFile(mock2); dropzone.addFile(mock3); dropzone.files.length.should.eql(3); return setTimeout((function() { dropzone.createThumbnail.callCount.should.eql(1); mock1.should.equal(ct_file); ct_callback(); dropzone.createThumbnail.callCount.should.eql(2); mock2.should.equal(ct_file); ct_callback(); dropzone.createThumbnail.callCount.should.eql(3); mock3.should.equal(ct_file); return done(); }), 10); }); return describe("when file is SVG", function() { return it("should use the SVG image itself", function(done) { var blob, createBlob; createBlob = function(data, type) { var BlobBuilder, builder, e; try { return new Blob([data], { type: type }); } catch (_error) { e = _error; BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder; builder = new BlobBuilder(); builder.append(data.buffer || data); return builder.getBlob(type); } }; blob = createBlob('foo', 'image/svg+xml'); dropzone.on("thumbnail", function(file, dataURI) { var fileReader; file.should.equal(blob); fileReader = new FileReader; fileReader.onload = function() { fileReader.result.should.equal(dataURI); return done(); }; return fileReader.readAsDataURL(file); }); return dropzone.createThumbnail(blob); }); }); }); }); describe("enqueueFile()", function() { it("should be wrapped by enqueueFiles()", function() { var mock1, mock2, mock3; sinon.stub(dropzone, "enqueueFile"); mock1 = getMockFile(); mock2 = getMockFile(); mock3 = getMockFile(); dropzone.enqueueFiles([mock1, mock2, mock3]); dropzone.enqueueFile.callCount.should.equal(3); dropzone.enqueueFile.args[0][0].should.equal(mock1); dropzone.enqueueFile.args[1][0].should.equal(mock2); return dropzone.enqueueFile.args[2][0].should.equal(mock3); }); it("should fail if the file has already been processed", function() { mockFile.status = Dropzone.ERROR; expect((function() { return dropzone.enqueueFile(mockFile); })).to["throw"]("This file can't be queued because it has already been processed or was rejected."); mockFile.status = Dropzone.COMPLETE; expect((function() { return dropzone.enqueueFile(mockFile); })).to["throw"]("This file can't be queued because it has already been processed or was rejected."); mockFile.status = Dropzone.UPLOADING; return expect((function() { return dropzone.enqueueFile(mockFile); })).to["throw"]("This file can't be queued because it has already been processed or was rejected."); }); return it("should set the status to QUEUED and call processQueue asynchronously if everything's ok", function(done) { mockFile.status = Dropzone.ADDED; sinon.stub(dropzone, "processQueue"); dropzone.processQueue.callCount.should.equal(0); dropzone.enqueueFile(mockFile); mockFile.status.should.equal(Dropzone.QUEUED); dropzone.processQueue.callCount.should.equal(0); return setTimeout(function() { dropzone.processQueue.callCount.should.equal(1); return done(); }, 10); }); }); describe("uploadFiles()", function() { var requests; requests = null; beforeEach(function() { requests = []; return xhr.onCreate = function(xhr) { return requests.push(xhr); }; }); afterEach(function() { return xhr.restore(); }); it("should be wrapped by uploadFile()", function() { sinon.stub(dropzone, "uploadFiles"); dropzone.uploadFile(mockFile); dropzone.uploadFiles.callCount.should.equal(1); return dropzone.uploadFiles.calledWith([mockFile]).should.be.ok; }); it("should use url options if strings", function(done) { dropzone.addFile(mockFile); return setTimeout(function() { expect(requests.length).to.equal(1); expect(requests[0].url).to.equal(dropzone.options.url); expect(requests[0].method).to.equal(dropzone.options.method); return done(); }, 10); }); it("should call url options if functions", function(done) { var method, url; method = "PUT"; url = "/custom/upload/url"; dropzone.options.method = sinon.stub().returns(method); dropzone.options.url = sinon.stub().returns(url); dropzone.addFile(mockFile); return setTimeout(function() { dropzone.options.method.callCount.should.equal(1); dropzone.options.url.callCount.should.equal(1); sinon.assert.calledWith(dropzone.options.method, [mockFile]); sinon.assert.calledWith(dropzone.options.url, [mockFile]); expect(requests.length).to.equal(1); expect(requests[0].url).to.equal(url); expect(requests[0].method).to.equal(method); return done(); }, 10); }); it("should ignore the onreadystate callback if readyState != 4", function(done) { dropzone.addFile(mockFile); return setTimeout(function() { mockFile.status.should.eql(Dropzone.UPLOADING); requests[0].status = 200; requests[0].readyState = 3; requests[0].onload(); mockFile.status.should.eql(Dropzone.UPLOADING); requests[0].readyState = 4; requests[0].onload(); mockFile.status.should.eql(Dropzone.SUCCESS); return done(); }, 10); }); it("should emit error and errormultiple when response was not OK", function(done) { var complete, completemultiple, error, errormultiple; dropzone.options.uploadMultiple = true; error = false; errormultiple = false; complete = false; completemultiple = false; dropzone.on("error", function() { return error = true; }); dropzone.on("errormultiple", function() { return errormultiple = true; }); dropzone.on("complete", function() { return complete = true; }); dropzone.on("completemultiple", function() { return completemultiple = true; }); dropzone.addFile(mockFile); return setTimeout(function() { mockFile.status.should.eql(Dropzone.UPLOADING); requests[0].status = 400; requests[0].readyState = 4; requests[0].onload(); expect((((true === error && error === errormultiple) && errormultiple === complete) && complete === completemultiple)).to.be.ok; return done(); }, 10); }); it("should include hidden files in the form and unchecked checkboxes and radiobuttons should be excluded", function(done) { var element, formData, mock1; element = Dropzone.createElement("<form action=\"/the/url\">\n <input type=\"hidden\" name=\"test\" value=\"hidden\" />\n <input type=\"checkbox\" name=\"unchecked\" value=\"1\" />\n <input type=\"checkbox\" name=\"checked\" value=\"value1\" checked=\"checked\" />\n <input type=\"radio\" value=\"radiovalue1\" name=\"radio1\" />\n <input type=\"radio\" value=\"radiovalue2\" name=\"radio1\" checked=\"checked\" />\n <select name=\"select\"><option value=\"1\">1</option><option value=\"2\" selected>2</option></select>\n</form>"); dropzone = new Dropzone(element, { url: "/the/url" }); formData = null; dropzone.on("sending", function(file, xhr, tformData) { formData = tformData; return sinon.spy(tformData, "append"); }); mock1 = getMockFile(); dropzone.addFile(mock1); return setTimeout(function() { formData.append.callCount.should.equal(5); formData.append.args[0][0].should.eql("test"); formData.append.args[0][1].should.eql("hidden"); formData.append.args[1][0].should.eql("checked"); formData.append.args[1][1].should.eql("value1"); formData.append.args[2][0].should.eql("radio1"); formData.append.args[2][1].should.eql("radiovalue2"); formData.append.args[3][0].should.eql("select"); formData.append.args[3][1].should.eql("2"); formData.append.args[4][0].should.eql("file"); formData.append.args[4][1].should.equal(mock1); return done(); }, 10); }); it("should all values of a select that has the multiple attribute", function(done) { var element, formData, mock1; element = Dropzone.createElement("<form action=\"/the/url\">\n <select name=\"select\" multiple>\n <option value=\"value1\">1</option>\n <option value=\"value2\" selected>2</option>\n <option value=\"value3\">3</option>\n <option value=\"value4\" selected>4</option>\n </select>\n</form>"); dropzone = new Dropzone(element, { url: "/the/url" }); formData = null; dropzone.on("sending", function(file, xhr, tformData) { formData = tformData; return sinon.spy(tformData, "append"); }); mock1 = getMockFile(); dropzone.addFile(mock1); return setTimeout(function() { formData.append.callCount.should.equal(3); formData.append.args[0][0].should.eql("select"); formData.append.args[0][1].should.eql("value2"); formData.append.args[1][0].should.eql("select"); formData.append.args[1][1].should.eql("value4"); formData.append.args[2][0].should.eql("file"); formData.append.args[2][1].should.equal(mock1); return done(); }, 10); }); describe("settings()", function() { it("should correctly set `withCredentials` on the xhr object", function() { dropzone.uploadFile(mockFile); requests.length.should.eql(1); requests[0].withCredentials.should.eql(false); dropzone.options.withCredentials = true; dropzone.uploadFile(mockFile); requests.length.should.eql(2); return requests[1].withCredentials.should.eql(true); }); it("should correctly set headers on the xhr object", function() { dropzone.options.headers = { "Foo-Header": "foobar" }; dropzone.uploadFile(mockFile); requests[0].requestHeaders["Foo-Header"].should.eql('foobar'); return (requests[0].requestHeaders["Accept"] === void 0).should.be["false"]; }); it("should correctly override headers on the xhr object", function() { dropzone.options.overrideDefaultHeaders = true; dropzone.options.headers = { "Foo-Header": "foobar" }; dropzone.uploadFile(mockFile); return (requests[0].requestHeaders["Accept"] === void 0).should.be["true"]; }); it("should properly use the paramName without [n] as file upload if uploadMultiple is false", function(done) { var formData, mock1, mock2, sendingCount; dropzone.options.uploadMultiple = false; dropzone.options.paramName = "myName"; formData = []; sendingCount = 0; dropzone.on("sending", function(files, xhr, tformData) { sendingCount++; formData.push(tformData); return sinon.spy(tformData, "append"); }); mock1 = getMockFile(); mock2 = getMockFile(); dropzone.addFile(mock1); dropzone.addFile(mock2); return setTimeout(function() { sendingCount.should.equal(2); formData.length.should.equal(2); formData[0].append.callCount.should.equal(1); formData[1].append.callCount.should.equal(1); formData[0].append.args[0][0].should.eql("myName"); formData[0].append.args[0][0].should.eql("myName"); return done(); }, 10); }); return it("should properly use the paramName with [n] as file upload if uploadMultiple is true", function(done) { var formData, mock1, mock2, sendingCount, sendingMultipleCount; dropzone.options.uploadMultiple = true; dropzone.options.paramName = "myName"; formData = null; sendingMultipleCount = 0; sendingCount = 0; dropzone.on("sending", function(file, xhr, tformData) { return sendingCount++; }); dropzone.on("sendingmultiple", function(files, xhr, tformData) { sendingMultipleCount++; formData = tformData; return sinon.spy(tformData, "append"); }); mock1 = getMockFile(); mock2 = getMockFile(); dropzone.addFile(mock1); dropzone.addFile(mock2); return setTimeout(function() { sendingCount.should.equal(2); sendingMultipleCount.should.equal(1); dropzone.uploadFiles([mock1, mock2]); formData.append.callCount.should.equal(2); formData.append.args[0][0].should.eql("myName[0]"); formData.append.args[1][0].should.eql("myName[1]"); return done(); }, 10); }); }); return describe("should properly set status of file", function() { return it("should correctly set `withCredentials` on the xhr object", function(done) { dropzone.addFile(mockFile); return setTimeout(function() { mockFile.status.should.eql(Dropzone.UPLOADING); requests.length.should.equal(1); requests[0].status = 400; requests[0].readyState = 4; requests[0].onload(); mockFile.status.should.eql(Dropzone.ERROR); mockFile = getMockFile(); dropzone.addFile(mockFile); return setTimeout(function() { mockFile.status.should.eql(Dropzone.UPLOADING); requests.length.should.equal(2); requests[1].status = 200; requests[1].readyState = 4; requests[1].onload(); mockFile.status.should.eql(Dropzone.SUCCESS); return done(); }, 10); }, 10); }); }); }); return describe("complete file", function() { return it("should properly emit the queuecomplete event when the complete queue is finished", function(done) { var completedFiles, mock1, mock2, mock3; mock1 = getMockFile(); mock2 = getMockFile(); mock3 = getMockFile(); mock1.status = Dropzone.ADDED; mock2.status = Dropzone.ADDED; mock3.status = Dropzone.ADDED; mock1.name = "mock1"; mock2.name = "mock2"; mock3.name = "mock3"; dropzone.uploadFiles = function(files) { return setTimeout(((function(_this) { return function() { return _this._finished(files, null, null); }; })(this)), 1); }; completedFiles = 0; dropzone.on("complete", function(file) { return completedFiles++; }); dropzone.on("queuecomplete", function() { completedFiles.should.equal(3); return done(); }); dropzone.addFile(mock1); dropzone.addFile(mock2); return dropzone.addFile(mock3); }); }); }); }); }).call(this);
webfatorial/dropzone
test/test.js
JavaScript
mit
82,314
chrome.app.runtime.onLaunched.addListener(function(){ chrome.app.window.create('index.html', { bounds: { width: Math.round(window.screen.availWidth - 100), height: Math.round(window.screen.availHeight - 100) } }); });
pioul/Minimalist-Markdown-Editor-for-Chrome
src/js/background.js
JavaScript
mit
230
"use strict"; /* ======== A Handy Little Nodeunit Reference ======== https://github.com/caolan/nodeunit Test methods: test.expect(numAssertions) test.done() Test assertions: test.ok(value, [message]) test.equal(actual, expected, [message]) test.notEqual(actual, expected, [message]) test.deepEqual(actual, expected, [message]) test.notDeepEqual(actual, expected, [message]) test.strictEqual(actual, expected, [message]) test.notStrictEqual(actual, expected, [message]) test.throws(block, [error], [message]) test.doesNotThrow(block, [error], [message]) test.ifError(value) */ var task = require("../tasks/tar.gz"), fs = require("fs"); exports["targz"] = { setUp: function(done) { // setup here done(); }, "targz sqlite3": function(test) { test.expect(1); var actual; actual = fs.statSync("tmp/node_sqlite3.node"); test.equal(actual.size, 831488); test.done(); } };
bendi/grunt-tar.gz
test/tar.gz_test.js
JavaScript
mit
1,003
if (Zepto.ajax.restore) { Zepto.ajax.restore(); } sinon.stub(Zepto, "ajax") .yieldsTo("success", { responseStatus : 200, responseDetails : null, responseData : { feed: { link : "http://github.com", title : "GitHub Public Timeline", entries : [ { title : "Croaky signed up", link : "http://github.com/Croaky/openbeerdatabase", author : "", publishedDate : "Thu, 24 Nov 2011 19:00:00 -0600", content : "\u003cstrong\u003eCroaky\u003c/strong\u003e signed up for GitHub.", contentSnippet : "Croaky signed up for GitHub.", categories : [] } ] } } });
tristandunn/reading
spec/javascripts/fixtures/github.com.js
JavaScript
mit
753
var baseURL; $.validator.addMethod("alfanumerico", function(value, element) { return this.optional(element) || /^[-._a-z0-9\- ]+$/i.test(value); }, "Este campo es alfanumerico."); $("#frmGuardaTipoDocumento").validate({ rules : { descripcion : "required", codigo : {required:true,alfanumerico:true}, }, messages : { descripcion : "Ingrese este campo.", codigo : {required:"Ingrese este campo.",alfanumerico:"Este campo es alfanumerico."}, }, submitHandler : function(form) { $.ajax(form.action, { async : false, type : "POST", data : $(form).serialize(), success : function(contenido) { //alert("contenido :"+ contenido); if(contenido=="error"){ var mensaje="Este tipo de documento ya ha sido registrado"; alert(mensaje); } else{ baseURL = $("#baseURL").val(); $.get(baseURL + "mantenimientoInterno/listarTiposDocumentos?info="+contenido, function(respuesta) { $("#contenidoPrincipal").html(respuesta); $("#title-page").html("Mantenimiento Tipo Entidad Documento - Listado"); }); } } }); } }); function cancelarTipoDocumento(){ var baseURL; baseURL = $("#baseURL").val(); $("#contenidoPrincipal").html("Cargando . . ."); $.get(baseURL + "mantenimientoInterno/listarTiposDocumentos", function(respuesta) { $("#contenidoPrincipal").html(respuesta); $("#title-page").html("Mantenimiento Tipo Entidad Documento - Listado"); }); }
javiervilcapaza/inst
inst/src/main/webapp/resources/scripts/mantenimientoInterno/tipoDocumentoFormulario.js
JavaScript
mit
1,492