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
//>>built define("dojox/atom/widget/nls/bg/PeopleEditor",{add:"\u0414\u043e\u0431\u0430\u0432\u0438",addAuthor:"\u0414\u043e\u0431\u0430\u0432\u0438 \u0430\u0432\u0442\u043e\u0440",addContributor:"\u0414\u043e\u0431\u0430\u0432\u0438 \u0441\u044a\u0442\u0440\u0443\u0434\u043d\u0438\u043a"}); //# sourceMappingURL=PeopleEditor.js.map
Caspar12/zh.sw
zh.web.site.admin/src/main/resources/static/js/dojo/dojox/atom/widget/nls/bg/PeopleEditor.js
JavaScript
apache-2.0
333
//carrythenews //https://en.wikipedia.org/wiki/All_the_Young_Dudes var Twitter = require('twitter'); var express = require('express'); var app = express(); var server = require('http').createServer(app); var io = require('socket.io')(server); var port = process.env.PORT || 3000; // Twitter client var client = new Twitter({ consumer_key: process.env.TWITTER_CONSUMER_KEY, consumer_secret: process.env.TWITTER_CONSUMER_SECRET, access_token_key: process.env.TWITTER_ACCESS_TOKEN_KEY, access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET, }); // Tweet stream client.stream('statuses/filter', {track: 'gun control, guns, no more guns'}, function(stream) { stream.on('data', function(tweet) { io.sockets.emit('new message', { username: 'newsguy', message: tweet.text }); //console.log(tweet.text); }); stream.on('error', function(error) { throw error; }); }); // Server server.listen(port, function () { console.log('Server listening at port %d', port); }); // Routing app.use(express.static(__dirname + '/public')); // Socket connection io.on('connection', function (socket) { console.log('socket connection'); });
adjavaherian/carrythenews
index.js
JavaScript
apache-2.0
1,191
/** * @license Copyright 2017 Google Inc. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ 'use strict'; /** * @fileoverview Ensures `<video>` elements have audio descriptions. * See base class in axe-audit.js for audit() implementation. */ const AxeAudit = require('./axe-audit.js'); const i18n = require('../../lib/i18n/i18n.js'); const UIStrings = { /** Title of an accesibility audit that evaluates if all video elements have child track elements that contain a description of the video content. This title is descriptive of the successful state and is shown to users when no user action is required. */ title: '`<video>` elements contain a `<track>` element with `[kind="description"]`', /** Title of an accesibility audit that evaluates if all video elements have child track elements that contain a description of the video content. This title is descriptive of the failing state and is shown to users when there is a failure that needs to be addressed. */ failureTitle: '`<video>` elements do not contain a `<track>` element with ' + '`[kind="description"]`.', /** Description of a Lighthouse audit that tells the user *why* they should try to pass. This is displayed after a user expands the section to see more. No character length limits. 'Learn More' becomes link text to additional documentation. */ description: 'Audio descriptions provide relevant information for videos that dialogue ' + 'cannot, such as facial expressions and scenes. ' + '[Learn more](https://web.dev/video-description/).', }; const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); class VideoDescription extends AxeAudit { /** * @return {LH.Audit.Meta} */ static get meta() { return { id: 'video-description', title: str_(UIStrings.title), failureTitle: str_(UIStrings.failureTitle), description: str_(UIStrings.description), requiredArtifacts: ['Accessibility'], }; } } module.exports = VideoDescription; module.exports.UIStrings = UIStrings;
wardpeet/lighthouse
lighthouse-core/audits/accessibility/video-description.js
JavaScript
apache-2.0
2,533
console.assert(false);
csgordon/SJS
sjsc/src/test/resources/testinput/endtoend/consoleassert1.js
JavaScript
apache-2.0
23
var searchData= [ ['l',['L',['../group__sim.html#af7412e8311468eed8eb02dcdc4d239dd',1,'sim_uid_t']]], ['l_5fpos',['l_pos',['../group__SHELL.html#a9fba40e48bcf1d2c0e391311acce12c9',1,'shell_context_struct']]], ['lastcommand',['lastCommand',['../group__dspi__driver.html#a606dff7a7dd4d18f4be97656f0102d59',1,'_dspi_master_handle::lastCommand()'],['../group__dspi__dma__driver.html#a8432d0950c952added32554a881b387c',1,'_dspi_master_dma_handle::lastCommand()'],['../group__dspi__edma__driver.html#a5273a137fd07ef8e8ff7be54ac7bd9e9',1,'_dspi_master_edma_handle::lastCommand()']]], ['lastscktopcsdelayinnanosec',['lastSckToPcsDelayInNanoSec',['../group__dspi__driver.html#af6e22013a735cf762e671973afbed487',1,'dspi_master_ctar_config_t']]], ['latency',['latency',['../group__sdramc.html#afc3c673532c14837867d7cabecd97b03',1,'sdramc_blockctl_config_t']]], ['length',['length',['../group__enet.html#a8f1b6c5523159bc56b37bfd98b378ab6',1,'enet_rx_bd_struct_t::length()'],['../group__enet.html#a7f6f448911920d9e7d9ac98f83472e1e',1,'enet_tx_bd_struct_t::length()'],['../group__flexcan__driver.html#a86c748c660b5a447d73b601d65464d68',1,'flexcan_frame_t::length()']]], ['level',['level',['../group__ftm.html#abbbf6e5fff8c24c718a43f6b7049806f',1,'ftm_chnl_pwm_signal_param_t::level()'],['../group__tpm.html#a5b49674b66d63f0c21ba27c41a4a2eaf',1,'tpm_chnl_pwm_signal_param_t::level()']]], ['line',['line',['../group__SHELL.html#a04e8c90f93e096fa50e3c8ae52055811',1,'shell_context_struct']]], ['loadvaluemode',['loadValueMode',['../group__pdb.html#a56a87449e519effe1fab11309aacf551',1,'pdb_config_t']]], ['location',['location',['../group__sdramc.html#adb47879cacae9b6ecdccee03c734da4b',1,'sdramc_blockctl_config_t']]], ['lockregister',['lockRegister',['../group__port.html#a9de84dc6aea5cd99f1e972d3b724de49',1,'port_pin_config_t']]], ['longsamplemode',['longSampleMode',['../group__adc16.html#a10104591e9e0320fb759d2bc5a5513a4',1,'adc16_config_t']]], ['lowcount1',['lowCount1',['../group__cmt.html#a202b0a2ad3e79343d3387ad56c1930c8',1,'cmt_modulate_config_t']]], ['lowcount2',['lowCount2',['../group__cmt.html#aa6145ac2362d2ea399bf9fbc4b843f19',1,'cmt_modulate_config_t']]] ];
scottdarch/Noer
FRDMK66NoEr/SDK_2.1_FRDM-K66F-GCC-Full/docs/Kinetis SDK API Reference Manual MK66F18_v2.1.0/search/variables_6c.js
JavaScript
apache-2.0
2,189
// This file has been autogenerated. var profile = require('../../../lib/util/profile'); exports.getMockedProfile = function () { var newProfile = new profile.Profile(); newProfile.addSubscription(new profile.Subscription({ id: 'c9cbd920-c00c-427c-852b-8aaf38badaeb', name: 'Azure SDK Powershell Test', user: { name: 'user@domain.example', type: 'user' }, tenantId: '72f988bf-86f1-41af-91ab-2d7cd011db47', registeredProviders: ['website'], _eventsCount: '1', isDefault: true }, newProfile.environments['AzureCloud'])); return newProfile; }; exports.setEnvironment = function() { process.env['AZURE_STORAGE_CONNECTION_STRING'] = 'DefaultEndpointsProtocol=https;AccountName=xplat;AccountKey=null'; }; exports.scopes = [[function (nock) { var result = nock('http://xplat.blob.core.windows.net:443') .put('/testblobcopysource/toCopy?comp=snapshot') .reply(201, "", { 'transfer-encoding': 'chunked', 'last-modified': 'Thu, 19 May 2016 10:03:29 GMT', etag: '"0x8D37FCCD42C9928"', server: 'Windows-Azure-Blob/1.0 Microsoft-HTTPAPI/2.0', 'x-ms-request-id': '6d3e8fc9-0001-003b-58b5-b1d459000000', 'x-ms-version': '2015-04-05', 'x-ms-snapshot': '2016-05-19T10:03:39.7172935Z', date: 'Thu, 19 May 2016 10:03:39 GMT', connection: 'close' }); return result; }, function (nock) { var result = nock('https://xplat.blob.core.windows.net:443') .put('/testblobcopysource/toCopy?comp=snapshot') .reply(201, "", { 'transfer-encoding': 'chunked', 'last-modified': 'Thu, 19 May 2016 10:03:29 GMT', etag: '"0x8D37FCCD42C9928"', server: 'Windows-Azure-Blob/1.0 Microsoft-HTTPAPI/2.0', 'x-ms-request-id': '6d3e8fc9-0001-003b-58b5-b1d459000000', 'x-ms-version': '2015-04-05', 'x-ms-snapshot': '2016-05-19T10:03:39.7172935Z', date: 'Thu, 19 May 2016 10:03:39 GMT', connection: 'close' }); return result; }]];
msfcolombo/azure-xplat-cli
test/recordings/cli.storage.blob-tests/cli_storage_blob_copy_should_start_to_copy_the_blobs_snapshot_by_SAS_asynchronously.nock.js
JavaScript
apache-2.0
1,888
// slugify.js (function($){ if (!window.calli) { window.calli = {}; } window.calli.slugify = function(label) { if (!label) return label; if (label.lastIndexOf('\\') > 0) { // IE file input label = label.substring(label.lastIndexOf('\\') + 1); } var name = removeDiacritics(label); if (!name.match(/[a-z][A-Z]/)) { name = name.toLowerCase(); } return name.replace(/\s+/g, '+').replace(/[^\w\+\-\_\.\!\~\*\'\(\);\,\&\=\$\[\]]+/g,'_').replace(/^_+/,'').replace(/_+$/,''); }; function removeDiacritics(str) { for(var i=0; i<diacritics.length; i++) { str = str.replace(diacritics[i].letters, diacritics[i].base); } return str; } var diacritics = [ {'base':'A', 'letters':/[\u0041\u24B6\uFF21\u00C0\u00C1\u00C2\u1EA6\u1EA4\u1EAA\u1EA8\u00C3\u0100\u0102\u1EB0\u1EAE\u1EB4\u1EB2\u0226\u01E0\u00C4\u01DE\u1EA2\u00C5\u01FA\u01CD\u0200\u0202\u1EA0\u1EAC\u1EB6\u1E00\u0104\u023A\u2C6F]/g}, {'base':'AA','letters':/[\uA732]/g}, {'base':'AE','letters':/[\u00C6\u01FC\u01E2]/g}, {'base':'AO','letters':/[\uA734]/g}, {'base':'AU','letters':/[\uA736]/g}, {'base':'AV','letters':/[\uA738\uA73A]/g}, {'base':'AY','letters':/[\uA73C]/g}, {'base':'B', 'letters':/[\u0042\u24B7\uFF22\u1E02\u1E04\u1E06\u0243\u0182\u0181]/g}, {'base':'C', 'letters':/[\u0043\u24B8\uFF23\u0106\u0108\u010A\u010C\u00C7\u1E08\u0187\u023B\uA73E]/g}, {'base':'D', 'letters':/[\u0044\u24B9\uFF24\u1E0A\u010E\u1E0C\u1E10\u1E12\u1E0E\u0110\u018B\u018A\u0189\uA779]/g}, {'base':'DZ','letters':/[\u01F1\u01C4]/g}, {'base':'Dz','letters':/[\u01F2\u01C5]/g}, {'base':'E', 'letters':/[\u0045\u24BA\uFF25\u00C8\u00C9\u00CA\u1EC0\u1EBE\u1EC4\u1EC2\u1EBC\u0112\u1E14\u1E16\u0114\u0116\u00CB\u1EBA\u011A\u0204\u0206\u1EB8\u1EC6\u0228\u1E1C\u0118\u1E18\u1E1A\u0190\u018E]/g}, {'base':'F', 'letters':/[\u0046\u24BB\uFF26\u1E1E\u0191\uA77B]/g}, {'base':'G', 'letters':/[\u0047\u24BC\uFF27\u01F4\u011C\u1E20\u011E\u0120\u01E6\u0122\u01E4\u0193\uA7A0\uA77D\uA77E]/g}, {'base':'H', 'letters':/[\u0048\u24BD\uFF28\u0124\u1E22\u1E26\u021E\u1E24\u1E28\u1E2A\u0126\u2C67\u2C75\uA78D]/g}, {'base':'I', 'letters':/[\u0049\u24BE\uFF29\u00CC\u00CD\u00CE\u0128\u012A\u012C\u0130\u00CF\u1E2E\u1EC8\u01CF\u0208\u020A\u1ECA\u012E\u1E2C\u0197]/g}, {'base':'J', 'letters':/[\u004A\u24BF\uFF2A\u0134\u0248]/g}, {'base':'K', 'letters':/[\u004B\u24C0\uFF2B\u1E30\u01E8\u1E32\u0136\u1E34\u0198\u2C69\uA740\uA742\uA744\uA7A2]/g}, {'base':'L', 'letters':/[\u004C\u24C1\uFF2C\u013F\u0139\u013D\u1E36\u1E38\u013B\u1E3C\u1E3A\u0141\u023D\u2C62\u2C60\uA748\uA746\uA780]/g}, {'base':'LJ','letters':/[\u01C7]/g}, {'base':'Lj','letters':/[\u01C8]/g}, {'base':'M', 'letters':/[\u004D\u24C2\uFF2D\u1E3E\u1E40\u1E42\u2C6E\u019C]/g}, {'base':'N', 'letters':/[\u004E\u24C3\uFF2E\u01F8\u0143\u00D1\u1E44\u0147\u1E46\u0145\u1E4A\u1E48\u0220\u019D\uA790\uA7A4]/g}, {'base':'NJ','letters':/[\u01CA]/g}, {'base':'Nj','letters':/[\u01CB]/g}, {'base':'O', 'letters':/[\u004F\u24C4\uFF2F\u00D2\u00D3\u00D4\u1ED2\u1ED0\u1ED6\u1ED4\u00D5\u1E4C\u022C\u1E4E\u014C\u1E50\u1E52\u014E\u022E\u0230\u00D6\u022A\u1ECE\u0150\u01D1\u020C\u020E\u01A0\u1EDC\u1EDA\u1EE0\u1EDE\u1EE2\u1ECC\u1ED8\u01EA\u01EC\u00D8\u01FE\u0186\u019F\uA74A\uA74C]/g}, {'base':'OI','letters':/[\u01A2]/g}, {'base':'OO','letters':/[\uA74E]/g}, {'base':'OU','letters':/[\u0222]/g}, {'base':'P', 'letters':/[\u0050\u24C5\uFF30\u1E54\u1E56\u01A4\u2C63\uA750\uA752\uA754]/g}, {'base':'Q', 'letters':/[\u0051\u24C6\uFF31\uA756\uA758\u024A]/g}, {'base':'R', 'letters':/[\u0052\u24C7\uFF32\u0154\u1E58\u0158\u0210\u0212\u1E5A\u1E5C\u0156\u1E5E\u024C\u2C64\uA75A\uA7A6\uA782]/g}, {'base':'S', 'letters':/[\u0053\u24C8\uFF33\u1E9E\u015A\u1E64\u015C\u1E60\u0160\u1E66\u1E62\u1E68\u0218\u015E\u2C7E\uA7A8\uA784]/g}, {'base':'T', 'letters':/[\u0054\u24C9\uFF34\u1E6A\u0164\u1E6C\u021A\u0162\u1E70\u1E6E\u0166\u01AC\u01AE\u023E\uA786]/g}, {'base':'TZ','letters':/[\uA728]/g}, {'base':'U', 'letters':/[\u0055\u24CA\uFF35\u00D9\u00DA\u00DB\u0168\u1E78\u016A\u1E7A\u016C\u00DC\u01DB\u01D7\u01D5\u01D9\u1EE6\u016E\u0170\u01D3\u0214\u0216\u01AF\u1EEA\u1EE8\u1EEE\u1EEC\u1EF0\u1EE4\u1E72\u0172\u1E76\u1E74\u0244]/g}, {'base':'V', 'letters':/[\u0056\u24CB\uFF36\u1E7C\u1E7E\u01B2\uA75E\u0245]/g}, {'base':'VY','letters':/[\uA760]/g}, {'base':'W', 'letters':/[\u0057\u24CC\uFF37\u1E80\u1E82\u0174\u1E86\u1E84\u1E88\u2C72]/g}, {'base':'X', 'letters':/[\u0058\u24CD\uFF38\u1E8A\u1E8C]/g}, {'base':'Y', 'letters':/[\u0059\u24CE\uFF39\u1EF2\u00DD\u0176\u1EF8\u0232\u1E8E\u0178\u1EF6\u1EF4\u01B3\u024E\u1EFE]/g}, {'base':'Z', 'letters':/[\u005A\u24CF\uFF3A\u0179\u1E90\u017B\u017D\u1E92\u1E94\u01B5\u0224\u2C7F\u2C6B\uA762]/g}, {'base':'a', 'letters':/[\u0061\u24D0\uFF41\u1E9A\u00E0\u00E1\u00E2\u1EA7\u1EA5\u1EAB\u1EA9\u00E3\u0101\u0103\u1EB1\u1EAF\u1EB5\u1EB3\u0227\u01E1\u00E4\u01DF\u1EA3\u00E5\u01FB\u01CE\u0201\u0203\u1EA1\u1EAD\u1EB7\u1E01\u0105\u2C65\u0250]/g}, {'base':'aa','letters':/[\uA733]/g}, {'base':'ae','letters':/[\u00E6\u01FD\u01E3]/g}, {'base':'ao','letters':/[\uA735]/g}, {'base':'au','letters':/[\uA737]/g}, {'base':'av','letters':/[\uA739\uA73B]/g}, {'base':'ay','letters':/[\uA73D]/g}, {'base':'b', 'letters':/[\u0062\u24D1\uFF42\u1E03\u1E05\u1E07\u0180\u0183\u0253]/g}, {'base':'c', 'letters':/[\u0063\u24D2\uFF43\u0107\u0109\u010B\u010D\u00E7\u1E09\u0188\u023C\uA73F\u2184]/g}, {'base':'d', 'letters':/[\u0064\u24D3\uFF44\u1E0B\u010F\u1E0D\u1E11\u1E13\u1E0F\u0111\u018C\u0256\u0257\uA77A]/g}, {'base':'dz','letters':/[\u01F3\u01C6]/g}, {'base':'e', 'letters':/[\u0065\u24D4\uFF45\u00E8\u00E9\u00EA\u1EC1\u1EBF\u1EC5\u1EC3\u1EBD\u0113\u1E15\u1E17\u0115\u0117\u00EB\u1EBB\u011B\u0205\u0207\u1EB9\u1EC7\u0229\u1E1D\u0119\u1E19\u1E1B\u0247\u025B\u01DD]/g}, {'base':'f', 'letters':/[\u0066\u24D5\uFF46\u1E1F\u0192\uA77C]/g}, {'base':'g', 'letters':/[\u0067\u24D6\uFF47\u01F5\u011D\u1E21\u011F\u0121\u01E7\u0123\u01E5\u0260\uA7A1\u1D79\uA77F]/g}, {'base':'h', 'letters':/[\u0068\u24D7\uFF48\u0125\u1E23\u1E27\u021F\u1E25\u1E29\u1E2B\u1E96\u0127\u2C68\u2C76\u0265]/g}, {'base':'hv','letters':/[\u0195]/g}, {'base':'i', 'letters':/[\u0069\u24D8\uFF49\u00EC\u00ED\u00EE\u0129\u012B\u012D\u00EF\u1E2F\u1EC9\u01D0\u0209\u020B\u1ECB\u012F\u1E2D\u0268\u0131]/g}, {'base':'j', 'letters':/[\u006A\u24D9\uFF4A\u0135\u01F0\u0249]/g}, {'base':'k', 'letters':/[\u006B\u24DA\uFF4B\u1E31\u01E9\u1E33\u0137\u1E35\u0199\u2C6A\uA741\uA743\uA745\uA7A3]/g}, {'base':'l', 'letters':/[\u006C\u24DB\uFF4C\u0140\u013A\u013E\u1E37\u1E39\u013C\u1E3D\u1E3B\u017F\u0142\u019A\u026B\u2C61\uA749\uA781\uA747]/g}, {'base':'lj','letters':/[\u01C9]/g}, {'base':'m', 'letters':/[\u006D\u24DC\uFF4D\u1E3F\u1E41\u1E43\u0271\u026F]/g}, {'base':'n', 'letters':/[\u006E\u24DD\uFF4E\u01F9\u0144\u00F1\u1E45\u0148\u1E47\u0146\u1E4B\u1E49\u019E\u0272\u0149\uA791\uA7A5]/g}, {'base':'nj','letters':/[\u01CC]/g}, {'base':'o', 'letters':/[\u006F\u24DE\uFF4F\u00F2\u00F3\u00F4\u1ED3\u1ED1\u1ED7\u1ED5\u00F5\u1E4D\u022D\u1E4F\u014D\u1E51\u1E53\u014F\u022F\u0231\u00F6\u022B\u1ECF\u0151\u01D2\u020D\u020F\u01A1\u1EDD\u1EDB\u1EE1\u1EDF\u1EE3\u1ECD\u1ED9\u01EB\u01ED\u00F8\u01FF\u0254\uA74B\uA74D\u0275]/g}, {'base':'oi','letters':/[\u01A3]/g}, {'base':'ou','letters':/[\u0223]/g}, {'base':'oo','letters':/[\uA74F]/g}, {'base':'p','letters':/[\u0070\u24DF\uFF50\u1E55\u1E57\u01A5\u1D7D\uA751\uA753\uA755]/g}, {'base':'q','letters':/[\u0071\u24E0\uFF51\u024B\uA757\uA759]/g}, {'base':'r','letters':/[\u0072\u24E1\uFF52\u0155\u1E59\u0159\u0211\u0213\u1E5B\u1E5D\u0157\u1E5F\u024D\u027D\uA75B\uA7A7\uA783]/g}, {'base':'s','letters':/[\u0073\u24E2\uFF53\u00DF\u015B\u1E65\u015D\u1E61\u0161\u1E67\u1E63\u1E69\u0219\u015F\u023F\uA7A9\uA785\u1E9B]/g}, {'base':'t','letters':/[\u0074\u24E3\uFF54\u1E6B\u1E97\u0165\u1E6D\u021B\u0163\u1E71\u1E6F\u0167\u01AD\u0288\u2C66\uA787]/g}, {'base':'tz','letters':/[\uA729]/g}, {'base':'u','letters':/[\u0075\u24E4\uFF55\u00F9\u00FA\u00FB\u0169\u1E79\u016B\u1E7B\u016D\u00FC\u01DC\u01D8\u01D6\u01DA\u1EE7\u016F\u0171\u01D4\u0215\u0217\u01B0\u1EEB\u1EE9\u1EEF\u1EED\u1EF1\u1EE5\u1E73\u0173\u1E77\u1E75\u0289]/g}, {'base':'v','letters':/[\u0076\u24E5\uFF56\u1E7D\u1E7F\u028B\uA75F\u028C]/g}, {'base':'vy','letters':/[\uA761]/g}, {'base':'w','letters':/[\u0077\u24E6\uFF57\u1E81\u1E83\u0175\u1E87\u1E85\u1E98\u1E89\u2C73]/g}, {'base':'x','letters':/[\u0078\u24E7\uFF58\u1E8B\u1E8D]/g}, {'base':'y','letters':/[\u0079\u24E8\uFF59\u1EF3\u00FD\u0177\u1EF9\u0233\u1E8F\u00FF\u1EF7\u1E99\u1EF5\u01B4\u024F\u1EFF]/g}, {'base':'z','letters':/[\u007A\u24E9\uFF5A\u017A\u1E91\u017C\u017E\u1E93\u1E95\u01B6\u0225\u0240\u2C6C\uA763]/g} ]; })(jQuery);
Thellmann/callimachus
webapp/scripts/slugify.js
JavaScript
apache-2.0
8,896
/****************************************************************************** * Copyright (c) 2016 Nicola Del Gobbo * Licensed under the Apache License, Version 2.0 (the "License"); you may not use * this file except in compliance with the License. You may obtain a copy of the * License at http://www.apache.org/licenses/LICENSE-2.0 * * THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED * WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, * MERCHANTABLITY OR NON-INFRINGEMENT. * * See the Apache Version 2.0 License for specific language governing permissions * and limitations under the License. * * Contributors - initial API implementation: * Nicola Del Gobbo <nicoladelgobbo@gmail.com> * Antonio D'Angelo <tonydangelo123@gmail.com> *****************************************************************************/ 'use strict'; var RESTfulError = require('../'); describe("Test restful-error utility class", function() { it("Should export function", function() { }); });
NickNaso/RESTfulError
test/restful-error.js
JavaScript
apache-2.0
1,135
$(function () { $('#li_search').addClass("active"); $('#CPH_body_table_articles tr:gt(1)').hover(function () { $(this).addClass('activeRow') }, function () { $(this).removeClass('activeRow') }); $('#CPH_body_table_articles tr:gt(1)').click(function (data) { var num = parseInt($(this).attr('id').replace(/\D+/g, "")); $(window.location).attr('href', 'ArticlePage.aspx?IdArticle=' + num.toString()); }); });
nesterione/blog-asp-webforms
BlogProject/BlogProject/Scripts/scriptSearch.js
JavaScript
apache-2.0
445
/* Copyright 2012 Mozilla Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; (function (root, factory) { if (typeof define === 'function' && define.amd) { define('pdfjs-web/pdf_history', ['exports'], factory); } else if (typeof exports !== 'undefined') { factory(exports); } else { factory((root.pdfjsWebPDFHistory = {})); } }(this, function (exports) { function PDFHistory(options) { this.linkService = options.linkService; this.initialized = false; this.initialDestination = null; this.initialBookmark = null; } PDFHistory.prototype = { /** * @param {string} fingerprint * @param {IPDFLinkService} linkService */ initialize: function pdfHistoryInitialize(fingerprint) { this.initialized = true; this.reInitialized = false; this.allowHashChange = true; this.historyUnlocked = true; this.isViewerInPresentationMode = false; this.previousHash = window.location.hash.substring(1); this.currentBookmark = ''; this.currentPage = 0; this.updatePreviousBookmark = false; this.previousBookmark = ''; this.previousPage = 0; this.nextHashParam = ''; this.fingerprint = fingerprint; this.currentUid = this.uid = 0; this.current = {}; var state = window.history.state; if (this._isStateObjectDefined(state)) { // This corresponds to navigating back to the document // from another page in the browser history. if (state.target.dest) { this.initialDestination = state.target.dest; } else { this.initialBookmark = state.target.hash; } this.currentUid = state.uid; this.uid = state.uid + 1; this.current = state.target; } else { // This corresponds to the loading of a new document. if (state && state.fingerprint && this.fingerprint !== state.fingerprint) { // Reinitialize the browsing history when a new document // is opened in the web viewer. this.reInitialized = true; } this._pushOrReplaceState({fingerprint: this.fingerprint}, true); } var self = this; window.addEventListener('popstate', function pdfHistoryPopstate(evt) { if (!self.historyUnlocked) { return; } if (evt.state) { // Move back/forward in the history. self._goTo(evt.state); return; } // If the state is not set, then the user tried to navigate to a // different hash by manually editing the URL and pressing Enter, or by // clicking on an in-page link (e.g. the "current view" link). // Save the current view state to the browser history. // Note: In Firefox, history.null could also be null after an in-page // navigation to the same URL, and without dispatching the popstate // event: https://bugzilla.mozilla.org/show_bug.cgi?id=1183881 if (self.uid === 0) { // Replace the previous state if it was not explicitly set. var previousParams = (self.previousHash && self.currentBookmark && self.previousHash !== self.currentBookmark) ? {hash: self.currentBookmark, page: self.currentPage} : {page: 1}; replacePreviousHistoryState(previousParams, function() { updateHistoryWithCurrentHash(); }); } else { updateHistoryWithCurrentHash(); } }, false); function updateHistoryWithCurrentHash() { self.previousHash = window.location.hash.slice(1); self._pushToHistory({hash: self.previousHash}, false, true); self._updatePreviousBookmark(); } function replacePreviousHistoryState(params, callback) { // To modify the previous history entry, the following happens: // 1. history.back() // 2. _pushToHistory, which calls history.replaceState( ... ) // 3. history.forward() // Because a navigation via the history API does not immediately update // the history state, the popstate event is used for synchronization. self.historyUnlocked = false; // Suppress the hashchange event to avoid side effects caused by // navigating back and forward. self.allowHashChange = false; window.addEventListener('popstate', rewriteHistoryAfterBack); history.back(); function rewriteHistoryAfterBack() { window.removeEventListener('popstate', rewriteHistoryAfterBack); window.addEventListener('popstate', rewriteHistoryAfterForward); self._pushToHistory(params, false, true); history.forward(); } function rewriteHistoryAfterForward() { window.removeEventListener('popstate', rewriteHistoryAfterForward); self.allowHashChange = true; self.historyUnlocked = true; callback(); } } function pdfHistoryBeforeUnload() { var previousParams = self._getPreviousParams(null, true); if (previousParams) { var replacePrevious = (!self.current.dest && self.current.hash !== self.previousHash); self._pushToHistory(previousParams, false, replacePrevious); self._updatePreviousBookmark(); } // Remove the event listener when navigating away from the document, // since 'beforeunload' prevents Firefox from caching the document. window.removeEventListener('beforeunload', pdfHistoryBeforeUnload, false); } window.addEventListener('beforeunload', pdfHistoryBeforeUnload, false); window.addEventListener('pageshow', function pdfHistoryPageShow(evt) { // If the entire viewer (including the PDF file) is cached in // the browser, we need to reattach the 'beforeunload' event listener // since the 'DOMContentLoaded' event is not fired on 'pageshow'. window.addEventListener('beforeunload', pdfHistoryBeforeUnload, false); }, false); window.addEventListener('presentationmodechanged', function(e) { self.isViewerInPresentationMode = !!e.detail.active; }); }, clearHistoryState: function pdfHistory_clearHistoryState() { this._pushOrReplaceState(null, true); }, _isStateObjectDefined: function pdfHistory_isStateObjectDefined(state) { return (state && state.uid >= 0 && state.fingerprint && this.fingerprint === state.fingerprint && state.target && state.target.hash) ? true : false; }, _pushOrReplaceState: function pdfHistory_pushOrReplaceState(stateObj, replace) { //#if CHROME // history.state.chromecomState is managed by chromecom.js. if (window.history.state && 'chromecomState' in window.history.state) { stateObj = stateObj || {}; stateObj.chromecomState = window.history.state.chromecomState; } //#endif if (replace) { //#if (GENERIC || CHROME) window.history.replaceState(stateObj, '', document.URL); //#else // window.history.replaceState(stateObj, ''); //#endif } else { //#if (GENERIC || CHROME) window.history.pushState(stateObj, '', document.URL); //#else // window.history.pushState(stateObj, ''); //#endif //#if CHROME // if (top === window) { // chrome.runtime.sendMessage('showPageAction'); // } //#endif } }, get isHashChangeUnlocked() { if (!this.initialized) { return true; } return this.allowHashChange; }, _updatePreviousBookmark: function pdfHistory_updatePreviousBookmark() { if (this.updatePreviousBookmark && this.currentBookmark && this.currentPage) { this.previousBookmark = this.currentBookmark; this.previousPage = this.currentPage; this.updatePreviousBookmark = false; } }, updateCurrentBookmark: function pdfHistoryUpdateCurrentBookmark(bookmark, pageNum) { if (this.initialized) { this.currentBookmark = bookmark.substring(1); this.currentPage = pageNum | 0; this._updatePreviousBookmark(); } }, updateNextHashParam: function pdfHistoryUpdateNextHashParam(param) { if (this.initialized) { this.nextHashParam = param; } }, push: function pdfHistoryPush(params, isInitialBookmark) { if (!(this.initialized && this.historyUnlocked)) { return; } if (params.dest && !params.hash) { params.hash = (this.current.hash && this.current.dest && this.current.dest === params.dest) ? this.current.hash : this.linkService.getDestinationHash(params.dest).split('#')[1]; } if (params.page) { params.page |= 0; } if (isInitialBookmark) { var target = window.history.state.target; if (!target) { // Invoked when the user specifies an initial bookmark, // thus setting initialBookmark, when the document is loaded. this._pushToHistory(params, false); this.previousHash = window.location.hash.substring(1); } this.updatePreviousBookmark = this.nextHashParam ? false : true; if (target) { // If the current document is reloaded, // avoid creating duplicate entries in the history. this._updatePreviousBookmark(); } return; } if (this.nextHashParam) { if (this.nextHashParam === params.hash) { this.nextHashParam = null; this.updatePreviousBookmark = true; return; } else { this.nextHashParam = null; } } if (params.hash) { if (this.current.hash) { if (this.current.hash !== params.hash) { this._pushToHistory(params, true); } else { if (!this.current.page && params.page) { this._pushToHistory(params, false, true); } this.updatePreviousBookmark = true; } } else { this._pushToHistory(params, true); } } else if (this.current.page && params.page && this.current.page !== params.page) { this._pushToHistory(params, true); } }, _getPreviousParams: function pdfHistory_getPreviousParams(onlyCheckPage, beforeUnload) { if (!(this.currentBookmark && this.currentPage)) { return null; } else if (this.updatePreviousBookmark) { this.updatePreviousBookmark = false; } if (this.uid > 0 && !(this.previousBookmark && this.previousPage)) { // Prevent the history from getting stuck in the current state, // effectively preventing the user from going back/forward in // the history. // // This happens if the current position in the document didn't change // when the history was previously updated. The reasons for this are // either: // 1. The current zoom value is such that the document does not need to, // or cannot, be scrolled to display the destination. // 2. The previous destination is broken, and doesn't actally point to a // position within the document. // (This is either due to a bad PDF generator, or the user making a // mistake when entering a destination in the hash parameters.) return null; } if ((!this.current.dest && !onlyCheckPage) || beforeUnload) { if (this.previousBookmark === this.currentBookmark) { return null; } } else if (this.current.page || onlyCheckPage) { if (this.previousPage === this.currentPage) { return null; } } else { return null; } var params = {hash: this.currentBookmark, page: this.currentPage}; if (this.isViewerInPresentationMode) { params.hash = null; } return params; }, _stateObj: function pdfHistory_stateObj(params) { return {fingerprint: this.fingerprint, uid: this.uid, target: params}; }, _pushToHistory: function pdfHistory_pushToHistory(params, addPrevious, overwrite) { if (!this.initialized) { return; } if (!params.hash && params.page) { params.hash = ('page=' + params.page); } if (addPrevious && !overwrite) { var previousParams = this._getPreviousParams(); if (previousParams) { var replacePrevious = (!this.current.dest && this.current.hash !== this.previousHash); this._pushToHistory(previousParams, false, replacePrevious); } } this._pushOrReplaceState(this._stateObj(params), (overwrite || this.uid === 0)); this.currentUid = this.uid++; this.current = params; this.updatePreviousBookmark = true; }, _goTo: function pdfHistory_goTo(state) { if (!(this.initialized && this.historyUnlocked && this._isStateObjectDefined(state))) { return; } if (!this.reInitialized && state.uid < this.currentUid) { var previousParams = this._getPreviousParams(true); if (previousParams) { this._pushToHistory(this.current, false); this._pushToHistory(previousParams, false); this.currentUid = state.uid; window.history.back(); return; } } this.historyUnlocked = false; if (state.target.dest) { this.linkService.navigateTo(state.target.dest); } else { this.linkService.setHash(state.target.hash); } this.currentUid = state.uid; if (state.uid > this.uid) { this.uid = state.uid; } this.current = state.target; this.updatePreviousBookmark = true; var currentHash = window.location.hash.substring(1); if (this.previousHash !== currentHash) { this.allowHashChange = false; } this.previousHash = currentHash; this.historyUnlocked = true; }, back: function pdfHistoryBack() { this.go(-1); }, forward: function pdfHistoryForward() { this.go(1); }, go: function pdfHistoryGo(direction) { if (this.initialized && this.historyUnlocked) { var state = window.history.state; if (direction === -1 && state && state.uid > 0) { window.history.back(); } else if (direction === 1 && state && state.uid < (this.uid - 1)) { window.history.forward(); } } } }; exports.PDFHistory = PDFHistory; }));
MASmedios/pdf.js
web/pdf_history.js
JavaScript
apache-2.0
15,400
exports.extensionFor = (format, service) => { if (format === 'mp3') { return 'mp3' } else if (format === 'ogg' || format === 'ogg_vorbis') { return 'ogg' } else if (format === 'pcm') { return service === 'gcp' ? 'wav' : 'pcm' } throw new Error(`No known file extension for "${format}" format`) }
eheikes/aws-tts
packages/tts-cli/lib/file-extensions.js
JavaScript
apache-2.0
318
'use strict'; describe('Service: GameService', function () { // load the service's module beforeEach(module('labrpgApp')); // defines a 4x4 board beforeEach( function () { var board = [ { id: 1, state: 'placed', card: { id: 1, shape: 'light', color: 'red', completed: false, reachable: false, visible: false, lab: { id: 'l1', ref: 'L1', name: 'light 1', description: 'LIGHT 1', theme: 'light', follows: [] } } }, { id: 2, state: 'placed', card: { id: 2, shape: 'light', color: 'red', completed: false, reachable: false, visible: false, lab: { id: 'l2', ref: 'L2', name: 'light 2', description: 'LIGHT 2', theme: 'light', follows: ['l1'] } } }, { id: 3, state: 'placed', card: { id: 3, shape: 'music', color: 'red', completed: false, reachable: false, visible: false, lab: { id: 'm1', ref: 'M1', name: 'music 1', description: 'MUSIC 1', theme: 'music', follows: ['l1'] } } }, { id: 4, state: 'placed', card: { id: 4, shape: 'music', color: 'red', completed: false, reachable: false, visible: false, lab: { id: 'm2', ref: 'M2', name: 'music 2', description: 'MUSIC 2', theme: 'music', follows: ['m1'] } } } ]; var boardDependency = { updateVisibleCells: function () { }, getCells: function () { return board; }, getCellAt: function (pos) { return board[pos]; }, deal: function () { return board; } }; module(function ($provide) { $provide.value('Boardservice', boardDependency); }); }); // instantiate service var Gameservice, Boardservice; beforeEach(inject(function (_Gameservice_, _Boardservice_) { Gameservice = _Gameservice_; Boardservice = _Boardservice_; })); describe('On reset', function () { it('has no completed cell', function () { Gameservice.reset(); var cell1 = Gameservice.getBoard()[0]; expect(cell1.state).toBe('placed'); Gameservice.reset(); }); it('has no selected cell', function () { Gameservice.reset(); expect(Gameservice.getSelectedCell()).toBeNull(); Gameservice.reset(); }); it('is not completed', function () { Gameservice.reset(); expect(Gameservice.isCompleted()).toBe(false); }); }); describe('When user clicks a cell', function () { it('becomes selected', function () { Gameservice.reset(); var cell1 = Gameservice.getBoard()[0]; expect(cell1.state).toBe('placed'); expect(Gameservice.getSelectedCell()).toBeNull(); Gameservice.playCell(cell1); expect(cell1.state).toBe('selected'); expect(Gameservice.getSelectedCell()).toBe(cell1); }); }); describe('When user clicks the completed checkbox', function () { it('card is switched', function () { Gameservice.reset(); var cells = Gameservice.getBoard(); var cell = cells[0]; var card = cell.card; expect(card.completed).toBe(false); Gameservice.completeCell(cell); expect(card.completed).toBe(true); Gameservice.completeCell(cell); expect(card.completed).toBe(false); }); }); describe('When user completed all cards', function () { it('game is completed', function () { Gameservice.reset(); expect(Gameservice.isCompleted()).toBe(false); var cells = Gameservice.getBoard(); cells[0].card.completed = true; cells[1].card.completed = true; cells[2].card.completed = true; cells[3].card.completed = true; expect(Gameservice.isCompleted()).toBe(true); }); }); });
cfalguiere/LabRPG
WebApp/test/spec/services/gameservice.js
JavaScript
apache-2.0
3,725
(function() { window.App.Views.Services = Backbone.View.extend({ initialize: function(params) { this.render(); return this; }, render: function() { $(this.el).html(HAML.services(this)); $('#app').html(this.el); $('nav#main-nav a').removeClass('active'); $('nav#main-nav a#services').addClass('active'); if ($('body').hasClass('fresh')) { $('body').removeClass('fresh'); $('.appear').each(function(i, obj) { $(obj).css('opacity', 0.0); return window.setTimeout(function() { return $(obj).animate({ "opacity": 1 }, 200); }, 100 * i + 1000); }); } else { $('section#canvas .appear').each(function(i, obj) { $(obj).css('opacity', 0.0); return window.setTimeout(function() { return $(obj).animate({ "opacity": 1 }, 200); }, 100 * i + 1000); }); } this.delegateEvents(); return this; } }); }).call(this);
svetli/tandem-auto.com
js/views/services.js
JavaScript
apache-2.0
937
var config = require('./config').getConfig(), logger = require('./logger'); var mailer; if(config.sendgrid.sendMail) { mailer = require('sendgrid')(config.sendgrid.api_user, config.sendgrid.api_key); } exports.send = function(mail, cb) { if(config.sendgrid.sendMail) { mailer.send(mail, function(err, info) { if(err) { logger.critical(err, ['mailer']); } if(typeof cb === 'function') cb(err, info); }); } else { console.log(mail); if(typeof cb === 'function') cb('', {}); } };
spaceshipsamurai/samurai-auth
server/config/mailer.js
JavaScript
apache-2.0
622
module.exports = function(config) { config.set({ browsers: ['Firefox'], frameworks: ['mocha', 'chai', 'fixture'], files: [ '../dist/build-i28n.js', '../test/integration/*.js', '../test/fixtures/*.html', ], preprocessors: { '../test/**/*.html' : ['html2js'], '../test/**/*.json' : ['json_fixtures'] }, jsonFixturesPreprocessor: { variableName: '__json__' }, plugins: [ 'karma-fixture', 'karma-json-fixtures-preprocessor', 'karma-html2js-preprocessor', 'karma-chai', 'karma-firefox-launcher', 'karma-mocha', ], }); };
zbraniecki/i28n
build/karma.conf.js
JavaScript
apache-2.0
636
'use strict'; var cache = {}; var loaders = [ { test: /\.js$/, loader: 'babel-loader' }, { test: /\.css$/, loader: 'style-loader!css-loader' } ]; var extensions = [ '', '.js', '.jsx', '.es6.js' ]; module.exports = [{ cache: cache, module: { loaders: loaders }, entry: { main: './src/Main.js', }, output: { path: './dist', filename: '[name].js' }, resolve: { extensions: extensions, root: [ __dirname, __dirname + '/src' ], alias: { } } }];
daiyam/js-framework-benchmark
vanillajs/webpack.config.js
JavaScript
apache-2.0
487
/* * Translated default messages for the jQuery validation plugin. * Locale: ZH (Chinese, 中文 (Zhōngwén), 汉语, 漢語) */ (function ($) { $.extend($.validator.messages, { required: "必填信息", remote: "请修正该信息", email: "请输入正确格式的电子邮件", url: "请输入合法的网址", date: "请输入合法的日期", dateISO: "请输入合法的日期 (ISO).", number: "请输入合法的数字", digits: "只能输入整数", creditcard: "请输入合法的信用卡号", equalTo: "请再次输入相同的值", accept: "请输入拥有合法后缀名的字符串", maxlength: $.validator.format("请输入一个长度最多是 {0} 的字符串"), minlength: $.validator.format("请输入一个长度最少是 {0} 的字符串"), rangelength: $.validator.format("请输入一个长度介于 {0} 和 {1} 之间的字符串"), range: $.validator.format("请输入一个介于 {0} 和 {1} 之间的值"), max: $.validator.format("请输入一个最大为 {0} 的值"), min: $.validator.format("请输入一个最小为 {0} 的值") }); }(jQuery)); jQuery.validator.addMethod("ip", function(value, element) { return this.optional(element) || (/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/.test(value) && (RegExp.$1 <256 && RegExp.$2<256 && RegExp.$3<256 && RegExp.$4<256)); }, "请输入合法的IP地址"); jQuery.validator.addMethod("abc",function(value, element) { return this.optional(element) || /^[a-zA-Z0-9_]*$/.test(value); },"请输入字母数字或下划线"); jQuery.validator.addMethod("username",function(value, element) { return this.optional(element) || /^[a-zA-Z0-9][a-zA-Z0-9_]{2,19}$/.test(value); },"3-20位字母或数字开头,允许字母数字下划线"); jQuery.validator.addMethod("noEqualTo",function(value, element, param) { return value != $(param).val(); },"请再次输入不同的值"); //真实姓名验证 jQuery.validator.addMethod("realName", function(value, element) { return this.optional(element) || /^[\u4e00-\u9fa5]{2,30}$/.test(value); }, "姓名只能为2-30个汉字"); // 字符验证 jQuery.validator.addMethod("userName", function(value, element) { return this.optional(element) || /^[\u0391-\uFFE5\w]+$/.test(value); }, "登录名只能包括中文字、英文字母、数字和下划线"); // 手机号码验证 jQuery.validator.addMethod("mobile", function(value, element) { var length = value.length; return this.optional(element) || (length == 11 && /^(((13[0-9]{1})|(15[0-9]{1}))+\d{8})$/.test(value)); }, "请正确填写您的手机号码"); // 电话号码验证 jQuery.validator.addMethod("simplePhone", function(value, element) { var tel = /^(\d{3,4}-?)?\d{7,9}$/g; return this.optional(element) || (tel.test(value)); }, "请正确填写您的电话号码"); // 电话号码验证 jQuery.validator.addMethod("phone", function(value, element) { var tel = /(^0[1-9]{1}\d{9,10}$)|(^1[3,4,5,6,7,8,9]\d{9}$)/g; return this.optional(element) || (tel.test(value)); }, "请正确填写电话号码"); // 邮政编码验证 jQuery.validator.addMethod("zipCode", function(value, element) { var tel = /^[0-9]{6}$/; return this.optional(element) || (tel.test(value)); }, "请正确填写您的邮政编码"); //QQ号码验证 jQuery.validator.addMethod("qq", function(value, element) { var tel = /^[1-9][0-9]{4,}$/; return this.optional(element) || (tel.test(value)); }, "请正确填写您的QQ号码"); //校验身份证好 jQuery.validator.addMethod("card",function(value, element) { return this.optional(element) || checkIdcard(value); },"请输入正确的身份证号码(15-18位)") //验证身份证函数 function checkIdcard(idcard){ idcard = idcard.toString(); //var Errors=new Array("验证通过!","身份证号码位数不对!","身份证号码出生日期超出范围或含有非法字符!","身份证号码校验错误!","身份证地区非法!"); var Errors=new Array(true,false,false,false,false); var area={11:"北京",12:"天津",13:"河北",14:"山西",15:"内蒙古",21:"辽宁",22:"吉林",23:"黑龙江",31:"上海",32:"江苏",33:"浙江",34:"安徽",35:"福建",36:"江西",37:"山东",41:"河南",42:"湖北",43:"湖南",44:"广东",45:"广西",46:"海南",50:"重庆",51:"四川",52:"贵州",53:"云南",54:"西藏",61:"陕西",62:"甘肃",63:"青海",64:"宁夏",65:"新疆",71:"台湾",81:"香港",82:"澳门",91:"国外"} var idcard,Y,JYM; var S,M; var idcard_array = new Array(); idcard_array = idcard.split(""); //地区检验 if(area[parseInt(idcard.substr(0,2))]==null) return Errors[4]; //身份号码位数及格式检验 switch(idcard.length){ case 15: if ( (parseInt(idcard.substr(6,2))+1900) % 4 == 0 || ((parseInt(idcard.substr(6,2))+1900) % 100 == 0 && (parseInt(idcard.substr(6,2))+1900) % 4 == 0 )){ ereg=/^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}$/;//测试出生日期的合法性 } else { ereg=/^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}$/;//测试出生日期的合法性 } if(ereg.test(idcard)) return Errors[0]; else return Errors[2]; break; case 18: //18 位身份号码检测 //出生日期的合法性检查 //闰年月日:((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9])) //平年月日:((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8])) if ( parseInt(idcard.substr(6,4)) % 4 == 0 || (parseInt(idcard.substr(6,4)) % 100 == 0 && parseInt(idcard.substr(6,4))%4 == 0 )){ ereg=/^[1-9][0-9]{5}19[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}[0-9Xx]$/;//闰年出生日期的合法性正则表达式 } else { ereg=/^[1-9][0-9]{5}19[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}[0-9Xx]$/;//平年出生日期的合法性正则表达式 } if(ereg.test(idcard)) {//测试出生日期的合法性 //计算校验位 S = (parseInt(idcard_array[0]) + parseInt(idcard_array[10])) * 7 + (parseInt(idcard_array[1]) + parseInt(idcard_array[11])) * 9 + (parseInt(idcard_array[2]) + parseInt(idcard_array[12])) * 10 + (parseInt(idcard_array[3]) + parseInt(idcard_array[13])) * 5 + (parseInt(idcard_array[4]) + parseInt(idcard_array[14])) * 8 + (parseInt(idcard_array[5]) + parseInt(idcard_array[15])) * 4 + (parseInt(idcard_array[6]) + parseInt(idcard_array[16])) * 2 + parseInt(idcard_array[7]) * 1 + parseInt(idcard_array[8]) * 6 + parseInt(idcard_array[9]) * 3 ; Y = S % 11; M = "F"; JYM = "10X98765432"; M = JYM.substr(Y,1);//判断校验位 if(M == idcard_array[17]) return Errors[0]; //检测ID的校验位 else return Errors[3]; } else return Errors[2]; break; default: return Errors[1]; break; } }
Honding/jfx
src/main/webapp/static/jquery-validation/1.11.0/jquery.validate.method.js
JavaScript
apache-2.0
7,170
/** * Copyright 2013, 2014 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ RED.editor = (function() { var editing_node = null; // TODO: should IMPORT/EXPORT get their own dialogs? function getCredentialsURL(nodeType, nodeID) { var dashedType = nodeType.replace(/\s+/g, '-'); return 'credentials/' + dashedType + "/" + nodeID; } /** * Validate a node * @param node - the node being validated * @returns {boolean} whether the node is valid. Sets node.dirty if needed */ function validateNode(node) { var oldValue = node.valid; node.valid = validateNodeProperties(node, node._def.defaults, node); if (node._def._creds) { node.valid = node.valid && validateNodeProperties(node, node._def.credentials, node._def._creds); } if (oldValue != node.valid) { node.dirty = true; } } /** * Validate a node's properties for the given set of property definitions * @param node - the node being validated * @param definition - the node property definitions (either def.defaults or def.creds) * @param properties - the node property values to validate * @returns {boolean} whether the node's properties are valid */ function validateNodeProperties(node, definition, properties) { var isValid = true; for (var prop in definition) { if (definition.hasOwnProperty(prop)) { if (!validateNodeProperty(node, definition, prop, properties[prop])) { isValid = false; } } } return isValid; } /** * Validate a individual node property * @param node - the node being validated * @param definition - the node property definitions (either def.defaults or def.creds) * @param property - the property name being validated * @param value - the property value being validated * @returns {boolean} whether the node proprty is valid */ function validateNodeProperty(node,definition,property,value) { var valid = true; if ("required" in definition[property] && definition[property].required) { valid = value !== ""; } if (valid && "validate" in definition[property]) { valid = definition[property].validate.call(node,value); } if (valid && definition[property].type && RED.nodes.getType(definition[property].type) && !("validate" in definition[property])) { if (!value || value == "_ADD_") { valid = false; } else { var v = RED.nodes.node(value).valid; valid = (v==null || v); } } return valid; } /** * Called when the node's properties have changed. * Marks the node as dirty and needing a size check. * Removes any links to non-existant outputs. * @param node - the node that has been updated * @returns {array} the links that were removed due to this update */ function updateNodeProperties(node) { node.resize = true; node.dirty = true; var removedLinks = []; if (node.ports) { if (node.outputs < node.ports.length) { while (node.outputs < node.ports.length) { node.ports.pop(); } RED.nodes.eachLink(function(l) { if (l.source === node && l.sourcePort >= node.outputs) { removedLinks.push(l); } }); } else if (node.outputs > node.ports.length) { while (node.outputs > node.ports.length) { node.ports.push(node.ports.length); } } } if (node.inputs === 0) { RED.nodes.eachLink(function(l) { if (l.target === node) { removedLinks.push(l); } }); } for (var l=0;l<removedLinks.length;l++) { RED.nodes.removeLink(removedLinks[l]); } return removedLinks; } $( "#dialog" ).dialog({ modal: true, autoOpen: false, closeOnEscape: false, width: 500, buttons: [ { id: "node-dialog-ok", text: "Ok", click: function() { if (editing_node) { var changes = {}; var changed = false; var wasDirty = RED.view.dirty(); var d; if (editing_node._def.oneditsave) { var oldValues = {}; for (d in editing_node._def.defaults) { if (editing_node._def.defaults.hasOwnProperty(d)) { if (typeof editing_node[d] === "string" || typeof editing_node[d] === "number") { oldValues[d] = editing_node[d]; } else { oldValues[d] = $.extend(true,{},{v:editing_node[d]}).v; } } } var rc = editing_node._def.oneditsave.call(editing_node); if (rc === true) { changed = true; } for (d in editing_node._def.defaults) { if (editing_node._def.defaults.hasOwnProperty(d)) { if (oldValues[d] === null || typeof oldValues[d] === "string" || typeof oldValues[d] === "number") { if (oldValues[d] !== editing_node[d]) { changes[d] = oldValues[d]; changed = true; } } else { if (JSON.stringify(oldValues[d]) !== JSON.stringify(editing_node[d])) { changes[d] = oldValues[d]; changed = true; } } } } } if (editing_node._def.defaults) { for (d in editing_node._def.defaults) { if (editing_node._def.defaults.hasOwnProperty(d)) { var input = $("#node-input-"+d); var newValue; if (input.attr('type') === "checkbox") { newValue = input.prop('checked'); } else { newValue = input.val(); } if (newValue != null) { if (editing_node[d] != newValue) { if (editing_node._def.defaults[d].type) { if (newValue == "_ADD_") { newValue = ""; } // Change to a related config node var configNode = RED.nodes.node(editing_node[d]); if (configNode) { var users = configNode.users; users.splice(users.indexOf(editing_node),1); } configNode = RED.nodes.node(newValue); if (configNode) { configNode.users.push(editing_node); } } changes[d] = editing_node[d]; editing_node[d] = newValue; changed = true; } } } } } if (editing_node._def.credentials) { var prefix = 'node-input'; var credDefinition = editing_node._def.credentials; var credsChanged = updateNodeCredentials(editing_node,credDefinition,prefix); changed = changed || credsChanged; } var removedLinks = updateNodeProperties(editing_node); if (changed) { var wasChanged = editing_node.changed; editing_node.changed = true; RED.view.dirty(true); RED.history.push({t:'edit',node:editing_node,changes:changes,links:removedLinks,dirty:wasDirty,changed:wasChanged}); } editing_node.dirty = true; validateNode(editing_node); RED.view.redraw(); } else if (RED.view.state() == RED.state.EXPORT) { if (/library/.test($( "#dialog" ).dialog("option","title"))) { //TODO: move this to RED.library var flowName = $("#node-input-filename").val(); if (!/^\s*$/.test(flowName)) { $.ajax({ url:'library/flows/'+flowName, type: "POST", data: $("#node-input-filename").attr('nodes'), contentType: "application/json; charset=utf-8" }).done(function() { RED.library.loadFlowLibrary(); RED.notify("Saved nodes","success"); }); } } } else if (RED.view.state() == RED.state.IMPORT) { RED.view.importNodes($("#node-input-import").val()); } $( this ).dialog( "close" ); } }, { id: "node-dialog-cancel", text: "Cancel", click: function() { if (editing_node._def) { if (editing_node._def.oneditcancel) { editing_node._def.oneditcancel.call(editing_node); } } $( this ).dialog( "close" ); } } ], resize: function(e,ui) { if (editing_node) { $(this).dialog('option',"sizeCache-"+editing_node.type,ui.size); } }, open: function(e) { $(this).parent().find(".ui-dialog-titlebar-close").hide(); RED.keyboard.disable(); if (editing_node) { var size = $(this).dialog('option','sizeCache-'+editing_node.type); if (size) { $(this).dialog('option','width',size.width); $(this).dialog('option','height',size.height); } } }, close: function(e) { RED.keyboard.enable(); if (RED.view.state() != RED.state.IMPORT_DRAGGING) { RED.view.state(RED.state.DEFAULT); } $( this ).dialog('option','height','auto'); $( this ).dialog('option','width','500'); if (editing_node) { RED.sidebar.info.refresh(editing_node); } RED.sidebar.config.refresh(); var buttons = $( this ).dialog("option","buttons"); if (buttons.length == 3) { $( this ).dialog("option","buttons",buttons.splice(1)); } editing_node = null; } }); /** * Create a config-node select box for this property * @param node - the node being edited * @param property - the name of the field * @param type - the type of the config-node */ function prepareConfigNodeSelect(node,property,type) { var input = $("#node-input-"+property); var node_def = RED.nodes.getType(type); input.replaceWith('<select style="width: 60%;" id="node-input-'+property+'"></select>'); updateConfigNodeSelect(property,type,node[property]); var select = $("#node-input-"+property); select.after(' <a id="node-input-lookup-'+property+'" class="btn"><i class="fa fa-pencil"></i></a>'); $('#node-input-lookup-'+property).click(function(e) { showEditConfigNodeDialog(property,type,select.find(":selected").val()); e.preventDefault(); }); var label = ""; var configNode = RED.nodes.node(node[property]); if (configNode && node_def.label) { if (typeof node_def.label == "function") { label = node_def.label.call(configNode); } else { label = node_def.label; } } input.val(label); } /** * Populate the editor dialog input field for this property * @param node - the node being edited * @param property - the name of the field * @param prefix - the prefix to use in the input element ids (node-input|node-config-input) */ function preparePropertyEditor(node,property,prefix) { var input = $("#"+prefix+"-"+property); if (input.attr('type') === "checkbox") { input.prop('checked',node[property]); } else { var val = node[property]; if (val == null) { val = ""; } input.val(val); } } /** * Add an on-change handler to revalidate a node field * @param node - the node being edited * @param definition - the definition of the node * @param property - the name of the field * @param prefix - the prefix to use in the input element ids (node-input|node-config-input) */ function attachPropertyChangeHandler(node,definition,property,prefix) { $("#"+prefix+"-"+property).change(function() { if (!validateNodeProperty(node, definition, property,this.value)) { $(this).addClass("input-error"); } else { $(this).removeClass("input-error"); } }); } /** * Assign the value to each credential field * @param node * @param credDef * @param credData * @param prefix */ function populateCredentialsInputs(node, credDef, credData, prefix) { var cred; for (cred in credDef) { if (credDef.hasOwnProperty(cred)) { if (credDef[cred].type == 'password') { if (credData[cred]) { $('#' + prefix + '-' + cred).val(credData[cred]); } else if (credData['has_' + cred]) { $('#' + prefix + '-' + cred).val('__PWRD__'); } else { $('#' + prefix + '-' + cred).val(''); } } else { preparePropertyEditor(credData, cred, prefix); } attachPropertyChangeHandler(node, credDef, cred, prefix); } } for (cred in credDef) { if (credDef.hasOwnProperty(cred)) { $("#" + prefix + "-" + cred).change(); } } } /** * Update the node credentials from the edit form * @param node - the node containing the credentials * @param credDefinition - definition of the credentials * @param prefix - prefix of the input fields * @return {boolean} whether anything has changed */ function updateNodeCredentials(node, credDefinition, prefix) { var changed = false; if(!node.credentials) { node.credentials = {_:{}}; } for (var cred in credDefinition) { if (credDefinition.hasOwnProperty(cred)) { var input = $("#" + prefix + '-' + cred); var value = input.val(); if (credDefinition[cred].type == 'password') { node.credentials['has_' + cred] = (value !== ""); if (value == '__PWRD__') { continue; } changed = true; } node.credentials[cred] = value; if (value != node.credentials._[cred]) { changed = true; } } } return changed; } /** * Prepare all of the editor dialog fields * @param node - the node being edited * @param definition - the node definition * @param prefix - the prefix to use in the input element ids (node-input|node-config-input) */ function prepareEditDialog(node,definition,prefix) { for (var d in definition.defaults) { if (definition.defaults.hasOwnProperty(d)) { if (definition.defaults[d].type) { prepareConfigNodeSelect(node,d,definition.defaults[d].type); } else { preparePropertyEditor(node,d,prefix); } attachPropertyChangeHandler(node,definition.defaults,d,prefix); } } var completePrepare = function() { if (definition.oneditprepare) { definition.oneditprepare.call(node); } for (var d in definition.defaults) { if (definition.defaults.hasOwnProperty(d)) { $("#"+prefix+"-"+d).change(); } } } if (definition.credentials) { if (node.credentials) { populateCredentialsInputs(node, definition.credentials, node.credentials, prefix); completePrepare(); } else { $.getJSON(getCredentialsURL(node.type, node.id), function (data) { node.credentials = data; node.credentials._ = $.extend(true,{},data); populateCredentialsInputs(node, definition.credentials, node.credentials, prefix); completePrepare(); }); } } else { completePrepare(); } } function showEditDialog(node) { editing_node = node; RED.view.state(RED.state.EDITING); var type = node.type; if (node.type.substring(0,8) == "subflow:") { type = "subflow"; var id = editing_node.type.substring(8); var buttons = $( "#dialog" ).dialog("option","buttons"); buttons.unshift({ class: 'leftButton', text: "Edit flow", click: function() { RED.view.showSubflow(id); $("#node-dialog-ok").click(); } }); $( "#dialog" ).dialog("option","buttons",buttons); } $("#dialog-form").html($("script[data-template-name='"+type+"']").html()); $('<input type="text" style="display: none;" />').appendTo("#dialog-form"); prepareEditDialog(node,node._def,"node-input"); $( "#dialog" ).dialog("option","title","Edit "+type+" node").dialog( "open" ); } function showEditConfigNodeDialog(name,type,id) { var adding = (id == "_ADD_"); var node_def = RED.nodes.getType(type); var configNode = RED.nodes.node(id); if (configNode == null) { configNode = { id: (1+Math.random()*4294967295).toString(16), _def: node_def, type: type } for (var d in node_def.defaults) { if (node_def.defaults[d].value) { configNode[d] = node_def.defaults[d].value; } } } $("#dialog-config-form").html($("script[data-template-name='"+type+"']").html()); prepareEditDialog(configNode,node_def,"node-config-input"); var buttons = $( "#node-config-dialog" ).dialog("option","buttons"); if (adding) { if (buttons.length == 3) { buttons = buttons.splice(1); } buttons[0].text = "Add"; $("#node-config-dialog-user-count").html("").hide(); } else { if (buttons.length == 2) { buttons.unshift({ class: 'leftButton', text: "Delete", click: function() { var configProperty = $(this).dialog('option','node-property'); var configId = $(this).dialog('option','node-id'); var configType = $(this).dialog('option','node-type'); var configNode = RED.nodes.node(configId); var configTypeDef = RED.nodes.getType(configType); if (configTypeDef.ondelete) { configTypeDef.ondelete.call(RED.nodes.node(configId)); } if (configTypeDef.oneditdelete) { configTypeDef.oneditdelete.call(RED.nodes.node(configId)); } RED.nodes.remove(configId); for (var i=0;i<configNode.users.length;i++) { var user = configNode.users[i]; for (var d in user._def.defaults) { if (user._def.defaults.hasOwnProperty(d) && user[d] == configId) { user[d] = ""; } } validateNode(user); } updateConfigNodeSelect(configProperty,configType,""); RED.view.dirty(true); $( this ).dialog( "close" ); RED.view.redraw(); } }); } buttons[1].text = "Update"; $("#node-config-dialog-user-count").html(configNode.users.length+" node"+(configNode.users.length==1?" uses":"s use")+" this config").show(); } $( "#node-config-dialog" ).dialog("option","buttons",buttons); $( "#node-config-dialog" ) .dialog("option","node-adding",adding) .dialog("option","node-property",name) .dialog("option","node-id",configNode.id) .dialog("option","node-type",type) .dialog("option","title",(adding?"Add new ":"Edit ")+type+" config node") .dialog( "open" ); } function updateConfigNodeSelect(name,type,value) { var select = $("#node-input-"+name); var node_def = RED.nodes.getType(type); select.children().remove(); RED.nodes.eachConfig(function(config) { if (config.type == type) { var label = ""; if (typeof node_def.label == "function") { label = node_def.label.call(config); } else { label = node_def.label; } select.append('<option value="'+config.id+'"'+(value==config.id?" selected":"")+'>'+label+'</option>'); } }); select.append('<option value="_ADD_"'+(value===""?" selected":"")+'>Add new '+type+'...</option>'); window.setTimeout(function() { select.change();},50); } $( "#node-config-dialog" ).dialog({ modal: true, autoOpen: false, width: 500, closeOnEscape: false, buttons: [ { id: "node-config-dialog-ok", text: "Ok", click: function() { var configProperty = $(this).dialog('option','node-property'); var configId = $(this).dialog('option','node-id'); var configType = $(this).dialog('option','node-type'); var configAdding = $(this).dialog('option','node-adding'); var configTypeDef = RED.nodes.getType(configType); var configNode; var d; if (configAdding) { configNode = {type:configType,id:configId,users:[]}; for (d in configTypeDef.defaults) { if (configTypeDef.defaults.hasOwnProperty(d)) { configNode[d] = $("#node-config-input-"+d).val(); } } configNode.label = configTypeDef.label; configNode._def = configTypeDef; RED.nodes.add(configNode); updateConfigNodeSelect(configProperty,configType,configNode.id); } else { configNode = RED.nodes.node(configId); for (d in configTypeDef.defaults) { if (configTypeDef.defaults.hasOwnProperty(d)) { var input = $("#node-config-input-"+d); if (input.attr('type') === "checkbox") { configNode[d] = input.prop('checked'); } else { configNode[d] = input.val(); } } } updateConfigNodeSelect(configProperty,configType,configId); } if (configTypeDef.credentials) { updateNodeCredentials(configNode,configTypeDef.credentials,"node-config-input"); } if (configTypeDef.oneditsave) { configTypeDef.oneditsave.call(RED.nodes.node(configId)); } validateNode(configNode); RED.view.dirty(true); $(this).dialog("close"); } }, { id: "node-config-dialog-cancel", text: "Cancel", click: function() { var configType = $(this).dialog('option','node-type'); var configId = $(this).dialog('option','node-id'); var configAdding = $(this).dialog('option','node-adding'); var configTypeDef = RED.nodes.getType(configType); if (configTypeDef.oneditcancel) { // TODO: what to pass as this to call if (configTypeDef.oneditcancel) { var cn = RED.nodes.node(configId); if (cn) { configTypeDef.oneditcancel.call(cn,false); } else { configTypeDef.oneditcancel.call({id:configId},true); } } } $( this ).dialog( "close" ); } } ], resize: function(e,ui) { }, open: function(e,ui) { $(this).parent().find(".ui-dialog-titlebar-close").hide(); if (RED.view.state() != RED.state.EDITING) { RED.keyboard.disable(); } }, close: function(e) { $("#dialog-config-form").html(""); if (RED.view.state() != RED.state.EDITING) { RED.keyboard.enable(); } RED.sidebar.config.refresh(); } }); $( "#subflow-dialog" ).dialog({ modal: true, autoOpen: false, closeOnEscape: false, width: 500, buttons: [ { id: "subflow-dialog-ok", text: "Ok", click: function() { if (editing_node) { var i; var changes = {}; var changed = false; var wasDirty = RED.view.dirty(); var newName = $("#subflow-input-name").val(); if (newName != editing_node.name) { changes['name'] = editing_node.name; editing_node.name = newName; changed = true; $("#btn-workspace-menu-"+editing_node.id.replace(".","-")).text("Subflow: "+newName); } RED.palette.refresh(); if (changed) { RED.nodes.eachNode(function(n) { if (n.type == "subflow:"+editing_node.id) { n.changed = true; updateNodeProperties(n); } }); var wasChanged = editing_node.changed; editing_node.changed = true; RED.view.dirty(true); var historyEvent = { t:'edit', node:editing_node, changes:changes, dirty:wasDirty, changed:wasChanged }; RED.history.push(historyEvent); } editing_node.dirty = true; RED.view.redraw(); } $( this ).dialog( "close" ); } }, { id: "subflow-dialog-cancel", text: "Cancel", click: function() { $( this ).dialog( "close" ); editing_node = null; } } ], open: function(e,ui) { $(this).parent().find(".ui-dialog-titlebar-close").hide(); RED.keyboard.disable(); }, close: function(e) { RED.keyboard.enable(); if (RED.view.state() != RED.state.IMPORT_DRAGGING) { RED.view.state(RED.state.DEFAULT); } RED.sidebar.info.refresh(editing_node); editing_node = null; } }); function showEditSubflowDialog(subflow) { editing_node = subflow; RED.view.state(RED.state.EDITING); $("#subflow-input-name").val(subflow.name); var userCount = 0; var subflowType = "subflow:"+editing_node.id; RED.nodes.eachNode(function(n) { if (n.type === subflowType) { userCount++; } }); $("#subflow-dialog-user-count").html("There "+(userCount==1?"is":"are")+" "+userCount+" instance"+(userCount==1?" ":"s")+" of this subflow").show(); $("#subflow-dialog").dialog("option","title","Edit flow "+subflow.name).dialog( "open" ); } return { edit: showEditDialog, editConfig: showEditConfigNodeDialog, editSubflow: showEditSubflowDialog, validateNode: validateNode, updateNodeProperties: updateNodeProperties // TODO: only exposed for edit-undo } })();
emiloberg/node-red
public/red/ui/editor.js
JavaScript
apache-2.0
34,492
import React from 'react' import Notifications from 'app/containers/profile/notifications' import PasswordChange from './password_change' import EditUser from 'app/components/settings/user/edit' import Restricted from 'app/restricted' import Flash from 'app/flash' import rpc from 'app/rpc' import {i18n} from 'app/utils/i18n' class Profile extends React.Component{ constructor(props){ super(props) this.state = { modal: undefined, avatar: this.props.avatar, lang: this.props.lang, tracking: this.props.tracking } } handleSubmit(){ this.props.onSubmit(this.state) } handleUpdate(section, data){ this.setState({ [section]: data }) } openPasswordChange(ev){ ev.preventDefault() this.setState({ modal: "change_password" }) } openPersonalData(ev){ ev.preventDefault() this.setState({ modal: "personal_data" }) } componentDidMount(){ const self=this $(this.refs.lang).dropdown({ onChange(lang){ // console.log("Set language to ", lang) self.setState({lang}) self.props.onSetLanguage(lang) } }) $(this.refs.tracking).checkbox() if (this.props.tracking) $(this.refs.tracking).checkbox("check") else $(this.refs.tracking).checkbox("uncheck") } componentWillReceiveProps(newprops){ if (newprops.tracking != this.props.tracking){ if (newprops.tracking) $(this.refs.tracking).checkbox("check") else $(this.refs.tracking).checkbox("uncheck") } } uploadAvatar(ev){ let fr = new FileReader() fr.onload = (ev) => { this.setState({avatar: ev.target.result}) rpc.call("settings.user.set", ["profile_avatar", {avatar: ev.target.result}]).then( () => { Flash.info(i18n("Avatar image saved")) this.props.onUpdateAvatar(ev.target.result) }) } fr.readAsDataURL(ev.target.files[0]) } render(){ let popup=[] switch(this.state.modal){ case "change_password": popup=( <PasswordChange onClose={() => this.setState({ modal: undefined })}/> ) break; case "personal_data": popup=( <EditUser user={this.props.user} onClose={() => this.setState({ modal: undefined })} onUpdateUser={this.props.onUpdateUser} /> ) break; } let {props, state} = this return ( <div className="ui central area white background extends" style={{flexDirection: "column", maxHeight: "calc( 100vh - 70px )"}}> <div className="ui top secondary menu"> <div className="right menu"> <a className="item" href="#" onClick={this.openPersonalData.bind(this)}><i className="ui icon user"/>{i18n("Personal data")}</a> <a className="item" href="#" onClick={this.openPasswordChange.bind(this)}><i className="ui icon lock"/>{i18n("Change password")}</a> </div> </div> <div className="ui scroll" style={{maxHeight: "calc( 100vh - 140px )"}}> <div className="ui text container"> <div style={{float:"left", margin: "0px 30px 30px 0"}}> <img src={state.avatar} className="ui bordered image medium" style={{width: 300, height: 300}}/> <div className="ui meta blue text"><label style={{cursor:"pointer"}}>{i18n("Upload new image")}<input onChange={this.uploadAvatar.bind(this)} style={{display:"none"}} type="file"/></label>.</div> </div> <h1 className="ui header">{props.user.name}</h1> <h2 className="ui header">{i18n("Basic user data")}</h2> <div className="ui inline field"> <label>{i18n("Email")}:</label> <span className="value">{props.user.email}</span> </div> <h2 className="ui header">{i18n("Language")}</h2> <div className="ui inline field"> <div className="ui selection dropdown" ref="lang"> <input type="hidden" name="lang" defaultValue={this.state.lang}/> <i className="dropdown icon"/> <div className="default text">Language</div> <div className="menu"> <div className="item" data-value="en"><i className="ui flag gb"/>English</div> <div className="item" data-value="es"><i className="ui flag es"/>Español</div> </div> </div> </div> <div style={{clear: "both"}}> <h2 className="ui header">{i18n("Usage tracking")}</h2> <div className="ui meta"> {i18n("By letting Serverboards get information about your use of Serverboards allows us to center on the most used features and to detect failures on the wild.")} <br/> {i18n("We will not access any personal information, just general data as which functionalities and plugins are most used and errors.")} </div> <div className="ui inline field"> <div ref="tracking" className="ui checkbox"> <input onChange={(ev) => this.handleUpdate("tracking", ev.target.checked)} type="checkbox" defaultChecked={props.tracking} id="tracking"/> <label>{i18n("Allow Serverboards to track which functionalities I use.")}</label> </div> </div> </div> <div style={{clear:"both"}}/> <Restricted perm="settings.user.view"> <Notifications user={props.user.email} onUpdate={(data) => this.handleUpdate("notifications", data)}/> </Restricted> <br/> <Restricted perm="settings.user.update"> <button className="ui teal button" onClick={this.handleSubmit.bind(this)}>{i18n("Update profile")}</button> </Restricted> <div style={{height: 20}}></div> </div> {popup} </div> </div> ) } } export default Profile
serverboards/serverboards
frontend/app/js/components/profile/index.js
JavaScript
apache-2.0
6,026
// This file was procedurally generated from the following sources: // - src/dstr-binding/obj-ptrn-id-init-fn-name-cover.case // - src/dstr-binding/default/let-stmt.template /*--- description: SingleNameBinding assigns `name` to "anonymous" functions "through" cover grammar (`let` statement) esid: sec-let-and-const-declarations-runtime-semantics-evaluation es6id: 13.3.1.4 features: [destructuring-binding] flags: [generated] info: | LexicalBinding : BindingPattern Initializer 1. Let rhs be the result of evaluating Initializer. 2. Let value be GetValue(rhs). 3. ReturnIfAbrupt(value). 4. Let env be the running execution context's LexicalEnvironment. 5. Return the result of performing BindingInitialization for BindingPattern using value and env as the arguments. 13.3.3.7 Runtime Semantics: KeyedBindingInitialization SingleNameBinding : BindingIdentifier Initializeropt [...] 6. If Initializer is present and v is undefined, then [...] d. If IsAnonymousFunctionDefinition(Initializer) is true, then i. Let hasNameProperty be HasOwnProperty(v, "name"). ii. ReturnIfAbrupt(hasNameProperty). iii. If hasNameProperty is false, perform SetFunctionName(v, bindingId). ---*/ let { cover = (function () {}), xCover = (0, function() {}) } = {}; assert.sameValue(cover.name, 'cover'); assert.notSameValue(xCover.name, 'xCover');
sebastienros/jint
Jint.Tests.Test262/test/language/statements/let/dstr-obj-ptrn-id-init-fn-name-cover.js
JavaScript
bsd-2-clause
1,439
Ext.define('Devon.Data', { singleton: true, serializeNull: function(value) { if (Ext.isNumeric(value)) { return value; } return null; } });
CoEValencia/chirr
demos/workspace/packages/local/devon-extjs/src/Data.js
JavaScript
bsd-2-clause
190
var index = require('./') var streamId = 0; Object.keys(index).forEach(function(key) { exports[key] = index[key]; }) exports.create = function(writer, options) { var asyncStream = index.create.apply(index, arguments); var state = { bufferId: 0, substreamId: 0 } if(arguments.length === 1 && typeof writer.write !== 'function') { options = writer; writer = null; } asyncStream.name = (options && options.name) || 'originalStream'+(streamId++ ? streamId : ''); asyncStream.on('finish', function() { streamId--; }); asyncStream.writer.name = 'originalWriter'; console.log('\n' + bold(asyncStream.name + green('.create()'))); console.log(createDiagram(asyncStream)); logEvents(asyncStream, state); return asyncStream; } function logEvents(asyncStream, state) { var _write = asyncStream.write; asyncStream.write = function(str) { var thisStream = _write.apply(this, arguments); console.log('\n' + bold(this.name + cyan('.write(') + reset(grey(str)) + cyan(')'))); console.log(createDiagram(this)); return thisStream; } var _beginAsync = asyncStream.beginAsync; asyncStream.beginAsync = function() { var newStream = _beginAsync.apply(this, arguments); newStream.name = newStream.name || 'stream'+(++state.substreamId); this.writer.name = 'buffer'+(++state.bufferId); console.log('\n' + bold(newStream.name + grey(' = ') + this.name + green('.beginAsync()'))); console.log(createDiagram(this)); logEvents(newStream, state); return newStream; } var _end = asyncStream.end; asyncStream.end = function() { var thisStream = _end.apply(this, arguments); console.log('\n' + bold(this.name + red('.end()'))); console.log(createDiagram(this)); return thisStream; } } function createDiagram(asyncStream) { var streams = []; var writers = []; var contents = []; var currentWriter = asyncStream._originalWriter; while(currentWriter) { var currentIndex = writers.length; writers.push(currentWriter.name); contents.push(currentWriter.toString()); if(currentWriter.stream) { streams[currentIndex] = currentWriter.stream.name; } if(currentWriter.stream === asyncStream) { streams[currentIndex] += '*' } currentWriter = currentWriter.next; } var line1 = ''; var line2 = ''; var line3 = ''; var line4 = ''; writers.forEach(function(writer, i) { var stream = streams[i] || ''; var content = contents[i] || ''; var longest = Math.max(writer.length, stream.length, content.length); line1 += stream + ' '.repeat(longest-stream.length); if(stream) { line2 += '↕' + ' '.repeat(longest-1); } else { line2 += ' '.repeat(longest); } line3 += writer + ' '.repeat(longest-writer.length); line4 += content + ' '.repeat(longest-content.length); if(i !== writers.length-1) { line1 += ' '; line2 += ' '; line3 += grey(' → '); line4 += ' '; } }) if(line1 === ' '.repeat(line1.length)) line1 = null; if(line2 === ' '.repeat(line2.length)) line2 = null; return (line1 ? line1 + '\n' : '') + (line2 ? grey(line2) + '\n' : '') + line3 + '\n' + magenta(line4) + '\n'; } var canFormat = (function () { if (process.stdout && !process.stdout.isTTY) { return false; } if (process.platform === 'win32') { return true; } if ('COLORTERM' in process.env) { return true; } if (process.env.TERM === 'dumb') { return false; } if (/^screen|^xterm|^vt100|color|ansi|cygwin|linux/i.test(process.env.TERM)) { return true; } return false; })(); function format(str, begin, end) { begin = canFormat ? '\u001b['+begin+'m' : ''; end = canFormat ? '\u001b['+end+'m' : ''; return begin + str + end; } function reset(str) { return format(str, 0, 0); } function red(str) { return format(str, 31, 39); } function cyan(str) { return format(str, 36, 39); } function magenta(str) { return format(str, 35, 39); } function green(str) { return format(str, 32, 39); } function grey(str) { return format(str, 90, 39); } function bold(str) { return format(str, 1, 22); }
ticolucci/dotfiles
atom/packages/atom-beautify/node_modules/async-writer/debug.js
JavaScript
bsd-2-clause
4,478
/*--- includes: [compareArray.js] flags: [async] ---*/ let stages = []; var promise = new Promise(function(resolve, reject) { stages.push('One'); reject('Oh no'); }); stages.push('Two'); promise.then(() => {stages.push('Three')}) .catch((v) => {stages.push(v)}) .then(() => assert.compareArray(stages, ['One', 'Two', 'Three', 'Oh no'])) .then($DONE, $DONE); stages.push('Three');
nginx/njs
test/js/promise_s10.t.js
JavaScript
bsd-2-clause
393
(function() { 'use strict'; // NOTE: If updating this list of required modules, also update the same in crds-angular! // TODO: Figure out a better way so we don't have to duplicate this in crds-angular require('angular'); require('angular-resource'); require('angular-sanitize'); require('angular-messages'); require('angular-number-picker'); require('angular-cookies'); require('angular-toggle-switch'); require('angular-scroll'); require('angular-stripe'); require('angular-animate'); require('angular-payments'); require('angular-bootstrap-npm'); require('angular-ui-router'); require('angular-ui-event'); require('angular-ui-mask'); require('angular-addthis'); require('angular-aside'); require('angular-number-picker'); require('angular-match-media'); require('angular-mailchimp'); require('angular-image-crop'); require('angulartics'); require('angulartics-gtm'); require('angularjs-slider'); })();
crdschurch/crds-corejs
app/ang.js
JavaScript
bsd-2-clause
961
var request = require('request') , querystring = require('querystring') , config = require('../config.js') , package = require('./package.js') module.exports = search function search(params, cb) { if (!params.q) { return cb(null, { hits: { total : 0 }}) } var page = parseInt(params.page || '0', 10); var qs = { from : page*config.elasticsearch.pageSize , size : config.elasticsearch.pageSize , pretty: false } var url = config.elasticsearch.url + '/package/_search?' + querystring.stringify(qs) var payload = { fields : ['name', 'keywords','description','author', 'version'] , query : { multi_match : { query : params.q , fields : ['name^4', 'keywords', 'description', 'readme'] } } , sort : ['_score'] } request.get({ url : url, json: payload }, function(e, r, o) { if (r && r.error) e = new Error(r.error) if (e) return cb(e) o.q = params.q o.page = page o.pageSize = config.elasticsearch.pageSize // make sure that an exact match gets the top hit var name = params.q.trim() if (o && o.error) { var er = new Error('Search Error: ' + o.error) er.code = o.status || 500 return cb(er, o) } if (r.statusCode !== 200 || !o) { var er = new Error('Search failed:' + JSON.stringify(o, null, 2)) er.code = r.statusCode if (er.code === 200) er.code = 500 return cb(er, o) } if (!o.hits || !o.hits.hits || !o.hits.hits.length || o.hits.hits[0]._id === name && page === 0) return cb(e, o) o.hits.hits = o.hits.hits.filter(function(n) { return n._id !== name }) if (page !== 0) { cb(null, o) } else { package(name, function(er, data) { if (er || data.name !== name || !data.versions || !data['dist-tags']) return cb(null, o) if (!data.keywords || !Array.isArray(data.keywords)) { if (typeof data.keywords === 'string') data.keywords = data.keywords.split(/[,\s]+/) else data.keywords = [] } o.hits.hits.unshift({ _index: 'npm', _type: 'package', _id: name, _score: 9999, fields: { author: data.maintainers[0].name, keywords: data.keywords, description: data.description, version: data['dist-tags'].latest, name: name } }) cb(null, o) }) } }); }
maxogden/npm-www
models/search.js
JavaScript
bsd-2-clause
2,601
import Component from '@ember/component'; import { inject as service } from '@ember/service'; import { task } from 'ember-concurrency'; export default Component.extend({ router: service(), store: service(), flashMessages: service(), deleteAppearanceModal: false, deleteAppearanceModalError: false, deleteAppearance: task(function *() { try { yield this.model.destroyRecord({ 'by': this.get('currentUser.user.id'), }); this.set('deleteAppearanceModal', false); this.set('deleteAppearanceModalError', false); this.flashMessages.success("Deleted!"); this.router.transitionTo('dashboard.conventions.convention.sessions.session.rounds.round.appearances'); } catch(e) { this.set('deleteAppearanceModalError', true); } }).drop(), });
barberscore/barberscore-web
app/components/appearance-delete.js
JavaScript
bsd-2-clause
804
var env = require('./src/environment'); var compiler = require('./src/compiler'); var parser = require('./src/parser'); var lexer = require('./src/lexer'); var loaders = require('./src/loaders'); module.exports = {}; module.exports.Environment = env.Environment; module.exports.Template = env.Template; if(loaders.FileSystemLoader) { module.exports.FileSystemLoader = loaders.FileSystemLoader; } else { module.exports.HttpLoader = loaders.HttpLoader; } module.exports.compiler = compiler; module.exports.parser = parser; module.exports.lexer = lexer;
jlongster/octoshot
node_modules/nunjucks/index.js
JavaScript
bsd-2-clause
562
/** * Удаляет smallcaps из выделения, сохраняя всех его потомков. * * @author dew1983@mail.ru <Suvorov Andrey M.> */ Ext.define( 'FBEditor.editor.command.smallcaps.DeleteWrapperCommand', { extend: 'FBEditor.editor.command.AbstractDeleteWrapperCommand', elementName: 'smallcaps' } );
Litres/FB3Editor
Frontend/app/editor/command/smallcaps/DeleteWrapperCommand.js
JavaScript
bsd-2-clause
370
// ES5-metaobject v1 09.11.2013 // Like .forEach from js 1.6 if(!Array.prototype.each){ Array.prototype.each=function(e){ for(var i=0,len=this.length;i<len;i++) e(this[i],i); } } // фильтрация элементов массива if(!Array.prototype.filter){ Array.prototype.filter=function(e){ var r = []; for(var i=0, len=this.length;i<len;i++){ if(e(this[i],i)) r.push(this[i]); } return r; } } // Преобразует массив объектов в другой массив if(!Array.prototype.map){ Array.prototype.map=function(e){ var r=[]; for(var i=0, len=this.length;i<len;i++){ r.push(e(this[i],i)); } return r; } } Object.prototype.clone=function(/*o*/) { if(!this || 'object' !== typeof this) { return this; } var c = 'function' == typeof this.pop ? [] : {}; var p, v; for(p in this) { if(this.hasOwnProperty(p)) { v = this[p]; if(v && 'object' === typeof v) { c[p] = v.clone(); } else { c[p] = v; } } } return c; } // IE8, Opera 11.11 not supported Function.prototype.bind // From: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind if (!Function.prototype.bind) { Function.prototype.bind = function (oThis) { if (typeof this !== "function") { // closest thing possible to the ECMAScript 5 internal IsCallable function throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable"); } var aArgs = Array.prototype.slice.call(arguments, 1), fToBind = this, fNOP = function () {}, fBound = function () { return fToBind.apply(this instanceof fNOP && oThis ? this : oThis, aArgs.concat(Array.prototype.slice.call(arguments))); }; fNOP.prototype = this.prototype; fBound.prototype = new fNOP(); return fBound; }; } // https://developer.mozilla.org/en-US/docs/Web/API/DOMTokenList // Since IE10, Opera 11.50, Chrome 8, FF 3.6 /* * classList.js: Cross-browser full element.classList implementation. * 2012-11-15 * * By Eli Grey, http://eligrey.com * Public Domain. * NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. */ /*global self, document, DOMException */ /*! @source http://purl.eligrey.com/github/classList.js/blob/master/classList.js*/ if (!( "classList" in document.createElement("_") && "classList" in document.createElementNS("http://www.w3.org/2000/svg", "svg") )) { (function (view) { "use strict"; if (!('Element' in view)) return; var classListProp = "classList" , protoProp = "prototype" , elemCtrProto = view.Element[protoProp] , objCtr = Object , strTrim = String[protoProp].trim || function () { return this.replace(/^\s+|\s+$/g, ""); } , arrIndexOf = Array[protoProp].indexOf || function (item) { var i = 0 , len = this.length ; for (; i < len; i++) { if (i in this && this[i] === item) { return i; } } return -1; } // Vendors: please allow content code to instantiate DOMExceptions , DOMEx = function (type, message) { this.name = type; this.code = DOMException[type]; this.message = message; } , checkTokenAndGetIndex = function (classList, token) { if (token === "") { throw new DOMEx( "SYNTAX_ERR" , "An invalid or illegal string was specified" ); } if (/\s/.test(token)) { throw new DOMEx( "INVALID_CHARACTER_ERR" , "String contains an invalid character" ); } return arrIndexOf.call(classList, token); } , ClassList = function (elem) { var trimmedClasses = strTrim.call(elem.getAttribute("class")) , classes = trimmedClasses ? trimmedClasses.split(/\s+/) : [] , i = 0 , len = classes.length ; for (; i < len; i++) { this.push(classes[i]); } this._updateClassName = function () { elem.setAttribute("class", this.toString()); }; } , classListProto = ClassList[protoProp] = [] , classListGetter = function () { return new ClassList(this); } ; // Most DOMException implementations don't allow calling DOMException's toString() // on non-DOMExceptions. Error's toString() is sufficient here. DOMEx[protoProp] = Error[protoProp]; classListProto.item = function (i) { return this[i] || null; }; classListProto.contains = function (token) { token += ""; return checkTokenAndGetIndex(this, token) !== -1; }; classListProto.add = function () { var tokens = arguments , i = 0 , l = tokens.length , token , updated = false ; do { token = tokens[i] + ""; if (checkTokenAndGetIndex(this, token) === -1) { this.push(token); updated = true; } } while (++i < l); if (updated) { this._updateClassName(); } }; classListProto.remove = function () { var tokens = arguments , i = 0 , l = tokens.length , token , updated = false ; do { token = tokens[i] + ""; var index = checkTokenAndGetIndex(this, token); if (index !== -1) { this.splice(index, 1); updated = true; } } while (++i < l); if (updated) { this._updateClassName(); } }; classListProto.toggle = function (token, forse) { token += ""; var result = this.contains(token) , method = result ? forse !== true && "remove" : forse !== false && "add" ; if (method) { this[method](token); } return !result; }; classListProto.toString = function () { return this.join(" "); }; if (objCtr.defineProperty) { var classListPropDesc = { get: classListGetter , enumerable: true , configurable: true }; try { objCtr.defineProperty(elemCtrProto, classListProp, classListPropDesc); } catch (ex) { // IE 8 doesn't support enumerable:true if (ex.number === -0x7FF5EC54) { classListPropDesc.enumerable = false; objCtr.defineProperty(elemCtrProto, classListProp, classListPropDesc); } } } else if (objCtr[protoProp].__defineGetter__) { elemCtrProto.__defineGetter__(classListProp, classListGetter); } }(window)); }
matraska23/expression
tables/js/es5-metaobject.js
JavaScript
bsd-2-clause
7,516
describe("Class", function() { describe("#extend", function() { var Klass, constructor, method; beforeEach(function() { constructor = jasmine.createSpy(), method = jasmine.createSpy(); Klass = L.Class.extend({ statics: {bla: 1}, includes: {mixin: true}, initialize: constructor, foo: 5, bar: method }); }); it("should create a class with the given constructor & properties", function() { var a = new Klass(); expect(constructor).toHaveBeenCalled(); expect(a.foo).toEqual(5); a.bar(); expect(method).toHaveBeenCalled(); }); it("should inherit parent classes' constructor & properties", function() { var Klass2 = Klass.extend({baz: 2}); var b = new Klass2(); expect(b instanceof Klass).toBeTruthy(); expect(b instanceof Klass2).toBeTruthy(); expect(constructor).toHaveBeenCalled(); expect(b.baz).toEqual(2); b.bar(); expect(method).toHaveBeenCalled(); }); it("should grant the ability to call parent methods, including constructor", function() { var Klass2 = Klass.extend({ initialize: function() {}, bar: function() {} }); var b = new Klass2(); expect(constructor).not.toHaveBeenCalled(); b.superclass.initialize.call(this); expect(constructor).toHaveBeenCalled(); b.superclass.bar.call(this); expect(method).toHaveBeenCalled(); }); it("should support static properties", function() { expect(Klass.bla).toEqual(1); }); it("should inherit parent static properties", function() { var Klass2 = Klass.extend({}); expect(Klass2.bla).toEqual(1); }); it("should include the given mixin", function() { var a = new Klass(); expect(a.mixin).toBeTruthy(); }); it("should be able to include multiple mixins", function() { var Klass2 = L.Class.extend({ includes: [{mixin: true}, {mixin2: true}] }); var a = new Klass2(); expect(a.mixin).toBeTruthy(); expect(a.mixin2).toBeTruthy(); }); it("should grant the ability to include the given mixin", function() { Klass.include({mixin2: true}); var a = new Klass(); expect(a.mixin2).toBeTruthy(); }); it("should merge options instead of replacing them", function() { var KlassWithOptions1 = L.Class.extend({ options: { foo1: 1, foo2: 2 } }); var KlassWithOptions2 = KlassWithOptions1.extend({ options: { foo2: 3, foo3: 4 } }); var a = new KlassWithOptions2(); expect(a.options).toEqual({ foo1: 1, foo2: 3, foo3: 4 }); }); }); });
igorshubovych/Leaflet
spec/suites/core/ClassSpec.js
JavaScript
bsd-2-clause
2,741
var _ = require("underscore") exports.TreeNode = function (depth) { this.depth = depth || 0 this.children = [] this.options = {} this.attributes = {} } _.extend(exports.TreeNode.prototype, { add_child: function () { var child_tree_node = new exports.TreeNode(this.depth + 1) this.children.push(child_tree_node) return child_tree_node } })
46bit/metamorphic
lib/metamorphic/tree_node.js
JavaScript
bsd-2-clause
365
/** * Copyright (c) 2015-present, Alejandro Mantilla <@AlejoJamC>. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree or translated in the assets folder. */ var express = require('express'); var indexRouter = express.Router(); var passport = require('passport'); var stormpath = require('stormpath'); /* ---------- MAIN MENU ---------- */ /* GET home page. */ indexRouter.get('/', function (req, res) { res.render('landing/index', { title: 'Dynamite Docs | Administracion y almacenamiento inteligente.', level: 'landing/', layout: 'landing/struct', isHome: true }); }); /* GET Pricing page. */ indexRouter.get('/pricing', function (req, res) { res.render('landing/pricing', { title: 'Precios | Dynamite Docs', level: 'landing/', layout: 'landing/struct' }); }); /* GET Contact page. */ indexRouter.get('/contact', function (req, res) { res.render('landing/contact', { title: 'Contacto | Dynamite Docs', level: 'landing/', layout: 'landing/struct' }); }); /* ---------- END MAIN MENU ---------- */ /* ---------- FOOTER MENU ---------- */ /* GET Help page. */ indexRouter.get('/help', function (req, res) { res.render('landing/help', { title: 'Ayuda | Dynamite Docs', level: 'landing/', layout: 'landing/struct' }); }); /* GET Privacy page. */ indexRouter.get('/privacy', function (req, res) { res.render('landing/privacy', { title: 'Privacidad | Dynamite Docs', level: 'landing/', layout: 'landing/struct' }); }); /* GET Sitemap page. */ indexRouter.get('/sitemap', function (req, res) { res.render('landing/sitemap', { title: 'Mapa del sitio | Dynamite Docs', level: 'landing/', layout: 'landing/struct' }); }); /* GET Terms page. */ indexRouter.get('/terms', function (req, res) { res.render('landing/terms', { title: 'Terminos y condiciones | Dynamite Docs', level: 'landing/', layout: 'landing/struct' }); }); /* ---------- END FOOTER MENU ---------- */ /* ---------- CROSS-PLATFORM ---------- */ /* GET Confirmation email page. */ indexRouter.get('/confirmation/:funct', function (req, res) { res.render('landing/confirmation', { title: 'Confirmación '+ req.params.funct + ' | Dynamite Docs', level: '../landing/', layout: 'landing/struct' }); }); /* POST Confirmation email page. */ indexRouter.post('/confirmation/:funct', function (req, res) { res.redirect('/'); }); /* GET Login page. */ indexRouter.get('/login', function (req, res) { res.render('dashboard/login', { title: 'Iniciar sesión | Dynamite Docs', level: '', isLogin: true }); }); /* POST Login page. */ indexRouter.post('/login', passport.authenticate('stormpath',{ successRedirect: '/dashboard', failureRedirect: '/login', failureFlash: 'Email o contraseña invalida.' })); /* GET Logout page. */ indexRouter.get('/logout', function (req, res) { req.logout(); res.redirect('/'); }); /* GET Reset Password page. */ indexRouter.get('/password/reset', function (req, res) { res.render('landing/passwordReset', { title: 'Recuperar contraseña | Dynamite Docs', level: '../landing/', layout: 'landing/struct' }); }); /* POST Confirmation email page. */ indexRouter.post('/password/reset', function (req, res) { res.redirect('/'); }); /* GET 404 page not found. */ //indexRouter.get("/*", function(req, res) { // res.render('landing/404', { // title: 'Oopsss página no encontrada | Dynamite Docs', // level: '../landing/', // layout: 'landing/struct' // }); //}); /* ---------- END CROSS-PLATFORM ---------- */ module.exports = indexRouter;
AlejoJamC/dynamite
routes/index.js
JavaScript
bsd-3-clause
3,924
/* jshint undef: true, unused: true */ /* global define, google: false */ define(['jquery','modules/mapStyles', 'velocity'], function($, MapStyles){ 'use strict'; var Map = { init: function() { if ($('#map-block').length) { this.createMap(); } $('.js-map-toggle').click(function() { if (!$('.changing-map').length) { var map = $('.js-map-wrapper'), fa = $('.js-map-btn [class*="pe-7s"]'); if (map.hasClass('active')) { Map.state.off(fa, map); } else { Map.state.on(fa, map); } } }); }, state: { on: function (btn, map) { btn.removeClass('pe-7s-map-marker').addClass('pe-7s-close'); map.addClass('changing-map'); map.addClass('active').velocity('stop').velocity({ translateY: ['0', '-100%'] }, 500, 'ease', function () { map.removeClass('changing-map'); }); }, off: function (btn, map) { btn.removeClass('pe-7s-close').addClass('pe-7s-map-marker'); map.addClass('changing-map'); map.velocity('stop').velocity({ translateY: ['-100%', '0'] }, 500, 'ease', function () { map.removeClass('active changing-map'); }); } }, createMap: function () { var mapBlock = document.getElementById('map-block'); var myLatlng = new google.maps.LatLng($(mapBlock).data('lon'), $(mapBlock).data('lat')); var mapOptions = { zoom: 15, center: myLatlng, mapTypeId: google.maps.MapTypeId.ROADMAP, styles: MapStyles }; var map = new google.maps.Map(mapBlock, mapOptions); var marker = new google.maps.Marker({ position: myLatlng, map: map }); google.maps.event.addListenerOnce(map, 'idle', function(){ $('.js-map-wrapper').hide(); }); } }; Map.init(); });
wadadaaa/marta
marta/static/js/modules/map.js
JavaScript
bsd-3-clause
1,769
exports.ExtractFromPages = ExtractFromPages; exports.ExtractLists = ExtractLists; exports.GetInnerText = GetInnerText; exports.GetCleanInnerText = GetCleanInnerText; exports.CleanText = CleanText; exports.GetAttribute = GetAttribute; exports.NoTransform = NoTransform; var JsonQuery = require('./JsonQuery'); var htmlparser = require('htmlparser'); var htmlencode = require('htmlencode'); //function to extract several lists. The purpose is to get *all* elements //of certain types. For example, extract all the urls on a page //Each request looks like the following: //example: { name: "url", // xpaths: ["html/body/div[id=wrapper]/div[id=main]/div[id=container]/div[id=cities-content]/div[id=cities-left]/div[id=cities-left-black]/div[id=terminals]/a"] , // transform : RemoveLastSlash} } //name is what each thing is //xpaths are where to find them //transform is what to do afterwards (text operation) function ExtractLists(jsonDom, requests) { //console.log(jsonDom); var extractionResults = new Object(); //console.log(requests); for (var i = 0; i < requests.length; i++) { //extractionResults = extractionResults.concat(ExtractList(jsonDom, requests[i])); //extractionResults.push(ExtractList(jsonDom, requests[i])); //console.log(extractionResults); var list = ExtractList(jsonDom, requests[i]); extractionResults[requests[i].name] = list[requests[i].name]; } return extractionResults; } function ExtractList(jsonDom, request) { //example: { name: "url", // xpaths: ["html/body/div[id=wrapper]/div[id=main]/div[id=container]/div[id=cities-content]/div[id=cities-left]/div[id=cities-left-black]/div[id=terminals]/a"] , // transform : RemoveLastSlash} //console.log(request); var rawList = JsonQuery.GetTagsByXPath(jsonDom, request.xpath); //console.log(jsonDom); //apply the transformation to each one var list = new Array(); for (var i = 0; i < rawList.length; i++) { //console.log("found something!"); var extraction = new Object(); list.push(request.transform(rawList[i])); } var listObject = new Object(); listObject[request.name] = list; return listObject; } //wrapper function function ExtractFromPagesAsync(jsonDom, extractionRequests, callback) { callback(ExtractFromPages(jsonDom, extractionRequests)); } //takes as input array of extractionRequests //extractionRequests are an array of extractionRequests //Each extraction request looks like: //name : string for attribute name //xpaths : array of xpaths //transformation : function specifying what string manipulations to do after extraction function ExtractFromPages(jsonDom, extractionRequests) { //ExtractionRequests is an array of objects containing: //extraction name //where to find raw data (xpath) //function to transform data var extractionResults = new Object(); for (var i = 0; i < extractionRequests.length; i++) { var extractedResult = TryExtractions(jsonDom, extractionRequests[i].xpaths, extractionRequests[i].transform) extractionResults[extractionRequests[i].name] = extractedResult; } return extractionResults; } //helper function used to try a particular xpath/transformation //returns undefined if unsuccesful //returns string of data if successful function TryExtractions(jsonDom, attributeRequests, transformation) { for (var i = 0; i < attributeRequests.length; i++) { var nodeInfo = JsonQuery.GetTagByXPath(jsonDom, attributeRequests[i]); if (nodeInfo != undefined) { //try text based transformation var transformed = transformation(nodeInfo); if (transformed != undefined) { return transformed; } } } return undefined; } function NoTransform(raw) { return raw; } //extracts the text nodes at a particular level. Does not get deeper nodes. function GetInnerText(json) { var textNodes = htmlparser.DomUtils.getElementsByTagType("text", json); var merged = ""; for (var i = 0; i < textNodes.length; i++) { merged = merged + textNodes[i]["raw"]; } //decode text to remove html formatting e.g &amp; var decoded = htmlencode.htmlDecode(merged); return decoded; } function GetCleanInnerText(json) { return CleanText(GetInnerText(json)); } //replace new line with " " //remove special characters such as &amp and replace with & function CleanText(text) { //console.log(text); //remove all the new lines return text.replace(/(\r\n|\n|\r)/gm, " "); } function GetAttribute(attributeName, json) { return JsonQuery.GetAttribute(json, attributeName); }
danpomerantz/buses
ExtractionLibrary.js
JavaScript
bsd-3-clause
4,464
var page = require('webpage').create(), system = require('system'), t, address; if (system.args.length === 1) { console.log('Usage: loadspeed.js <some URL>'); phantom.exit(); } else { t = Date.now(); address = system.args[1]; page.open(address, function (status) { if (status !== 'success') { console.log('FAIL to load the address'); } else { t = Date.now() - t; console.log('Page title is ' + page.evaluate(function () { return document.title; })); console.log('Loading time ' + t + ' msec'); } phantom.exit(); }); }
blorenz/phantomjs
examples/loadspeed.js
JavaScript
bsd-3-clause
659
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @flow */ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. 'use strict'; const util = require('util'); const Console = require('console').Console; const chalk = require('chalk'); class CustomConsole extends Console { warn() { return super.warn(chalk.yellow(util.format.apply(this, arguments))); } error() { return super.error(chalk.red(util.format.apply(this, arguments))); } } module.exports = CustomConsole;
sampepose/jest
packages/jest-util/src/Console.js
JavaScript
bsd-3-clause
1,824
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ 'use strict'; const mockComponent = require.requireActual('./mockComponent'); require.requireActual('../Libraries/polyfills/babelHelpers.js'); require.requireActual('../Libraries/polyfills/Object.es7.js'); require.requireActual('../Libraries/polyfills/error-guard'); global.__DEV__ = true; global.Promise = require.requireActual('promise'); global.regeneratorRuntime = require.requireActual('regenerator-runtime/runtime'); global.requestAnimationFrame = function(callback) { setTimeout(callback, 0); }; global.cancelAnimationFrame = function(id) { clearTimeout(id); }; jest .mock('setupDevtools') .mock('npmlog'); // there's a __mock__ for it. jest.setMock('ErrorUtils', require('ErrorUtils')); jest .mock('InitializeCore', () => {}) .mock('Image', () => mockComponent('Image')) .mock('Text', () => mockComponent('Text')) .mock('TextInput', () => mockComponent('TextInput')) .mock('Modal', () => mockComponent('Modal')) .mock('View', () => mockComponent('View')) .mock('RefreshControl', () => require.requireMock('RefreshControlMock')) .mock('ScrollView', () => require.requireMock('ScrollViewMock')) .mock( 'ActivityIndicator', () => mockComponent('ActivityIndicator'), ) .mock('ListView', () => require.requireMock('ListViewMock')) .mock('ListViewDataSource', () => { const DataSource = require.requireActual('ListViewDataSource'); DataSource.prototype.toJSON = function() { function ListViewDataSource(dataBlob) { this.items = 0; // Ensure this doesn't throw. try { Object.keys(dataBlob).forEach(key => { this.items += dataBlob[key] && ( dataBlob[key].length || dataBlob[key].size || 0 ); }); } catch (e) { this.items = 'unknown'; } } return new ListViewDataSource(this._dataBlob); }; return DataSource; }) .mock('AnimatedImplementation', () => { const AnimatedImplementation = require.requireActual('AnimatedImplementation'); const oldCreate = AnimatedImplementation.createAnimatedComponent; AnimatedImplementation.createAnimatedComponent = function(Component) { const Wrapped = oldCreate(Component); Wrapped.__skipSetNativeProps_FOR_TESTS_ONLY = true; return Wrapped; }; return AnimatedImplementation; }) .mock('ReactNative', () => { const ReactNative = require.requireActual('ReactNative'); const NativeMethodsMixin = ReactNative.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.NativeMethodsMixin; [ 'measure', 'measureInWindow', 'measureLayout', 'setNativeProps', 'focus', 'blur', ].forEach((key) => { let warned = false; NativeMethodsMixin[key] = function() { if (warned) { return; } warned = true; console.warn( 'Calling .' + key + '() in the test renderer environment is not ' + 'supported. Instead, mock out your components that use ' + 'findNodeHandle with replacements that don\'t rely on the ' + 'native environment.', ); }; }); return ReactNative; }) .mock('ensureComponentIsNative', () => () => true); const mockEmptyObject = {}; const mockNativeModules = { AlertManager: { alertWithArgs: jest.fn(), }, AppState: { addEventListener: jest.fn(), }, AsyncLocalStorage: { multiGet: jest.fn((keys, callback) => process.nextTick(() => callback(null, []))), multiSet: jest.fn((entries, callback) => process.nextTick(() => callback(null))), multiRemove: jest.fn((keys, callback) => process.nextTick(() => callback(null))), multiMerge: jest.fn((entries, callback) => process.nextTick(() => callback(null))), clear: jest.fn(callback => process.nextTick(() => callback(null))), getAllKeys: jest.fn(callback => process.nextTick(() => callback(null, []))), }, BuildInfo: { appVersion: '0', buildVersion: '0', }, Clipboard: { setString: jest.fn(), }, DataManager: { queryData: jest.fn(), }, DeviceInfo: { Dimensions: { window: { fontScale: 2, height: 1334, scale: 2, width: 750, }, }, }, FacebookSDK: { login: jest.fn(), logout: jest.fn(), queryGraphPath: jest.fn((path, method, params, callback) => callback()), }, FbRelayNativeAdapter: { updateCLC: jest.fn(), }, GraphPhotoUpload: { upload: jest.fn(), }, I18n: { translationsDictionary: JSON.stringify({ 'Good bye, {name}!|Bye message': '\u{00A1}Adi\u{00F3}s {name}!', }), }, ImageLoader: { getSize: jest.fn( (url) => new Promise(() => ({width: 320, height: 240})) ), prefetchImage: jest.fn(), }, ImageViewManager: { getSize: jest.fn( (uri, success) => process.nextTick(() => success(320, 240)) ), prefetchImage: jest.fn(), }, KeyboardObserver: { addListener: jest.fn(), removeListeners: jest.fn(), }, Linking: { openURL: jest.fn(), canOpenURL: jest.fn( () => new Promise((resolve) => resolve(true)) ), addEventListener: jest.fn(), getInitialURL: jest.fn( () => new Promise((resolve) => resolve()) ), removeEventListener: jest.fn(), }, LocationObserver: { getCurrentPosition: jest.fn(), startObserving: jest.fn(), stopObserving: jest.fn(), }, ModalFullscreenViewManager: {}, NetInfo: { fetch: jest.fn( () => new Promise((resolve) => resolve()) ), addEventListener: jest.fn(), isConnected: { fetch: jest.fn( () => new Promise((resolve) => resolve()) ), addEventListener: jest.fn(), }, }, Networking: { sendRequest: jest.fn(), abortRequest: jest.fn(), addListener: jest.fn(), removeListeners: jest.fn(), }, PushNotificationManager: { presentLocalNotification: jest.fn(), scheduleLocalNotification: jest.fn(), cancelAllLocalNotifications: jest.fn(), removeAllDeliveredNotifications: jest.fn(), getDeliveredNotifications: jest.fn(callback => process.nextTick(() => [])), removeDeliveredNotifications: jest.fn(), setApplicationIconBadgeNumber: jest.fn(), getApplicationIconBadgeNumber: jest.fn(callback => process.nextTick(() => callback(0))), cancelLocalNotifications: jest.fn(), getScheduledLocalNotifications: jest.fn(callback => process.nextTick(() => callback())), requestPermissions: jest.fn(() => Promise.resolve({alert: true, badge: true, sound: true})), abandonPermissions: jest.fn(), checkPermissions: jest.fn(callback => process.nextTick(() => callback({alert: true, badge: true, sound: true}))), getInitialNotification: jest.fn(() => Promise.resolve(null)), addListener: jest.fn(), removeListeners: jest.fn(), }, SourceCode: { scriptURL: null, }, StatusBarManager: { setColor: jest.fn(), setStyle: jest.fn(), setHidden: jest.fn(), setNetworkActivityIndicatorVisible: jest.fn(), setBackgroundColor: jest.fn(), setTranslucent: jest.fn(), }, Timing: { createTimer: jest.fn(), deleteTimer: jest.fn(), }, UIManager: { AndroidViewPager: { Commands: { setPage: jest.fn(), setPageWithoutAnimation: jest.fn(), }, }, blur: jest.fn(), createView: jest.fn(), dispatchViewManagerCommand: jest.fn(), focus: jest.fn(), setChildren: jest.fn(), manageChildren: jest.fn(), updateView: jest.fn(), removeSubviewsFromContainerWithID: jest.fn(), replaceExistingNonRootView: jest.fn(), customBubblingEventTypes: {}, customDirectEventTypes: {}, AndroidTextInput: { Commands: {}, }, ModalFullscreenView: { Constants: {}, }, ScrollView: { Constants: {}, }, View: { Constants: {}, }, }, BlobModule: { BLOB_URI_SCHEME: 'content', BLOB_URI_HOST: null, enableBlobSupport: jest.fn(), disableBlobSupport: jest.fn(), createFromParts: jest.fn(), sendBlob: jest.fn(), release: jest.fn(), }, WebSocketModule: { connect: jest.fn(), send: jest.fn(), sendBinary: jest.fn(), ping: jest.fn(), close: jest.fn(), addListener: jest.fn(), removeListeners: jest.fn(), }, }; Object.keys(mockNativeModules).forEach(module => { try { jest.doMock(module, () => mockNativeModules[module]); // needed by FacebookSDK-test } catch (e) { jest.doMock(module, () => mockNativeModules[module], {virtual: true}); } }); jest .doMock('NativeModules', () => mockNativeModules) .doMock('ReactNativePropRegistry', () => ({ register: id => id, getByID: () => mockEmptyObject, })); jest.doMock('requireNativeComponent', () => { const React = require('react'); return viewName => class extends React.Component { render() { return React.createElement( viewName, this.props, this.props.children, ); } }; });
frantic/react-native
jest/setup.js
JavaScript
bsd-3-clause
9,308
module.exports = require("./lib/hapi-auth-man");
ubaltaci/hapi-auth-man
index.js
JavaScript
bsd-3-clause
48
//表示用のステージを作成します var stage = new Stage( 300, 300 ); //ステージをベースにレイヤーを作成し、windowにアタッチします addLayer( new Layer( stage ) ); //Imageオブジェクトを生成します var image = new Image(); //Imageオブジェクトに画像のソースURLを設定します //このあたりはhtmlのimageと同じような概念となります image.src = "assets/images/image.png"; //画像リソースは読み込みが完了しないと扱えないので //onloadで画像の読み込み完了を待ちます image.addEventListener("load", onLoadImage); function onLoadImage(){ //イベントを解放します image.removeEventListener("load", onLoadImage); //読み込み完了時に画像リソースからBitmapDataを作成し、Bitmapをstageに追加します var bd = new BitmapData( image ); var bitmap = new Bitmap( bd ); //bitmapはタッチイベントを取得出来ないのでspriteを生成し、その中にbitmapを入れます var sprite = new Sprite(); sprite.addChild( bitmap ); //spriteをstageに追加します stage.addChild( sprite ); //spriteにタッチイベントを設定します sprite.addEventListener("touchBegin", onTouch); } function onTouch(){ alert("Hello!", alertCallback); } function alertCallback() { console.log("alerted"); }
sonicmoov/herlock-samples
touch/main.js
JavaScript
bsd-3-clause
1,441
/* global SETTINGS:false */ import React from "react" import R from "ramda" import { Provider } from "react-redux" import { assert } from "chai" import { mount } from "enzyme" import sinon from "sinon" import { EditorView } from "prosemirror-view" import EditPostForm from "./EditPostForm" import Editor from "./Editor" import { beginEditing, editPostKey } from "./EditPostForm" import { LINK_TYPE_ARTICLE } from "../lib/channels" import * as forms from "../actions/forms" import { actions } from "../actions" import { makePost } from "../factories/posts" import IntegrationTestHelper from "../util/integration_test_helper" describe("EditPostForm", () => { let helper, post, wrapper const renderEditPostForm = (props = {}) => mount( <Provider store={helper.store}> <EditPostForm post={post} editing {...props} /> </Provider> ) const setEditorText = (wrapper, text) => wrapper .find("Editor") .props() .onChange(text) beforeEach(() => { helper = new IntegrationTestHelper() post = makePost() helper.getPostStub.returns(Promise.resolve(post)) helper.store.dispatch(actions.posts.get(post.id)) helper.sandbox.stub(EditorView.prototype, "focus") wrapper = renderEditPostForm() }) afterEach(() => { helper.cleanup() }) it("should use the ArticleEditor if an article post", () => { post.post_type = LINK_TYPE_ARTICLE wrapper = renderEditPostForm() assert.ok(wrapper.find("ArticleEditor").exists()) }) it("should use an Editor when a text post", () => { wrapper = renderEditPostForm() assert.ok(wrapper.find(Editor).exists()) }) it("should have the autofocus prop", () => { assert.isTrue(wrapper.find("Editor").props().autoFocus) }) it("should trigger an update when text is input", async () => { const state = await helper.listenForActions([forms.FORM_UPDATE], () => { setEditorText(wrapper, "new post text") }) assert.equal(R.keys(state.forms).length, 1) assert.deepInclude(state.forms[R.keys(state.forms)[0]], { value: { text: "new post text" } }) }) it("should cancel and go away", async () => { const mockPreventDefault = helper.sandbox.stub() const state = await helper.listenForActions([forms.FORM_END_EDIT], () => { wrapper.find(".cancel").simulate("click", { preventDefault: mockPreventDefault }) }) assert.deepEqual(state.forms, {}) sinon.assert.calledWith(mockPreventDefault) }) it("should submit the form and only submit the text field", async () => { const { requestType, successType } = actions.posts.patch helper.editPostStub.returns(Promise.resolve(post)) beginEditing(helper.store.dispatch, editPostKey(post), post, undefined) await helper.listenForActions([forms.FORM_UPDATE], () => { setEditorText(wrapper, "edited text") }) const state = await helper.listenForActions( [requestType, successType, forms.FORM_END_EDIT], () => { wrapper.find("form").simulate("submit") } ) assert.deepEqual(state.forms, {}) assert.deepEqual(helper.editPostStub.args[0], [ post.id, { text: "edited text", id: post.id } ]) }) })
mitodl/open-discussions
static/js/components/EditPostForm_test.js
JavaScript
bsd-3-clause
3,233
const mongoose = require('mongoose'); const Schema = mongoose.Schema; const UserSchema = new Schema({ name: { type: String, required: true, unique: true, }, online: { type: Boolean, default: false, }, creation_date: { type: Date, default: new Date(), }, }); UserSchema.post('validate', (doc) => { if (doc.isNew) { doc.creation_date = new Date(); } }); const User = mongoose.model('User', UserSchema); module.exports = User;
involvestecnologia/business-chat-spike
backend/src/models/v1/user.js
JavaScript
bsd-3-clause
477
'use strict'; /* global countScopes */ describe('tooltip', function() { var bodyEl = $('body'), sandboxEl; var $rootScope, $compile, $templateCache, $$rAF, $animate, $timeout, $httpBackend, $tooltip, scope; beforeEach(module('ngSanitize')); beforeEach(module('ngAnimate')); beforeEach(module('ngAnimateMock')); beforeEach(module('mgcrea.ngStrap.tooltip')); beforeEach(inject(function($injector) { $rootScope = $injector.get('$rootScope'); $compile = $injector.get('$compile'); $templateCache = $injector.get('$templateCache'); $$rAF = $injector.get('$$rAF'); $animate = $injector.get('$animate'); $timeout = $injector.get('$timeout'); var flush = $animate.flush || $animate.triggerCallbacks; $animate.flush = function() { flush.call($animate); if(!$animate.triggerCallbacks) $timeout.flush(); }; $httpBackend = $injector.get('$httpBackend'); $tooltip = $injector.get('$tooltip'); bodyEl.html(''); sandboxEl = $('<div>').attr('id', 'sandbox').appendTo(bodyEl); scope = $rootScope.$new(); })); afterEach(function() { scope.$destroy(); sandboxEl.remove(); }); // Templates var templates = { 'default': { scope: {tooltip: {title: 'Hello Tooltip!'}}, element: '<a title="{{tooltip.title}}" bs-tooltip>hover me</a>' }, 'default-with-id': { scope: {tooltip: {title: 'Hello Tooltip!'}}, element: '<a id="link1" title="{{tooltip.title}}" bs-tooltip>hover me</a>' }, 'markup-button': { element: '<button type="button" bs-tooltip="tooltip">hover me</button>' }, 'markup-scope': { element: '<a bs-tooltip="tooltip">hover me</a>' }, 'markup-ngRepeat': { scope: {items: [{name: 'foo', tooltip: 'Hello Tooltip!'}]}, element: '<ul><li ng-repeat="item in items"><a title="{{item.tooltip}}" bs-tooltip>{{item.name}}</a></li></ul>' }, 'markup-ngClick-service': { element: '<a ng-click="showTooltip()">click me</a>' }, 'options-delay': { element: '<a data-delay="15" bs-tooltip="tooltip">hover me</a>' }, 'options-delay-multiple': { element: '<a data-delay="15,30" bs-tooltip="tooltip">hover me</a>' }, 'options-keyboard': { scope: {tooltip: {title: 'Hello Tooltip!', keyboard: true}}, element: '<a data-keyboard="true" bs-tooltip="tooltip">hover me</a>' }, 'options-animation': { element: '<a data-animation="am-flip-x" bs-tooltip="tooltip">hover me</a>' }, 'options-placement-top': { element: '<a data-placement="top" bs-tooltip="tooltip" data-viewport="null">hover me</a>' }, 'options-placement-right': { element: '<a data-placement="right" bs-tooltip="tooltip" data-viewport="null">hover me</a>' }, 'options-placement-bottom': { element: '<a data-placement="bottom" bs-tooltip="tooltip" data-viewport="null">hover me</a>' }, 'options-placement-left': { element: '<a data-placement="left" bs-tooltip="tooltip" data-viewport="null">hover me</a>' }, 'options-placement-exotic-top-left': { element: '<a data-placement="top-left" bs-tooltip="tooltip" data-viewport="null">hover me</a>' }, 'options-placement-exotic-top-right': { element: '<a data-placement="top-right" bs-tooltip="tooltip" data-viewport="null">hover me</a>' }, 'options-placement-exotic-bottom-left': { element: '<a data-placement="bottom-left" bs-tooltip="tooltip" data-viewport="null">hover me</a>' }, 'options-placement-exotic-bottom-right': { element: '<a data-placement="bottom-right" bs-tooltip="tooltip" data-viewport="null">hover me</a>' }, 'options-placement-exotic-right-top': { element: '<a data-placement="right-top" bs-tooltip="tooltip" data-viewport="null">hover me</a>' }, 'options-placement-exotic-right-bottom': { element: '<a data-placement="right-bottom" bs-tooltip="tooltip" data-viewport="null">hover me</a>' }, 'options-placement-exotic-left-top': { element: '<a data-placement="left-top" bs-tooltip="tooltip" data-viewport="null">hover me</a>' }, 'options-placement-exotic-left-bottom': { element: '<a data-placement="left-bottom" bs-tooltip="tooltip" data-viewport="null">hover me</a>' }, 'options-placement-auto': { element: '<a data-placement="auto" bs-tooltip="tooltip" data-viewport="null">hover me</a>' }, 'options-placement-auto-top': { element: '<a data-placement="auto top" bs-tooltip="tooltip" data-viewport="null">hover me</a>' }, 'options-placement-auto-right': { element: '<a data-placement="auto right" bs-tooltip="tooltip" data-viewport="null">hover me</a>' }, 'options-placement-auto-bottom': { element: '<a data-placement="auto bottom" bs-tooltip="tooltip" data-viewport="null">hover me</a>' }, 'options-placement-auto-left': { element: '<a data-placement="auto left" bs-tooltip="tooltip" data-viewport="null">hover me</a>' }, 'options-placement-auto-exotic-top-left': { element: '<a data-placement="auto top-left" bs-tooltip="tooltip" data-viewport="null">hover me</a>' }, 'options-placement-auto-exotic-top-right': { element: '<a data-placement="auto top-right" bs-tooltip="tooltip" data-viewport="null">hover me</a>' }, 'options-placement-auto-exotic-bottom-left': { element: '<a data-placement="auto bottom-left" bs-tooltip="tooltip" data-viewport="null">hover me</a>' }, 'options-placement-auto-exotic-bottom-right': { element: '<a data-placement="auto bottom-right" bs-tooltip="tooltip" data-viewport="null">hover me</a>' }, 'options-placement-viewport-top': { element: '<a data-placement="top" bs-tooltip="tooltip" data-viewport="\'#sandbox\'">hover me</a>' }, 'options-placement-viewport-right': { element: '<a data-placement="right" bs-tooltip="tooltip" data-viewport="\'#sandbox\'">hover me</a>' }, 'options-placement-viewport-bottom': { element: '<a data-placement="bottom" bs-tooltip="tooltip" data-viewport="\'#sandbox\'">hover me</a>' }, 'options-placement-viewport-left': { element: '<a data-placement="left" bs-tooltip="tooltip" data-viewport="\'#sandbox\'">hover me</a>' }, 'options-placement-viewport-padding': { element: '<a data-placement="right" bs-tooltip="tooltip" data-viewport="{ selector: \'#sandbox\', padding: 10 }">hover me</a>' }, 'options-placement-viewport-exotic': { element: '<a data-placement="bottom-right" bs-tooltip="tooltip" data-viewport="{ selector: \'#sandbox\', padding: 10 }">hover me</a>' }, 'options-trigger': { element: '<a data-trigger="click" bs-tooltip="tooltip">click me</a>' }, 'options-html': { scope: {tooltip: {title: 'title<br>next'}}, element: '<a data-html="{{html}}" bs-tooltip="tooltip">hover me</a>' }, 'options-container': { element: '<a data-container="{{container}}" bs-tooltip="tooltip">hover me</a>' }, 'options-template': { scope: {tooltip: {title: 'Hello Tooltip!', counter: 0}, items: ['foo', 'bar', 'baz']}, element: '<a title="{{tooltip.title}}" data-template-url="custom" bs-tooltip>hover me</a>' }, 'options-contentTemplate': { scope: {tooltip: {title: 'Hello Tooltip!', counter: 0}, items: ['foo', 'bar', 'baz']}, element: '<a title="{{tooltip.title}}" data-content-template="custom" bs-tooltip>hover me</a>' }, 'bsShow-attr': { scope: {tooltip: {title: 'Hello Tooltip!'}}, element: '<a title="{{tooltip.title}}" bs-tooltip bs-show="true">hover me</a>' }, 'bsShow-binding': { scope: {isVisible: false, tooltip: {title: 'Hello Tooltip!'}}, element: '<a title="{{tooltip.title}}" bs-tooltip bs-show="isVisible">hover me</a>' }, 'bsEnabled-attr': { scope: {tooltip: {title: 'Hello Tooltip!'}}, element: '<a title="{{tooltip.title}}" bs-tooltip bs-enabled="false">hover me</a>' }, 'bsEnabled-attr-binding': { scope: {tooltip: {title: 'Hello Tooltip!'}, isEnabled: true}, element: '<a title="{{tooltip.title}}" bs-tooltip bs-enabled="isEnabled">hover me</a>' }, 'bsTooltip-string': { element: '<a bs-tooltip="tooltip.title">hover me</a>' }, 'bsTooltip-ngRepeat-string': { scope: {items: [{name: 'foo', tooltip: 'Hello Tooltip!'}]}, element: '<ul><li ng-repeat="item in items"><a bs-tooltip="item.tooltip">{{item.name}}</a></li></ul>' }, 'bsTooltip-noValue': { scope: {title: 'Inherited Title'}, element: '<a bs-tooltip>hover me</a>' } }; function compileDirective(template, locals) { template = templates[template]; angular.extend(scope, template.scope || templates['default'].scope, locals); var element = $(template.element).appendTo(sandboxEl); element = $compile(element)(scope); scope.$digest(); return jQuery(element[0]); } // Tests describe('with default template', function() { it('should open on mouseenter', function() { var elm = compileDirective('default'); expect(sandboxEl.children('.tooltip').length).toBe(0); angular.element(elm[0]).triggerHandler('mouseenter'); $animate.flush(); expect(sandboxEl.children('.tooltip').length).toBe(1); }); it('should close on mouseleave', function() { var elm = compileDirective('default'); expect(sandboxEl.children('.tooltip').length).toBe(0); angular.element(elm[0]).triggerHandler('mouseenter'); $animate.flush(); angular.element(elm[0]).triggerHandler('mouseleave'); expect(sandboxEl.children('.tooltip').length).toBe(0); }); it('should correctly compile inner content', function() { var elm = compileDirective('default'); angular.element(elm[0]).triggerHandler('mouseenter'); $animate.flush(); expect(sandboxEl.find('.tooltip-inner').html()).toBe(scope.tooltip.title); }); it('should support scope as object', function() { var elm = compileDirective('markup-scope'); angular.element(elm[0]).triggerHandler('mouseenter'); $animate.flush(); expect(sandboxEl.find('.tooltip-inner').html()).toBe(scope.tooltip.title); }); it('should support ngRepeat markup', function() { var elm = compileDirective('markup-ngRepeat'); angular.element(elm.find('[bs-tooltip]')).triggerHandler('mouseenter'); $animate.flush(); expect(sandboxEl.find('.tooltip-inner').html()).toBe(scope.items[0].tooltip); }); it('should support button markup', function() { var elm = compileDirective('markup-button'); angular.element(elm[0]).triggerHandler('mouseenter'); $animate.flush(); expect(sandboxEl.children('.tooltip').length).toBe(1); angular.element(elm[0]).triggerHandler('click'); expect(sandboxEl.children('.tooltip').length).toBe(1); }); }); describe('resource allocation', function() { it('should not create additional scopes after first show', function() { var elm = compileDirective('default'); expect(sandboxEl.children('.tooltip').length).toBe(0); angular.element(elm[0]).triggerHandler('mouseenter'); $animate.flush(); expect(sandboxEl.children('.tooltip').length).toBe(1); angular.element(elm[0]).triggerHandler('mouseleave'); $animate.flush(); expect(sandboxEl.children('.tooltip').length).toBe(0); var scopeCount = countScopes(scope, 0); for (var i = 0; i < 10; i++) { angular.element(elm[0]).triggerHandler('mouseenter'); $animate.flush(); angular.element(elm[0]).triggerHandler('mouseleave'); $animate.flush(); } expect(countScopes(scope, 0)).toBe(scopeCount); }); it('should destroy scopes when destroying directive scope', function() { var scopeCount = countScopes(scope, 0); var originalScope = scope; scope = scope.$new(); var elm = compileDirective('default'); for (var i = 0; i < 10; i++) { angular.element(elm[0]).triggerHandler('mouseenter'); $animate.flush(); angular.element(elm[0]).triggerHandler('mouseleave'); $animate.flush(); } scope.$destroy(); scope = originalScope; expect(countScopes(scope, 0)).toBe(scopeCount); }); }); describe('bsShow attribute', function() { it('should support setting to a boolean value', function() { var elm = compileDirective('bsShow-attr'); expect(sandboxEl.children('.tooltip').length).toBe(1); }); it('should support binding', function() { var elm = compileDirective('bsShow-binding'); expect(scope.isVisible).toBeFalsy(); expect(sandboxEl.children('.tooltip').length).toBe(0); scope.isVisible = true; scope.$digest(); expect(sandboxEl.children('.tooltip').length).toBe(1); scope.isVisible = false; scope.$digest(); expect(sandboxEl.children('.tooltip').length).toBe(0); }); it('should support initial value false', function() { var elm = compileDirective('bsShow-binding'); expect(scope.isVisible).toBeFalsy(); expect(sandboxEl.children('.tooltip').length).toBe(0); }); it('should support initial value true', function() { var elm = compileDirective('bsShow-binding', {isVisible: true}); expect(scope.isVisible).toBeTruthy(); expect(sandboxEl.children('.tooltip').length).toBe(1); }); it('should support undefined value', function() { var elm = compileDirective('bsShow-binding', {isVisible: undefined}); expect(sandboxEl.children('.tooltip').length).toBe(0); }); it('should support string value', function() { var elm = compileDirective('bsShow-binding', {isVisible: 'a string value'}); expect(sandboxEl.children('.tooltip').length).toBe(0); scope.isVisible = 'TRUE'; scope.$digest(); expect(sandboxEl.children('.tooltip').length).toBe(1); scope.isVisible = 'dropdown'; scope.$digest(); expect(sandboxEl.children('.tooltip').length).toBe(0); scope.isVisible = 'datepicker,tooltip'; scope.$digest(); expect(sandboxEl.children('.tooltip').length).toBe(1); }); }); describe('bsEnabled attribute', function() { it('should support setting to a boolean value', function() { var elm = compileDirective('bsEnabled-attr'); expect(sandboxEl.children('.tooltip').length).toBe(0); angular.element(elm[0]).triggerHandler('mouseenter'); $animate.flush(); expect(sandboxEl.children('.tooltip').length).toBe(0); }); it('should open on mouseenter when enabled', function() { var elm = compileDirective('bsEnabled-attr-binding'); expect(sandboxEl.children('.tooltip').length).toBe(0); angular.element(elm[0]).triggerHandler('mouseenter'); $animate.flush(); expect(sandboxEl.children('.tooltip').length).toBe(1); }); it('should close on mouseleave when enabled', function() { var elm = compileDirective('bsEnabled-attr-binding'); expect(sandboxEl.children('.tooltip').length).toBe(0); angular.element(elm[0]).triggerHandler('mouseenter'); $animate.flush(); expect(sandboxEl.children('.tooltip').length).toBe(1); angular.element(elm[0]).triggerHandler('mouseleave'); expect(sandboxEl.children('.tooltip').length).toBe(0); }); it('should not open on mouseenter when disabled', function() { var elm = compileDirective('bsEnabled-attr-binding', { isEnabled: false }); expect(sandboxEl.children('.tooltip').length).toBe(0); angular.element(elm[0]).triggerHandler('mouseenter'); $animate.flush(); expect(sandboxEl.children('.tooltip').length).toBe(0); }); it('should close on mouseleave when disabled', function() { var elm = compileDirective('bsEnabled-attr-binding'); expect(sandboxEl.children('.tooltip').length).toBe(0); angular.element(elm[0]).triggerHandler('mouseenter'); $animate.flush(); expect(sandboxEl.children('.tooltip').length).toBe(1); scope.isEnabled = false; scope.$digest(); angular.element(elm[0]).triggerHandler('mouseleave'); expect(sandboxEl.children('.tooltip').length).toBe(0); }); it('should support undefined value', function() { var elm = compileDirective('bsEnabled-attr-binding', { isEnabled: undefined }); angular.element(elm[0]).triggerHandler('mouseenter'); $animate.flush(); expect(sandboxEl.children('.tooltip').length).toBe(1); }); it('should support string values', function() { var elm = compileDirective('bsEnabled-attr-binding', { isEnabled: 'true' }); angular.element(elm[0]).triggerHandler('mouseenter'); $animate.flush(); expect(sandboxEl.children('.tooltip').length).toBe(1); angular.element(elm[0]).triggerHandler('mouseleave'); scope.isEnabled = 'false'; scope.$digest(); angular.element(elm[0]).triggerHandler('mouseenter'); expect(sandboxEl.children('.tooltip').length).toBe(0); angular.element(elm[0]).triggerHandler('mouseleave'); scope.isEnabled = '1'; scope.$digest(); angular.element(elm[0]).triggerHandler('mouseenter'); expect(sandboxEl.children('.tooltip').length).toBe(1); angular.element(elm[0]).triggerHandler('mouseleave'); scope.isEnabled = '0'; scope.$digest(); angular.element(elm[0]).triggerHandler('mouseenter'); expect(sandboxEl.children('.tooltip').length).toBe(0); angular.element(elm[0]).triggerHandler('mouseleave'); scope.isEnabled = 'tooltip'; scope.$digest(); angular.element(elm[0]).triggerHandler('mouseenter'); expect(sandboxEl.children('.tooltip').length).toBe(1); }); }); describe('bsTooltip attribute', function() { it('should support string value', function() { var elm = compileDirective('bsTooltip-string'); angular.element(elm[0]).triggerHandler('mouseenter'); $animate.flush(); expect(sandboxEl.find('.tooltip-inner').html()).toBe(scope.tooltip.title); }); it('should support string value from within ngRepeat markup', function() { var elm = compileDirective('bsTooltip-ngRepeat-string'); angular.element(elm.find('[bs-tooltip]')).triggerHandler('mouseenter'); $animate.flush(); expect(sandboxEl.find('.tooltip-inner').html()).toBe(scope.items[0].tooltip); }); it('should overwrite inherited title when no value specified', function() { var elm = compileDirective('bsTooltip-noValue'); angular.element(elm[0]).triggerHandler('mouseenter'); $animate.flush(); expect(sandboxEl.find('.tooltip-inner').html()).toBe(''); }); }); describe('using service', function() { it('should correctly open on next digest', function() { var myTooltip = $tooltip(sandboxEl, templates['default'].scope.tooltip); scope.$digest(); expect(bodyEl.children('.tooltip').length).toBe(0); myTooltip.show(); $animate.flush(); expect(bodyEl.children('.tooltip').length).toBe(1); myTooltip.hide(); expect(bodyEl.children('.tooltip').length).toBe(0); }); it('should open if option show is true', function() { var options = angular.extend({ show: true }, templates['default'].scope.tooltip); var myTooltip = $tooltip(sandboxEl, options); scope.$digest(); $animate.flush(); expect(bodyEl.children('.tooltip').length).toBe(1); myTooltip.hide(); scope.$digest(); $animate.flush(); expect(bodyEl.children('.tooltip').length).toBe(0); }); it('should do nothing when hiding an already hidden popup', function() { var myTooltip = $tooltip(sandboxEl, templates['default'].scope.tooltip); scope.$digest(); expect(function() { myTooltip.hide(); }).not.toThrow(); }); it('should correctly be destroyed', function() { var myTooltip = $tooltip(sandboxEl, templates['default'].scope.tooltip); scope.$digest(); expect(bodyEl.children('.tooltip').length).toBe(0); myTooltip.show(); expect(bodyEl.children('.tooltip').length).toBe(1); myTooltip.destroy(); expect(bodyEl.children('.tooltip').length).toBe(0); expect(bodyEl.children().length).toBe(1); }); it('should correctly work with ngClick', function() { var elm = compileDirective('markup-ngClick-service'); var myTooltip = $tooltip(sandboxEl, templates['default'].scope.tooltip); scope.showTooltip = function() { myTooltip.$promise.then(myTooltip.show); }; expect(bodyEl.children('.tooltip').length).toBe(0); angular.element(elm[0]).triggerHandler('click'); expect(bodyEl.children('.tooltip').length).toBe(1); }); it('should correctly work with ngClick with an isolated scope', function() { scope = scope.$new(true); var elm = compileDirective('markup-ngClick-service'); var myTooltip = $tooltip(sandboxEl, {scope:scope, trigger: 'manual'}); scope.showTooltip = function() { myTooltip.$promise.then(myTooltip.show); }; expect(bodyEl.children('.tooltip').length).toBe(0); angular.element(elm[0]).triggerHandler('click'); expect(bodyEl.children('.tooltip').length).toBe(1); }); it('should store config id value in instance', function() { var myTooltip = $tooltip(sandboxEl, {scope:scope, trigger: 'manual', id: 'instance1'}); expect(myTooltip.$id).toBe('instance1'); }); it('should fallback to element id value when id is not provided in config', function() { var myTooltip = $tooltip(sandboxEl, {scope:scope, trigger: 'manual'}); expect(myTooltip.$id).toBe('sandbox'); }); }); describe('using scope helpers', function() { var elm, elmScope; beforeEach(function() { elm = compileDirective('default'); elmScope = angular.element(elm).scope().$$childTail; scope.$digest(); }); it('should correctly open on next digest', function() { expect(sandboxEl.children('.tooltip').length).toBe(0); expect(elmScope.$isShown).toBeFalsy(); elmScope.$show(); scope.$digest(); expect(sandboxEl.children('.tooltip').length).toBe(1); expect(elmScope.$isShown).toBeTruthy(); elmScope.$hide(); scope.$digest(); expect(sandboxEl.children('.tooltip').length).toBe(0); expect(elmScope.$isShown).toBeFalsy(); elmScope.$toggle(); scope.$digest(); expect(sandboxEl.children('.tooltip').length).toBe(1); expect(elmScope.$isShown).toBeTruthy(); elmScope.$toggle(); scope.$digest(); expect(sandboxEl.children('.tooltip').length).toBe(0); expect(elmScope.$isShown).toBeFalsy(); }); it('should do nothing when hiding an already hidden popup', function() { expect(sandboxEl.children('.tooltip').length).toBe(0); expect(elmScope.$isShown).toBeFalsy(); elmScope.$hide(); scope.$digest(); expect(sandboxEl.children('.tooltip').length).toBe(0); expect(elmScope.$isShown).toBeFalsy(); }); it('should do nothing when showing an already visible popup', function() { expect(sandboxEl.children('.tooltip').length).toBe(0); expect(elmScope.$isShown).toBeFalsy(); elmScope.$show(); scope.$digest(); expect(sandboxEl.children('.tooltip').length).toBe(1); expect(elmScope.$isShown).toBeTruthy(); elmScope.$show(); scope.$digest(); expect(sandboxEl.children('.tooltip').length).toBe(1); expect(elmScope.$isShown).toBeTruthy(); }); }); describe('show / hide events', function() { it('should dispatch show and show.before events', function() { var myTooltip = $tooltip(sandboxEl, templates['default'].scope.tooltip); var emit = spyOn(myTooltip.$scope, '$emit'); scope.$digest(); myTooltip.show(); expect(emit).toHaveBeenCalledWith('tooltip.show.before', myTooltip); // show only fires AFTER the animation is complete expect(emit).not.toHaveBeenCalledWith('tooltip.show', myTooltip); $animate.flush(); expect(emit).toHaveBeenCalledWith('tooltip.show', myTooltip); }); it('should dispatch hide and hide.before events', function() { var myTooltip = $tooltip(sandboxEl, templates['default'].scope.tooltip); scope.$digest(); myTooltip.show(); var emit = spyOn(myTooltip.$scope, '$emit'); myTooltip.hide(); expect(emit).toHaveBeenCalledWith('tooltip.hide.before', myTooltip); // hide only fires AFTER the animation is complete expect(emit).not.toHaveBeenCalledWith('tooltip.hide', myTooltip); $animate.flush(); expect(emit).toHaveBeenCalledWith('tooltip.hide', myTooltip); }); it('should namespace show/hide events using the prefixEvent', function() { var myTooltip = $tooltip(sandboxEl, angular.extend({prefixEvent: 'datepicker'}, templates['default'].scope.tooltip)); var emit = spyOn(myTooltip.$scope, '$emit'); scope.$digest(); myTooltip.show(); myTooltip.hide(); $animate.flush(); expect(emit).toHaveBeenCalledWith('datepicker.show.before', myTooltip); expect(emit).toHaveBeenCalledWith('datepicker.show', myTooltip); expect(emit).toHaveBeenCalledWith('datepicker.hide.before', myTooltip); expect(emit).toHaveBeenCalledWith('datepicker.hide', myTooltip); }); it('should be invisible until it is positioned', inject(function ($$rAF) { var myTooltip = $tooltip(sandboxEl, templates['default'].scope.tooltip); scope.$digest(); myTooltip.show(); expect(bodyEl.children('.tooltip').css('visibility')).toBe('hidden'); // Positioning and visibility occurs inside the rAF callback. $$rAF.flush(); expect(bodyEl.children('.tooltip').css('visibility')).toBe('visible'); })); it('should call show.before event with tooltip element instance id', function() { var elm = compileDirective('default-with-id'); var id = ""; scope.$on('tooltip.show.before', function(evt, tooltip) { id = tooltip.$id; }); angular.element(elm[0]).triggerHandler('mouseenter'); scope.$digest(); expect(id).toBe('link1'); }); }); describe('options', function() { describe('animation', function() { it('should default to `am-fade` animation', function() { var elm = compileDirective('default'); angular.element(elm[0]).triggerHandler('mouseenter'); expect(sandboxEl.children('.tooltip').hasClass('am-fade')).toBeTruthy(); }); it('should support custom animation', function() { var elm = compileDirective('options-animation'); angular.element(elm[0]).triggerHandler('mouseenter'); expect(sandboxEl.children('.tooltip').hasClass('am-flip-x')).toBeTruthy(); }); }); describe('delay', function() { it('should support delay', function(done) { var elm = compileDirective('options-delay'); angular.element(elm[0]).triggerHandler('mouseenter'); $animate.flush(); expect(sandboxEl.children('.tooltip').length).toBe(0); setTimeout(function() { expect(sandboxEl.children('.tooltip').length).toBe(1); done(); }, 20); }); it('should support multiple delay', function(done) { var elm = compileDirective('options-delay-multiple'); angular.element(elm[0]).triggerHandler('mouseenter'); $animate.flush(); expect(sandboxEl.children('.tooltip').length).toBe(0); setTimeout(function() { expect(sandboxEl.children('.tooltip').length).toBe(1); done(); }, 20); }); }); describe('keyboard', function() { it('should dismiss and stopPropagation if ESC is pressed when trigger !== "focus"', function() { var myTooltip = $tooltip(sandboxEl, angular.extend({trigger: 'click'}, templates['options-keyboard'].scope.tooltip)); scope.$digest(); expect(bodyEl.children('.tooltip').length).toBe(0); myTooltip.show(); expect(bodyEl.children('.tooltip').length).toBe(1); var evt = jQuery.Event( 'keyup', { keyCode: 27, which: 27 } ); spyOn(evt, 'stopPropagation'); myTooltip.$onKeyUp(evt); expect(bodyEl.children('.tooltip').length).toBe(0); expect(evt.stopPropagation).toHaveBeenCalled(); }); it('should NOT stopPropagation if ESC is pressed while tooltip is hidden', function() { var myTooltip = $tooltip(sandboxEl, angular.extend({trigger: 'click'}, templates['options-keyboard'].scope.tooltip)); scope.$digest(); var evt = jQuery.Event( 'keyup', { keyCode: 27, which: 27 } ); spyOn(evt, 'stopPropagation'); myTooltip.$onKeyUp(evt); expect(evt.stopPropagation).not.toHaveBeenCalled(); }); it('should blur and stopPropagation if ESC is pressed when trigger === "focus"', function() { var myTooltip = $tooltip(sandboxEl, angular.extend({trigger: 'focus'}, templates['options-keyboard'].scope.tooltip)); spyOn(sandboxEl[0], 'blur'); var evt = jQuery.Event( 'keyup', { keyCode: 27, which: 27 } ); spyOn(evt, 'stopPropagation'); myTooltip.$onFocusKeyUp(evt); expect(sandboxEl[0].blur).toHaveBeenCalled(); expect(evt.stopPropagation).toHaveBeenCalled(); }); }); describe('placement', function() { it('should default to `top` placement', function() { var elm = compileDirective('default'); angular.element(elm[0]).triggerHandler('mouseenter'); $$rAF.flush(); expect(sandboxEl.children('.tooltip').hasClass('top')).toBeTruthy(); }); it('should support placement', function() { var elm = compileDirective('options-placement-bottom'); angular.element(elm[0]).triggerHandler('mouseenter'); $$rAF.flush(); expect(sandboxEl.children('.tooltip').hasClass('bottom')).toBeTruthy(); }); it('should support exotic-placement', function() { var elm = compileDirective('options-placement-exotic-bottom-right'); angular.element(elm[0]).triggerHandler('mouseenter'); $$rAF.flush(); expect(sandboxEl.children('.tooltip').hasClass('bottom-right')).toBeTruthy(); }); describe('auto placement', function () { it('should remove `auto` from placements when auto positioning', function () { var elm = compileDirective('options-placement-auto-top'); angular.element(elm[0]).triggerHandler('mouseenter'); // need to change the width and height so we don't trigger // the repositioning sandboxEl.children('.tooltip').css({ width: 0, height: 0 }); $$rAF.flush(); expect(sandboxEl.children('.tooltip').hasClass('top')).toBeTruthy(); }); it('should remove `auto` from exotic placements when auto positioning', function () { var elm = compileDirective('options-placement-auto-exotic-top-left'); angular.element(elm[0]).triggerHandler('mouseenter'); // need to change the width and height so we don't trigger // the repositioning sandboxEl.children('.tooltip').css({ width: 0, height: 0 }); $$rAF.flush(); expect(sandboxEl.children('.tooltip').hasClass('bottom-right')).toBeTruthy(); }); it('should default to `top` when `auto` placement is set without a preference', function () { var elm = compileDirective('options-placement-auto'); angular.element(elm[0]).triggerHandler('mouseenter'); // need to change the width and height so we don't trigger // the repositioning sandboxEl.children('.tooltip').css({ width: 0, height: 0 }); $$rAF.flush(); expect(sandboxEl.children('.tooltip').hasClass('top')).toBeTruthy(); }); }); }); describe('trigger', function() { it('should support an alternative trigger', function() { var elm = compileDirective('options-trigger'); expect(sandboxEl.children('.tooltip').length).toBe(0); angular.element(elm[0]).triggerHandler('click'); expect(sandboxEl.children('.tooltip').length).toBe(1); angular.element(elm[0]).triggerHandler('click'); expect(sandboxEl.children('.tooltip').length).toBe(0); }); }); describe('html', function() { it('should not compile inner content by default', function() { var elm = compileDirective('default', {tooltip: {title: 'title<br>next'}}); angular.element(elm[0]).triggerHandler('mouseenter'); expect(sandboxEl.find('.tooltip-inner').html()).not.toBe('title<br>next'); }); it('should compile inner content if html is truthy', function() { var elm = compileDirective('options-html', {html: 'true'}); angular.element(elm[0]).triggerHandler('mouseenter'); expect(sandboxEl.find('.tooltip-inner').html()).toBe('title<br>next'); }); it('should NOT compile inner content if html is false', function() { var elm = compileDirective('options-html', {html: 'false'}); angular.element(elm[0]).triggerHandler('mouseenter'); expect(sandboxEl.find('.tooltip-inner').html()).not.toBe('title<br>next'); }); }); describe('template', function() { it('should support custom template', function() { $templateCache.put('custom', '<div class="tooltip"><div class="tooltip-inner">foo: {{title}}</div></div>'); var elm = compileDirective('options-template'); angular.element(elm[0]).triggerHandler('mouseenter'); expect(sandboxEl.find('.tooltip-inner').text()).toBe('foo: ' + scope.tooltip.title); }); it('should support custom template loaded by ngInclude', function() { $templateCache.put('custom', [200, '<div class="tooltip"><div class="tooltip-inner">foo: {{title}}</div></div>', {}, 'OK']); var elm = compileDirective('options-template'); angular.element(elm[0]).triggerHandler('mouseenter'); expect(sandboxEl.find('.tooltip-inner').text()).toBe('foo: ' + scope.tooltip.title); }); it('should request custom template via $http', function() { $httpBackend.expectGET('custom').respond(200, '<div class="tooltip"><div class="tooltip-inner">foo: {{title}}</div></div>'); var elm = compileDirective('options-template'); $httpBackend.flush(); angular.element(elm[0]).triggerHandler('mouseenter'); expect(sandboxEl.find('.tooltip-inner').text()).toBe('foo: ' + scope.tooltip.title); }); it('should request custom template via $http only once', function() { $httpBackend.expectGET('custom').respond(200, '<div class="tooltip"><div class="tooltip-inner">foo: {{title}}</div></div>'); var elm = compileDirective('options-template'); var elmBis = compileDirective('options-template'); $httpBackend.flush(); angular.element(elm[0]).triggerHandler('mouseenter'); expect(sandboxEl.find('.tooltip-inner').text()).toBe('foo: ' + scope.tooltip.title); }); it('should support template with ngRepeat', function() { $templateCache.put('custom', '<div class="tooltip"><div class="tooltip-inner"><ul><li ng-repeat="item in items">{{item}}</li></ul></div></div>'); var elm = compileDirective('options-template'); angular.element(elm[0]).triggerHandler('mouseenter'); expect(sandboxEl.find('.tooltip-inner').text()).toBe('foobarbaz'); // Consecutive toggles angular.element(elm[0]).triggerHandler('mouseleave'); angular.element(elm[0]).triggerHandler('mouseenter'); expect(sandboxEl.find('.tooltip-inner').text()).toBe('foobarbaz'); }); it('should support template with ngClick', function() { $templateCache.put('custom', '<div class="tooltip"><div class="tooltip-inner"><a class="btn" ng-click="tooltip.counter=tooltip.counter+1">click me</a></div></div>'); var elm = compileDirective('options-template'); angular.element(elm[0]).triggerHandler('mouseenter'); expect(angular.element(sandboxEl.find('.tooltip-inner > .btn')[0]).triggerHandler('click')); expect(scope.tooltip.counter).toBe(1); // Consecutive toggles angular.element(elm[0]).triggerHandler('mouseleave'); angular.element(elm[0]).triggerHandler('mouseenter'); expect(angular.element(sandboxEl.find('.tooltip-inner > .btn')[0]).triggerHandler('click')); expect(scope.tooltip.counter).toBe(2); }); }); describe('contentTemplate', function() { it('should support custom contentTemplate', function() { $templateCache.put('custom', 'foo: {{title}}'); var elm = compileDirective('options-contentTemplate'); angular.element(elm[0]).triggerHandler('mouseenter'); expect(sandboxEl.find('.tooltip-inner').text()).toBe('foo: ' + scope.tooltip.title); }); }); describe('container', function() { it('accepts element object', function() { var testElm = angular.element('<div></div>'); sandboxEl.append(testElm); var myTooltip = $tooltip(sandboxEl, angular.extend({}, templates['default'].scope.tooltip, {container: testElm})); scope.$digest(); myTooltip.show(); $animate.flush(); expect(angular.element(testElm.children()[0]).hasClass('tooltip')).toBeTruthy(); }); it('should be contained by element specified in data-container', function() { var testElm = angular.element('<div id="testElm"></div>'); sandboxEl.append(testElm); var elm = compileDirective('options-container', angular.extend({}, templates['default'].scope.tooltip, {container: '#testElm'})); expect(testElm.children('.tooltip').length).toBe(0); angular.element(elm[0]).triggerHandler('mouseenter'); $animate.flush(); expect(testElm.children('.tooltip').length).toBe(1); }); it('should belong to sandbox when data-container is falsy', function() { var elm = compileDirective('options-container', angular.extend({}, templates['default'].scope.tooltip, {container: 'false'})); expect(sandboxEl.children('.tooltip').length).toBe(0); angular.element(elm[0]).triggerHandler('mouseenter'); $animate.flush(); expect(sandboxEl.children('.tooltip').length).toBe(1); }); }); describe('viewport', function () { it('should default the viewport to body with a padding of 0 when not set', function () { var myTooltip = $tooltip(sandboxEl, {}); var tipOptions = myTooltip.$options; expect(tipOptions.viewport.selector).toBe('body'); expect(tipOptions.viewport.padding).toBe(0); }); it('should support using an element', function () { var myViewport = angular.element(document.createElement('div')); var myTooltip = $tooltip(sandboxEl, { viewport: myViewport }); var tipOptions = myTooltip.$options; expect(tipOptions.viewport).toBe(myViewport); }); it('should support specifying a selector and padding', function () { var myViewport = { selector: '#someSelector', padding: 100 }; var myTooltip = $tooltip(sandboxEl, { viewport: myViewport }); var tipOptions = myTooltip.$options; expect(tipOptions.viewport.selector).toBe('#someSelector'); expect(tipOptions.viewport.padding).toBe(100); }); }); }); describe('placements', function () { function calculatePlacements(placements, styleEl) { if (styleEl) { bodyEl.append(styleEl); } for (var placement in placements) { var elm = compileDirective(placement); angular.element(elm[0]).triggerHandler('mouseenter'); // Find the tip in the sandbox and grab it's // top and left styles var tipElement = sandboxEl.children('.tooltip')[0]; placements[placement] = { top: tipElement.style.top, left: tipElement.style.left, }; // Clear the sandbox after we've rendered // each tooltip sandboxEl.html(''); } if (styleEl) { styleEl.remove(); } return placements; } var standardPlacements, autoPlacements, viewportPlacements; beforeEach(function () { var styleEl = $('<style>' + ' body { padding: 0; margin: 0; } ' + ' #sandbox { height: 100px; width: 100px; } ' + ' a { display: inline-block; height: 20px; width: 20px; } ' + ' .tooltip { height: 100px; width: 200px; position: absolute; } ' + // Tooltip is purposely bigger than sandbox to trigger auto placement '</style>'); standardPlacements = calculatePlacements({ 'options-placement-top': {}, 'options-placement-right': {}, 'options-placement-bottom': {}, 'options-placement-left': {}, 'options-placement-exotic-top-left': {}, 'options-placement-exotic-top-right': {}, 'options-placement-exotic-bottom-left': {}, 'options-placement-exotic-bottom-right': {}, 'options-placement-exotic-right-top': {}, 'options-placement-exotic-right-bottom': {}, 'options-placement-exotic-left-top': {}, 'options-placement-exotic-left-bottom': {} }, styleEl); autoPlacements = calculatePlacements({ 'options-placement-auto-top': {}, 'options-placement-auto-right': {}, 'options-placement-auto-bottom': {}, 'options-placement-auto-left': {}, 'options-placement-auto-exotic-top-left': {}, 'options-placement-auto-exotic-top-right': {}, 'options-placement-auto-exotic-bottom-left': {}, 'options-placement-auto-exotic-bottom-right': {} }, styleEl); // Change the style for viewport testing styleEl = $('<style>' + ' body { padding: 0; margin: 0; } ' + ' #sandbox { height: 200px; width: 200px; position: absolute; top: 100px; left: 100px; } ' + ' a { display: inline-block; height: 20px; width: 20px; position: absolute; } ' + ' .tooltip { height: 100px; width: 100px; position: absolute; } ' + ' a[data-placement="top"] { bottom: 0; left: 0; } ' + ' a[data-placement="right"] { top: 0; left: 0; } ' + ' a[data-placement="bottom"] { top: 0; right: 0; } ' + ' a[data-placement="left"] { bottom: 0; right: 0; } ' + '</style>'); viewportPlacements = calculatePlacements({ 'options-placement-viewport-top': {}, 'options-placement-viewport-right': {}, 'options-placement-viewport-bottom': {}, 'options-placement-viewport-left': {}, 'options-placement-viewport-padding': {}, 'options-placement-viewport-exotic': {} }, styleEl); }); describe('default placement', function () { it('should be placed off screen till its been positioned', inject(function (dimensions) { // Spy on setOffset and make it do nothing. That way // the initial position is maintained. spyOn(dimensions, 'setOffset').and.callFake(function () {}); var elm = compileDirective('options-placement-top'); angular.element(elm[0]).triggerHandler('mouseenter'); var tip = sandboxEl.children('.tooltip')[0]; expect(tip.style.top).toBe('-9999px'); expect(tip.style.left).toBe('-9999px'); })); it('should have the correct width when right:0 is previously set for the tooltip', inject(function (dimensions) { bodyEl.append('<style>' + ' .tooltip { position: absolute; right: 0; } ' + '</style>'); var elm = compileDirective('options-placement-top'); angular.element(elm[0]).triggerHandler('mouseenter'); var tip = sandboxEl.children('.tooltip')[0]; expect(tip.offsetWidth <= 500).toBe(true); })); }); describe('standard placements', function() { it('should position the tooltip above the target when placement is `top`', function () { var placement = standardPlacements['options-placement-top']; expect(placement.top).toBe('-100px'); expect(placement.left).toBe('-90px'); }); it('should position the tooltip to the right of the target when placement is `right`', function () { var placement = standardPlacements['options-placement-right']; expect(placement.top).toBe('-40px'); expect(placement.left).toBe('20px'); }); it('should position the tooltip below the target when placement is `bottom`', function () { var placement = standardPlacements['options-placement-bottom']; expect(placement.top).toBe('20px'); expect(placement.left).toBe('-90px'); }); it('should position the tooltip to the left of the target when placement is `left`', function () { var placement = standardPlacements['options-placement-left']; expect(placement.top).toBe('-40px'); expect(placement.left).toBe('-200px'); }); it('should position the tooltip to the top-left of the target when placement is `top-left`', function () { var placement = standardPlacements['options-placement-exotic-top-left']; expect(placement.top).toBe('-100px'); expect(placement.left).toBe('0px'); }); it('should position the tooltip to the top-right of the target when placement is `top-right`', function () { var placement = standardPlacements['options-placement-exotic-top-right']; expect(placement.top).toBe('-100px'); expect(placement.left).toBe('-180px'); }); it('should position the tooltip to the bottom-left of the target when placement is `bottom-left`', function () { var placement = standardPlacements['options-placement-exotic-bottom-left']; expect(placement.top).toBe('20px'); expect(placement.left).toBe('0px'); }); it('should position the tooltip to the bottom-right of the target when placement is `bottom-right`', function () { var placement = standardPlacements['options-placement-exotic-bottom-right']; expect(placement.top).toBe('20px'); expect(placement.left).toBe('-180px'); }); it('should position the tooltip to the left-top of the target when placement is `left-top`', function () { var placement = standardPlacements['options-placement-exotic-left-top']; expect(placement.top).toBe('-80px'); expect(placement.left).toBe('-200px'); }); it('should position the tooltip to the left-bottom of the target when placement is `left-bottom`', function () { var placement = standardPlacements['options-placement-exotic-left-bottom']; expect(placement.top).toBe('0px'); expect(placement.left).toBe('-200px'); }); it('should position the tooltip to the right-top of the target when placement is `right-top`', function () { var placement = standardPlacements['options-placement-exotic-right-top']; expect(placement.top).toBe('-80px'); expect(placement.left).toBe('20px'); }); it('should position the tooltip to the right-bottom of the target when placement is `right-bottom`', function () { var placement = standardPlacements['options-placement-exotic-right-bottom']; expect(placement.top).toBe('0px'); expect(placement.left).toBe('20px'); }); }); describe('auto placements', function () { it('should position the tooltip below the target when initial placement results in positioning outside its container', function () { var autoTop = autoPlacements['options-placement-auto-top']; var bottom = standardPlacements['options-placement-bottom']; // top is offscreen, so it should swap to bottom and match the standard bottom expect(autoTop.top).toBe(bottom.top); expect(autoTop.left).toBe(bottom.left) }); it('should position the tooltip to the left of the target when initial placement results in positioning outside its container', function () { var autoRight = autoPlacements['options-placement-auto-right']; var left = standardPlacements['options-placement-left']; // right is offscreen, so it should swap to left and match the standard left expect(autoRight.top).toBe(left.top); expect(autoRight.left).toBe(left.left) }); it('should position the tooltip above the target when initial placement results in positioning outside its container', function () { var autoBottom = autoPlacements['options-placement-auto-bottom']; var top = standardPlacements['options-placement-top']; // bottom is offscreen, so it should swap to top and match the standard top expect(autoBottom.top).toBe(top.top); expect(autoBottom.left).toBe(top.left) }); it('should position the tooltip to the right of the target when initial placement results in positioning outside its container', function () { var autoLeft = autoPlacements['options-placement-auto-left']; var right = standardPlacements['options-placement-right']; // left is offscreen, so it should swap to right and match the standard right expect(autoLeft.top).toBe(right.top); expect(autoLeft.left).toBe(right.left) }); it('should position the tooltip to the bottom-left of the target when initial placement results in positioning outside its container', function () { var autoTopRight = autoPlacements['options-placement-auto-exotic-top-right']; var bottomLeft = standardPlacements['options-placement-exotic-bottom-left']; // should swap to bottom-left and match the standard bottom-left expect(autoTopRight.top).toBe(bottomLeft.top); expect(autoTopRight.left).toBe(bottomLeft.left) }); it('should position the tooltip to the bottom-right of the target when initial placement results in positioning outside its container', function () { var autoTopLeft = autoPlacements['options-placement-auto-exotic-top-left']; var bottomRight = standardPlacements['options-placement-exotic-bottom-right']; // should swap to bottom-right and match the standard bottom-right expect(autoTopLeft.top).toBe(bottomRight.top); expect(autoTopLeft.left).toBe(bottomRight.left) }); it('should position the tooltip to the top-left of the target when initial placement results in positioning outside its container', function () { var autoBottomRight = autoPlacements['options-placement-auto-exotic-bottom-right']; var topLeft = standardPlacements['options-placement-exotic-top-left']; // should swap to top-left and match the standard top-left expect(autoBottomRight.top).toBe(topLeft.top); expect(autoBottomRight.left).toBe(topLeft.left) }); it('should position the tooltip to the top-left of the target when initial placement results in positioning outside its container', function () { var autoBottomLeft = autoPlacements['options-placement-auto-exotic-bottom-left']; var topRight = standardPlacements['options-placement-exotic-top-right']; // should swap to top-right and match the standard top-right expect(autoBottomLeft.top).toBe(topRight.top); expect(autoBottomLeft.left).toBe(topRight.left) }); }); describe('viewport placements', function () { it('should shift down when positioning results in being outsie of the viewport', function () { var right = viewportPlacements['options-placement-viewport-right']; expect(right.top).toBe('0px'); expect(right.left).toBe('20px'); }); it('should shift left when positioning results in being outside of the viewport', function () { var bottom = viewportPlacements['options-placement-viewport-bottom']; expect(bottom.top).toBe('20px'); expect(bottom.left).toBe('100px'); }); it('should shift right when positioning results in being outside of the viewport', function () { var top = viewportPlacements['options-placement-viewport-top']; expect(top.top).toBe('80px'); expect(top.left).toBe('0px'); }); it('should shift up when positioning results in being outside of the viewport', function () { var top = viewportPlacements['options-placement-viewport-left']; expect(top.top).toBe('100px'); expect(top.left).toBe('80px'); }); it('should use the padding to position the tooltip from the edge of the viewport', function () { var padding = viewportPlacements['options-placement-viewport-padding']; expect(padding.top).toBe('10px'); expect(padding.left).toBe('20px'); }); it('should ignore exotic placements', function () { var exotic = viewportPlacements['options-placement-viewport-exotic']; expect(exotic.top).toBe('20px'); expect(exotic.left).toBe('-80px'); }); }); }); });
kiril-malyhin/To_Do_List-Currency_Exchange-REST-SOAP
vendor/bower/bower-asset/angular-strap/src/tooltip/test/tooltip.spec.js
JavaScript
bsd-3-clause
53,805
(function() { phantom.Fs = function() { this.write = function(file, content, mode) { native function write(); return write(file, content, mode); }; this.read = function(file) { native function read(); return read(file); }; this.lastModified = function(file) { native function lastModified(); return lastModified(file); }; this.exists = function(file) { native function exists(); return exists(file); }; this.isFile = function(file) { native function isFile(); return isFile(file); }; this.isDirectory = function(file) { native function isDirectory(); return isDirectory(file); }; this.list = function(file) { native function list(); return list(file); }; this.copy = function(src,dest) { native function copy(); return copy(src,dest); }; this.remove = function(path) { native function remove(); return remove(path); }; this.makeDirectory = function(path) { native function makeDirectory(); return makeDirectory(path); }; this.makeTree = function(path) { native function makeTree(); return makeTree(path); }; this.touch = function(file) { native function touch(); return touch(file); }; this.size = function(file) { native function size(); return size(file); }; this.tempPath = function(file) { native function tempPath(); return tempPath(file); }; } })();
KDAB/phantomjs-cef
modules/03-fs.js
JavaScript
bsd-3-clause
1,556
/*! jQuery UI - v1.10.4 - 2015-08-02 * http://jqueryui.com * Copyright 2015 jQuery Foundation and other contributors; Licensed MIT */ jQuery(function(e){e.datepicker.regional["pt-BR"]={closeText:"Fechar",prevText:"&#x3C;Anterior",nextText:"Próximo&#x3E;",currentText:"Hoje",monthNames:["Janeiro","Fevereiro","Março","Abril","Maio","Junho","Julho","Agosto","Setembro","Outubro","Novembro","Dezembro"],monthNamesShort:["Jan","Fev","Mar","Abr","Mai","Jun","Jul","Ago","Set","Out","Nov","Dez"],dayNames:["Domingo","Segunda-feira","Terça-feira","Quarta-feira","Quinta-feira","Sexta-feira","Sábado"],dayNamesShort:["Dom","Seg","Ter","Qua","Qui","Sex","Sáb"],dayNamesMin:["Dom","Seg","Ter","Qua","Qui","Sex","Sáb"],weekHeader:"Sm",dateFormat:"dd/mm/yy",firstDay:0,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},e.datepicker.setDefaults(e.datepicker.regional["pt-BR"])});
janicevn79/zendbook
public/js/jquery-ui-1.10.4.custom/development-bundle/ui/minified/i18n/jquery.ui.datepicker-pt-BR.min.js
JavaScript
bsd-3-clause
869
var pkg = require('dylmomo');
JacksonGL/NPM-Vuln-PoC
directory-traversal/dylmomo/test.js
JavaScript
bsd-3-clause
30
'use strict'; function earcut(data, holeIndices, dim) { dim = dim || 2; var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = []; if (!outerNode) return triangles; var minX, minY, maxX, maxY, x, y, size; if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim); // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox if (data.length > 80 * dim) { minX = maxX = data[0]; minY = maxY = data[1]; for (var i = dim; i < outerLen; i += dim) { x = data[i]; y = data[i + 1]; if (x < minX) minX = x; if (y < minY) minY = y; if (x > maxX) maxX = x; if (y > maxY) maxY = y; } // minX, minY and size are later used to transform coords into integers for z-order calculation size = Math.max(maxX - minX, maxY - minY); } earcutLinked(outerNode, triangles, dim, minX, minY, size); return triangles; } // create a circular doubly linked list from polygon points in the specified winding order function linkedList(data, start, end, dim, clockwise) { var i, last; if (clockwise === (signedArea(data, start, end, dim) > 0)) { for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last); } else { for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last); } if (last && equals(last, last.next)) { removeNode(last); last = last.next; } return last; } // eliminate colinear or duplicate points function filterPoints(start, end) { if (!start) return start; if (!end) end = start; var p = start, again; do { again = false; if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) { removeNode(p); p = end = p.prev; if (p === p.next) return null; again = true; } else { p = p.next; } } while (again || p !== end); return end; } // main ear slicing loop which triangulates a polygon (given as a linked list) function earcutLinked(ear, triangles, dim, minX, minY, size, pass) { if (!ear) return; // interlink polygon nodes in z-order if (!pass && size) indexCurve(ear, minX, minY, size); var stop = ear, prev, next; // iterate through ears, slicing them one by one while (ear.prev !== ear.next) { prev = ear.prev; next = ear.next; if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) { // cut off the triangle triangles.push(prev.i / dim); triangles.push(ear.i / dim); triangles.push(next.i / dim); removeNode(ear); // skipping the next vertice leads to less sliver triangles ear = next.next; stop = next.next; continue; } ear = next; // if we looped through the whole remaining polygon and can't find any more ears if (ear === stop) { // try filtering points and slicing again if (!pass) { earcutLinked(filterPoints(ear), triangles, dim, minX, minY, size, 1); // if this didn't work, try curing all small self-intersections locally } else if (pass === 1) { ear = cureLocalIntersections(ear, triangles, dim); earcutLinked(ear, triangles, dim, minX, minY, size, 2); // as a last resort, try splitting the remaining polygon into two } else if (pass === 2) { splitEarcut(ear, triangles, dim, minX, minY, size); } break; } } } // check whether a polygon node forms a valid ear with adjacent nodes function isEar(ear) { var a = ear.prev, b = ear, c = ear.next; if (area(a, b, c) >= 0) return false; // reflex, can't be an ear // now make sure we don't have other points inside the potential ear var p = ear.next.next; while (p !== ear.prev) { if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false; p = p.next; } return true; } function isEarHashed(ear, minX, minY, size) { var a = ear.prev, b = ear, c = ear.next; if (area(a, b, c) >= 0) return false; // reflex, can't be an ear // triangle bbox; min & max are calculated like this for speed var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x), minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y), maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x), maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y); // z-order range for the current triangle bbox; var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size); // first look for points inside the triangle in increasing z-order var p = ear.nextZ; while (p && p.z <= maxZ) { if (p !== ear.prev && p !== ear.next && pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false; p = p.nextZ; } // then look for points in decreasing z-order p = ear.prevZ; while (p && p.z >= minZ) { if (p !== ear.prev && p !== ear.next && pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false; p = p.prevZ; } return true; } // go through all polygon nodes and cure small local self-intersections function cureLocalIntersections(start, triangles, dim) { var p = start; do { var a = p.prev, b = p.next.next; if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) { triangles.push(a.i / dim); triangles.push(p.i / dim); triangles.push(b.i / dim); // remove two nodes involved removeNode(p); removeNode(p.next); p = start = b; } p = p.next; } while (p !== start); return p; } // try splitting polygon into two and triangulate them independently function splitEarcut(start, triangles, dim, minX, minY, size) { // look for a valid diagonal that divides the polygon into two var a = start; do { var b = a.next.next; while (b !== a.prev) { if (a.i !== b.i && isValidDiagonal(a, b)) { // split the polygon in two by the diagonal var c = splitPolygon(a, b); // filter colinear points around the cuts a = filterPoints(a, a.next); c = filterPoints(c, c.next); // run earcut on each half earcutLinked(a, triangles, dim, minX, minY, size); earcutLinked(c, triangles, dim, minX, minY, size); return; } b = b.next; } a = a.next; } while (a !== start); } // link every hole into the outer loop, producing a single-ring polygon without holes function eliminateHoles(data, holeIndices, outerNode, dim) { var queue = [], i, len, start, end, list; for (i = 0, len = holeIndices.length; i < len; i++) { start = holeIndices[i] * dim; end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; list = linkedList(data, start, end, dim, false); if (list === list.next) list.steiner = true; queue.push(getLeftmost(list)); } queue.sort(compareX); // process holes from left to right for (i = 0; i < queue.length; i++) { eliminateHole(queue[i], outerNode); outerNode = filterPoints(outerNode, outerNode.next); } return outerNode; } function compareX(a, b) { return a.x - b.x; } // find a bridge between vertices that connects hole with an outer ring and and link it function eliminateHole(hole, outerNode) { outerNode = findHoleBridge(hole, outerNode); if (outerNode) { var b = splitPolygon(outerNode, hole); filterPoints(b, b.next); } } // David Eberly's algorithm for finding a bridge between hole and outer polygon function findHoleBridge(hole, outerNode) { var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m; // find a segment intersected by a ray from the hole's leftmost point to the left; // segment's endpoint with lesser x will be potential connection point do { if (hy <= p.y && hy >= p.next.y) { var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y); if (x <= hx && x > qx) { qx = x; if (x === hx) { if (hy === p.y) return p; if (hy === p.next.y) return p.next; } m = p.x < p.next.x ? p : p.next; } } p = p.next; } while (p !== outerNode); if (!m) return null; if (hx === qx) return m.prev; // hole touches outer segment; pick lower endpoint // look for points inside the triangle of hole point, segment intersection and endpoint; // if there are no points found, we have a valid connection; // otherwise choose the point of the minimum angle with the ray as connection point var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan; p = m.next; while (p !== stop) { if (hx >= p.x && p.x >= mx && pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) { tan = Math.abs(hy - p.y) / (hx - p.x); // tangential if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) { m = p; tanMin = tan; } } p = p.next; } return m; } // interlink polygon nodes in z-order function indexCurve(start, minX, minY, size) { var p = start; do { if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, size); p.prevZ = p.prev; p.nextZ = p.next; p = p.next; } while (p !== start); p.prevZ.nextZ = null; p.prevZ = null; sortLinked(p); } // Simon Tatham's linked list merge sort algorithm // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html function sortLinked(list) { var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1; do { p = list; list = null; tail = null; numMerges = 0; while (p) { numMerges++; q = p; pSize = 0; for (i = 0; i < inSize; i++) { pSize++; q = q.nextZ; if (!q) break; } qSize = inSize; while (pSize > 0 || (qSize > 0 && q)) { if (pSize === 0) { e = q; q = q.nextZ; qSize--; } else if (qSize === 0 || !q) { e = p; p = p.nextZ; pSize--; } else if (p.z <= q.z) { e = p; p = p.nextZ; pSize--; } else { e = q; q = q.nextZ; qSize--; } if (tail) tail.nextZ = e; else list = e; e.prevZ = tail; tail = e; } p = q; } tail.nextZ = null; inSize *= 2; } while (numMerges > 1); return list; } // z-order of a point given coords and size of the data bounding box function zOrder(x, y, minX, minY, size) { // coords are transformed into non-negative 15-bit integer range x = 32767 * (x - minX) / size; y = 32767 * (y - minY) / size; x = (x | (x << 8)) & 0x00FF00FF; x = (x | (x << 4)) & 0x0F0F0F0F; x = (x | (x << 2)) & 0x33333333; x = (x | (x << 1)) & 0x55555555; y = (y | (y << 8)) & 0x00FF00FF; y = (y | (y << 4)) & 0x0F0F0F0F; y = (y | (y << 2)) & 0x33333333; y = (y | (y << 1)) & 0x55555555; return x | (y << 1); } // find the leftmost node of a polygon ring function getLeftmost(start) { var p = start, leftmost = start; do { if (p.x < leftmost.x) leftmost = p; p = p.next; } while (p !== start); return leftmost; } // check if a point lies within a convex triangle function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) { return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 && (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 && (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0; } // check if a diagonal between two polygon nodes is valid (lies in polygon interior) function isValidDiagonal(a, b) { return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b); } // signed area of a triangle function area(p, q, r) { return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); } // check if two points are equal function equals(p1, p2) { return p1.x === p2.x && p1.y === p2.y; } // check if two segments intersect function intersects(p1, q1, p2, q2) { if ((equals(p1, q1) && equals(p2, q2)) || (equals(p1, q2) && equals(p2, q1))) return true; return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 && area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0; } // check if a polygon diagonal intersects any polygon segments function intersectsPolygon(a, b) { var p = a; do { if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && intersects(p, p.next, a, b)) return true; p = p.next; } while (p !== a); return false; } // check if a polygon diagonal is locally inside the polygon function locallyInside(a, b) { return area(a.prev, a, a.next) < 0 ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0; } // check if the middle point of a polygon diagonal is inside the polygon function middleInside(a, b) { var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2; do { if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x)) inside = !inside; p = p.next; } while (p !== a); return inside; } // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two; // if one belongs to the outer ring and another to a hole, it merges it into a single ring function splitPolygon(a, b) { var a2 = new Node(a.i, a.x, a.y), b2 = new Node(b.i, b.x, b.y), an = a.next, bp = b.prev; a.next = b; b.prev = a; a2.next = an; an.prev = a2; b2.next = a2; a2.prev = b2; bp.next = b2; b2.prev = bp; return b2; } // create a node and optionally link it with previous one (in a circular doubly linked list) function insertNode(i, x, y, last) { var p = new Node(i, x, y); if (!last) { p.prev = p; p.next = p; } else { p.next = last.next; p.prev = last; last.next.prev = p; last.next = p; } return p; } function removeNode(p) { p.next.prev = p.prev; p.prev.next = p.next; if (p.prevZ) p.prevZ.nextZ = p.nextZ; if (p.nextZ) p.nextZ.prevZ = p.prevZ; } function Node(i, x, y) { // vertice index in coordinates array this.i = i; // vertex coordinates this.x = x; this.y = y; // previous and next vertice nodes in a polygon ring this.prev = null; this.next = null; // z-order curve value this.z = null; // previous and next nodes in z-order this.prevZ = null; this.nextZ = null; // indicates whether this is a steiner point this.steiner = false; } // return a percentage difference between the polygon area and its triangulation area; // used to verify correctness of triangulation earcut.deviation = function (data, holeIndices, dim, triangles) { var hasHoles = holeIndices && holeIndices.length; var outerLen = hasHoles ? holeIndices[0] * dim : data.length; var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim)); if (hasHoles) { for (var i = 0, len = holeIndices.length; i < len; i++) { var start = holeIndices[i] * dim; var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; polygonArea -= Math.abs(signedArea(data, start, end, dim)); } } var trianglesArea = 0; for (i = 0; i < triangles.length; i += 3) { var a = triangles[i] * dim; var b = triangles[i + 1] * dim; var c = triangles[i + 2] * dim; trianglesArea += Math.abs( (data[a] - data[c]) * (data[b + 1] - data[a + 1]) - (data[a] - data[b]) * (data[c + 1] - data[a + 1])); } return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea); }; function signedArea(data, start, end, dim) { var sum = 0; for (var i = start, j = end - dim; i < end; i += dim) { sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]); j = i; } return sum; } // turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts earcut.flatten = function (data) { var dim = data[0][0].length, result = {vertices: [], holes: [], dimensions: dim}, holeIndex = 0; for (var i = 0; i < data.length; i++) { for (var j = 0; j < data[i].length; j++) { for (var d = 0; d < dim; d++) result.vertices.push(data[i][j][d]); } if (i > 0) { holeIndex += data[i - 1].length; result.holes.push(holeIndex); } } return result; }; export default earcut;
huiyan-fe/mapv
src/webgl/draw/earcut.js
JavaScript
bsd-3-clause
18,449
/** Based on https://github.com/OpenACalendar/OpenACalendar-Web-Core/blob/master/core/theme/default/js/index/createSite.js from http://ican.openacalendar.org/ **/ var hasUserEditedPublicId = false; var titleObj; var keyObj; var titleAdminFunc = function() { if (!hasUserEditedPublicId) { slug = titleObj.val().replace(/\W/g, '').toLowerCase(); keyObj.val( slug ); } }; var publicIdFunc = function() { hasUserEditedPublicId = true; }; $(document).ready(function() { titleObj = $('#NewTreeFormFieldTitleAdminWrapper input'); titleObj.change(titleAdminFunc); titleObj.keyup(titleAdminFunc); keyObj = $('#NewTreeFormFieldPublicIdWrapper input') keyObj.keyup(publicIdFunc); });
QuestionKey/QuestionKey-Core
src/QuestionKeyBundle/Resources/public/js/newTreeSlug.js
JavaScript
bsd-3-clause
729
var conn; if (document.location.hostname == "localhost" || document.location.hostname.indexOf('192.168') > -1) { conn = new WebSocket('ws://' + document.domain + ':10666'); } else { conn = new WebSocket('ws://' + document.domain + '/ws/'); } var playNextOrLastGenre = function() { if (queueList.children().length == 0) { //queue is empty emptyQueue = true; state = 'genre'; conn.send('emptyQueue'); } else { emptyQueue = false; playNext(); } }; conn.onopen = function() { console.log("Connection established!"); playNextOrLastGenre(); setInterval(function() { if(emptyQueue) { console.log("asking for songs in empty queue"); conn.send('emptyQueue'); } else { console.log("asking for songs"); conn.send('getSongs'); } }, 6000); conn.onmessage = function(event) { handleSongs(JSON.parse(event.data)); } };
ParalelniPolis/bitcoinJukebox
desktopQueue/www/js/websocket.js
JavaScript
bsd-3-clause
973
/* * Copyright 2014, Gregg Tavares. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Gregg Tavares. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ "use strict"; /** * A module or provide `setTimeout` and `setInterval` like functionality * but that's based on a clock provided by the game. This is useful * especially during debugging because you might pause in the debugger. * normal timeouts and intervals will not pause. These will. Similarly * if you slowed the clock down (bullet time) these timers could slow * down too. * * @module Timeout */ define(function() { var s_nextId = 0; var s_clockInMs = 0; // always sorted by next to trigger. var s_timeouts = []; var s_timeoutsToInsert = []; var s_timeoutsToRemoveById = []; var insertTimeout = function(timeout) { var timeToTrigger = timeout.timeToTrigger; var start = 0; var end = s_timeouts.length; while (start < end) { var index = start + (end - start) / 2 | 0; var otherTimeToTrigger = s_timeouts[index].timeToTrigger; if (timeToTrigger < otherTimeToTrigger) { end = index; } else if (timeToTrigger > otherTimeToTrigger) { start = index + 1; } else { break; } } s_timeouts.splice(index, 0, timeout); }; //var removeTimeout = function(timeout) { // var ndx = s_timeouts[timeout]; // if (ndx >= 0) { // s_timeouts.splice(ndx, 1); // } //}; var removeTimeoutById = function(id) { for (var ii = 0; ii < s_timeouts.length; ++ii) { if (s_timeouts[ii].id === id) { s_timeouts.splice(ii, 1); return; } } }; var makeTimeout = function(callback) { return { id: ++s_nextId, callback: callback, }; }; var setTriggerTime = function(timeout, timeInMs) { timeout.timeToTrigger = s_clockInMs + timeInMs; }; /** * Same as normal setTimeout * @param {callback} callback function to call when it times out * @param {number} timeInMs duration of timeout * @return {number} id for timeout * @memberOf module:Timeout */ var setTimeout = function(callback, timeInMs) { var timeout = makeTimeout(callback); setTriggerTime(timeout, timeInMs); s_timeoutsToInsert.push(timeout); return timeout.id; }; /** * Same as normal setInterval * @param {callback} callback function to call at each interval * @param {number} timeInMs duration of internval * @return {number} id for interval * @memberOf module:Timeout */ var setInterval = function(callback, timeInMs) { var timeout = makeTimeout(function() { setTriggerTime(timeout, timeout.timeInMs); s_timeoutsToInsert.push(timeout); callback(); }); timeout.timeInMs = timeInMs; s_timeoutsToInsert.push(timeout); return timeout.id; }; /** * Same as normal clearTimeout * @param {number} id of timeout to clear. * @memberOf module:Timeout */ var clearTimeout = function(id) { s_timeoutsToRemoveById.push(id); }; /** * Same as normal clearInterval * @param {number} id of interval to clear. * @memberOf module:Timeout */ var clearInterval = function(id) { s_timeoutsToRemoveById.push(id); }; /** * Processes the intervals and timeouts * * This is how you control the clock for the timouts * * A typical usage might be * * * var g = {}; * GameSupport.run(g, mainloop); * * function mainloop() { * Timeout.process(globals.elapsedTime); * }; * * @param {number} elapsedTimeInSeconds number of seconds to advance the clock. * @memberOf module:Timeout */ var process = function(elapsedTimeInSeconds) { // insert any unscheduled timeouts if (s_timeoutsToInsert.length) { s_timeoutsToInsert.forEach(insertTimeout); s_timeoutsToInsert = []; } // Now remove any if (s_timeoutsToRemoveById.length) { s_timeoutsToRemoveById.forEach(removeTimeoutById); s_timeoutsToRemoveById = []; } s_clockInMs += elapsedTimeInSeconds * 1000; // process timeouts for (var ii = 0; ii < s_timeouts.length; ++ii) { var timeout = s_timeouts[ii]; if (s_clockInMs < timeout.timeToTrigger) { break; } timeout.callback(); } // remove expired timeouts s_timeouts.splice(0, ii); }; return { clearInterval: clearInterval, clearTimeout: clearTimeout, process: process, setInterval: setInterval, setTimeout: setTimeout, }; });
greggman/hft-unity3d
src/hft/scripts/misc/timeout.js
JavaScript
bsd-3-clause
5,954
/** * This view is an example list of people. */ Ext.define('Vegi.view.main.MainToolbar', { extend: 'Ext.tab.Panel', alias: 'widget.mainmaintoolbar', requires: [ 'Vegi.view.main.MainToolbarViewModel', 'Vegi.view.main.MainToolbarViewController', 'Ext.tab.Panel', 'Ext.grid.Panel', 'Ext.tab.Tab', 'Ext.toolbar.Fill', 'Ext.toolbar.Toolbar', 'Ext.toolbar.Paging', ], controller: 'mainmaintoolbar', viewModel: { type: 'mainmaintoolbar' }, dock: 'top', height: 60, cls: 'main-toolbar-category', items: [ { xtype: 'label', cls: 'biggertext' }, { xtype: 'tbfill', flex: 1 }, { xtype: 'textfield', name: 'searchbox', hidden: true, emptyText: 'Search.....', cls: 'search-textfield-main-toolbar', width: 230 }, { iconCls:'x-fa fa-search', ui: 'header', tooltip: 'Search', listeners: { mouseover: 'onSearchButtonMouseover' //mouseout: 'onSearchButtonMouseout' } } ], listeners: { beforerender: 'onMainToolbarShow' } });
hwaqar44/vegi
public/vegi/classic/src/view/main/MainToolbar.js
JavaScript
bsd-3-clause
1,068
// test dependencies that require transformation let pluginsToTransform = [ 'phovea_*', 'tdp_*', 'lineupjs' ].join('|'); if(pluginsToTransform.length > 0) { /** Attention: Negative Lookahead! This regex adds the specified repos to a whitelist that holds plugins that are excluded from the transformIgnorePatterns. * This means that pluginsToTransform should contain all repos that export ts files. They can only be handled by the transformation. */ pluginsToTransform = `(?!${pluginsToTransform})`; } /** * TODO check if we can process inline webpack loaders (e.g. as found in https://github.com/phovea/phovea_ui/blob/master/src/_bootstrap.ts) * see also https://jestjs.io/docs/en/webpack#mocking-css-modules */ module.exports = { transform: { "^.+\\.(js|ts|tsx)$": "ts-jest", "\\.xml$": "jest-raw-loader" }, testRegex: "(.*(test|spec))\\.(tsx?)$", moduleFileExtensions: [ "ts", "tsx", "js", "jsx", "json", "node" ], modulePaths: [ "src" ], transformIgnorePatterns: [`../node_modules/${pluginsToTransform}`, `node_modules/${pluginsToTransform}`], globals: { "__VERSION__": "TEST_VERSION", "__APP_CONTEXT__": "TEST_CONTEXT", // has to be set to true, otherwise i18n import fails "tsconfig": { "esModuleInterop": true } }, moduleNameMapper: { "^.+\\.(css|less|scss|sass|png|jpg|gif)$": "identity-obj-proxy" } }
datavisyn/datavisyn-scatterplot
jest.config.js
JavaScript
bsd-3-clause
1,418
describe("Metadata dialog", function() { var cartodb_layer, vis, user; beforeEach(function() { vis = new cdb.admin.Visualization({ name: "test_table", description: "Table description", tags: ["jam","testing"], privacy: "PUBLIC", type: "table" }); cartodb_layer = new cdb.admin.CartoDBLayer({ table_name: 'test_table'}); vis.map.layers.reset([ new cdb.geo.MapLayer(), cartodb_layer ]); user = TestUtil.createUser(); cartodb_layer.table.permission.owner = user; vis.permission.owner = user; view = new cdb.admin.MetadataDialog({ vis: vis, user: user }); }); afterEach(function() { view.clean(); }); it("should render properly", function(done) { view.render(); expect(view.$('section.modal:eq(0) h3').text()).toBe('Table metadata'); expect(view.$('input[name="name"]').val()).toBe('test_table'); expect(view.$('textarea[name="description"]').val()).toBe('Table description'); // expect(view.$('input[name="source"]').val()).toBe(''); // expect(view.$('input[name="license"]').val()).toBe(''); expect(view.$('ul li.tagit-choice').size()).toBe(2); expect(view.$('div.info.error').length).toBe(1); expect(view.$('div.owner').length).toBe(0); expect(view.$('div.foot input[type="submit"]').length).toBe(1); setTimeout(function() { expect(view.$('.jspContainer').length).toBe(1); done(); },100); }); it("should render visualization metadata title if visualization is derived", function() { vis.set('type', 'derived'); var new_view = new cdb.admin.MetadataDialog({ vis: vis, user: user }); new_view.render(); expect(new_view.$('section.modal:eq(0) h3').text()).toBe('Visualization metadata'); new_view.clean(); }); it("should render owner block and disable all fields if table owner is different", function() { // Table var new_guy = new cdb.admin.User({ username: 'tests', id: 10 }); cartodb_layer.table.permission.owner = new_guy; vis.permission.owner = new_guy; view.render(); expect(view.$('div.owner').length).toBe(1); expect(view.$('input[name="name"]').is('[readonly]')).toBeTruthy(); expect(view.$('textarea[name="description"]').is('[readonly]')).toBeTruthy(); // expect(view.$('input[name="source"]').is('[readonly]')).toBeTruthy(); // expect(view.$('input[name="license"]').is('[readonly]')).toBeTruthy(); expect(view.$('ul.readonly').length).toBe(1); expect(view.$('div.foot input[type="submit"]').length).toBe(0); }); it("should disable all fields if table has a query applied", function() { // Table var new_guy = new cdb.admin.User({ username: 'tests', id: 10 }); cartodb_layer.table.permission.owner = new_guy; vis.permission.owner = new_guy; view.render(); expect(view.$('div.owner').length).toBe(1); expect(view.$('input[name="name"]').is('[readonly]')).toBeTruthy(); expect(view.$('textarea[name="description"]').is('[readonly]')).toBeTruthy(); // expect(view.$('input[name="source"]').is('[readonly]')).toBeTruthy(); // expect(view.$('input[name="license"]').is('[readonly]')).toBeTruthy(); expect(view.$('ul.readonly').length).toBe(1); expect(view.$('div.foot input[type="submit"]').length).toBe(0); }); it("should render owner block and disable all fields if vis owner is different", function() { // Vis var new_guy = new cdb.admin.User({ username: 'tests', id: 10 }); cartodb_layer.table.permission.owner = new_guy; vis.set('type', 'derived'); vis.permission.owner = new_guy; view.render(); expect(view.$('div.owner').length).toBe(1); expect(view.$('input[name="name"]').is('[readonly]')).toBeTruthy(); expect(view.$('textarea[name="description"]').is('[readonly]')).toBeTruthy(); // expect(view.$('input[name="source"]').is('[readonly]')).toBeTruthy(); // expect(view.$('input[name="license"]').is('[readonly]')).toBeTruthy(); expect(view.$('ul.readonly').length).toBe(1); expect(view.$('div.foot input[type="submit"]').length).toBe(0); }); it("should render owner block and disable all fields if vis owner is different", function() { // Vis var new_guy = new cdb.admin.User({ username: 'tests', id: 10 }); cartodb_layer.table.permission.owner = new_guy; vis.set('type', 'derived'); vis.permission.owner = new_guy; view.render(); expect(view.$('div.owner').length).toBe(1); expect(view.$('input[name="name"]').is('[readonly]')).toBeTruthy(); expect(view.$('textarea[name="description"]').is('[readonly]')).toBeTruthy(); // expect(view.$('input[name="source"]').is('[readonly]')).toBeTruthy(); // expect(view.$('input[name="license"]').is('[readonly]')).toBeTruthy(); expect(view.$('ul.readonly').length).toBe(1); expect(view.$('div.foot input[type="submit"]').length).toBe(0); }); it("should disable name field when table is synced", function() { cartodb_layer.table.synchronization.set('id', 'test'); view.render(); expect(view.$('input[name="name"]').is('[readonly]')).toBeTruthy(); expect(view.$('textarea[name="description"]').is('[readonly]')).toBeFalsy(); // expect(view.$('input[name="source"]').is('[readonly]')).toBeFalsy(); // expect(view.$('input[name="license"]').is('[readonly]')).toBeFalsy(); expect(view.$('ul.readonly').length).toBe(0); expect(view.$('div.foot input[type="submit"]').length).toBe(1); }); it("should disable all fields when table has a query applied", function() { cartodb_layer.table.sqlView = { isReadOnly: function() { return true; } } view.render(); expect(view.$('input[name="name"]').is('[readonly]')).toBeTruthy(); expect(view.$('textarea[name="description"]').is('[readonly]')).toBeTruthy(); // expect(view.$('input[name="source"]').is('[readonly]')).toBeTruthy(); // expect(view.$('input[name="license"]').is('[readonly]')).toBeTruthy(); expect(view.$('ul.readonly').length).toBe(1); expect(view.$('div.foot input[type="submit"]').length).toBe(0); }); it("should show error info when name input is empty and don't send response signal", function() { var called = false; var new_view = new cdb.admin.MetadataDialog({ vis: vis, user: user, onResponse: function(r) { called = true; } }); new_view.render(); new_view.$('input[name="name"]').val(''); new_view._ok(); expect(new_view.$('.info.error').hasClass('active')).toBeTruthy(); expect(called).toBeFalsy(); new_view.clean(); }); it("should return all form data serialized", function() { var o = {}; var new_view = new cdb.admin.MetadataDialog({ vis: vis, user: user, onResponse: function(r) { o = r } }); new_view.render(); new_view.$('input[name="name"]').val('name'); new_view.$('textarea[name="description"]').val('description'); // new_view.$('input[name="source"]').val('source'); // new_view.$('input[name="license"]').val('license'); new_view._saveModel(); expect(o.name).toBe('name'); expect(o.description).toBe('description'); // expect(o.source).toBe('source'); expect(o.tags.length).toBe(2); // expect(o.license).toBe('license'); new_view.clean(); }); });
comilla/map
lib/assets/test/spec/cartodb/table/header/metadata_dialog.spec.js
JavaScript
bsd-3-clause
7,444
/** * Created by Hendrik Strobelt (hendrik.strobelt.com) on 12/4/16. */ class LinePlot extends VComponent { // Super class methods ---------------- static get events() { return { thresholdChanged: 'lineplot-thresholdChanged', cellHovered: 'lineplot-cellhovered', moreContext: 'lineplot-morecontext' } } get defaultOptions() { return { pos: {x: 0, y: 50}, // A y scale that also defines the height or 'null' to use auto scale yScale: null, // Default parameter for linear auto scale minValue: -1, maxValue: 1, height: 150, // Cell width along x axis cellWidth: 25, extendButton: true, // Distance between plot and axis (!! must be reflected in layers as well) axisPadding: 10 } } get layout() { return [ {name: 'main', pos: {x: 60, y: 0}}, {name: 'overlay', pos: {x: 60, y: 0}}, {name: 'axis', pos: {x: 60 - this.options.axisPadding, y: 0}} ] } get _dataFormat() { return { timeSteps: 3, cellValues: [{index: 0, values: [0.1, 0.3, 0.5]}, {index: 1, values: [0.4, 0.5, 0.6]}], selectedCells: [], deselectedCells: [] } } _init() { this.thresholdValue = 0; this._initAxisAndSlider(); } _initAxisAndSlider() { const yScale = this.yScale.copy(); yScale.clamp(true); const axisParent = this.layers.axis; axisParent.append('g').attr('class', 'y-axis').call(d3.axisLeft(yScale)); // Add a zero line: this.layers.main.append('line').attr('class', 'zeroLine'); // Add the slider: const dragging = () => this.eventHandler.trigger( LinePlot.events.thresholdChanged, {newValue: yScale.invert(d3.event.y)}); axisParent.append('line').attrs({ class: 'slider-bg', y1: yScale.range()[1], y2: yScale.range()[0] }).styles({'stroke-width': '20', 'stroke': 'black', 'opacity': '0'}) .call(d3.drag().on('start drag', dragging)); axisParent.append('circle').attrs({ class: 'slider-handle non-active', cy: yScale(this.thresholdValue), r: 5 }); this.layers.overlay.append('line').attr('class', 'thresholdLine'); } _wrangle(data) { const dataLength = data.timeSteps; this.xScale = d3.scaleLinear().domain([0, dataLength]) .range([0, dataLength * this.options.cellWidth]); // Determine Min/Max values let minValue = Number.MAX_VALUE; let maxValue = -Number.MAX_VALUE; data.cellValues.forEach(cell => { cell.values.forEach(value => { if (minValue > value) minValue = value; if (maxValue < value) maxValue = value; }) }) if (minValue < 0) { const maxAbs = maxValue > -minValue ? maxValue : -minValue; this.options.minValue = -maxAbs; this.options.maxValue = maxAbs; } else { this.options.minValue = 0; this.options.maxValue = maxValue; } // Determine if update axis is necessary: const st = this._states; st.needsAxisUpdate = (st.dataLength === null || st.dataLength !== dataLength); st.dataLength = dataLength; return data; } _render(renderData) { const dataLength = renderData.timeSteps; this.xScale = d3.scaleLinear().domain([0, dataLength]) .range([0, dataLength * this.options.cellWidth]); this._updateLines(renderData); this._updateAxisAndSlider(); if (this.options.extendButton) this._updateExtendButton() } _updateAxisAndSlider() { const yScale = this.yScale; const xScale = this.xScale; const clampedYScale = yScale.copy().clamp(true); const axisParent = this.layers.axis; axisParent.select('.y-axis').call(d3.axisLeft(yScale)); // Update zero line this.layers.main.select('.zeroLine') .attrs({ x1: xScale.range()[0], x2: xScale.range()[1], y1: yScale(0), y2: yScale(0) }); // Update the slider area const dragging = () => { const v = Util.round(clampedYScale.invert(d3.event.y), 3); if (this._states.threshold !== v) { this._states.threshold = v; this.eventHandler.trigger( LinePlot.events.thresholdChanged, {newValue: v}); } } axisParent.select('.slider-bg').attrs({ y1: yScale.range()[1], y2: yScale.range()[0] }).call(d3.drag().on('start drag', dragging)); this._updateThreshold(); } _updateThreshold() { const xScale = this.xScale; // Update threshold handle and threshold line const tValue = this.yScale(this.thresholdValue); this.layers.axis.select('.slider-handle').attrs({ cy: tValue, }); this.layers.overlay.select('.thresholdLine') .attrs({ x1: xScale.range()[0]-this.options.axisPadding, x2: xScale.range()[1], y1: tValue, y2: tValue }); } _updateLines(renderData) { const xScale = this.xScale; const yScale = this.yScale; const lineOpacity = 1.0 / (Math.sqrt(renderData.cellValues.length) + 0.00001); const lineGenerator = d3.line() .x((d, i) => xScale(i)) .y(d => yScale(d)); this._updateLineSubset({ container: this.layers.main, data: renderData.cellValues.filter(d => !_.includes(renderData.selectedCells, d.index)), lineGenerator, lineOpacity }) const highlightedCells = this._updateLineSubset({ container: this.layers.overlay, data: renderData.cellValues.filter(d => _.includes(renderData.selectedCells, d.index)), lineOpacity: null, lineGenerator }) const hover = active => d => this.eventHandler.trigger(LinePlot.events.cellHovered, {index: active ? d.index : -1}); highlightedCells .on('mouseover', hover(true)) .on('mouseout', hover(false)); } _updateLineSubset({container, data, lineGenerator, lineOpacity}) { const valueLines = container.selectAll('.valueLine').data(data); valueLines.exit().remove(); return valueLines .enter().append('path') .merge(valueLines) .attrs({ "class": d => "valueLine id_" + d.index, d: d => lineGenerator(d.values) }) .styles({ opacity: lineOpacity }); } _updateExtendButton() { const xScale = this.xScale; const eb = this.layers.overlay.selectAll('.extendButton').data(['\uf141']) eb.enter().append('text').attrs({ class: 'extendButton fontAwesome noselect' }).text(d => d) .on('click', () => this.eventHandler.trigger(LinePlot.events.moreContext, this)) .append('title').text('fill until right border') eb.attrs({ 'transform': SVG.translate({x: xScale.range()[1] + 5, y: this.options.height / 2}) }) } // Lineplot methods ---------------- get yScale() { const op = this.options; if (op.yScale) return op.yScale.range([op.height, 0]); // Else: return d3.scaleLinear().domain([op.minValue, op.maxValue]) .range([op.height, 0]); } actionUpdateThreshold(newValue) { this.thresholdValue = newValue; this._updateThreshold(); } actionUpdateSelectedCells(selCells) { this.renderData.selectedCells = selCells; this._render(this.renderData); } actionCellHovered(cell) { this.layers.overlay.selectAll('.valueLine') .classed('hovered', d => cell === d.index) .filter(d => cell === d.index).raise() } _bindLocalEvents(eventHandler) { this._bindEvent(eventHandler, LinePlot.events.thresholdChanged, ({newValue}) => this.actionUpdateThreshold(newValue)) this._bindEvent(eventHandler, LinePlot.events.cellHovered, cell => this.actionCellHovered(cell)) } } LinePlot;
HendrikStrobelt/LSTMVis
client/js/vis/lineplot.js
JavaScript
bsd-3-clause
8,675
/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @emails react-core */ 'use strict'; var React; var ReactDOM; describe('ReactES6Class', function() { var container; var freeze = function(expectation) { Object.freeze(expectation); return expectation; }; var Inner; var attachedListener = null; var renderedName = null; beforeEach(function() { React = require('React'); ReactDOM = require('ReactDOM'); container = document.createElement('div'); attachedListener = null; renderedName = null; Inner = class extends React.Component { getName() { return this.props.name; } render() { attachedListener = this.props.onClick; renderedName = this.props.name; return <div className={this.props.name} />; } }; }); function test(element, expectedTag, expectedClassName) { var instance = ReactDOM.render(element, container); expect(container.firstChild).not.toBeNull(); expect(container.firstChild.tagName).toBe(expectedTag); expect(container.firstChild.className).toBe(expectedClassName); return instance; } it('preserves the name of the class for use in error messages', function() { class Foo extends React.Component { } expect(Foo.name).toBe('Foo'); }); it('throws if no render function is defined', function() { spyOn(console, 'error'); class Foo extends React.Component { } expect(() => ReactDOM.render(<Foo />, container)).toThrow(); expect(console.error.calls.length).toBe(1); expect(console.error.argsForCall[0][0]).toBe( 'Warning: Foo(...): No `render` method found on the returned component ' + 'instance: you may have forgotten to define `render`, returned ' + 'null/false from a stateless component, or tried to render an element ' + 'whose type is a function that isn\'t a React component.' ); }); it('renders a simple stateless component with prop', function() { class Foo extends React.Component { render() { return <Inner name={this.props.bar} />; } } test(<Foo bar="foo" />, 'DIV', 'foo'); test(<Foo bar="bar" />, 'DIV', 'bar'); }); it('renders based on state using initial values in this.props', function() { class Foo extends React.Component { constructor(props) { super(props); this.state = {bar: this.props.initialValue}; } render() { return <span className={this.state.bar} />; } } test(<Foo initialValue="foo" />, 'SPAN', 'foo'); }); it('renders based on state using props in the constructor', function() { class Foo extends React.Component { constructor(props) { super(props); this.state = {bar: props.initialValue}; } changeState() { this.setState({bar: 'bar'}); } render() { if (this.state.bar === 'foo') { return <div className="foo" />; } return <span className={this.state.bar} />; } } var instance = test(<Foo initialValue="foo" />, 'DIV', 'foo'); instance.changeState(); test(<Foo />, 'SPAN', 'bar'); }); it('renders based on context in the constructor', function() { class Foo extends React.Component { constructor(props, context) { super(props, context); this.state = {tag: context.tag, className: this.context.className}; } render() { var Tag = this.state.tag; return <Tag className={this.state.className} />; } } Foo.contextTypes = { tag: React.PropTypes.string, className: React.PropTypes.string, }; class Outer extends React.Component { getChildContext() { return {tag: 'span', className: 'foo'}; } render() { return <Foo />; } } Outer.childContextTypes = { tag: React.PropTypes.string, className: React.PropTypes.string, }; test(<Outer />, 'SPAN', 'foo'); }); it('renders only once when setting state in componentWillMount', function() { var renderCount = 0; class Foo extends React.Component { constructor(props) { super(props); this.state = {bar: props.initialValue}; } componentWillMount() { this.setState({bar: 'bar'}); } render() { renderCount++; return <span className={this.state.bar} />; } } test(<Foo initialValue="foo" />, 'SPAN', 'bar'); expect(renderCount).toBe(1); }); it('should throw with non-object in the initial state property', function() { [['an array'], 'a string', 1234].forEach(function(state) { class Foo extends React.Component { constructor() { super(); this.state = state; } render() { return <span />; } } expect(() => test(<Foo />, 'span', '')).toThrow( 'Foo.state: must be set to an object or null' ); }); }); it('should render with null in the initial state property', function() { class Foo extends React.Component { constructor() { super(); this.state = null; } render() { return <span />; } } test(<Foo />, 'SPAN', ''); }); it('setState through an event handler', function() { class Foo extends React.Component { constructor(props) { super(props); this.state = {bar: props.initialValue}; } handleClick() { this.setState({bar: 'bar'}); } render() { return ( <Inner name={this.state.bar} onClick={this.handleClick.bind(this)} /> ); } } test(<Foo initialValue="foo" />, 'DIV', 'foo'); attachedListener(); expect(renderedName).toBe('bar'); }); it('should not implicitly bind event handlers', function() { class Foo extends React.Component { constructor(props) { super(props); this.state = {bar: props.initialValue}; } handleClick() { this.setState({bar: 'bar'}); } render() { return ( <Inner name={this.state.bar} onClick={this.handleClick} /> ); } } test(<Foo initialValue="foo" />, 'DIV', 'foo'); expect(attachedListener).toThrow(); }); it('renders using forceUpdate even when there is no state', function() { class Foo extends React.Component { constructor(props) { super(props); this.mutativeValue = props.initialValue; } handleClick() { this.mutativeValue = 'bar'; this.forceUpdate(); } render() { return ( <Inner name={this.mutativeValue} onClick={this.handleClick.bind(this)} /> ); } } test(<Foo initialValue="foo" />, 'DIV', 'foo'); attachedListener(); expect(renderedName).toBe('bar'); }); it('will call all the normal life cycle methods', function() { var lifeCycles = []; class Foo extends React.Component { constructor() { super(); this.state = {}; } componentWillMount() { lifeCycles.push('will-mount'); } componentDidMount() { lifeCycles.push('did-mount'); } componentWillReceiveProps(nextProps) { lifeCycles.push('receive-props', nextProps); } shouldComponentUpdate(nextProps, nextState) { lifeCycles.push('should-update', nextProps, nextState); return true; } componentWillUpdate(nextProps, nextState) { lifeCycles.push('will-update', nextProps, nextState); } componentDidUpdate(prevProps, prevState) { lifeCycles.push('did-update', prevProps, prevState); } componentWillUnmount() { lifeCycles.push('will-unmount'); } render() { return <span className={this.props.value} />; } } test(<Foo value="foo" />, 'SPAN', 'foo'); expect(lifeCycles).toEqual([ 'will-mount', 'did-mount', ]); lifeCycles = []; // reset test(<Foo value="bar" />, 'SPAN', 'bar'); expect(lifeCycles).toEqual([ 'receive-props', freeze({value: 'bar'}), 'should-update', freeze({value: 'bar'}), {}, 'will-update', freeze({value: 'bar'}), {}, 'did-update', freeze({value: 'foo'}), {}, ]); lifeCycles = []; // reset ReactDOM.unmountComponentAtNode(container); expect(lifeCycles).toEqual([ 'will-unmount', ]); }); it('warns when classic properties are defined on the instance, but does not invoke them.', function() { spyOn(console, 'error'); var getDefaultPropsWasCalled = false; var getInitialStateWasCalled = false; class Foo extends React.Component { constructor() { super(); this.contextTypes = {}; this.propTypes = {}; } getInitialState() { getInitialStateWasCalled = true; return {}; } getDefaultProps() { getDefaultPropsWasCalled = true; return {}; } render() { return <span className="foo" />; } } test(<Foo />, 'SPAN', 'foo'); expect(getInitialStateWasCalled).toBe(false); expect(getDefaultPropsWasCalled).toBe(false); expect(console.error.calls.length).toBe(4); expect(console.error.argsForCall[0][0]).toContain( 'getInitialState was defined on Foo, a plain JavaScript class.' ); expect(console.error.argsForCall[1][0]).toContain( 'getDefaultProps was defined on Foo, a plain JavaScript class.' ); expect(console.error.argsForCall[2][0]).toContain( 'propTypes was defined as an instance property on Foo.' ); expect(console.error.argsForCall[3][0]).toContain( 'contextTypes was defined as an instance property on Foo.' ); }); it('should warn when misspelling shouldComponentUpdate', function() { spyOn(console, 'error'); class NamedComponent extends React.Component { componentShouldUpdate() { return false; } render() { return <span className="foo" />; } } test(<NamedComponent />, 'SPAN', 'foo'); expect(console.error.calls.length).toBe(1); expect(console.error.argsForCall[0][0]).toBe( 'Warning: ' + 'NamedComponent has a method called componentShouldUpdate(). Did you ' + 'mean shouldComponentUpdate()? The name is phrased as a question ' + 'because the function is expected to return a value.' ); }); it('should warn when misspelling componentWillReceiveProps', function() { spyOn(console, 'error'); class NamedComponent extends React.Component { componentWillRecieveProps() { return false; } render() { return <span className="foo" />; } } test(<NamedComponent />, 'SPAN', 'foo'); expect(console.error.calls.length).toBe(1); expect(console.error.argsForCall[0][0]).toBe( 'Warning: ' + 'NamedComponent has a method called componentWillRecieveProps(). Did ' + 'you mean componentWillReceiveProps()?' ); }); it('should throw AND warn when trying to access classic APIs', function() { spyOn(console, 'error'); var instance = test(<Inner name="foo" />, 'DIV', 'foo'); expect(() => instance.getDOMNode()).toThrow(); expect(() => instance.replaceState({})).toThrow(); expect(() => instance.isMounted()).toThrow(); expect(() => instance.setProps({name: 'bar'})).toThrow(); expect(() => instance.replaceProps({name: 'bar'})).toThrow(); expect(console.error.calls.length).toBe(3); expect(console.error.argsForCall[0][0]).toContain( 'getDOMNode(...) is deprecated in plain JavaScript React classes. ' + 'Use ReactDOM.findDOMNode(component) instead.' ); expect(console.error.argsForCall[1][0]).toContain( 'replaceState(...) is deprecated in plain JavaScript React classes' ); expect(console.error.argsForCall[2][0]).toContain( 'isMounted(...) is deprecated in plain JavaScript React classes' ); }); it('supports this.context passed via getChildContext', function() { class Bar extends React.Component { render() { return <div className={this.context.bar} />; } } Bar.contextTypes = {bar: React.PropTypes.string}; class Foo extends React.Component { getChildContext() { return {bar: 'bar-through-context'}; } render() { return <Bar />; } } Foo.childContextTypes = {bar: React.PropTypes.string}; test(<Foo />, 'DIV', 'bar-through-context'); }); it('supports classic refs', function() { class Foo extends React.Component { render() { return <Inner name="foo" ref="inner" />; } } var instance = test(<Foo />, 'DIV', 'foo'); expect(instance.refs.inner.getName()).toBe('foo'); }); it('supports drilling through to the DOM using findDOMNode', function() { var instance = test(<Inner name="foo" />, 'DIV', 'foo'); var node = ReactDOM.findDOMNode(instance); expect(node).toBe(container.firstChild); }); });
cody/react
src/isomorphic/modern/class/__tests__/ReactES6Class-test.js
JavaScript
bsd-3-clause
13,434
/** * This is the top-level body page for the search UI. */ cinema.views.MetaDataSearchPage = Backbone.View.extend({ events: { 'click .c-search-page-next-results': 'handlePageNextResults' }, initialize: function (settings) { this.basePath = settings.basePath; this.histogramModel = settings.histogramModel; this.visModel = settings.visModel; this.layerModel = settings.layerModel; this.zoomWidth = $(window).width() * 0.23; this.searchModel = new cinema.models.SearchModel({ basePath: this.basePath, histogramModel: this.histogramModel, visModel: this.visModel, layerModel: this.layerModel }); this.resultIndex = 0; this.offscreenLayerModel = new cinema.models.LayerModel(this.visModel.getDefaultPipelineSetup(), { info: this.visModel }); this.offscreenControlModel = new cinema.models.ControlModel({ info: this.visModel }); this.offscreenViewpointModel = new cinema.models.ViewPointModel({ controlModel: this.offscreenControlModel }); this.listenTo(cinema.events, 'c:handlesearchquery', this.handleSearchQuery); this.listenTo(cinema.events, 'c:handlesearchzoom', this.handleSearchZoom); }, render: function () { this.$el.html(cinema.templates.compositeSearchPage()); this.$('[title]').tooltip({ placement: 'bottom', delay: {show: 100} }); var viewpoint = this.offscreenControlModel.getControls(); this.compositeSearchResultContainer = $(cinema.templates.compositeSearchResultContainer({ viewpoint: viewpoint })); this.compositeSearchResultContainer.appendTo(this.$('.c-search-results-list-area')); this.offscreenVisualizationCanvasWidget = new cinema.views.VisualizationCanvasWidget({ el: this.compositeSearchResultContainer, model: this.visModel, viewpoint: this.offscreenViewpointModel, layers: this.offscreenLayerModel }).render().showViewpoint(); this.compositeSearchResultContainer.hide(); }, handlePageNextResults: function () { $('.c-search-page-next-results').hide(); if ((this.searchModel.results.length - this.resultIndex) > 12) { this.nextPageCount = 12; this._showNextResult(); } else { this.nextPageCount = this.searchModel.results.length - this.resultIndex; this._showNextResult(); } }, handleSearchZoom: function (event) { this.zoomWidth = Number(event.zoomWidth); this.$('.c-search-result-wrapper').css('width', this.zoomWidth).css('height', this.zoomWidth); }, handleSearchQuery: function (event) { this.clearResults(); var that = this; $('.c-search-page-next-results').hide(); $('.c-search-filter').val(event.searchQuery); setTimeout(function(){ var expressions = event.searchQuery.split(' Sort By '), filterExpression, numberOfSearchResults = 0, sortExpression; if (expressions.length === 2) { console.log("if"); filterExpression = that.searchModel.validateQuery(expressions[0]); sortExpression = that.searchModel.validateQuery(expressions[1]); if (filterExpression !== null && filterExpression !== '') { numberOfSearchResults = that.searchModel.filterBy(filterExpression); } else { numberOfSearchResults = that.searchModel.allResults(); } if (numberOfSearchResults > 0 && sortExpression !== null && sortExpression !== '') { that.searchModel.sortBy(sortExpression); } that.searchModel.setResultsList(); if (numberOfSearchResults > 0) { that._showResults(); } } else if (expressions.length === 1) { filterExpression = that.searchModel.validateQuery(expressions[0]); if (filterExpression !== null && filterExpression !== '') { numberOfSearchResults = that.searchModel.filterBy(filterExpression); } else { numberOfSearchResults = that.searchModel.allResults(); } that.searchModel.setResultsList(); if (numberOfSearchResults > 0) { that._showResults(); } } }, 100); }, clearResults: function () { $('.c-search-results-list-area').empty(); }, /** Returns whether we are at the bottom of the page */ _canScroll: function () { return this.$('.c-search-page-bottom').visible(true); }, _setScrollWaypoint: function () { var view = this; Scrollpoints.add(this.$('.c-search-page-bottom')[0], function () { if (view.searchModel.results) { view._showNextResult(); } }); }, _showResults: function () { this.resultIndex = 0; this.nextPageCount = 12; this.$('.c-search-result-message').text( this.searchModel.results.length + ' results'); this._showNextResult(); }, _showNextResult: function () { var self = this; if (this.searchModel.results.length <= this.resultIndex) { return; } var viewpoint = this.searchModel.results[this.resultIndex]; var query = this.layerModel.serialize(); this.offscreenVisualizationCanvasWidget.once('c:drawn', function () { self.resultIndex += 1; self.nextPageCount -= 1; var image = self.offscreenVisualizationCanvasWidget.getImage(); image.onload = function() { $('<img src="' + image.src + '" class = "c-search-result-wrapper"/>'). attr('image-key', self.searchModel.objectToOrdinal(viewpoint)). css('width', self.zoomWidth). css('height', self.zoomWidth). appendTo(self.$('.c-search-results-list-area')); $('html, body').scrollTop($('.c-search-result-wrapper').last().offset().top); }; if (self.nextPageCount !== 0) { self._showNextResult(); } else if (this.resultIndex < this.searchModel.results.length) { $('.c-search-page-next-results').show(); } else { /*jshint -W035 */ } }, this).updateTheQuery(query, viewpoint); } });
Kitware/cinema
web/src/js/lib/widgets/MetaDataSearchPage.js
JavaScript
bsd-3-clause
6,750
describe('Parsing', function() { describe('Replacement', function() { beforeEach(function() { foreigner.locale = 'en'; }); afterEach(function() { foreigner.locale = ''; foreigner.translations = {}; }); it('should work when the string contains only an interpolation', function() { foreigner.translations.en = { test_1: '{test}' }; expect(foreigner.t('test_1', {test: 'Hello'})).toEqual('Hello'); }); it('should output the string as-is when parameters aren’t passed', function() { foreigner.translations.en = { test_1: 'Hello, {name}.' }; expect(foreigner.t('test_1')).toEqual('Hello, {name}.'); }); it('should output the string with an empty string replacing variables when passing an empty object', function() { foreigner.translations.en = { test_1: 'Hello, {name}.' }; expect(foreigner.t('test_1', {})).toEqual('Hello, .'); }); it('should allow you to escape { and } characters', function() { // jshint ignore:start foreigner.translations.en = { test_1: '\{test', test_2: 'test\}', test_3: '\{test\}' }; // jshint ignore:end expect(foreigner.t('test_1')).toEqual('{test'); expect(foreigner.t('test_2')).toEqual('test}'); expect(foreigner.t('test_3')).toEqual('{test}'); }); it('should gracefully handle quotes (since it ends up in a JS String)', function() { foreigner.translations.en = { test_1: 'This is a dbl quote: "', test_2: "This is a single quote: '" }; expect(foreigner.t('test_1')).toEqual('This is a dbl quote: "'); expect(foreigner.t('test_2')).toEqual("This is a single quote: '"); }); it('should not care about whitespace in a variable', function() { foreigner.translations.en = { test_1: '{test }', test_2: '{ test}', test_3: '{test }', test_4: '{ test}' }; expect(foreigner.t('test_1', {test: 'Hello'})).toEqual('Hello'); expect(foreigner.t('test_2', {test: 'Hello'})).toEqual('Hello'); expect(foreigner.t('test_3', {test: 'Hello'})).toEqual('Hello'); expect(foreigner.t('test_4', {test: 'Hello'})).toEqual('Hello'); }); it('should maintain exact strings - not affected by variables', function() { foreigner.translations.en = { test_1: 'x{test}', test_2: '\n{test}', test_3: ' {test}', test_4: 'x { test}', test_5: 'x{test} x ', test_6: 'x\n{test}\n' }; expect(foreigner.t('test_1', {test: 'Hello'})).toEqual('xHello'); expect(foreigner.t('test_2', {test: 'Hello'})).toEqual('\nHello'); expect(foreigner.t('test_3', {test: 'Hello'})).toEqual(' Hello'); expect(foreigner.t('test_4', {test: 'Hello'})).toEqual('x Hello'); expect(foreigner.t('test_5', {test: 'Hello'})).toEqual('xHello x '); expect(foreigner.t('test_6', {test: 'Hello'})).toEqual('x\nHello\n'); }); it('should handle extended character literals', function() { foreigner.translations.en = { test_1: '☺{test}', test_2: '中{test}中国话不用彁字。😁' }; expect(foreigner.t('test_1', {test: 'Hello'})).toEqual('☺Hello'); expect(foreigner.t('test_2', {test: 'Hello'})).toEqual('中Hello中国话不用彁字。😁'); }); it('shouldn’t matter if it has html or something in it', function() { foreigner.translations.en = { test_1: '<div class="test">content: {test}</div>' }; expect(foreigner.t('test_1', {test: 'Hello'})).toEqual('<div class="test">content: Hello</div>'); }); it('should return the string with an empty string as the replacement if the variable provided is null', function() { foreigner.translations.en = { greet: 'Hello, {name}' }; expect(foreigner.t('greet', {name: null})).toEqual('Hello, '); }); }); describe('Selects', function() { beforeEach(function() { foreigner.locale = 'en'; }); afterEach(function() { foreigner.locale = ''; foreigner.translations = {}; }); it('should be very whitespace agnostic', function() { foreigner.translations.en = { test_1: '{VAR, select, key{a} other{b}}', test_2: '{VAR,select,key{a}other{b}}', test_3: '{ VAR , select , key {a} other {b} }', test_4: '{ \n VAR \n , \n select \n\n , \n \n key \n \n {a} \n other \n {b} \n \n }', test_5: '{ \t VAR \n , \n\t\r select \n\t , \t \n key \n \t {a} \n other \t {b} \t \t }' }; expect(foreigner.t('test_1', {VAR: null})).toEqual('b'); expect(foreigner.t('test_2', {VAR: null})).toEqual('b'); expect(foreigner.t('test_3', {VAR: null})).toEqual('b'); expect(foreigner.t('test_4', {VAR: null})).toEqual('b'); expect(foreigner.t('test_5', {VAR: null})).toEqual('b'); }); it('should allow you to use keywords in other places, including in select keys', function() { foreigner.translations.en = { test_1: 'x {TEST, select, select{a} other{b} }', test_2: 'x {TEST, select, TEST{a} other{b} }' }; // use `select` as a select key expect(foreigner.t('test_1', {TEST: 'select'})).toEqual('x a'); // use the exact variable name as a key name expect(foreigner.t('test_2', {TEST: 'TEST'})).toEqual('x a'); }); }); describe('Plurals', function() { beforeEach(function() { foreigner.locale = 'en'; }); afterEach(function() { foreigner.locale = ''; foreigner.translations = {}; }); it('should be very whitespace agnostic', function () { foreigner.translations.en = { test_1: '{ NUM, plural, one{1} other{2} }', test_2: '{NUM,plural,one{1}other{2}}', test_3: '{\nNUM, \nplural,\n one\n\n{1}\n other {2}\n\n\n}', test_4: '{\tNUM\t,\t\t\r plural\t\n, \tone\n{1} other\t\n{2}\n\n\n}' }; expect(foreigner.t('test_1', {NUM: 1})).toEqual('1'); expect(foreigner.t('test_2', {NUM: 1})).toEqual('1'); expect(foreigner.t('test_3', {NUM: 1})).toEqual('1'); expect(foreigner.t('test_4', {NUM: 1})).toEqual('1'); }); it('should be able to match `zero` given a value of 0', function() { foreigner.translations.en = { found_coins: 'You found {coinsCount, plural, zero{# coins} one{one coin} two{two coins} other{# coins}}.', }; expect(foreigner.t('found_coins', {coinsCount: 0})).toEqual('You found 0 coins.'); }); it('should be able to match `one` given a value of 1', function() { foreigner.translations.en = { found_coins: 'You found {coinsCount, plural, zero{# coins} one{one coin} two{two coins} other{# coins}}.', }; expect(foreigner.t('found_coins', {coinsCount: 1})).toEqual('You found one coin.'); }); it('should be able to match `two` given a value of 2', function() { foreigner.translations.en = { found_coins: 'You found {coinsCount, plural, zero{# coins} one{one coin} two{two coins} other{# coins}}.', }; expect(foreigner.t('found_coins', {coinsCount: 2})).toEqual('You found two coins.'); }); it('should be able to match any specific number given the exact value of the number', function() { foreigner.translations.en = { skill_points: 'You have {skillPoints, plural, 2{2 skill points} two{two skill points} 4{four skill points}} to spend.', }; expect(foreigner.t('skill_points', {skillPoints: 4})).toEqual('You have four skill points to spend.'); }); it('should be able to match 0, 1 and 2, and override the named key given the same number and named key are specified', function() { foreigner.translations.en = { skill_points: 'You have {skillPoints, plural, 2{2 skill points} two{two skill points} 4{four skill points}} to spend.', }; expect(foreigner.t('skill_points', {skillPoints: 2})).toEqual('You have 2 skill points to spend.'); }); it('should be able to fall back to `other` when the value doesn’t match any choice', function() { foreigner.translations.en = { found_coins: 'You found {coinsCount, plural, zero{# coins} one{one coin} two{two coins} other{# coins}}.', }; expect(foreigner.t('found_coins', {coinsCount: 3})).toEqual('You found 3 coins.'); }); it('should be able to match `other` when no other choice is defined', function() { foreigner.translations.en = { found_gems: 'You found {gemsCount, plural, other{gems}}.' }; expect(foreigner.t('found_gems', {gemsCount: 1})).toEqual('You found gems.'); }); }); describe('Selects', function() { beforeEach(function() { foreigner.locale = 'en'; foreigner.translations.en = { the_cake_is: 'The cake is {opinion, select, good{good} bad{bad} other{a lie}}.' }; }); afterEach(function() { foreigner.locale = ''; foreigner.translations = {}; }); it('should be able to match a choice', function() { expect(foreigner.t('the_cake_is', {opinion: 'good'})).toEqual('The cake is good.'); }); it('should be able to fall back to `other` when the value doesn’t match any choice', function() { expect(foreigner.t('the_cake_is', {opinion: 'dont_know'})).toEqual('The cake is a lie.'); }); }); });
mirego/foreigner.js
test/parsing_spec.js
JavaScript
bsd-3-clause
9,517
var recruitMgr=(function(config,functions){ /** * 创建datatable * @returns {*|jQuery} */ function createTable(){ var ownTable=$("#myTable").dataTable({ "bServerSide": true, "sAjaxSource": config.ajaxUrls.recruitGetAll, "bInfo":true, "bProcessing":true, "bLengthChange": false, "bFilter": false, "bSort":false, "bAutoWidth": false, "iDisplayLength":config.perLoadCounts.table, "sPaginationType":"full_numbers", "oLanguage": { "sUrl":config.dataTable.langUrl }, "aoColumns": [ { "mDataProp": "job"}, { "mDataProp": "date"}, { "mDataProp": "published", "fnRender":function(oObj){ return config.status.published[oObj.aData.published]; } }, { "mDataProp": "opt", "fnRender":function(oObj){ return '<a href="recruit/update?id='+oObj.aData.id+'">修改</a>&nbsp;' + '<a class="delete" href="'+oObj.aData.id+'">删除</a>'; } } ] , "fnServerParams": function ( aoData ) { aoData.push({ name:"filter", value:$("#filter").val()?"published="+$("#filter").val():"" }) }, "fnServerData": function(sSource, aoData, fnCallback) { //回调函数 $.ajax({ "dataType":'json', "type":"get", "url":sSource, "data":aoData, "success": function (response) { if(response.success===false){ functions.ajaxReturnErrorHandler(response.error_code); }else{ var json = { "sEcho" : response.sEcho }; for (var i = 0, iLen = response.aaData.length; i < iLen; i++) { response.aaData[i].opt="opt"; } json.aaData=response.aaData; json.iTotalRecords = response.iTotalRecords; json.iTotalDisplayRecords = response.iTotalDisplayRecords; fnCallback(json); } } }); }, "fnFormatNumber":function(iIn){ return iIn; } }); return ownTable; } return { ownTable:null, createTable:function(){ this.ownTable=createTable(); }, tableRedraw:function(){ this.ownTable.fnSettings()._iDisplayStart=0; this.ownTable.fnDraw(); }, delete:function(id){ functions.showLoading(); var me=this; $.ajax({ url:config.ajaxUrls.recruitDelete+"?id="+id, type:"post", dataType:"json", success:function(response){ if(response.success){ $().toastmessage("showSuccessToast",config.messages.optSuccess); me.ownTable.fnDraw(); functions.hideLoading(); }else{ functions.ajaxReturnErrorHandler(response.error_code); } }, error:function(){ functions.ajaxErrorHandler(); } }); }, published:function(id,value){ functions.showLoading(); $.ajax({ url: config.ajaxUrls.recruitPublished + "?id=" + id + "&published=" + value, type: "post", dataType: "json", success: function (response) { if (response.success) { $().toastmessage("showSuccessToast", config.messages.optSuccess); functions.hideLoading(); } else { functions.ajaxReturnErrorHandler(response.message); } }, error: function () { functions.ajaxErrorHandler(); } }); } } })(config,functions); $(document).ready(function(){ recruitMgr.createTable(); $("#searchBtn").click(function(){ recruitMgr.tableRedraw(); }); $("#myTable").on("click","a.delete",function(){ if(confirm(config.messages.confirmDelete)){ recruitMgr.delete($(this).attr("href")); } return false; }).on("change",".published",function(){ recruitMgr.published($(this).data("id"),$(this).val()); }) });
csboyty/markor-csr
backend/web/js/src/recruitMgr.js
JavaScript
bsd-3-clause
5,093
/** * Diamond Group */ import React from 'react' export default class Diamond extends React.Component { constructor() { } getWrapperStyle() { let offsetFix = this.props.isOdd ? 0.5 : 0 if(!this.props.isFirst) { if(this.props.isOdd) { offsetFix-- } } let rowFix = this.props.isOdd ? 1 : 0.5 let top = this.props.rowGroup * this.props.size * 0.5 + this.props.spacing * this.props.rowGroup let left = (this.props.offset + offsetFix) * (this.props.size + this.props.spacing) return { width: `${this.props.size}px`, height: `${this.props.size}px`, top: `${top}px`, left: `${left}px` } } extraStyle() { let baseStyle = this.props.isOdd ? "odd" : "even" baseStyle += this.props.isFirst ? " first" : "" return `${baseStyle} ${this.props.className || ""}` } getInnerStyle() { let style = {} if(this.props.fillImage) { style['background'] = `url(${this.props.fillImage}) no-repeat center` style['backgroundSize'] = `cover` } return style } render() { return ( <li className={`diamond-wrapper ${this.extraStyle()}`} style={this.getWrapperStyle()}> <div className="diamond-box"> <div className="diamond-box-inner" style={this.getInnerStyle()}> {this.props.children} </div> </div> </li> ) } }
elct9620/TLM-Website
app/components/Diamond.js
JavaScript
bsd-3-clause
1,567
var RecordRenderer = function(path, name, editor, dialog_id, field_values){ this.path = path; this.name = name; this.editor = editor; this.dialog_id = dialog_id; this.field_values = field_values; } RecordRenderer.prototype.render = function(){ var text1 = {"id": "fieldcontain-text-1", "label": "Title", "val": this.name}; this.renderField(text1); for(var i=0; i<this.field_values.length; i++){ this.renderField(this.field_values[i]); } var btn = this.editor.split(".")[0]; if(btn === "track"){ btn = "text"; } if(btn.indexOf(" (") >= 0){ btn = btn.split(" (")[0]; } btn = replaceSpace(btn); $("#"+btn.toLowerCase()+"-buttons").remove(); } RecordRenderer.prototype.renderField = function(value){ var splits = value.id.split("-"); var type = splits[1], n = splits[2]; var element_id = "#form-"+splits[1]+"-"+splits[2]; this.renderType[type](this.dialog_id, element_id, value, this.name, this.path); } RecordRenderer.prototype.renderType = { text: function(dialog, el_id, obj, name){ if(el_id != "#form-text-1"){ $("#"+dialog+" "+el_id).attr("value", obj.val); }else{ /*$("#"+dialog+" "+el_id).attr("readonly", "readonly"); $("#"+dialog+" "+el_id).after("read-only") $("#"+dialog+" "+el_id).val(name);*/ //for next release in order rename to work $("#"+dialog+" "+el_id).after('<input type="hidden" id="form-text-hidden-1" value="'+name+'">'); $("#"+dialog+" "+el_id).val(name); } }, textarea: function(dialog, el_id, obj){ $("#"+dialog+" "+el_id).attr("value", obj.val); }, warning: function(dialog, el_id, obj){ $("#"+dialog+" "+el_id).attr("value", obj.val); }, checkbox: function(dialog, el_id, obj){ var splits = new Array(); splits = obj.val.split(","); for(var i=0; i<splits.length; i++){ $("#"+obj.id).find("input[value="+splits[i]+"]").prop("checked", true); } }, radio: function(dialog, el_id, obj){ $("#"+dialog+" input[value="+obj.val+"]").prop("checked", true); }, select: function(dialog, el_id, obj){ $("#"+obj.id).find("option[value='"+obj.val+"']").prop("selected", true); }, image: function(dialog, el_id, obj, name, path){ var splits = path.split("/"); $("#"+obj.id).html('<img src="/'+splits[0]+'/pcapi/records/'+splits[1]+'/'+splits[2]+'/'+name+'/'+obj.val+'"><br>'); }, audio: function(dialog, el_id, obj, name, path){ var splits = path.split("/"); $("#"+obj.id).html('<a href="/'+splits[0]+'/pcapi/records/'+splits[1]+'/'+splits[2]+'/'+name+'/'+obj.val+'">'+obj.val+'</a>') }, track: function(){ return ""; }, range: function(dialog, el_id, obj){ $("#"+dialog+" "+el_id).attr("value", obj.val); } }
cobweb-eu/fieldtrip-authoring-tool
src/js/former/jquery.former.renderer.js
JavaScript
bsd-3-clause
2,737
export {default as hypergraph} from "./src/hypergraph";
AndreaSimeone/d3-hypergraph
index.js
JavaScript
bsd-3-clause
56
describe("Service: updateFormValidity", function(){ var updateFieldValidity; var updateFormValidity; beforeEach(function(){ module('ngValidation'); }); beforeEach(inject(function(_updateFormValidity_){ updateFormValidity = _updateFormValidity_; })); it("sets form validity", function(){ var form = { name: jasmine.createSpyObj('name', ['$setValidity']), title: jasmine.createSpyObj('title', ['$setValidity']) }; var titleValidity = { present: true , magic: false } updateFormValidity(form, { name: { present: true , magic: false }, title: { present: false , magic: false } }); expect(form.name.$setValidity).toHaveBeenCalledWith('present', true); expect(form.name.$setValidity).toHaveBeenCalledWith('magic', false); expect(form.title.$setValidity).toHaveBeenCalledWith('present', false); expect(form.title.$setValidity).toHaveBeenCalledWith('magic', false); }); });
mightymoose/ng-validation
spec/formModificationSpec.js
JavaScript
bsd-3-clause
1,173
/** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @flow * @fullSyntaxTransform */ 'use strict'; const GraphQL = { error: require('graphql/error'), language: require('graphql/language'), language_parser: require('graphql/language/parser'), language_source: require('graphql/language/source'), type: require('graphql/type'), type_definition: require('graphql/type/definition'), type_directives: require('graphql/type/directives'), type_introspection: require('graphql/type/introspection'), type_scalars: require('graphql/type/scalars'), utilities: require('graphql/utilities'), utilities_buildClientSchema: require('graphql/utilities/buildClientSchema'), utilities_buildASTSchema: require('graphql/utilities/buildASTSchema'), validation: require('graphql/validation'), validation_rules_KnownFragmentNames: require('graphql/validation/rules/KnownFragmentNames'), validation_rules_NoUndefinedVariables: require('graphql/validation/rules/NoUndefinedVariables'), validation_rules_NoUnusedFragments: require('graphql/validation/rules/NoUnusedFragments'), validation_rules_ScalarLeafs: require('graphql/validation/rules/ScalarLeafs'), validation_validate: require('graphql/validation/validate'), }; module.exports = GraphQL;
xuorig/relay
scripts/babel-relay-plugin/src/GraphQL.js
JavaScript
bsd-3-clause
1,519
/*--------------------------------------------------------------------------- Copyright 2012 Daniel C. Bünzli. All rights reserved. Distributed under a BSD3 license. ---------------------------------------------------------------------------*/ /** Luigi main. */ var Luigi = function () { var init = false; var luigi_conf = { base : "/luigi/", langs : { "en": "en", "fr" : "fr" }, library : { "en" : "Digital CIRA", "fr" : "CIRA numérique" } }; function main () { if (!init) { init = true; var ui = Ui.create (luigi_conf, window.location); if (DEBUG) { // Convenient global environment pollution. window.luigi_conf = luigi_conf; window.ui = ui; window.J = J; window.Workaround = Workaround; window.Debug = Debug; window.Request = Request; window.Doc = Doc; window.Ui = Ui; } } } document.addEventListener("DOMContentLoaded", main, false); } ();
dbuenzli/remat
attic/luigi-base.js
JavaScript
bsd-3-clause
1,026
var searchData= [ ['todo_20list',['Todo List',['../a00480.html',1,'']]] ];
malcolmreynolds/GTSAM
doc/html/search/pages_74.js
JavaScript
bsd-3-clause
77
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /** * ImageEditor is the top level object that holds together and connects * everything needed for image editing. * @param {Viewport} viewport The viewport. * @param {ImageView} imageView The ImageView containing the images to edit. * @param {ImageEditor.Prompt} prompt Prompt instance. * @param {Object} DOMContainers Various DOM containers required for the editor. * @param {Array.<ImageEditor.Mode>} modes Available editor modes. * @param {function} displayStringFunction String formatting function. * @constructor */ function ImageEditor( viewport, imageView, prompt, DOMContainers, modes, displayStringFunction) { this.rootContainer_ = DOMContainers.root; this.container_ = DOMContainers.image; this.modes_ = modes; this.displayStringFunction_ = displayStringFunction; ImageUtil.removeChildren(this.container_); var document = this.container_.ownerDocument; this.viewport_ = viewport; this.viewport_.sizeByFrame(this.container_); this.buffer_ = new ImageBuffer(); this.viewport_.addRepaintCallback(this.buffer_.draw.bind(this.buffer_)); this.imageView_ = imageView; this.imageView_.addContentCallback(this.onContentUpdate_.bind(this)); this.buffer_.addOverlay(this.imageView_); this.panControl_ = new ImageEditor.MouseControl( this.rootContainer_, this.container_, this.getBuffer()); this.panControl_.setDoubleTapCallback(this.onDoubleTap_.bind(this)); this.mainToolbar_ = new ImageEditor.Toolbar( DOMContainers.toolbar, displayStringFunction); this.modeToolbar_ = new ImageEditor.Toolbar( DOMContainers.mode, displayStringFunction, this.onOptionsChange.bind(this)); this.prompt_ = prompt; this.createToolButtons(); this.commandQueue_ = null; } /** * @return {boolean} True if no user commands are to be accepted. */ ImageEditor.prototype.isLocked = function() { return !this.commandQueue_ || this.commandQueue_.isBusy(); }; /** * @return {boolean} True if the command queue is busy. */ ImageEditor.prototype.isBusy = function() { return this.commandQueue_ && this.commandQueue_.isBusy(); }; /** * Reflect the locked state of the editor in the UI. * @param {boolean} on True if locked. */ ImageEditor.prototype.lockUI = function(on) { ImageUtil.setAttribute(this.rootContainer_, 'locked', on); }; /** * Report the tool use to the metrics subsystem. * @param {string} name Action name. */ ImageEditor.prototype.recordToolUse = function(name) { ImageUtil.metrics.recordEnum( ImageUtil.getMetricName('Tool'), name, this.actionNames_); }; /** * Content update handler. * @private */ ImageEditor.prototype.onContentUpdate_ = function() { for (var i = 0; i != this.modes_.length; i++) { var mode = this.modes_[i]; ImageUtil.setAttribute(mode.button_, 'disabled', !mode.isApplicable()); } }; /** * Open the editing session for a new image. * * @param {string} url Image url. * @param {Object} metadata Metadata. * @param {Object} effect Transition effect object. * @param {function(function)} saveFunction Image save function. * @param {function} displayCallback Display callback. * @param {function} loadCallback Load callback. */ ImageEditor.prototype.openSession = function( url, metadata, effect, saveFunction, displayCallback, loadCallback) { if (this.commandQueue_) throw new Error('Session not closed'); this.lockUI(true); var self = this; this.imageView_.load( url, metadata, effect, displayCallback, function(loadType, delay, error) { self.lockUI(false); self.commandQueue_ = new CommandQueue( self.container_.ownerDocument, self.imageView_.getCanvas(), saveFunction); self.commandQueue_.attachUI( self.getImageView(), self.getPrompt(), self.lockUI.bind(self)); self.updateUndoRedo(); loadCallback(loadType, delay, error); }); }; /** * Close the current image editing session. * @param {function} callback Callback. */ ImageEditor.prototype.closeSession = function(callback) { this.getPrompt().hide(); if (this.imageView_.isLoading()) { if (this.commandQueue_) { console.warn('Inconsistent image editor state'); this.commandQueue_ = null; } this.imageView_.cancelLoad(); this.lockUI(false); callback(); return; } if (!this.commandQueue_) { // Session is already closed. callback(); return; } this.executeWhenReady(callback); this.commandQueue_ = null; }; /** * Commit the current operation and execute the action. * * @param {function} callback Callback. */ ImageEditor.prototype.executeWhenReady = function(callback) { if (this.commandQueue_) { this.leaveModeGently(); this.commandQueue_.executeWhenReady(callback); } else { if (!this.imageView_.isLoading()) console.warn('Inconsistent image editor state'); callback(); } }; /** * @return {boolean} True if undo queue is not empty. */ ImageEditor.prototype.canUndo = function() { return this.commandQueue_ && this.commandQueue_.canUndo(); }; /** * Undo the recently executed command. */ ImageEditor.prototype.undo = function() { if (this.isLocked()) return; this.recordToolUse('undo'); // First undo click should dismiss the uncommitted modifications. if (this.currentMode_ && this.currentMode_.isUpdated()) { this.currentMode_.reset(); return; } this.getPrompt().hide(); this.leaveMode(false); this.commandQueue_.undo(); this.updateUndoRedo(); }; /** * Redo the recently un-done command. */ ImageEditor.prototype.redo = function() { if (this.isLocked()) return; this.recordToolUse('redo'); this.getPrompt().hide(); this.leaveMode(false); this.commandQueue_.redo(); this.updateUndoRedo(); }; /** * Update Undo/Redo buttons state. */ ImageEditor.prototype.updateUndoRedo = function() { var canUndo = this.commandQueue_ && this.commandQueue_.canUndo(); var canRedo = this.commandQueue_ && this.commandQueue_.canRedo(); ImageUtil.setAttribute(this.undoButton_, 'disabled', !canUndo); this.redoButton_.hidden = !canRedo; }; /** * @return {HTMLCanvasElement} The current image canvas. */ ImageEditor.prototype.getCanvas = function() { return this.getImageView().getCanvas(); }; /** * @return {ImageBuffer} ImageBuffer instance. */ ImageEditor.prototype.getBuffer = function() { return this.buffer_ }; /** * @return {ImageView} ImageView instance. */ ImageEditor.prototype.getImageView = function() { return this.imageView_ }; /** * @return {Viewport} Viewport instance. */ ImageEditor.prototype.getViewport = function() { return this.viewport_ }; /** * @return {ImageEditor.Prompt} Prompt instance. */ ImageEditor.prototype.getPrompt = function() { return this.prompt_ }; /** * Handle the toolbar controls update. * @param {Object} options A map of options. */ ImageEditor.prototype.onOptionsChange = function(options) { ImageUtil.trace.resetTimer('update'); if (this.currentMode_) { this.currentMode_.update(options); } ImageUtil.trace.reportTimer('update'); }; /** * ImageEditor.Mode represents a modal state dedicated to a specific operation. * Inherits from ImageBuffer.Overlay to simplify the drawing of * mode-specific tools. * @param {string} name The mode name. * @constructor */ ImageEditor.Mode = function(name) { this.name = name; this.message_ = 'enter_when_done'; }; ImageEditor.Mode.prototype = {__proto__: ImageBuffer.Overlay.prototype }; /** * @return {Viewport} Viewport instance. */ ImageEditor.Mode.prototype.getViewport = function() { return this.viewport_ }; /** * @return {ImageView} ImageView instance. */ ImageEditor.Mode.prototype.getImageView = function() { return this.imageView_ }; /** * @return {string} The mode-specific message to be displayed when entering. */ ImageEditor.Mode.prototype.getMessage = function() { return this.message_ }; /** * @return {boolean} True if the mode is applicable in the current context. */ ImageEditor.Mode.prototype.isApplicable = function() { return true }; /** * Called once after creating the mode button. * * @param {ImageEditor} editor The editor instance. * @param {HTMLElement} button The mode button. */ ImageEditor.Mode.prototype.bind = function(editor, button) { this.editor_ = editor; this.editor_.registerAction_(this.name); this.button_ = button; this.viewport_ = editor.getViewport(); this.imageView_ = editor.getImageView(); }; /** * Called before entering the mode. */ ImageEditor.Mode.prototype.setUp = function() { this.editor_.getBuffer().addOverlay(this); this.updated_ = false; }; /** * Create mode-specific controls here. * @param {ImageEditor.Toolbar} toolbar The toolbar to populate. */ ImageEditor.Mode.prototype.createTools = function(toolbar) {}; /** * Called before exiting the mode. */ ImageEditor.Mode.prototype.cleanUpUI = function() { this.editor_.getBuffer().removeOverlay(this); }; /** * Called after exiting the mode. */ ImageEditor.Mode.prototype.cleanUpCaches = function() {}; /** * Called when any of the controls changed its value. * @param {Object} options A map of options. */ ImageEditor.Mode.prototype.update = function(options) { this.markUpdated(); }; /** * Mark the editor mode as updated. */ ImageEditor.Mode.prototype.markUpdated = function() { this.updated_ = true; }; /** * @return {boolean} True if the mode controls changed. */ ImageEditor.Mode.prototype.isUpdated = function() { return this.updated_ }; /** * Resets the mode to a clean state. */ ImageEditor.Mode.prototype.reset = function() { this.editor_.modeToolbar_.reset(); this.updated_ = false; }; /** * One-click editor tool, requires no interaction, just executes the command. * @param {string} name The mode name. * @param {Command} command The command to execute on click. * @constructor */ ImageEditor.Mode.OneClick = function(name, command) { ImageEditor.Mode.call(this, name); this.instant = true; this.command_ = command; }; ImageEditor.Mode.OneClick.prototype = {__proto__: ImageEditor.Mode.prototype}; /** * @return {Command} command. */ ImageEditor.Mode.OneClick.prototype.getCommand = function() { return this.command_; }; /** * Register the action name. Required for metrics reporting. * @param {string} name Button name. * @private */ ImageEditor.prototype.registerAction_ = function(name) { this.actionNames_.push(name); }; /** * Populate the toolbar. */ ImageEditor.prototype.createToolButtons = function() { this.mainToolbar_.clear(); this.actionNames_ = []; var self = this; function createButton(name, handler) { return self.mainToolbar_.addButton(name, handler, name); } for (var i = 0; i != this.modes_.length; i++) { var mode = this.modes_[i]; mode.bind(this, createButton(mode.name, this.enterMode.bind(this, mode))); } this.undoButton_ = createButton('undo', this.undo.bind(this)); this.registerAction_('undo'); this.redoButton_ = createButton('redo', this.redo.bind(this)); this.registerAction_('redo'); }; /** * @return {ImageEditor.Mode} The current mode. */ ImageEditor.prototype.getMode = function() { return this.currentMode_ }; /** * The user clicked on the mode button. * * @param {ImageEditor.Mode} mode The new mode. */ ImageEditor.prototype.enterMode = function(mode) { if (this.isLocked()) return; if (this.currentMode_ == mode) { // Currently active editor tool clicked, commit if modified. this.leaveMode(this.currentMode_.updated_); return; } this.recordToolUse(mode.name); this.leaveModeGently(); // The above call could have caused a commit which might have initiated // an asynchronous command execution. Wait for it to complete, then proceed // with the mode set up. this.commandQueue_.executeWhenReady(this.setUpMode_.bind(this, mode)); }; /** * Set up the new editing mode. * * @param {ImageEditor.Mode} mode The mode. * @private */ ImageEditor.prototype.setUpMode_ = function(mode) { this.currentTool_ = mode.button_; ImageUtil.setAttribute(this.currentTool_, 'pressed', true); this.currentMode_ = mode; this.currentMode_.setUp(); if (this.currentMode_.instant) { // Instant tool. this.leaveMode(true); return; } this.getPrompt().show(this.currentMode_.getMessage()); this.modeToolbar_.clear(); this.currentMode_.createTools(this.modeToolbar_); this.modeToolbar_.show(true); }; /** * The user clicked on 'OK' or 'Cancel' or on a different mode button. * @param {boolean} commit True if commit is required. */ ImageEditor.prototype.leaveMode = function(commit) { if (!this.currentMode_) return; if (!this.currentMode_.instant) { this.getPrompt().hide(); } this.modeToolbar_.show(false); this.currentMode_.cleanUpUI(); if (commit) { var self = this; var command = this.currentMode_.getCommand(); if (command) { // Could be null if the user did not do anything. this.commandQueue_.execute(command); this.updateUndoRedo(); } } this.currentMode_.cleanUpCaches(); this.currentMode_ = null; ImageUtil.setAttribute(this.currentTool_, 'pressed', false); this.currentTool_ = null; }; /** * Leave the mode, commit only if required by the current mode. */ ImageEditor.prototype.leaveModeGently = function() { this.leaveMode(this.currentMode_ && this.currentMode_.updated_ && this.currentMode_.implicitCommit); }; /** * Enter the editor mode with the given name. * * @param {string} name Mode name. * @private */ ImageEditor.prototype.enterModeByName_ = function(name) { for (var i = 0; i != this.modes_.length; i++) { var mode = this.modes_[i]; if (mode.name == name) { if (!mode.button_.hasAttribute('disabled')) this.enterMode(mode); return; } } console.error('Mode "' + name + '" not found.'); }; /** * Key down handler. * @param {Event} event The keydown event. * @return {boolean} True if handled. */ ImageEditor.prototype.onKeyDown = function(event) { switch (util.getKeyModifiers(event) + event.keyIdentifier) { case 'U+001B': // Escape case 'Enter': if (this.getMode()) { this.leaveMode(event.keyIdentifier == 'Enter'); return true; } break; case 'Ctrl-U+005A': // Ctrl+Z if (this.commandQueue_.canUndo()) { this.undo(); return true; } break; case 'Ctrl-U+0059': // Ctrl+Y if (this.commandQueue_.canRedo()) { this.redo(); return true; } break; case 'U+0041': // 'a' this.enterModeByName_('autofix'); return true; case 'U+0042': // 'b' this.enterModeByName_('exposure'); return true; case 'U+0043': // 'c' this.enterModeByName_('crop'); return true; case 'U+004C': // 'l' this.enterModeByName_('rotate_left'); return true; case 'U+0052': // 'r' this.enterModeByName_('rotate_right'); return true; } return false; }; /** * Double tap handler. * @param {number} x X coordinate of the event. * @param {number} y Y coordinate of the event. * @private */ ImageEditor.prototype.onDoubleTap_ = function(x, y) { if (this.getMode()) { var action = this.buffer_.getDoubleTapAction(x, y); if (action == ImageBuffer.DoubleTapAction.COMMIT) this.leaveMode(true); else if (action == ImageBuffer.DoubleTapAction.CANCEL) this.leaveMode(false); } }; /** * Hide the tools that overlap the given rectangular frame. * * @param {Rect} frame Hide the tool that overlaps this rect. * @param {Rect} transparent But do not hide the tool that is completely inside * this rect. */ ImageEditor.prototype.hideOverlappingTools = function(frame, transparent) { var tools = this.rootContainer_.ownerDocument.querySelectorAll('.dimmable'); for (var i = 0; i != tools.length; i++) { var tool = tools[i]; var toolRect = tool.getBoundingClientRect(); ImageUtil.setAttribute(tool, 'dimmed', (frame && frame.intersects(toolRect)) && !(transparent && transparent.contains(toolRect))); } }; /** * A helper object for panning the ImageBuffer. * * @param {HTMLElement} rootContainer The top-level container. * @param {HTMLElement} container The container for mouse events. * @param {ImageBuffer} buffer Image buffer. * @constructor */ ImageEditor.MouseControl = function(rootContainer, container, buffer) { this.rootContainer_ = rootContainer; this.container_ = container; this.buffer_ = buffer; var handlers = { 'touchstart': this.onTouchStart, 'touchend': this.onTouchEnd, 'touchcancel': this.onTouchCancel, 'touchmove': this.onTouchMove, 'mousedown': this.onMouseDown, 'mouseup': this.onMouseUp }; for (var eventName in handlers) { container.addEventListener( eventName, handlers[eventName].bind(this), false); } // Mouse move handler has to be attached to the window to receive events // from outside of the window. See: http://crbug.com/155705 window.addEventListener('mousemove', this.onMouseMove.bind(this), false); }; /** * Maximum movement for touch to be detected as a tap (in pixels). * @private */ ImageEditor.MouseControl.MAX_MOVEMENT_FOR_TAP_ = 8; /** * Maximum time for touch to be detected as a tap (in milliseconds). * @private */ ImageEditor.MouseControl.MAX_TAP_DURATION_ = 500; /** * Maximum distance from the first tap to the second tap to be considered * as a double tap. * @private */ ImageEditor.MouseControl.MAX_DISTANCE_FOR_DOUBLE_TAP_ = 32; /** * Maximum time for touch to be detected as a double tap (in milliseconds). * @private */ ImageEditor.MouseControl.MAX_DOUBLE_TAP_DURATION_ = 1000; /** * Convert the event position from the event object to client coordinates. * * @param {MouseEvent|Touch} e Pointer position. * @return {Object} A pair of x,y in client coordinates. * @private */ ImageEditor.MouseControl.getPosition_ = function(e) { var clientRect = e.target.getBoundingClientRect(); return { x: e.clientX - clientRect.left, y: e.clientY - clientRect.top }; }; /** * Returns touch position or null if there is more than one touch position. * * @param {TouchEvent} e Event. * @return {object?} A pair of x,y in client coordinates. * @private */ ImageEditor.MouseControl.prototype.getTouchPosition_ = function(e) { if (e.targetTouches.length == 1) return ImageEditor.MouseControl.getPosition_(e.targetTouches[0]); else return null; }; /** * Touch start handler. * @param {TouchEvent} e Event. */ ImageEditor.MouseControl.prototype.onTouchStart = function(e) { var position = this.getTouchPosition_(e); if (position) { this.touchStartInfo_ = { x: position.x, y: position.y, time: Date.now() }; this.dragHandler_ = this.buffer_.getDragHandler(position.x, position.y, true /* touch */); this.dragHappened_ = false; } e.preventDefault(); }; /** * Touch end handler. * @param {TouchEvent} e Event. */ ImageEditor.MouseControl.prototype.onTouchEnd = function(e) { if (!this.dragHappened_ && Date.now() - this.touchStartInfo_.time <= ImageEditor.MouseControl.MAX_TAP_DURATION_) { this.buffer_.onClick(this.touchStartInfo_.x, this.touchStartInfo_.y); if (this.previousTouchStartInfo_ && Date.now() - this.previousTouchStartInfo_.time < ImageEditor.MouseControl.MAX_DOUBLE_TAP_DURATION_) { var prevTouchCircle = new Circle( this.previousTouchStartInfo_.x, this.previousTouchStartInfo_.y, ImageEditor.MouseControl.MAX_DISTANCE_FOR_DOUBLE_TAP_); if (prevTouchCircle.inside(this.touchStartInfo_.x, this.touchStartInfo_.y)) { this.doubleTapCallback_(this.touchStartInfo_.x, this.touchStartInfo_.y); } } this.previousTouchStartInfo_ = this.touchStartInfo_; } else { this.previousTouchStartInfo_ = null; } this.onTouchCancel(e); e.preventDefault(); }; /** * Default double tap handler. * @param {number} x X coordinate of the event. * @param {number} y Y coordinate of the event. * @private */ ImageEditor.MouseControl.prototype.doubleTapCallback_ = function(x, y) {}; /** * Sets callback to be called when double tap detected. * @param {function(number, number)} callback New double tap callback. */ ImageEditor.MouseControl.prototype.setDoubleTapCallback = function(callback) { this.doubleTapCallback_ = callback; }; /** * Touch chancel handler. */ ImageEditor.MouseControl.prototype.onTouchCancel = function() { this.dragHandler_ = null; this.dragHappened_ = false; this.touchStartInfo_ = null; this.lockMouse_(false); }; /** * Touch move handler. * @param {TouchEvent} e Event. */ ImageEditor.MouseControl.prototype.onTouchMove = function(e) { var position = this.getTouchPosition_(e); if (!position) return; if (this.touchStartInfo_ && !this.dragHappened_) { var tapCircle = new Circle(this.touchStartInfo_.x, this.touchStartInfo_.y, ImageEditor.MouseControl.MAX_MOVEMENT_FOR_TAP_); this.dragHappened_ = !tapCircle.inside(position.x, position.y); } if (this.dragHandler_ && this.dragHappened_) { this.dragHandler_(position.x, position.y); this.lockMouse_(true); } e.preventDefault(); }; /** * Mouse down handler. * @param {MouseEvent} e Event. */ ImageEditor.MouseControl.prototype.onMouseDown = function(e) { var position = ImageEditor.MouseControl.getPosition_(e); this.dragHandler_ = this.buffer_.getDragHandler(position.x, position.y, false /* mouse */); this.dragHappened_ = false; this.updateCursor_(position); e.preventDefault(); }; /** * Mouse up handler. * @param {MouseEvent} e Event. */ ImageEditor.MouseControl.prototype.onMouseUp = function(e) { var position = ImageEditor.MouseControl.getPosition_(e); if (!this.dragHappened_) { this.buffer_.onClick(position.x, position.y); } this.dragHandler_ = null; this.dragHappened_ = false; this.lockMouse_(false); e.preventDefault(); }; /** * Mouse move handler. * @param {MouseEvent} e Event. */ ImageEditor.MouseControl.prototype.onMouseMove = function(e) { var position = ImageEditor.MouseControl.getPosition_(e); if (this.dragHandler_ && !e.which) { // mouseup must have happened while the mouse was outside our window. this.dragHandler_ = null; this.lockMouse_(false); } this.updateCursor_(position); if (this.dragHandler_) { this.dragHandler_(position.x, position.y); this.dragHappened_ = true; this.lockMouse_(true); } e.preventDefault(); }; /** * Update the UI to reflect mouse drag state. * @param {boolean} on True if dragging. * @private */ ImageEditor.MouseControl.prototype.lockMouse_ = function(on) { ImageUtil.setAttribute(this.rootContainer_, 'mousedrag', on); }; /** * Update the cursor. * * @param {Object} position An object holding x and y properties. * @private */ ImageEditor.MouseControl.prototype.updateCursor_ = function(position) { var oldCursor = this.container_.getAttribute('cursor'); var newCursor = this.buffer_.getCursorStyle( position.x, position.y, !!this.dragHandler_); if (newCursor != oldCursor) // Avoid flicker. this.container_.setAttribute('cursor', newCursor); }; /** * A toolbar for the ImageEditor. * @param {HTMLElement} parent The parent element. * @param {function} displayStringFunction A string formatting function. * @param {function} updateCallback The callback called when controls change. * @constructor */ ImageEditor.Toolbar = function(parent, displayStringFunction, updateCallback) { this.wrapper_ = parent; this.displayStringFunction_ = displayStringFunction; this.updateCallback_ = updateCallback; }; /** * Clear the toolbar. */ ImageEditor.Toolbar.prototype.clear = function() { ImageUtil.removeChildren(this.wrapper_); }; /** * Create a control. * @param {string} tagName The element tag name. * @return {HTMLElement} The created control element. * @private */ ImageEditor.Toolbar.prototype.create_ = function(tagName) { return this.wrapper_.ownerDocument.createElement(tagName); }; /** * Add a control. * @param {HTMLElement} element The control to add. * @return {HTMLElement} The added element. */ ImageEditor.Toolbar.prototype.add = function(element) { this.wrapper_.appendChild(element); return element; }; /** * Add a text label. * @param {string} name Label name. * @return {HTMLElement} The added label. */ ImageEditor.Toolbar.prototype.addLabel = function(name) { var label = this.create_('span'); label.textContent = this.displayStringFunction_(name); return this.add(label); }; /** * Add a button. * @param {string} name Button name. * @param {function} handler onClick handler. * @param {string=} opt_class Extra class name. * @return {HTMLElement} The added button. */ ImageEditor.Toolbar.prototype.addButton = function( name, handler, opt_class) { var button = this.create_('button'); if (opt_class) button.classList.add(opt_class); var label = this.create_('span'); label.textContent = this.displayStringFunction_(name); button.appendChild(label); button.label = this.displayStringFunction_(name); button.addEventListener('click', handler, false); return this.add(button); }; /** * Add a range control (scalar value picker). * * @param {string} name An option name. * @param {number} min Min value of the option. * @param {number} value Default value of the option. * @param {number} max Max value of the options. * @param {number} scale A number to multiply by when setting * min/value/max in DOM. * @param {boolean=} opt_showNumeric True if numeric value should be displayed. * @return {HTMLElement} Range element. */ ImageEditor.Toolbar.prototype.addRange = function( name, min, value, max, scale, opt_showNumeric) { var self = this; scale = scale || 1; var range = this.create_('input'); range.className = 'range'; range.type = 'range'; range.name = name; range.min = Math.ceil(min * scale); range.max = Math.floor(max * scale); var numeric = this.create_('div'); numeric.className = 'numeric'; function mirror() { numeric.textContent = Math.round(range.getValue() * scale) / scale; } range.setValue = function(newValue) { range.value = Math.round(newValue * scale); mirror(); }; range.getValue = function() { return Number(range.value) / scale; }; range.reset = function() { range.setValue(value); }; range.addEventListener('change', function() { mirror(); self.updateCallback_(self.getOptions()); }, false); range.setValue(value); var label = this.create_('div'); label.textContent = this.displayStringFunction_(name); label.className = 'label ' + name; this.add(label); this.add(range); if (opt_showNumeric) this.add(numeric); return range; }; /** * @return {Object} options A map of options. */ ImageEditor.Toolbar.prototype.getOptions = function() { var values = {}; for (var child = this.wrapper_.firstChild; child; child = child.nextSibling) { if (child.name) values[child.name] = child.getValue(); } return values; }; /** * Reset the toolbar. */ ImageEditor.Toolbar.prototype.reset = function() { for (var child = this.wrapper_.firstChild; child; child = child.nextSibling) { if (child.reset) child.reset(); } }; /** * Show/hide the toolbar. * @param {boolean} on True if show. */ ImageEditor.Toolbar.prototype.show = function(on) { if (!this.wrapper_.firstChild) return; // Do not show empty toolbar; this.wrapper_.hidden = !on; }; /** A prompt panel for the editor. * * @param {HTMLElement} container Container element. * @param {function} displayStringFunction A formatting function. * @constructor */ ImageEditor.Prompt = function(container, displayStringFunction) { this.container_ = container; this.displayStringFunction_ = displayStringFunction; }; /** * Reset the prompt. */ ImageEditor.Prompt.prototype.reset = function() { this.cancelTimer(); if (this.wrapper_) { this.container_.removeChild(this.wrapper_); this.wrapper_ = null; this.prompt_ = null; } }; /** * Cancel the delayed action. */ ImageEditor.Prompt.prototype.cancelTimer = function() { if (this.timer_) { clearTimeout(this.timer_); this.timer_ = null; } }; /** * Schedule the delayed action. * @param {function} callback Callback. * @param {number} timeout Timeout. */ ImageEditor.Prompt.prototype.setTimer = function(callback, timeout) { this.cancelTimer(); var self = this; this.timer_ = setTimeout(function() { self.timer_ = null; callback(); }, timeout); }; /** * Show the prompt. * * @param {string} text The prompt text. * @param {number} timeout Timeout in ms. * @param {Object} formatArgs varArgs for the formatting fuction. */ ImageEditor.Prompt.prototype.show = function(text, timeout, formatArgs) { this.showAt.apply(this, ['center'].concat(Array.prototype.slice.call(arguments))); }; /** * * @param {string} pos The 'pos' attribute value. * @param {string} text The prompt text. * @param {number} timeout Timeout in ms. * @param {Object} formatArgs varArgs for the formatting fuction. */ ImageEditor.Prompt.prototype.showAt = function(pos, text, timeout, formatArgs) { this.reset(); if (!text) return; var document = this.container_.ownerDocument; this.wrapper_ = document.createElement('div'); this.wrapper_.className = 'prompt-wrapper'; this.wrapper_.setAttribute('pos', pos); this.container_.appendChild(this.wrapper_); this.prompt_ = document.createElement('div'); this.prompt_.className = 'prompt'; // Create an extra wrapper which opacity can be manipulated separately. var tool = document.createElement('div'); tool.className = 'dimmable'; this.wrapper_.appendChild(tool); tool.appendChild(this.prompt_); var args = [text].concat(Array.prototype.slice.call(arguments, 3)); this.prompt_.textContent = this.displayStringFunction_.apply(null, args); var close = document.createElement('div'); close.className = 'close'; close.addEventListener('click', this.hide.bind(this)); this.prompt_.appendChild(close); setTimeout( this.prompt_.setAttribute.bind(this.prompt_, 'state', 'fadein'), 0); if (timeout) this.setTimer(this.hide.bind(this), timeout); }; /** * Hide the prompt. */ ImageEditor.Prompt.prototype.hide = function() { if (!this.prompt_) return; this.prompt_.setAttribute('state', 'fadeout'); // Allow some time for the animation to play out. this.setTimer(this.reset.bind(this), 500); };
zcbenz/cefode-chromium
chrome/browser/resources/file_manager/js/image_editor/image_editor.js
JavaScript
bsd-3-clause
31,038
var Login = function () { var handleLogin = function() { $('.login-form').validate({ errorElement: 'span', //default input error message container errorClass: 'help-block', // default input error message class focusInvalid: false, // do not focus the last invalid input rules: { username: { required: true }, password: { required: true }, remember: { required: false } }, messages: { username: { required: "Username is required." }, password: { required: "Password is required." } }, invalidHandler: function (event, validator) { //display error alert on form submit $('.alert-danger', $('.login-form')).show(); }, highlight: function (element) { // hightlight error inputs $(element) .closest('.form-group').addClass('has-error'); // set error class to the control group }, success: function (label) { label.closest('.form-group').removeClass('has-error'); label.remove(); }, errorPlacement: function (error, element) { error.insertAfter(element.closest('.input-icon')); }, /*submitHandler: function (form) { form.submit(); }*/ }); $('.login-form input').keypress(function (e) { if (e.which == 13) { if ($('.login-form').validate().form()) { $('.login-form').submit(); } return false; } }); } var handleForgetPassword = function () { $('.forget-form').validate({ errorElement: 'span', //default input error message container errorClass: 'help-block', // default input error message class focusInvalid: false, // do not focus the last invalid input ignore: "", rules: { email: { required: true, email: true } }, messages: { email: { required: "Email is required." } }, invalidHandler: function (event, validator) { //display error alert on form submit }, highlight: function (element) { // hightlight error inputs $(element) .closest('.form-group').addClass('has-error'); // set error class to the control group }, success: function (label) { label.closest('.form-group').removeClass('has-error'); label.remove(); }, errorPlacement: function (error, element) { error.insertAfter(element.closest('.input-icon')); }, /*submitHandler: function (form) { form.submit(); }*/ }); $('.forget-form input').keypress(function (e) { if (e.which == 13) { if ($('.forget-form').validate().form()) { $('.forget-form').submit(); } return false; } }); jQuery('#forget-password').click(function () { jQuery('.login-form').hide(); jQuery('.forget-form').show(); }); jQuery('#back-btn').click(function () { jQuery('.login-form').show(); jQuery('.forget-form').hide(); }); } var handleRegister = function () { function format(state) { if (!state.id) { return state.text; } var $state = $( '<span><img src="../assets/global/img/flags/' + state.element.value.toLowerCase() + '.png" class="img-flag" /> ' + state.text + '</span>' ); return $state; } if (jQuery().select2 && $('#country_list').length > 0) { $("#country_list").select2({ placeholder: '<i class="fa fa-map-marker"></i>&nbsp;Select a Country', templateResult: format, templateSelection: format, width: 'auto', escapeMarkup: function(m) { return m; } }); $('#country_list').change(function() { $('.register-form').validate().element($(this)); //revalidate the chosen dropdown value and show error or success message for the input }); } $('.register-form').validate({ errorElement: 'span', //default input error message container errorClass: 'help-block', // default input error message class focusInvalid: false, // do not focus the last invalid input ignore: "", rules: { fullname: { required: true }, email: { required: true, email: true }, address: { required: true }, city: { required: true }, country: { required: true }, username: { required: true }, password: { required: true }, rpassword: { equalTo: "#register_password" }, tnc: { required: true } }, messages: { // custom messages for radio buttons and checkboxes tnc: { required: "Please accept TNC first." } }, invalidHandler: function (event, validator) { //display error alert on form submit }, highlight: function (element) { // hightlight error inputs $(element) .closest('.form-group').addClass('has-error'); // set error class to the control group }, success: function (label) { label.closest('.form-group').removeClass('has-error'); label.remove(); }, errorPlacement: function (error, element) { if (element.attr("name") == "tnc") { // insert checkbox errors after the container error.insertAfter($('#register_tnc_error')); } else if (element.closest('.input-icon').length === 1) { error.insertAfter(element.closest('.input-icon')); } else { error.insertAfter(element); } }, /*submitHandler: function (form) { form.submit(); }*/ }); $('.register-form input').keypress(function (e) { if (e.which == 13) { if ($('.register-form').validate().form()) { $('.register-form').submit(); } return false; } }); jQuery('#register-btn').click(function () { jQuery('.login-form').hide(); jQuery('.register-form').show(); }); jQuery('#register-back-btn').click(function () { jQuery('.login-form').show(); jQuery('.register-form').hide(); }); } return { //main function to initiate the module init: function () { //handleLogin(); //handleForgetPassword(); //handleRegister(); // init background slide images $.backstretch([ "../images/bg/bg1.jpg", "../images/bg/bg2.jpg", "../images/bg/bg3.jpg", "../images/bg/bg4.jpg" ], { fade: 1000, duration: 8000 } ); } }; }(); jQuery(document).ready(function() { Login.init(); });
hustshenl/yii2-metronic-lite
src/assets/admin/pages/scripts/login-4.js
JavaScript
bsd-3-clause
8,458
define(['handsontable-full'],function(Handsontable){ window.Handsontable=Handsontable; return Handsontable; });
flydreamzzh/report
backend/web/js/lib/handsontable/dist/defineHandsontable.js
JavaScript
bsd-3-clause
120
'use strict'; var Wallpaper = function (options) { this.id = options.id || 'wallpaper'; this.canvas = document.getElementById(this.id); this.ctx = this.canvas.getContext('2d'); this.xPos = 0; this.yPos = 0; this.width = options.width || 450; this.height = options.height || 450; this.ctx.clearRect(0, 0, this.width, this.height); var self = this; var randRGB = function () { return Math.floor(Math.random() * 255); }; var randOpacity = function () { return Math.round(Math.random() * 0.6 * 10) / 10; }; var randSize = function () { return Math.floor(Math.random() * 25 + 10); }; var currR = randRGB(); var currG = randRGB(); this.randomizeShape = function () { this.ctx.fillStyle = 'rgba(' + currR + ', ' + currG + ', ' + randRGB() + ', ' + randOpacity() + ')'; this.ctx.fillRect(this.xPos, this.yPos, this.xPos + randSize(), this.yPos + randSize()); if (this.xPos > this.width) { if (this.yPos > this.height) { currR = randRGB(); currG = randRGB(); } this.xPos = 0; } else { this.xPos += Math.sin(Math.floor(this.height / 25)) + Math.floor(this.height / 25); } if (this.yPos > this.height) { this.yPos = 10; } else { this.yPos += Math.sin(Math.floor(this.width / 25)) + Math.floor(this.width / 25); } }; this.generate = function () { setInterval(function () { requestAnimationFrame(self.randomizeShape.bind(self)); }, 1); }; };
ednapiranha/wallpaper
wallpaper.js
JavaScript
bsd-3-clause
1,578
/* * Copyright (c) 2011 Yahoo! Inc. All rights reserved. Copyrights licensed under the New BSD License. * See LICENSE file included with this code project for license terms. */ // Load modules var Email = require('./email'); var Config = require('./config'); var Utils = require('./utils'); // Welcome page exports.welcome = function (req, res, next) { res.api.redirect = req.api.profile.view; next(); }; // About page exports.about = function (req, res, next) { res.api.view = { template: 'about' }; next(); }; // Developer page exports.developer = function (req, res, next) { res.api.view = { template: 'developer', locals: { theme: 'developer' } }; next(); }; // Developer Console exports.console = function (req, res, next) { res.api.view = { template: 'console' }; next(); }; // Set I'm with stupid cookie exports.stupid = function (req, res, next) { res.api.cookie = { values: ['imwithstupid=true'], attributes: ['Path=/'] }; res.api.redirect = '/'; next(); }; // Feedback page exports.feedback = function (req, res, next) { if (req.method === 'GET') { res.api.view = { template: 'feedback' }; next(); } else { var feedback = 'From: ' + (req.body.username ? req.body.username : req.body.name + ' <' + req.body.email + '>') + '\n\n' + req.body.message; Email.send(Config.email.feedback, 'Posmile site feedback', feedback); res.api.view = { template: 'feedback', locals: { env: { message: 'Your feedback has been received!'}} }; next(); } }; // Client configuration script exports.config = function (req, res, next) { var config = Utils.clone(Config.host); config.web.uri = Config.host.uri('web'); config.api.uri = Config.host.uri('api'); res.api.result = 'var postmile = ' + JSON.stringify(config) + ';'; res.api.isAPI = true; next(); }; // Socket.IO Script Proxy exports.socketio = function (req, res, next) { res.api.redirect = Config.host.uri('api') + '/socket.io/socket.io.js'; next(); };
dalmaer/postmile
web/misc.js
JavaScript
bsd-3-clause
2,201
var go = {}; go; var _ = require('lodash'); var moment = require('moment'); var vumigo = require('vumigo_v02'); var Q = require('q'); var Choice = vumigo.states.Choice; var ChoiceState = vumigo.states.ChoiceState; var HttpApi = vumigo.http.api.HttpApi; var JsonApi = vumigo.http.api.JsonApi; // override moment default century switch at '68 with '49 moment.parseTwoDigitYear = function (input) { return +input + (+input > 49 ? 1900 : 2000); }; go.migration = { make_migration_state: function (app, next_state) { return (function(app) { return function (name) { // NOTE: only go through this if the migration flag is set if(!app.im.config.migration_flag) { return app.states.create(next_state); } return go.utils .is_migrated_user( app.im, go.utils.normalize_msisdn(app.contact.msisdn, '27')) .then(function (is_migrated) { if(is_migrated) { return app.states.create(next_state); } else { return new ChoiceState(name, { question: app.$( "MomConnect is doing maintenance so some features may be " + "unavailable. Reply STOP to opt-out via SMS. To change to" + " baby messaging try again next week."), choices: [ new Choice('continue', app.$('Continue')), ], next: next_state }); } }); }; })(app); } }; go.utils = { // Shared utils lib // make choices options with options make_month_choices: function($, start, limit) { // start should be 0 for Jan - array position var choices = [ new Choice('01', $('Jan')), new Choice('02', $('Feb')), new Choice('03', $('Mar')), new Choice('04', $('Apr')), new Choice('05', $('May')), new Choice('06', $('Jun')), new Choice('07', $('Jul')), new Choice('08', $('Aug')), new Choice('09', $('Sep')), new Choice('10', $('Oct')), new Choice('11', $('Nov')), new Choice('12', $('Dec')) ]; var choices_show = []; var choices_show_count = 0; var end = start + limit; for (var i=start; i<end; i++) { var val = (i >= 12 ? (i-12) : i); choices_show[choices_show_count] = choices[val]; choices_show_count++; } return choices_show; }, get_today: function(config) { var today; if (config.testing_today) { today = new Date(config.testing_today); } else { today = new Date(); } return today; }, get_tomorrow: function(config) { var today = go.utils.get_today(config); var moment_tomorrow = moment(today).add(1, 'days'); return moment_tomorrow.format('YYYY-MM-DD'); }, is_weekend: function(config) { var today = go.utils.get_today(config); var moment_today = moment.utc(today); return moment_today.format('dddd') === 'Saturday' || moment_today.format('dddd') === 'Sunday'; }, is_public_holiday: function(config) { var today = go.utils.get_today(config); var moment_today = moment.utc(today); var date_as_string = moment_today.format('YYYY-MM-DD'); return _.contains(config.public_holidays, date_as_string); }, is_out_of_hours: function(config) { var today = go.utils.get_today(config); var moment_today = moment.utc(today); // get business hours from config, -2 for utc to local time conversion var opening_time = Math.min.apply(null, config.helpdesk_hours) - 2; var closing_time = Math.max.apply(null, config.helpdesk_hours) - 2; return (moment_today.hour() < opening_time || moment_today.hour() >= closing_time); }, get_due_year_from_month: function(month, today) { // if due month is less than current month then mother must be due next year motoday = moment(today); if ((motoday.month()+1) > parseInt(month, 10)) { return motoday.year()+1; } else { return motoday.year(); } }, check_valid_number: function(input){ // an attempt to solve the insanity of JavaScript numbers var numbers_only = new RegExp('^\\d+$'); if (input !== '' && numbers_only.test(input) && !Number.isNaN(Number(input))){ return true; } else { return false; } }, check_valid_phone_number: function(input) { // check that it is a number, starts with 0, and has at 10 digits if (go.utils.check_valid_number(input) && input[0] === '0' && input.length === 10) { return true; } else { return false; } }, check_number_in_range: function(input, start, end){ return go.utils.check_valid_number(input) && (parseInt(input, 10) >= start) && (parseInt(input, 10) <= end); }, double_digit_day: function(input) { input_numeric = parseInt(input, 10); if (parseInt(input, 10) < 10) { return "0" + input_numeric.toString(); } else { return input_numeric.toString(); } }, validate_id_sa: function(id) { var i, c, even = '', sum = 0, check = id.slice(-1); if (id.length != 13 || id.match(/\D/)) { return false; } if (!moment(id.slice(0,6), 'YYMMDD', true).isValid()) { return false; } id = id.substr(0, id.length - 1); for (i = 0; id.charAt(i); i += 2) { c = id.charAt(i); sum += +c; even += id.charAt(i + 1); } even = '' + even * 2; for (i = 0; even.charAt(i); i++) { c = even.charAt(i); sum += +c; } sum = 10 - ('' + sum).charAt(1); return ('' + sum).slice(-1) == check; }, is_valid_date: function(date, format) { // implements strict validation with 'true' below return moment(date, format, true).isValid(); }, get_entered_due_date: function(month, day, config) { var year = go.utils.get_due_year_from_month(month, go.utils.get_today(config)); return (year +'-'+ month +'-'+ go.utils.double_digit_day(day)); }, get_entered_birth_date: function(year, month, day) { return year +'-'+ month +'-'+ go.utils.double_digit_day(day); }, extract_id_dob: function(id) { return moment(id.slice(0,6), 'YYMMDD').format('YYYY-MM-DD'); }, is_true: function(bool) { //If is is not undefined and boolean is true return (!_.isUndefined(bool) && (bool==='true' || bool===true)); }, readable_sa_msisdn: function(msisdn) { readable_no = '0' + msisdn.slice(msisdn.length-9, msisdn.length); return readable_no; }, normalize_msisdn: function(raw, country_code) { // don't touch shortcodes if (raw.length <= 5) { return raw; } // remove chars that are not numbers or + raw = raw.replace(/[^0-9+]/g); if (raw.substr(0,2) === '00') { return '+' + raw.substr(2); } if (raw.substr(0,1) === '0') { return '+' + country_code + raw.substr(1); } if (raw.substr(0,1) === '+') { return raw; } if (raw.substr(0, country_code.length) === country_code) { return '+' + raw; } return raw; }, incr_user_extra: function(data_to_increment, amount_to_increment) { if (_.isUndefined(data_to_increment)) { new_data_amount = 1; } else { new_data_amount = parseInt(data_to_increment, 10) + amount_to_increment; } return new_data_amount.toString(); }, get_timestamp: function() { return moment().format("YYYYMMDDHHmmss"); }, get_subscription_type: function(type){ var types = { "optout": 4, "babyloss": 5, "servicerating": 6, "nurse_optout": 8 }; return types[type]; }, get_swt: function(im) { if (im.config.name.substring(0,9) === "nurse_sms") { return 4; // swt = 4 for nurse sms optout } else if (im.config.name.substring(0,10) === "nurse_ussd") { return 3; // swt = 3 for nurse ussd optout } else if (im.config.name.substring(0,10) === "smsinbound") { return 2; // swt = 2 for sms optout } else { return 1; // swt = 1 for ussd optout } }, get_faccode: function(contact) { return contact.extra.clinic_code || null; }, incr_kv: function(im, name) { return im.api_request('kv.incr', {key: name, amount: 1}) .then(function(result){ return result.value; }); }, decr_kv: function(im, name) { return im.api_request('kv.incr', {key: name, amount: -1}) .then(function(result){ return result.value; }); }, set_kv: function(im, name, value) { return im.api_request('kv.set', {key: name, value: value}) .then(function(result){ return result.value; }); }, get_kv: function(im, name, default_value) { // returns the default if null/undefined return im.api_request('kv.get', {key: name}) .then(function(result){ if(result.value === null) return default_value; return result.value; }); }, adjust_percentage_registrations: function(im, metric_prefix) { return Q.all([ go.utils.get_kv(im, [metric_prefix, 'no_incomplete_registrations'].join('.'), 0), go.utils.get_kv(im, [metric_prefix, 'no_complete_registrations'].join('.'), 0) ]).spread(function(no_incomplete, no_complete) { var total_attempted = no_incomplete + no_complete; var percentage_incomplete = parseFloat(((no_incomplete / total_attempted) * 100).toFixed(2)); var percentage_complete = parseFloat(((no_complete / total_attempted) * 100).toFixed(2)); return Q.all([ im.metrics.fire.last([metric_prefix, 'percent_incomplete_registrations'].join('.'), percentage_incomplete), im.metrics.fire.last([metric_prefix, 'percent_complete_registrations'].join('.'), percentage_complete) ]); }); }, incr_kv_conversions: function(im, contact, env) { var is_reg_by = contact.extra.is_registered_by; if (is_reg_by === 'personal' || is_reg_by === 'chw') { return go.utils.incr_kv(im, [env, is_reg_by, 'conversions_to_clinic'].join('.')); } }, adjust_conversion_rates: function(im, env) { return Q.all([ go.utils.get_kv(im, [env, 'personal', 'conversion_registrations'].join('.'), 0), go.utils.get_kv(im, [env, 'chw', 'conversion_registrations'].join('.'), 0), go.utils.get_kv(im, [env, 'personal', 'conversions_to_clinic'].join('.'), 0), go.utils.get_kv(im, [env, 'chw', 'conversions_to_clinic'].join('.'), 0) ]).spread(function(personal_regs, chw_regs, personal_convs, chw_convs) { if (personal_regs > 0 && chw_regs > 0) { var personal_conv_rate = parseFloat(((personal_convs / personal_regs) * 100).toFixed(2)); var chw_conv_rate = parseFloat(((chw_convs / chw_regs) * 100).toFixed(2)); return Q.all([ im.metrics.fire.last([env, 'personal', 'conversion_rate'].join('.'), personal_conv_rate), im.metrics.fire.last([env, 'chw', 'conversion_rate'].join('.'), chw_conv_rate) ]); } else { return Q(); } }); }, adjust_percentage_serviceratings: function(im, metric_prefix) { return Q.all([ go.utils.get_kv(im, [im.config.metric_store, metric_prefix, 'sum', 'servicerating_start'].join('.'), 0), go.utils.get_kv(im, [im.config.metric_store, metric_prefix, 'sum', 'servicerating_success'].join('.'), 0) ]).spread(function(no_started, no_finished) { var percentage_complete = parseFloat(((no_finished / no_started) * 100).toFixed(2)); var percentage_incomplete = 100 - percentage_complete; return Q.all([ im.metrics.fire.last([metric_prefix, 'percent_incomplete_serviceratings'].join('.'), percentage_incomplete), im.metrics.fire.last([metric_prefix, 'percent_complete_serviceratings'].join('.'), percentage_complete) ]); }); }, fire_users_metrics: function(im, store_name, env, metric_prefix) { return go.utils.incr_kv(im, [store_name, 'unique_users'].join('.')) .then(function() { return Q.all([ go.utils.get_kv(im, [env, 'clinic', 'unique_users'].join('.'), 0), go.utils.get_kv(im, [env, 'chw', 'unique_users'].join('.'), 0), go.utils.get_kv(im, [env, 'personal', 'unique_users'].join('.'), 0) ]).spread(function(clinic_users, chw_users, personal_users) { var total_users = clinic_users + chw_users + personal_users; var clinic_percentage = (clinic_users / total_users) * 100; var chw_percentage = (chw_users / total_users) * 100; var personal_percentage = (personal_users / total_users) * 100; return Q.all([ im.metrics.fire.inc([metric_prefix, 'sum', 'unique_users'].join('.')), im.metrics.fire.last([env, 'clinic', 'percentage_users'].join('.'), clinic_percentage), im.metrics.fire.last([env, 'chw', 'percentage_users'].join('.'), chw_percentage), im.metrics.fire.last([env, 'personal', 'percentage_users'].join('.'), personal_percentage), im.metrics.fire.inc([env, 'sum', 'unique_users'].join('.')) ]); }); }); }, jembi_clinic_validate: function (im, clinic_code) { var params = { 'criteria': 'code:' + clinic_code }; return go.utils .jembi_json_api_call('get', params, null, 'facilityCheck', im); }, validate_clinic_code: function(im, clinic_code) { if (!go.utils.check_valid_number(clinic_code) || clinic_code.length !== 6) { return Q() .then(function() { return false; }); } else { return go.utils .jembi_clinic_validate(im, clinic_code) .then(function(json_result) { var rows = JSON.parse(json_result.data).rows; if (rows.length === 0) { return false; } else { return rows[0][2]; } }); } }, jembi_nc_clinic_validate: function (im, clinic_code) { var params = { 'criteria': 'value:' + clinic_code }; return go.utils .jembi_json_api_call('get', params, null, 'NCfacilityCheck', im); }, validate_nc_clinic_code: function(im, clinic_code) { if (!go.utils.check_valid_number(clinic_code) || clinic_code.length !== 6) { return Q() .then(function() { return false; }); } else { return go.utils .jembi_nc_clinic_validate(im, clinic_code) .then(function(json_result) { var rows = JSON.parse(json_result.data).rows; if (rows.length === 0) { return false; } else { return rows[0][2]; } }); } }, is_alpha_numeric_only: function(input) { alpha_numeric = new RegExp('^[A-Za-z0-9]+$'); return alpha_numeric.test(input); }, get_servicerating_data: function(im) { var servicerating_data = []; for (var question in im.user.answers) { servicerating_data.push({ "question": question, "answer": im.user.answers[question] }); } return servicerating_data; }, build_servicerating_json: function(im, contact, type) { var JSON_template = { "mha": 1, "swt": go.utils.get_swt(im), // "supplier_unique_id": servicerating_id, // Marked as Optional in mini-scope and custom // api doesn't provide an id so not submitting "dmsisdn": contact.msisdn, "cmsisdn": contact.msisdn, "type": go.utils.get_subscription_type(type), "faccode": go.utils.get_faccode(contact), "encdate": go.utils.get_timestamp(), "data": go.utils.get_servicerating_data(im) }; return JSON_template; }, jembi_send_servicerating: function(im, contact, metric_prefix, type) { var built_json = go.utils.build_servicerating_json(im, contact, type); return go.utils .jembi_json_api_call('post', null, built_json, 'serviceRating', im) .then(function(json_result) { var metric_name = [metric_prefix, "sum", "servicerating_to_jembi"].join('.'); return go.utils.json_success_fail_metric(im, metric_name, json_result); }); }, get_patient_id: function(contact) { var formatter = { 'sa_id': function () { return contact.extra.sa_id + '^^^ZAF^NI'; }, 'passport': function () { return contact.extra.passport_no + '^^^' + contact.extra.passport_origin.toUpperCase() + '^PPN'; }, 'none': function () { return contact.msisdn.replace('+', '') + '^^^ZAF^TEL'; } }[contact.extra.id_type]; return formatter(); }, get_nurse_id: function(contact) { var formatter = { 'sa_id': function () { return contact.extra.nc_sa_id_no + '^^^ZAF^NI'; }, 'passport': function () { return contact.extra.nc_passport_num + '^^^' + contact.extra.nc_passport_country.toUpperCase() + '^PPN'; } }[contact.extra.nc_id_type]; if (_.isUndefined(contact.extra.nc_id_type) || contact.extra.nc_id_type === null) { return contact.msisdn.replace('+', '') + '^^^ZAF^TEL'; } else { return formatter(); } }, get_dob: function(contact) { if (!_.isUndefined(contact.extra.dob)) { return moment(contact.extra.dob, 'YYYY-MM-DD').format('YYYYMMDD'); } else if (!_.isUndefined(contact.extra.nc_dob)) { return moment(contact.extra.nc_dob, 'YYYY-MM-DD').format('YYYYMMDD'); } else { return null; } }, get_optoutreason: function(contact) { var optoutreason_map = { "miscarriage": 1, "stillbirth": 2, "babyloss": 3, "not_useful": 4, "other": 5, "unknown": 6, "job_change": 7, "number_owner_change": 8 }; return optoutreason_map[contact.extra.opt_out_reason] || 6; }, build_jembi_json: function(im, contact, user, type) { var JSON_template = { "mha": 1, "swt": go.utils.get_swt(im), "dmsisdn": user.msisdn, "cmsisdn": contact.msisdn, "id": go.utils.get_patient_id(contact), "type": go.utils.get_subscription_type(type), "lang": contact.extra.language_choice, "encdate": go.utils.get_timestamp(), "faccode": go.utils.get_faccode(contact), "dob": go.utils.get_dob(contact) }; if (type === 'optout') { JSON_template.optoutreason = go.utils.get_optoutreason(contact); } return JSON_template; }, get_nurse_optoutreason: function(contact) { var optoutreason_map = { "miscarriage": 1, "stillbirth": 2, "babyloss": 3, "not_useful": 4, "other": 5, "unknown": 6, "job_change": 7, "number_owner_change": 8 }; return optoutreason_map[contact.extra.nc_opt_out_reason] || 6; }, jembi_optout_send_json: function(contact, user, type, im, metric_prefix) { var built_json = go.utils.build_jembi_json(im, contact, user, type); return go.utils .jembi_json_api_call('post', null, built_json, 'optout', im) .then(function(json_result) { var metric_name = [metric_prefix, "sum", "optout_to_jembi"].join('.'); return go.utils.json_success_fail_metric(im, metric_name, json_result); }); }, build_nurse_jembi_json: function(im, contact, user, type) { var JSON_template = { "mha": 1, "swt": go.utils.get_swt(im), "dmsisdn": user.msisdn, "cmsisdn": contact.msisdn, "type": go.utils.get_subscription_type(type), "encdate": go.utils.get_timestamp(), "faccode": contact.extra.nc_faccode || null, "dob": go.utils.get_dob(contact) || null, "id": go.utils.get_nurse_id(contact), "optoutreason": go.utils.get_nurse_optoutreason(contact) }; return JSON_template; }, jembi_nurse_optout_send_json: function(contact, user, type, im, metric_prefix) { var built_json = go.utils.build_nurse_jembi_json(im, contact, user, type); return go.utils .jembi_json_api_call('post', null, built_json, 'nc/optout', im); }, jembi_babyloss_send_json: function(contact, user, type, im, metric_prefix) { var built_json = go.utils.build_jembi_json(im, contact, user, type); return go.utils .jembi_json_api_call('post', null, built_json, 'subscription', im) .then(function(json_result) { var metric_name = [metric_prefix, "sum", "babyloss_to_jembi"].join('.'); return go.utils.json_success_fail_metric(im, metric_name, json_result); }); }, json_success_fail_metric: function(im, metric_name, json_result) { var metric_to_fire = json_result.code >= 200 && json_result.code < 300 ? metric_name + '_success' : metric_name + '_fail'; return im.metrics.fire.inc(metric_to_fire, {amount: 1}); }, jembi_json_api_call: function(method, params, payload, endpoint, im) { var http = new HttpApi(im, { auth: { username: im.config.jembi.username, password: im.config.jembi.password }, headers: { 'Content-Type': ['application/json'] } }); switch(method) { case "post": return http.post(im.config.jembi.url_json + endpoint, { data: JSON.stringify(payload) }); case "get": return http.get(im.config.jembi.url_json + endpoint, { params: params }); } }, control_api_call: function (method, params, payload, endpoint, im) { var http = new HttpApi(im, { headers: { 'Content-Type': ['application/json'], 'Authorization': ['ApiKey ' + im.config.control.username + ':' + im.config.control.api_key] } }); switch (method) { case "post": return http.post(im.config.control.url + endpoint, { data: JSON.stringify(payload) }); case "get": return http.get(im.config.control.url + endpoint, { params: params }); case "patch": return http.patch(im.config.control.url + endpoint, { data: JSON.stringify(payload) }); case "put": return http.put(im.config.control.url + endpoint, { params: params, data: JSON.stringify(payload) }); case "delete": return http.delete(im.config.control.url + endpoint); } }, control_v2_api_call: function (method, params, payload, endpoint, im) { var http = new JsonApi(im, { headers: { 'Authorization': ['Token ' + im.config.control_v2.api_token] } }); switch (method) { case "post": return http.post(im.config.control_v2.url + endpoint, { data: payload }); case "get": return http.get(im.config.control_v2.url + endpoint, { params: params }); case "patch": return http.patch(im.config.control_v2.url + endpoint, { data: payload }); case "put": return http.put(im.config.control_v2.url + endpoint, { params: params, data: payload }); case "delete": return http.delete(im.config.control_v2.url + endpoint); } }, is_migrated_user: function (im, msisdn) { var http = new JsonApi(im, { headers: { 'Authorization': ['Token ' + im.config.identity_store.api_token] } }); return http .get(im.config.identity_store.url + '/identities/search/', { params: { 'details__addresses__msisdn': msisdn, } }) .then(function (response) { return response.data.count > 0; }); }, subscription_type_and_rate: function(contact, im) { // Returns the subscription type, rate and start point // for loss and baby message subscriptions var response = { sub_type: null, sub_rate: null, sub_seq_start: 1 }; if (im.config.name.substring(0,6) == "optout") { response.sub_type = im.config.subscription[im.user.answers.states_start]; response.sub_rate = im.config.rate.two_per_week; } else if (im.config.name.substring(0,10) == "smsinbound") { response.sub_type = im.config.subscription.baby1; response.sub_rate = im.config.rate.two_per_week; } return response; }, get_edd: function(im, contact) { // Return estimated due date YYYY-MM-DD, default to null if unknown if (!_.isUndefined(contact.extra.due_date_month) && !_.isUndefined(contact.extra.due_date_day)) { var day = contact.extra.due_date_day; var month = contact.extra.due_date_month; var year = go.utils.get_due_year_from_month(month, go.utils.get_today(im.config)); return [year, month, day].join('-'); } else { return null; } }, get_identification_no: function(contact) { if (contact.extra.id_type === 'sa_id') { return contact.extra.sa_id; } else if (contact.extra.id_type === 'passport') { return contact.extra.passport_no; } else { return null; } }, get_hcw_no: function(device_msisdn, contact_msisdn) { var n_device_msisdn = go.utils.normalize_msisdn(device_msisdn, '27'); var n_contact_msisdn = go.utils.normalize_msisdn(contact_msisdn, '27'); if (n_device_msisdn === n_contact_msisdn) { return null; } else { return n_device_msisdn; } }, get_passport_origin: function(id_type, passport_origin) { if (id_type === 'passport') { return passport_origin; } else { return null; } }, post_registration: function(device_msisdn, contact, im, reg_type) { var payload = { hcw_msisdn: go.utils.get_hcw_no(device_msisdn, contact.msisdn), // +27... mom_msisdn: go.utils.normalize_msisdn(contact.msisdn, '27'), // +27... mom_id_type: contact.extra.id_type, // 'sa_id' | 'passport' | 'none' mom_passport_origin: go.utils.get_passport_origin( contact.extra.id_type, contact.extra.passport_origin), mom_lang: contact.extra.language_choice, // 'en' | 'af' | 'xh' ... mom_edd: go.utils.get_edd(im, contact), // 'YYYY-MM-DD' | null mom_id_no: go.utils.get_identification_no(contact), mom_dob: contact.extra.dob || null, // 'YYYY-MM-DD' | null consent: contact.extra.consent === 'true' || null, // 'true' | null clinic_code: contact.extra.clinic_code || null, authority: reg_type, // 'clinic' | 'chw' | 'personal' }; return go.utils .control_v2_api_call("post", null, payload, 'registrations/', im) .then(function(post_response) { return go.utils.json_success_fail_metric(im, 'registration_call', post_response); }); }, post_nursereg: function(im, contact, dmsisdn, rmsisdn) { var payload = { cmsisdn: go.utils.normalize_msisdn(contact.msisdn, '27'), // +27... dmsisdn: go.utils.normalize_msisdn(dmsisdn, '27'), // +27... faccode: contact.extra.nc_faccode, id_type: contact.extra.nc_id_type, dob: contact.extra.nc_dob, sanc_reg_no: contact.extra.nc_sanc || null, persal_no: contact.extra.nc_persal || null }; if (contact.extra.nc_id_type === 'sa_id') { payload.id_type = 'sa_id'; payload.id_no = contact.extra.nc_sa_id_no; payload.dob = contact.extra.nc_dob; } else if (contact.extra.nc_id_type === 'passport') { payload.id_type = 'passport'; payload.id_no = contact.extra.nc_passport_num; payload.passport_origin = contact.extra.nc_passport_country; payload.dob = contact.extra.nc_dob; } else { payload.id_type = null; payload.id_no = null; payload.dob = null; } if (rmsisdn) { payload.rmsisdn = rmsisdn; } return go.utils .control_v2_api_call("post", null, payload, 'nurseregs/', im); }, post_subscription: function(contact, im, metric_prefix, env, opts) { var payload = { contact_key: contact.key, lang: contact.extra.language_choice, message_set: "/api/v1/message_set/" + opts.sub_type + "/", next_sequence_number: opts.sub_seq_start, schedule: "/api/v1/periodic_task/" + opts.sub_rate + "/", to_addr: contact.msisdn, user_account: contact.user_account }; return go.utils .control_api_call("post", null, payload, 'subscription/', im) .then(function(doc_result) { if (doc_result.code >= 200 && doc_result.code < 300){ return Q.all([ im.metrics.fire.inc([metric_prefix, "sum", "subscription_to_protocol_success"].join('.'), {amount:1}), im.metrics.fire.inc([env, "sum", "subscriptions"].join('.'), {amount:1}) ]); } else { //TODO - implement proper fail issue #36 return im.metrics.fire.inc([metric_prefix, "sum", "subscription_to_protocol_fail"].join('.'), {amount:1}); } }); }, get_subscriptions_by_msisdn: function(msisdn, im) { var params = { to_addr: msisdn }; return go.utils .control_api_call("get", params, null, 'subscription/', im) .then(function(result) { return JSON.parse(result.data); }); }, subscription_unsubscribe_all: function(contact, im) { return go.utils .get_subscriptions_by_msisdn(contact.msisdn, im) .then(function(update) { var clean = true; // clean tracks if api call is unnecessary for (i=0;i<update.objects.length;i++) { if (update.objects[i].active === true){ update.objects[i].active = false; clean = false; } } if (!clean) { return go.utils.control_api_call("patch", {}, update, 'subscription/', im); } else { return Q(); } }); }, get_nursereg_by_id: function(nursereg_id, im) { return go.utils .control_v2_api_call("get", null, null, 'nurseregistrations/' + nursereg_id + '/', im) .then(function(get_response) { return get_response.data; }); }, patch_last_reg: function(contact, im, optout_reason) { return go.utils .get_nursereg_by_id(contact.extra.nc_last_reg_id, im) .then(function(nursereg) { nursereg.opted_out = true; nursereg.optout_count += 1; nursereg.optout_reason = optout_reason; return go.utils.control_v2_api_call("patch", null, nursereg, 'nurseregistrations/' + contact.extra.nc_last_reg_id + '/', im); }); }, subscription_count_active: function(contact, im) { // This function is used in the public line to determine routing // depending on whether users have an active subscription var params = { to_addr: contact.msisdn }; return go.utils .control_api_call("get", params, null, 'subscription/', im) .then(function(json_result) { var subs = JSON.parse(json_result.data); var active = 0; for (i=0;i<subs.objects.length;i++) { if (subs.objects[i].active === true) { active++; } } return active; }); }, support_log_ticket: function(message, contact, im, metric_prefix) { var payload = { conversation: "/api/v1/snappybouncer/conversation/key/" + im.config.snappybouncer.conversation + "/", message: message, contact_key: contact.key, msisdn: contact.msisdn, faccode: parseInt(contact.extra.clinic_code, 10) || null }; return go.utils .control_api_call("post", null, payload, 'snappybouncer/ticket/', im) .then(function(doc_result) { var metric; if (doc_result.code >= 200 && doc_result.code < 300){ metric = (([metric_prefix, "sum", "ticket_logged_to_control_success"].join('.'))); } else { //TODO - implement proper fail issue #36 metric = (([metric_prefix, "sum", "ticket_logged_to_control_fail"].join('.'))); } return im.metrics.fire.inc(metric, {amount: 1}); }); }, servicerating_log: function(contact, im, metric_prefix) { var payload = { "user_account": contact.user_account, "conversation_key": im.config.conversation_key, "contact": contact, "answers": im.user.answers }; return go.utils .control_api_call("post", null, payload, 'servicerating/rate/', im) .then(function(doc_result) { var metric; if (doc_result.code >= 200 && doc_result.code < 300){ metric = (([metric_prefix, "sum", "servicerating_success"].join('.'))); } else { //TODO - implement proper fail issue #36 metric = (([metric_prefix, "sum", "subscription_to_protocol_fail"].join('.'))); } return im.metrics.fire.inc(metric, {amount: 1}); }); }, get_snappy_topics: function (im, faq_id) { var http = new JsonApi(im, { auth: { username: im.config.snappy.username, password: 'x' } }); return http.get(im.config.snappy.endpoint + 'account/'+im.config.snappy.account_id+'/faqs/'+faq_id+'/topics', { data: JSON.stringify(), headers: { 'Content-Type': ['application/json'] } }); }, get_snappy_topic_content: function(im, faq_id, topic_id) { var http = new JsonApi(im, { auth: { username: im.config.snappy.username, password: 'x' } }); return http.get(im.config.snappy.endpoint + 'account/'+im.config.snappy.account_id+'/faqs/'+faq_id+'/topics/'+topic_id+'/questions', { data: JSON.stringify(), headers: { 'Content-Type': ['application/json'] } }); }, set_language: function(user, contact) { if (contact.extra.language_choice !== null) { return user.set_lang(contact.extra.language_choice); } else { return Q(); } }, timed_out: function(im) { return im.msg.session_event === 'new' && im.user.state.name && im.user.state.name !== 'states_start'; }, get_reg_source: function(contact) { var reg_source; var reg_options = ['clinic', 'chw', 'personal']; if (!_.contains(reg_options, contact.extra.is_registered_by)) { reg_source = 'unknown'; } else { reg_source = contact.extra.is_registered_by; } return reg_source; }, adjust_percentage_optouts: function(im, env) { var m_store = im.config.metric_store; return Q.all([ go.utils.get_kv(im, [m_store, env, 'sum', 'subscriptions'].join('.'), 0), go.utils.get_kv(im, [m_store, env, 'sum', 'optouts'].join('.'), 0), go.utils.get_kv(im, [m_store, env, 'sum', 'optout_cause', 'non_loss'].join('.'), 0), go.utils.get_kv(im, [m_store, env, 'sum', 'optout_cause', 'loss'].join('.'), 0), go.utils.get_kv(im, [m_store, env, 'optout', 'sum', 'subscription_to_protocol_success'].join('.'), 0) ]).spread(function(total_subscriptions, total_optouts, non_loss_optouts, loss_optouts, loss_msg_signups) { var percentage_optouts = parseFloat(((total_optouts/total_subscriptions)*100).toFixed(2)); var percentage_non_loss_optouts = parseFloat(((non_loss_optouts / total_subscriptions) * 100).toFixed(2)); var percentage_loss_msg_signups = parseFloat(((loss_msg_signups / loss_optouts) * 100).toFixed(2)); return Q.all([ im.metrics.fire.last([env, 'percent', 'optout', 'all'].join('.'), percentage_optouts), im.metrics.fire.last([env, 'percent', 'optout', 'non_loss'].join('.'), percentage_non_loss_optouts), im.metrics.fire.last([env, 'percent', 'optout', 'loss', 'msgs'].join('.'), percentage_loss_msg_signups) ]); }); }, loss_message_opt_in: function(im, contact, metric_prefix, env, opts) { return Q.all([ // ensure user is not opted out go.utils.opt_in(im, contact), // activate new subscription go.utils.post_subscription(contact, im, metric_prefix, env, opts), // send new subscription info to jembi go.utils.jembi_babyloss_send_json(contact, contact, 'babyloss', im, metric_prefix) ]); }, opt_out: function(im, contact, optout_reason, api_optout, unsub_all, jembi_optout, metric_prefix, env) { var queue1 = []; var prior_opt_out_reason; // Start Queue 1 if (optout_reason !== undefined) { prior_opt_out_reason = contact.extra.opt_out_reason || 'unknown'; // if reason was not previously saved it should be 'unknown' (from smsinbound) contact.extra.opt_out_reason = optout_reason; queue1.push(function() { return im.contacts.save(contact); }); } // End Queue 1 return Q .all(queue1.map(Q.try)) .then(function() { return go.utils .opted_out(im, contact) .then(function(opted_out) { // if the contact is not opted out, opt them out OR // if the contact has opted out, but has an opted-out reason 'unknown' // (through SMSing STOP) but is now dialing in to opt-out line and // supplying a reason for their optout, opt them out again if (opted_out === false || (prior_opt_out_reason === 'unknown' && im.config.name.substring(0,6) === "optout")) { var queue2 = []; // Start Queue 2 if (api_optout === true) { // vumi optout queue2.push(function() { return im.api_request('optout.optout', { address_type: "msisdn", address_value: contact.msisdn, message_id: im.msg.message_id }); }); } if (unsub_all === true) { // deactivate all subscriptions queue2.push(function() { return go.utils.subscription_unsubscribe_all(contact, im); }); } if (jembi_optout === true) { // send optout to jembi queue2.push(function() { return go.utils.jembi_optout_send_json(contact, contact, 'optout', im, metric_prefix); }); // fire opt-out registration source metric var reg_source = go.utils.get_reg_source(contact); queue2.push(function() { return im.metrics.fire.inc([env, 'sum', 'optout_on', reg_source].join('.'), {amount: 1}); }); // fire sum of all opt-outs metric queue2.push(function() { return im.metrics.fire.inc([env, 'sum', 'optouts'].join('.'), {amount: 1}); }); // fire loss / non-loss metric var loss_causes = ['miscarriage', 'babyloss', 'stillbirth']; if (_.contains(loss_causes, contact.extra.opt_out_reason)) { queue2.push(function() { return im.metrics.fire.inc([env, 'sum', 'optout_cause', 'loss'].join('.'), {amount: 1}); }); } else { queue2.push(function() { return im.metrics.fire.inc([env, 'sum', 'optout_cause', 'non_loss'].join('.'), {amount: 1}); }); } // fire cause metric queue2.push(function() { return im.metrics.fire.inc([env, 'sum', 'optout_cause', optout_reason].join('.'), {amount: 1}); }); } // End Queue 2 return Q .all(queue2.map(Q.try)) .then(function() { return go.utils.adjust_percentage_optouts(im, env); }); } else { return Q(); } }); }); }, nurse_optout: function(im, contact, optout_reason, api_optout, unsub_all, jembi_optout, patch_last_reg, metric_prefix, env) { var queue1 = []; var prior_opt_out_reason; // Start Queue 1 if (optout_reason !== undefined) { prior_opt_out_reason = contact.extra.nc_opt_out_reason || 'unknown'; // if reason was not previously saved it should be 'unknown' (from smsinbound) contact.extra.nc_opt_out_reason = optout_reason; queue1.push(function() { return im.contacts.save(contact); }); } // End Queue 1 return Q .all(queue1.map(Q.try)) .then(function() { return go.utils .opted_out(im, contact) .then(function(opted_out) { // if the contact is not opted out, opt them out OR // if the contact has opted out, but has an opted-out reason 'unknown' // (through SMSing STOP) but is now dialing in to opt-out line and // supplying a reason for their optout, opt them out again if (opted_out === false || (prior_opt_out_reason === 'unknown' && im.config.name.substring(0,10) === "nurse_ussd")) { var queue2 = []; // Start Queue 2 if (api_optout === true) { // vumi optout queue2.push(function() { return im.api_request('optout.optout', { address_type: "msisdn", address_value: contact.msisdn, message_id: im.msg.message_id }); }); } if (unsub_all === true) { // deactivate all subscriptions queue2.push(function() { return go.utils.subscription_unsubscribe_all(contact, im); }); } if (jembi_optout === true) { // send optout to jembi queue2.push(function() { return go.utils.jembi_nurse_optout_send_json(contact, contact, 'nurse_optout', im, metric_prefix); }); // Add Metrics // fire total source opt-outs metric (last) queue2.push(function() { return im.metrics.fire.inc( [metric_prefix, 'optouts', 'last'].join('.'), {amount: 1}); }); // fire total source opt-outs metric (sum) queue2.push(function() { return im.metrics.fire.sum( [metric_prefix, 'optouts', 'sum'].join('.'), 1); }); // fire total opt-outs metric (last) queue2.push(function() { return im.metrics.fire.inc( [env, 'nurseconnect', 'optouts', 'last'].join('.'), {amount: 1}); }); // fire total opt-outs metric (sum) queue2.push(function() { return im.metrics.fire.sum( [env, 'nurseconnect', 'optouts', 'sum'].join('.'), 1); }); // fire opt-out reason metrics (last) queue2.push(function() { return im.metrics.fire.inc( [env, 'nurseconnect', 'optouts', optout_reason, 'last'] .join('.'), {amount: 1}); }); // fire opt-out reason metrics (sum) queue2.push(function() { return im.metrics.fire.inc( [env, 'nurseconnect', 'optouts', optout_reason, 'sum'] .join('.'), 1); }); } if (patch_last_reg === true) { // patch last registration to show opted out queue2.push(function() { return go.utils.patch_last_reg(contact, im, optout_reason); }); } // End Queue 2 return Q.all(queue2.map(Q.try)); } else { return Q(); } }); }); }, opted_out: function(im, contact) { return im .api_request('optout.status', { address_type: "msisdn", address_value: contact.msisdn }) .then(function(result) { return result.opted_out; }); }, opted_out_by_msisdn: function(im, msisdn) { return im.contacts .get(msisdn, {create: true}) .then(function(contact) { return go.utils.opted_out(im, contact); }); }, opt_in: function(im, contact) { contact.extra.opt_out_reason = ''; return Q.all([ im.api_request('optout.cancel_optout', { address_type: "msisdn", address_value: contact.msisdn }), im.contacts.save(contact) ]); }, nurse_opt_in: function(im, contact) { contact.extra.nc_opt_out_reason = ''; return Q.all([ im.api_request('optout.cancel_optout', { address_type: "msisdn", address_value: contact.msisdn }), im.contacts.save(contact) ]); }, attach_session_length_helper: function (im) { // If we have transport metadata then attach the session length // helper to this app if(!im.msg.transport_metadata) return; var slh = new go.SessionLengthHelper(im, { name: function () { var metadata = im.msg.transport_metadata.aat_ussd; var provider; if(metadata) { provider = (metadata.provider || 'unspecified').toLowerCase(); } else { provider = 'unknown'; } return [im.config.name, provider].join('.'); }, clock: function () { return go.utils.get_today(im.config); } }); slh.attach(); return slh; } }; go.SessionLengthHelper = function () { var vumigo = require('vumigo_v02'); var events = vumigo.events; var Eventable = events.Eventable; var SessionLengthHelper = Eventable.extend(function(self, im, params) { /**class:SessionLengthHelper A helper for common session length calculation tasks. :param InteractionMachine im: The interaction machine that the metrics should be run on. :param object params: Optional parameters: { name: 'default', clock: function () { return new Date(); }, metrics_prefix: 'session_length_helper' } */ self.im = im; self.user = im.user; self.name = params.name || 'default'; self.now = params.clock || function () { return new Date(); }; self.metrics_prefix = params.metrics_prefix || 'session_length_helper'; self.mark = {}; self.attach = function () { self.im.on('session:new', function (e) { return self.mark.session_start(); }); self.im.on('session:close', function (e) { return self.mark.session_close(); }); self.im.on('im:shutdown', function() { return self.increment_and_fire(self.name); }); }; self.mark.session_start = function () { self.user.metadata.session_length_helper = {}; self.user.metadata.session_length_helper.start = Number(self.now()); return self; }; self.mark.session_close = function () { if(!self.user.metadata.session_length_helper) { self.user.metadata.session_length_helper = {}; } self.user.metadata.session_length_helper.stop = Number(self.now()); return self; }; self.duration = function() { var data = self.user.metadata.session_length_helper; if(data && data.stop && data.start) { return data.stop - data.start; } return -1; }; self.get_today_as_string = function() { var today_iso = self.now().toISOString(); return today_iso.split('T')[0]; }; self.ensure_today = function (name) { var sentinel_key_name = [self.metrics_prefix, name, 'sentinel'].join('.'); return self.im .api_request('kv.get', { key: sentinel_key_name }) .then(function (result) { if(result.value != self.get_today_as_string()) { return self.reset_for_today(name); } }); }; self.reset_for_today = function (name) { var sentinel_key_name = [self.metrics_prefix, name, 'sentinel'].join('.'); var key_name = [self.metrics_prefix, name].join('.'); return self.im .api_request('kv.set', { key: key_name, value: 0 }) .then(function (result) { return self.im.api_request('kv.set', { key: sentinel_key_name, value: self.get_today_as_string() }); }); }; self.store = function(name) { return self.im .api_request('kv.incr', { key: [self.metrics_prefix, name].join('.'), amount: self.duration() }) .then(function (result){ return result.value; }); }; self.fire_metrics = function (name, result) { var full_name = [self.metrics_prefix, name].join('.'); return self.im.metrics.fire.max(full_name, result / 1000); }; self.increment_and_fire = function (fn_or_str) { var name = vumigo.utils.maybe_call(fn_or_str, self); return self .ensure_today(name) .then(function (result) { // return early if we've got nothing to report if(self.duration() < 0) return; return self .store(name) .then(function (result) { return self.fire_metrics(name, result); }); }); }; }); return SessionLengthHelper; }(); go.app = function() { var vumigo = require('vumigo_v02'); var Q = require('q'); var MetricsHelper = require('go-jsbox-metrics-helper'); var App = vumigo.App; var Choice = vumigo.states.Choice; var ChoiceState = vumigo.states.ChoiceState; var EndState = vumigo.states.EndState; var GoNDOH = App.extend(function(self) { App.call(self, 'states_start'); var $ = self.$; self.init = function() { self.env = self.im.config.env; self.metric_prefix = [self.env, self.im.config.name].join('.'); self.store_name = [self.im.config.metric_store, self.env, self.im.config.name].join('.'); mh = new MetricsHelper(self.im); mh // Total unique users // This adds <env>.servicerating.sum.unique_users 'last' metric // As well as <env>.servicerating.sum.unique_users.transient 'sum' metric .add.total_unique_users([self.metric_prefix, 'sum', 'unique_users'].join('.')) // Total sessions // This adds <env>.servicerating.sum.sessions 'last' metric // As well as <env>.servicerating.sum.sessions.transient 'sum' metric .add.total_sessions([self.metric_prefix, 'sum', 'sessions'].join('.')) // Average sessions to complete service rating // Ideally would have used 'enter:question_1_friendliness' here, but double on-enter // bug is creating problems .add.tracker({ action: 'exit', state: 'states_start' }, { action: 'exit', state: 'question_5_privacy' }, { sessions_between_states: [self.metric_prefix, 'avg.sessions_rate_service'].join('.') }) ; // Navigation tracking to measure drop-offs self.im.on('state:exit', function(e) { return self.im.metrics.fire.inc([self.metric_prefix, 'sum', e.state.name, 'exits'].join('.'), 1); }); return self.im.contacts .for_user() .then(function(user_contact) { self.contact = user_contact; }); }; self.states.add('states_start', function(name) { if (self.contact.extra.is_registered_by === 'clinic') { if (self.contact.extra.last_service_rating === 'never' || self.contact.extra.last_service_rating === undefined) { // undefined allows older registrations to rate service return go.utils .incr_kv(self.im, [self.store_name, 'sum', 'servicerating_start'].join('.')) .then(function() { return go.utils.adjust_percentage_serviceratings(self.im, self.metric_prefix); }) .then(function() { return self.states.create('question_1_friendliness'); }); } else { return self.states.create('end_thanks_revisit'); } } else { return self.states.create('end_reg_clinic'); } }); self.states.add('question_1_friendliness', function(name) { return go.utils.set_language(self.im.user, self.contact) .then(function() { return new ChoiceState(name, { question: $('Welcome. When you signed up, were staff at the facility friendly & helpful?'), choices: [ new Choice('very-satisfied', $('Very Satisfied')), new Choice('satisfied', $('Satisfied')), new Choice('not-satisfied', $('Not Satisfied')), new Choice('very-unsatisfied', $('Very unsatisfied')) ], next: 'question_2_waiting_times_feel' }); }); }); self.states.add('question_2_waiting_times_feel', function(name) { return new ChoiceState(name, { question: $('How do you feel about the time you had to wait at the facility?'), choices: [ new Choice('very-satisfied', $('Very Satisfied')), new Choice('satisfied', $('Satisfied')), new Choice('not-satisfied', $('Not Satisfied')), new Choice('very-unsatisfied', $('Very unsatisfied')) ], next: 'question_3_waiting_times_length' }); }); self.states.add('question_3_waiting_times_length', function(name) { return new ChoiceState(name, { question: $('How long did you wait to be helped at the clinic?'), choices: [ new Choice('less-than-an-hour', $('Less than an hour')), new Choice('between-1-and-3-hours', $('Between 1 and 3 hours')), new Choice('more-than-4-hours', $('More than 4 hours')), new Choice('all-day', $('All day')) ], next: 'question_4_cleanliness' }); }); self.states.add('question_4_cleanliness', function(name) { return new ChoiceState(name, { question: $('Was the facility clean?'), choices: [ new Choice('very-satisfied', $('Very Satisfied')), new Choice('satisfied', $('Satisfied')), new Choice('not-satisfied', $('Not Satisfied')), new Choice('very-unsatisfied', $('Very unsatisfied')) ], next: 'question_5_privacy' }); }); self.states.add('question_5_privacy', function(name) { return new ChoiceState(name, { question: $('Did you feel that your privacy was respected by the staff?'), choices: [ new Choice('very-satisfied', $('Very Satisfied')), new Choice('satisfied', $('Satisfied')), new Choice('not-satisfied', $('Not Satisfied')), new Choice('very-unsatisfied', $('Very unsatisfied')) ], next: 'log_servicerating_send_sms' }); }); self.states.add('log_servicerating_send_sms', function(name) { return Q.all([ go.utils.servicerating_log(self.contact, self.im, self.metric_prefix), go.utils.jembi_send_servicerating(self.im, self.contact, self.metric_prefix, "servicerating"), self.im.outbound.send_to_user({ endpoint: 'sms', content: $("Thank you for rating our service.") }) ]) .then(function() { self.contact.extra.last_service_rating = go.utils.get_timestamp(); return Q.all([ self.im.contacts.save(self.contact), go.utils.adjust_percentage_serviceratings(self.im, self.metric_prefix) ]); }) .then(function() { return self.states.create('end_thanks'); }); }); self.states.add('end_thanks', function(name) { return new EndState(name, { text: $('Thank you for rating our service.'), next: 'end_thanks_revisit' }); }); self.states.add('end_reg_clinic', function(name) { return new EndState(name, { text: $('Please register at a clinic before using this line.'), next: 'states_start' }); }); self.states.add('end_thanks_revisit', function(name) { return new EndState(name, { text: $('Sorry, you\'ve already rated service. For baby and pregnancy ' + 'help or if you have compliments or complaints ' + 'dial {{public_channel}} or reply to any of the SMSs you receive') .context({ public_channel: self.im.config.public_channel }), next: 'end_thanks_revisit' }); }); self.states.add('states_error', function(name) { return new EndState(name, { text: 'Sorry, something went wrong when saving the data. Please try again.', next: 'states_start' }); }); }); return { GoNDOH: GoNDOH }; }(); go.init = function() { var vumigo = require('vumigo_v02'); var InteractionMachine = vumigo.InteractionMachine; var GoNDOH = go.app.GoNDOH; return { im: new InteractionMachine(api, new GoNDOH()) }; }();
praekelt/go-ndoh
go-app-servicerating.js
JavaScript
bsd-3-clause
66,212
#!/usr/bin/env node /** * Copyright 2004-present Facebook. All Rights Reserved. */ var fs = require('fs'); var path = require('path'); var spawn = require('child_process').spawn; var CLI_MODULE_PATH = function() { return path.resolve( process.cwd(), 'node_modules', 'react-unity', 'cli-unity' ); }; var cli; try { cli = require(CLI_MODULE_PATH()); } catch(e) {} if (cli) { cli.run(); } else { var args = process.argv.slice(2); if (args.length === 0) { console.error( 'You did not pass any commands, did you mean to run `react-unity init`?' ); process.exit(1); } switch (args[0]) { case 'init': if (args[1]) { init(args[1]); } else { console.error( 'Usage: react-unity init <ProjectName>' ); process.exit(1); } break; default: console.error( 'Command `%s` unrecognized. ' + 'Did you mean to run this inside a react-unity project?', args[0] ); process.exit(1); break; } } function init(name) { if (!name.match(/^[$A-Z_][0-9A-Z_$]*$/i)) { console.error( '"%s" is not a valid name for a project. Please use a valid identifier ' + 'name (alphanumeric).', name ); process.exit(1); } var root = path.resolve(name); var projectName = path.basename(root); console.log( 'This will walk you through creating a new React Unity project in', root ); if (!fs.existsSync(root)) { fs.mkdirSync(root); } var packageJson = { name: projectName, version: '0.0.1', private: true, scripts: { start: 'node_modules/react-unity/packager/packager.sh' } }; fs.writeFileSync(path.join(root, 'package.json'), JSON.stringify(packageJson)); process.chdir(root); //run('npm install --save git://github.com/pgavazzi/react-unity.git', function(e) { run('npm install --save ../react-unity', function(e) { if (e) { console.error('`npm install --save git://github.com/pgavazzi/react-unity.git` failed'); process.exit(1); } var cli = require(CLI_MODULE_PATH()); cli.init(root, projectName); }); } function run(command, cb) { var parts = command.split(/\s+/); var cmd = parts[0]; var args = parts.slice(1); var proc = spawn(cmd, args, {stdio: 'inherit'}); proc.on('close', function(code) { if (code !== 0) { cb(new Error('Command exited with a non-zero status')); } else { cb(null); } }); }
pgavazzi/react-unity
react-unity-cli/index.js
JavaScript
bsd-3-clause
2,469
require('sqlite3').verbose(); var fs = require('fs'); var MBTiles = require('..'); var tape = require('tape'); var non_existent = __dirname + '/fixtures/non_existent.mbtiles'; try { fs.unlinkSync(non_existent); } catch (err) {} tape('Open with ro mode', function(assert) { new MBTiles(non_existent + '?mode=ro', function(err, mbtiles) { assert.ok(err); assert.ok(err.message.match(/SQLITE_CANTOPEN: unable to open database file/)); assert.end(); }) }) tape('Open with rw mode', function(assert) { new MBTiles(non_existent + '?mode=rw', function(err, mbtiles) { assert.ok(err); assert.ok(err.message.match(/SQLITE_CANTOPEN: unable to open database file/)); assert.end(); }) }) tape('Open with rwc mode', function(assert) { new MBTiles(non_existent + '?mode=rwc', function(err, mbtiles) { assert.notOk(err); assert.end(); }) })
mapbox/node-mbtiles
test/mode.test.js
JavaScript
bsd-3-clause
876
// Copyright 2015 The Vanadium Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. var sections = require('./constants').sections; module.exports = selectTab; /* * Exported function that sets the given state to the given tabKey. * If there is an error, however, the error event is run. */ function selectTab(state, events, tabKey) { // If the tab is invalid, go to the error page. if (sections.get(tabKey) === undefined) { //TODO(aghassemi) Needs to be 404 error when we have support for 404 events.error(new Error('Invalid help page: ' + tabKey)); } else { // Since the tabKey is valid, the selectedTab can be updated. state.selectedTab.set(tabKey); } }
vanadium/browser
src/components/help/selectTab.js
JavaScript
bsd-3-clause
766
var vows = require('vows'), assert = require('assert'), get = require('../src/get'), getIn = require('../src/getIn'), multiGet = require('../src/multiGet'); vows.describe('multiGet()').addBatch({ 'Getting': { topic: function() { return { foo: 1, bar: 'baz', baz: {blah: 2} }; }, 'a property': function(obj) { var o1 = multiGet(obj, 'foo'); var o2 = get(obj, 'foo'); assert.deepEqual(o1, o2); }, 'a nested property': function(obj) { var o1 = multiGet(obj, ['baz', 'blah']); var o2 = getIn(obj, ['baz', 'blah']); assert.deepEqual(o1, o2); }, 'an array property': function() { var arr = [1, 2, 3]; var o1 = multiGet(arr, 2); var o2 = get(arr, 2); assert.equal(o1, o2); } } }).export(module);
pombredanne/sprout
test/multiGet-test.js
JavaScript
bsd-3-clause
837
/** * Runner of handlers */ const findElementWithHandler = elm => { if (elm.getAttribute('data-handler')) { return elm; } if (!elm.parentNode || elm.parentNode.nodeName === 'BODY') { return false; } return findElementWithHandler(elm.parentNode); }; export default handlers => { if (!handlers) { throw new Error('Nothing to handle'); } document.body.addEventListener('click', (e) => { if (e.target.tagName === 'HTML') { return; } const trigger = findElementWithHandler(e.target || e.srcElement); if (!trigger) { return; } const handler = trigger.getAttribute('data-handler'); if (!handler) { // nothing to do return; } if (trigger.tagName === 'A' && (e.metaKey || e.ctrlKey || e.shiftKey)) { // honour default behaviour on <a>s when using modifier keys when clicking // meta / ctrl open in new tab // shift opens in a new window return; } if (typeof handlers[handler] === 'function') { handlers[handler](trigger, e); } else { if (console && console.log) { console.log('unknown handler \'%s\' on %o', handler, trigger); } } }); };
grrr-amsterdam/garp_scaffold
public/js/src/modules/handle.js
JavaScript
bsd-3-clause
1,191
"use strict";Object.defineProperty(exports, "__esModule", { value: true });exports["default"] = invariant;function invariant(condition, message) { if (!condition) { throw new Error(message);}}module.exports = exports["default"];
dmitriiabramov/esfmt
package/invariant.js
JavaScript
bsd-3-clause
240
$(document).ready(function() { cancelar = $("#cancelarV"); if(cancelar.exists()) { cancelar.click(function() { if(confirm('Al cancelar se perderan los cambios hechos en este formulario, desea continuar?')) { document.location.href = $("#YIIbaseUrl").val() + "/curso/" + $("#curso_id").val(); } }); } });
fipasoft/scrum
app/themes/fipa/javascript/view/sesion.js
JavaScript
bsd-3-clause
325
var validators = require('../validators'); var kwery = require('kwery'); var uniqueName = validators.uniqueName; describe('Validators', function () { var errors, sanitize; beforeEach(function () { errors = {}; sanitize = {}; }); describe('Valid', function () { describe('Unique', function () { it('adds no error when name property is unique within its parent', function () { var data_layer = { find: kwery.flat.bind(null, [ { name: 'products', path: '/products', } ]), }; var validator = uniqueName(data_layer); var data = { name: 'home', parent: '/', }; validator(data, 'name', errors, sanitize, function () { sanitize.should.eql({}); errors.should.eql({}); }); }); it('adds no error when when the same name exists on a different level', function () { var data_layer = { find: kwery.flat.bind(null, [ { name: 'home', path: '/nl/home', } ]), }; var validator = uniqueName(data_layer); var data = { name: 'home', parent: '/', }; validator(data, 'name', errors, sanitize, function () { sanitize.should.eql({}); errors.should.eql({}); }); }); it('adds no error if paths match because then its updating itself', function () { var data_layer = { find: kwery.flat.bind(null, [ { name: 'home', path: '/home', } ]), }; var validator = uniqueName(data_layer); var data = { name: 'home', path: '/home', }; validator(data, 'name', errors, sanitize, function () { sanitize.should.eql({}); errors.should.eql({}); }); }); it('adds no error when there are no matching results', function () { var data_layer = { find: kwery.flat.bind(null, []), }; var validator = uniqueName(data_layer); var data = { name: 'home', parent: '/', }; validator(data, 'name', errors, sanitize, function () { sanitize.should.eql({}); errors.should.eql({}); }); }); }); }); describe('Invalid', function () { describe('Unique', function () { it('adds an error when name property isnt unique within the root', function () { var data_layer = { find: kwery.flat.bind(null, [ { name: 'home', path: '/home', } ]), }; var validator = uniqueName(data_layer); var data = { name: 'home', parent: '/', }; validator(data, 'name', errors, sanitize, function () { sanitize.should.eql({}); errors.should.eql({ name: [ 'Should be unique' ] }); }); }); it('adds an error when name property isnt unique within its parent', function () { var data_layer = { find: kwery.flat.bind(null, [ { name: 'home', path: '/products/home', } ]), }; var validator = uniqueName(data_layer); var data = { name: 'home', parent: '/products', }; validator(data, 'name', errors, sanitize, function () { sanitize.should.eql({}); errors.should.eql({ name: [ 'Should be unique' ] }); }); }); it('adds an error and is case insensitive', function () { var data_layer = { find: kwery.flat.bind(null, [ { name: 'Home', path: '/home', } ]), }; var validator = uniqueName(data_layer); var data = { name: 'home', parent: '/', }; validator(data, 'name', errors, sanitize, function () { sanitize.should.eql({}); errors.should.eql({ name: [ 'Should be unique' ] }); }); }); }); }); });
Enome/jungles
types/specs/validators.js
JavaScript
bsd-3-clause
4,306
/* Copyright (c) 2015-present, salesforce.com, inc. All rights reserved */ /* Licensed under BSD 3-Clause - see LICENSE.txt or git.io/sfdc-license */ export default {"viewBox":"0 0 52 52","xmlns":"http://www.w3.org/2000/svg","path":{"d":"M50 10c0-2.2-1.8-4-4-4H6c-2.2 0-4 1.8-4 4v32c0 2.2 1.8 4 4 4h40c2.2 0 4-1.8 4-4V10zM6.9 29c-1.7 0-3-1.3-3-3s1.3-3 3-3 3 1.3 3 3-1.4 3-3 3zM44 38.5c0 .8-.7 1.5-1.5 1.5h-29c-.8 0-1.5-.7-1.5-1.5v-25c0-.8.7-1.5 1.5-1.5h29c.8 0 1.5.7 1.5 1.5v25z"}};
salesforce/design-system-react
icons/utility/tablet_landscape.js
JavaScript
bsd-3-clause
485
function runTest() { var Events = FBTest.FirebugWindow.FireDiff.events, Firebug = FBTest.FirebugWindow.Firebug, FBTrace = FBTest.FirebugWindow.FBTrace; var cssPanel; function setEditorValue(editor, value) { var editorInput = editor.input; editorInput.value = value; Firebug.Editor.update(true); } var tests = [ { name: "newProperty", execute: function(win) { cssPanel.editElementStyle(); var editor = cssPanel.editor; setEditorValue(editor, "whitespace"); setEditorValue(editor, "background-color"); Firebug.Editor.tabNextEditor(); setEditorValue(editor, "orange"); setEditorValue(editor, "red"); Firebug.Editor.stopEditing(); }, verify: function(win, number, change) { FBTest.compare(change.changeSource, Events.ChangeSource.FIREBUG_CHANGE, "Change source: " + change.changeSource); FBTest.compare(change.changeType, "DOM", "Change type: " + change.changeType); FBTest.compare(change.subType, "attr_changed", "Sub type: " + change.subType); FBTest.compare(change.attrName, "style", "Attribute Name: " + change.attrName); FBTest.compare(change.value, "background-color: red;", "Value: " + change.value); FBTest.compare(change.previousValue, "", "Prev Value: " + change.previousValue); FBTest.compare(change.isAddition(), false, "Is Addition: " + change.isAddition()); FBTest.compare(change.isRemoval(), false, "Is Removal: " + change.isRemoval()); }, eventCount: 1 }, { name: "editProperty", execute: function(win) { var panelNode = cssPanel.panelNode; var rule = panelNode.getElementsByClassName("cssPropValue")[0]; Firebug.Editor.startEditing(rule, rule.textContent); var editor = cssPanel.editor; setEditorValue(editor, "yellow"); setEditorValue(editor, "green !important"); Firebug.Editor.stopEditing(); }, verify: function(win, number, change) { FBTest.compare(change.changeSource, Events.ChangeSource.FIREBUG_CHANGE, "Change source: " + change.changeSource); FBTest.compare(change.changeType, "DOM", "Change type: " + change.changeType); FBTest.compare(change.subType, "attr_changed", "Sub type: " + change.subType); FBTest.compare(change.attrName, "style", "Attribute Name: " + change.attrName); FBTest.compare(change.value, "background-color: green ! important;", "Value: " + change.value); FBTest.compare(change.previousValue, "background-color: red;", "Prev Value: " + change.previousValue); FBTest.compare(change.isAddition(), false, "Is Addition: " + change.isAddition()); FBTest.compare(change.isRemoval(), false, "Is Removal: " + change.isRemoval()); }, eventCount: 1 }, { name: "renameProperty", execute: function(win) { FBTrace.sysout("renameProperty"); var panelNode = cssPanel.panelNode; var rule = panelNode.getElementsByClassName("cssPropName")[0]; FBTrace.sysout("renameProperty: " + rule, rule.cloneNode(true)); Firebug.Editor.startEditing(rule, rule.textContent); var editor = cssPanel.editor; setEditorValue(editor, "border-color"); setEditorValue(editor, "color"); Firebug.Editor.stopEditing(); }, verify: function(win, number, change) { FBTest.compare(change.changeSource, Events.ChangeSource.FIREBUG_CHANGE, "Change source: " + change.changeSource); FBTest.compare(change.changeType, "DOM", "Change type: " + change.changeType); FBTest.compare(change.subType, "attr_changed", "Sub type: " + change.subType); FBTest.compare(change.attrName, "style", "Attribute Name: " + change.attrName); FBTest.compare(change.value, "color: green ! important;", "Value: " + change.value); FBTest.compare(change.previousValue, "background-color: green ! important;", "Prev Value: " + change.previousValue); FBTest.compare(change.isAddition(), false, "Is Addition: " + change.isAddition()); FBTest.compare(change.isRemoval(), false, "Is Removal: " + change.isRemoval()); }, eventCount: 1 }, { name: "disableProperty", execute: function(win) { FBTrace.sysout("disableProperty"); var panelNode = cssPanel.panelNode; var rule = panelNode.getElementsByClassName("cssProp")[0]; FBTrace.sysout("disableProperty: " + rule, rule.cloneNode(true)); cssPanel.disablePropertyRow(rule); cssPanel.disablePropertyRow(rule); }, verify: function(win, number, change) { FBTest.compare(change.changeSource, Events.ChangeSource.FIREBUG_CHANGE, "Change source: " + change.changeSource); FBTest.compare(change.changeType, "DOM", "Change type: " + change.changeType); FBTest.compare(change.subType, "attr_changed", "Sub type: " + change.subType); FBTest.compare(change.attrName, "style", "Attribute Name: " + change.attrName); FBTest.compare(change.value, number ? "color: green ! important;" : "", "Value: " + change.value); FBTest.compare(change.previousValue, number ? "" : "color: green ! important;", "Prev Value: " + change.previousValue); FBTest.compare(change.isAddition(), false, "Is Addition: " + change.isAddition()); FBTest.compare(change.isRemoval(), false, "Is Removal: " + change.isRemoval()); }, eventCount: 2 }, { name: "deleteProperty", execute: function(win) { var panelNode = cssPanel.panelNode; var rule = panelNode.getElementsByClassName("cssPropName")[0]; Firebug.Editor.startEditing(rule, rule.textContent); var editor = cssPanel.editor; setEditorValue(editor, "border-color"); setEditorValue(editor, ""); Firebug.Editor.stopEditing(); }, verify: function(win, number, change) { FBTest.compare(change.changeSource, Events.ChangeSource.FIREBUG_CHANGE, "Change source: " + change.changeSource); FBTest.compare(change.changeType, "DOM", "Change type: " + change.changeType); FBTest.compare(change.subType, "attr_changed", "Sub type: " + change.subType); FBTest.compare(change.attrName, "style", "Attribute Name: " + change.attrName); FBTest.compare(change.value, "", "Value: " + change.value); FBTest.compare(change.previousValue, "color: green ! important;", "Prev Value: " + change.previousValue); FBTest.compare(change.isAddition(), false, "Is Addition: " + change.isAddition()); FBTest.compare(change.isRemoval(), false, "Is Removal: " + change.isRemoval()); }, eventCount: 1 }, ]; var urlBase = FBTest.getHTTPURLBase(); FBTestFirebug.openNewTab(urlBase + "module/index.htm", function(win) { FBTestFirebug.openFirebug(); FBTestFireDiff.enableDiffPanel( function() { FBTestFirebug.selectPanel("html"); cssPanel = FW.Firebug.chrome.selectSidePanel("css"); //FBTestFirebug.selectPanel("css"); //cssPanel = FBTestFirebug.getSelectedPanel(); FW.FBTrace.sysout("cssPanel", cssPanel); cssPanel.select(win.document.getElementById("attrModified")); FBTestFireDiff.executeModuleTests(tests, win); }); }); }
kpdecker/firediff
test/module/stylesEditorTest.js
JavaScript
bsd-3-clause
7,473
(function () { 'use strict'; // iPad and iPod detection var isiPad = function(){ return (navigator.platform.indexOf("iPad") != -1); }; var isiPhone = function(){ return ( (navigator.platform.indexOf("iPhone") != -1) || (navigator.platform.indexOf("iPod") != -1) ); }; // Go to next section var gotToNextSection = function(){ var el = $('.fh5co-learn-more'), w = el.width(), divide = -w/2; el.css('margin-left', divide); }; // Loading page var loaderPage = function() { $(".fh5co-loader").fadeOut("slow"); }; // FullHeight var fullHeight = function() { if ( !isiPad() && !isiPhone() ) { $('.js-fullheight').css('height', $(window).height() - 49); $(window).resize(function(){ $('.js-fullheight').css('height', $(window).height() - 49); }) } }; // Scroll Next var ScrollNext = function() { $('body').on('click', '.scroll-btn', function(e){ e.preventDefault(); $('html, body').animate({ scrollTop: $( $(this).closest('[data-next="yes"]').next()).offset().top }, 1000, 'easeInOutExpo'); return false; }); }; // Click outside of offcanvass var mobileMenuOutsideClick = function() { $(document).click(function (e) { var container = $("#fh5co-offcanvas, .js-fh5co-nav-toggle"); if (!container.is(e.target) && container.has(e.target).length === 0) { if ( $('body').hasClass('offcanvas-visible') ) { $('body').removeClass('offcanvas-visible'); $('.js-fh5co-nav-toggle').removeClass('active'); } } }); }; // Offcanvas var offcanvasMenu = function() { $('body').prepend('<div id="fh5co-offcanvas" />'); $('#fh5co-offcanvas').prepend('<ul id="fh5co-side-links">'); $('body').prepend('<a href="#" class="js-fh5co-nav-toggle fh5co-nav-toggle"><i></i></a>'); $('.left-menu li, .right-menu li').each(function(){ var $this = $(this); $('#fh5co-offcanvas ul').append($this.clone()); }); }; // Burger Menu var burgerMenu = function() { $('body').on('click', '.js-fh5co-nav-toggle', function(event){ var $this = $(this); $('body').toggleClass('fh5co-overflow offcanvas-visible'); $this.toggleClass('active'); event.preventDefault(); }); }; // Animations var contentWayPoint = function() { var i = 0; $('.animate-box').waypoint( function( direction ) { if( direction === 'down' && !$(this.element).hasClass('animated') ) { i++; $(this.element).addClass('item-animate'); setTimeout(function(){ $('body .animate-box.item-animate').each(function(k){ var el = $(this); setTimeout( function () { el.addClass('fadeInUp animated'); el.removeClass('item-animate'); }, k * 200, 'easeInOutExpo' ); }); }, 100); } } , { offset: '95%' } ); }; // Document on load. $(function(){ gotToNextSection(); loaderPage(); fullHeight(); ScrollNext(); mobileMenuOutsideClick(); offcanvasMenu(); burgerMenu(); // Animate contentWayPoint(); }); acelayablog.initHighlightjs(); }()); $(document).ready(function() { acelayablog.initSearchForm(); acelayablog.initShareButtons(); acelayablog.initSearch(); acelayablog.initToTopButton(); });
acelaya/blog
src/content/assets/js/main.js
JavaScript
bsd-3-clause
3,937
/*! * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2016 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ sap.ui.define(['jquery.sap.global', 'sap/ui/core/IconPool', 'sap/ui/core/theming/Parameters'], function(jQuery, IconPool, Parameters) { "use strict"; /** * ListitemBase renderer. * * @namespace */ var ListItemBaseRenderer = {}; // create ARIA announcements var mAriaAnnouncements = {}; ListItemBaseRenderer.renderInvisible = function(rm, oLI) { this.openItemTag(rm, oLI); rm.writeInvisiblePlaceholderData(oLI); rm.write(">"); this.closeItemTag(rm, oLI); }; ListItemBaseRenderer.isModeMatched = function(sMode, iOrder) { var mOrderConfig = (sap.m.ListBaseRenderer || {}).ModeOrder || {}; return (mOrderConfig[sMode] == iOrder); }; /** * Renders the mode when item mode is in correct order * * @param {sap.ui.core.RenderManager} rm The RenderManager that can be used for writing to the Render-Output-Buffer. * @param {sap.ui.core.Control} oLI an object representation of the control that should be rendered. * @param {int} [iOrder] expected order for the rendering * @protected */ ListItemBaseRenderer.renderMode = function(rm, oLI, iOrder) { var sMode = oLI.getMode(); if (!this.isModeMatched(sMode, iOrder)) { return; } var oModeControl = oLI.getModeControl(true); if (oModeControl) { this.renderModeContent(rm, oLI, oModeControl); } }; ListItemBaseRenderer.renderModeContent = function(rm, oLI, oModeControl) { var sMode = oLI.getMode(), mModeConfig = { Delete : "D", MultiSelect : "M", SingleSelect : "S", SingleSelectLeft : "SL" }; rm.write("<div"); rm.writeAttribute("id", oLI.getId() + "-mode"); rm.addClass("sapMLIBSelect" + mModeConfig[sMode]); this.decorateMode(rm, oLI); rm.writeClasses(); rm.writeStyles(); rm.write(">"); rm.renderControl(oModeControl); rm.write("</div>"); }; ListItemBaseRenderer.decorateMode = function(rm, oLI) { // determine whether animation is necessary or not if (!sap.ui.getCore().getConfiguration().getAnimation() || !oLI.getListProperty("modeAnimationOn")) { return; } var sMode = oLI.getMode(), sLastListMode = oLI.getListProperty("lastMode"); // determine whether list mode is changed or not if (!sLastListMode || sLastListMode == sMode) { return; } if (sMode == sap.m.ListMode.None) { rm.addClass("sapMLIBUnselectAnimation"); } else { rm.addClass("sapMLIBSelectAnimation"); } }; /** * Renders counter if it is not empty * * @param {sap.ui.core.RenderManager} rm The RenderManager that can be used for writing to the Render-Output-Buffer. * @param {sap.ui.core.Control} oLI an object representation of the control that should be rendered. * @protected */ ListItemBaseRenderer.renderCounter = function(rm, oLI) { var iCounter = oLI.getCounter(); if (iCounter) { this.renderCounterContent(rm, oLI, iCounter); } }; ListItemBaseRenderer.renderCounterContent = function(rm, oLI, iCounter) { rm.write("<div"); rm.writeAttribute("id", oLI.getId() + "-counter"); var sAriaLabel = sap.ui.getCore().getLibraryResourceBundle("sap.m").getText("LIST_ITEM_COUNTER", iCounter); rm.writeAttribute("aria-label", sAriaLabel); rm.addClass("sapMLIBCounter"); rm.writeClasses(); rm.write(">"); rm.write(iCounter); rm.write("</div>"); }; /** * Renders type for the list item * * @param {sap.ui.core.RenderManager} rm The RenderManager that can be used for writing to the Render-Output-Buffer. * @param {sap.ui.core.Control} oLI an object representation of the control that should be rendered. * @protected */ ListItemBaseRenderer.renderType = function(rm, oLI) { var oTypeControl = oLI.getTypeControl(); if (oTypeControl) { rm.renderControl(oTypeControl); } }; /** * Renders list item HTML starting tag * * @param {sap.ui.core.RenderManager} rm The RenderManager that can be used for writing to the Render-Output-Buffer. * @param {sap.ui.core.Control} oLI an object representation of the control that should be rendered. * @protected */ ListItemBaseRenderer.openItemTag = function(rm, oLI) { rm.write("<li"); }; /** * Renders list item HTML closing tag * * @param {sap.ui.core.RenderManager} rm The RenderManager that can be used for writing to the Render-Output-Buffer. * @param {sap.ui.core.Control} oLI an object representation of the control that should be rendered. * @protected */ ListItemBaseRenderer.closeItemTag = function(rm, oLI) { rm.write("</li>"); }; /** * Determines whether flex box wrapper is necessary or not. * * @param {sap.ui.core.RenderManager} rm The RenderManager that can be used for writing to the Render-Output-Buffer. * @param {sap.ui.core.Control} oLI an object representation of the control that should be rendered. * @protected */ ListItemBaseRenderer.handleNoFlex = function(rm, oLI) { return !jQuery.support.hasFlexBoxSupport; }; ListItemBaseRenderer.renderTabIndex = function(rm, oLI) { rm.writeAttribute("tabindex", "-1"); }; ListItemBaseRenderer.renderTooltip = function(rm, oLI) { var sTooltip = oLI.getTooltip_AsString(); if (sTooltip) { rm.writeAttributeEscaped("title", sTooltip); } }; /** * Adds the classes needed to recognize the element as focusable. * * @param {sap.ui.core.RenderManager} rm The RenderManager that can be used for writing to the Render-Output-Buffer * @param {sap.ui.core.Control} [oLI] an object representation of the control that should be rendered * @protected */ ListItemBaseRenderer.addFocusableClasses = function(rm, oLI) { if (sap.ui.Device.system.desktop) { rm.addClass("sapMLIBFocusable"); this.addLegacyOutlineClass(rm, oLI); } }; /** * Adds the classes for legacy browsers, which do not support normal outlines. * * @param {sap.ui.core.RenderManager} rm The RenderManager that can be used for writing to the Render-Output-Buffer * @param {sap.ui.core.Control} [oLI] an object representation of the control that should be rendered * @protected */ ListItemBaseRenderer.addLegacyOutlineClass = function(rm, oLI) { if (sap.ui.Device.browser.msie) { rm.addClass("sapMLIBLegacyOutline"); } }; /** * Creates an invisible aria node for the given message bundle text * in the static UIArea and returns its id for ARIA announcements * * This method should be used when text is reached frequently. * * @param {String} sKey key of the announcement * @param {String} [sBundleText] key of the announcement * @returns {String} id of the generated invisible aria node * @protected */ ListItemBaseRenderer.getAriaAnnouncement = function(sKey, sBundleText) { if (mAriaAnnouncements[sKey]) { return mAriaAnnouncements[sKey]; } sBundleText = sBundleText || "LIST_ITEM_" + sKey.toUpperCase(); mAriaAnnouncements[sKey] = new sap.ui.core.InvisibleText({ text : sap.ui.getCore().getLibraryResourceBundle("sap.m").getText(sBundleText) }).toStatic().getId(); return mAriaAnnouncements[sKey]; }; /** * Returns aria accessibility role * * @param {sap.ui.core.Control} oLI an object representation of the control * @returns {String} * @protected */ ListItemBaseRenderer.getAriaRole = function(oLI) { return "option"; }; /** * Returns the inner aria labelledby ids for the accessibility * * @param {sap.ui.core.Control} oLI an object representation of the control * @returns {String|undefined} * @protected */ ListItemBaseRenderer.getAriaLabelledBy = function(oLI) { if (oLI.getAriaLabelledBy().length) { return oLI.getId(); } }; /** * Returns the inner aria describedby ids for the accessibility * * @param {sap.ui.core.Control} oLI an object representation of the control * @returns {String|undefined} * @protected */ ListItemBaseRenderer.getAriaDescribedBy = function(oLI) { var aDescribedBy = [], sType = oLI.getType(), mType = sap.m.ListType; if (oLI.getListProperty("showUnread") && oLI.getUnread()) { aDescribedBy.push(this.getAriaAnnouncement("unread")); } if (oLI.getMode() == sap.m.ListMode.Delete) { aDescribedBy.push(this.getAriaAnnouncement("deletable")); } if (sType == mType.Navigation) { aDescribedBy.push(this.getAriaAnnouncement("navigation")); } else if (sType == mType.Detail || sType == mType.DetailAndActive) { aDescribedBy.push(this.getAriaAnnouncement("detail")); } return aDescribedBy.join(" "); }; /** * Returns the accessibility state of the control * * @param {sap.ui.core.Control} oLI an object representation of the control * @protected */ ListItemBaseRenderer.getAccessibilityState = function(oLI) { var sAriaLabelledBy = this.getAriaLabelledBy(oLI), sAriaDescribedBy = this.getAriaDescribedBy(oLI), mAccessibilityState = { role: this.getAriaRole(oLI) }; if (oLI.isSelectable()) { mAccessibilityState.selected = oLI.getProperty("selected"); } if (sAriaLabelledBy) { mAccessibilityState.labelledby = { value: sAriaLabelledBy.trim(), append: true }; } if (sAriaDescribedBy) { mAccessibilityState.describedby = { value: sAriaDescribedBy.trim(), append: true }; } return mAccessibilityState; }; /** * Hook for rendering list item contents * * @param {sap.ui.core.RenderManager} rm The RenderManager that can be used for writing to the Render-Output-Buffer. * @param {sap.ui.core.Control} oLI an object representation of the control that should be rendered. * @protected */ ListItemBaseRenderer.renderLIContent = function(rm, oLI) { }; /** * Hook for changing list item attributes * * @param {sap.ui.core.RenderManager} rm The RenderManager that can be used for writing to the Render-Output-Buffer. * @param {sap.ui.core.Control} oLI an object representation of the control that should be rendered. * @protected */ ListItemBaseRenderer.renderLIAttributes = function(rm, oLI) { }; ListItemBaseRenderer.renderLIContentWrapper = function(rm, oLI) { rm.write('<div class="sapMLIBContent"'); rm.writeAttribute("id", oLI.getId() + "-content"); rm.write(">"); // additional content with class for no-flex case if (this.handleNoFlex()) { rm.write('<div class="sapMLIBContentNF">'); } this.renderLIContent(rm, oLI); if (this.handleNoFlex()) { rm.write('</div>'); } rm.write('</div>'); }; /** * Renders the HTML for the given control, using the provided. * * {@link sap.ui.core.RenderManager}. * * @param {sap.ui.core.RenderManager} rm The RenderManager that can be used for writing to the Render-Output-Buffer. * @param {sap.ui.core.Control} oLI an object representation of the control that should be rendered. * @public */ ListItemBaseRenderer.render = function(rm, oLI) { // render invisible placeholder if (!oLI.getVisible()) { this.renderInvisible(rm, oLI); return false; } // start this.openItemTag(rm, oLI); rm.writeControlData(oLI); // classes rm.addClass("sapMLIB"); rm.addClass("sapMLIB-CTX"); rm.addClass("sapMLIBShowSeparator"); rm.addClass("sapMLIBType" + oLI.getType()); if (sap.ui.Device.system.desktop && oLI.isActionable()) { rm.addClass("sapMLIBActionable"); rm.addClass("sapMLIBHoverable"); } if (oLI.getSelected()) { rm.addClass("sapMLIBSelected"); } if (this.handleNoFlex()) { rm.addClass("sapMLIBNoFlex"); } if (oLI.getListProperty("showUnread") && oLI.getUnread()) { rm.addClass("sapMLIBUnread"); } this.addFocusableClasses(rm, oLI); // attributes this.renderTooltip(rm, oLI); this.renderTabIndex(rm, oLI); // handle accessibility states if (sap.ui.getCore().getConfiguration().getAccessibility()) { rm.writeAccessibilityState(oLI, this.getAccessibilityState(oLI)); } // item attributes hook this.renderLIAttributes(rm, oLI); rm.writeClasses(); rm.writeStyles(); rm.write(">"); // mode for left hand side of the content this.renderMode(rm, oLI, -1); this.renderLIContentWrapper(rm, oLI); this.renderCounter(rm, oLI); this.renderType(rm, oLI); // mode for right hand side of the content this.renderMode(rm, oLI, 1); this.closeItemTag(rm, oLI); }; return ListItemBaseRenderer; }, /* bExport= */ true);
dirga123/clr
openui5/sap/m/ListItemBaseRenderer-dbg.js
JavaScript
isc
12,367
import assert from 'assert'; import metadata from '../../../lib/filter/metadata'; describe('filter/metadata metadata', () => { it('should return true when a match is found', () => { assert.equal( metadata( { data: { draft: true, title: 'test', }, }, { draft: true, } ), true ); assert.equal( metadata( { data: { draft: true, title: 'test', }, }, { draft: true, title: 'test', } ), true ); assert.equal( metadata( { data: { draft: true, title: 'test', date: 'ok', }, }, { draft: true, title: 'test', } ), true ); }); it('should return false when a match is not found', () => { assert.equal( metadata( { data: { draft: false, title: 'test', }, }, { draft: true, } ), false ); assert.equal( metadata( { data: { draft: true, }, }, { draft: true, title: 'test', } ), false ); assert.equal( metadata( { data: { draft: true, title: 'surprise', }, }, { draft: true, title: 'test', } ), false ); assert.equal( metadata( { data: { draft: true, title: 'surprise', date: 'ok', }, }, { draft: true, title: 'test', } ), false ); }); });
yarnjs/yarn
test/unit/filter/metadata.spec.js
JavaScript
mit
1,885
/* eslint no-unused-vars: 0, no-constant-condition: 0 */ import {Binding, createOverrideContext} from 'aurelia-binding'; import {Container} from 'aurelia-dependency-injection'; import {ShadowDOM} from './shadow-dom'; /** * Represents a node in the view hierarchy. */ interface ViewNode { /** * Binds the node and it's children. * @param bindingContext The binding context to bind to. * @param overrideContext A secondary binding context that can override the standard context. */ bind(bindingContext: Object, overrideContext?: Object): void; /** * Triggers the attach for the node and its children. */ attached(): void; /** * Triggers the detach for the node and its children. */ detached(): void; /** * Unbinds the node and its children. */ unbind(): void; } export class View { /** * The Dependency Injection Container that was used to create this View instance. */ container: Container; /** * The ViewFactory that built this View instance. */ viewFactory: ViewFactory; /** * Contains the DOM Nodes which represent this View. If the view was created via the "enhance" API, this will be an Element, otherwise it will be a DocumentFragment. If not created via "enhance" then the fragment will only contain nodes when the View is detached from the DOM. */ fragment: DocumentFragment | Element; /** * The primary binding context that this view is data-bound to. */ bindingContext: Object; /** * The override context which contains properties capable of overriding those found on the binding context. */ overrideContext: Object; /** * The Controller instance that owns this View. */ controller: Controller; /** * Creates a View instance. * @param container The container from which the view was created. * @param viewFactory The factory that created this view. * @param fragment The DOM fragement representing the view. * @param controllers The controllers inside this view. * @param bindings The bindings inside this view. * @param children The children of this view. */ constructor(container: Container, viewFactory: ViewFactory, fragment: DocumentFragment, controllers: Controller[], bindings: Binding[], children: ViewNode[], slots: Object) { this.container = container; this.viewFactory = viewFactory; this.resources = viewFactory.resources; this.fragment = fragment; this.firstChild = fragment.firstChild; this.lastChild = fragment.lastChild; this.controllers = controllers; this.bindings = bindings; this.children = children; this.slots = slots; this.hasSlots = false; this.fromCache = false; this.isBound = false; this.isAttached = false; this.bindingContext = null; this.overrideContext = null; this.controller = null; this.viewModelScope = null; this.animatableElement = undefined; this._isUserControlled = false; this.contentView = null; for (let key in slots) { this.hasSlots = true; break; } } /** * Returns this view to the appropriate view cache. */ returnToCache(): void { this.viewFactory.returnViewToCache(this); } /** * Triggers the created callback for this view and its children. */ created(): void { let i; let ii; let controllers = this.controllers; for (i = 0, ii = controllers.length; i < ii; ++i) { controllers[i].created(this); } } /** * Binds the view and it's children. * @param bindingContext The binding context to bind to. * @param overrideContext A secondary binding context that can override the standard context. */ bind(bindingContext: Object, overrideContext?: Object, _systemUpdate?: boolean): void { let controllers; let bindings; let children; let i; let ii; if (_systemUpdate && this._isUserControlled) { return; } if (this.isBound) { if (this.bindingContext === bindingContext) { return; } this.unbind(); } this.isBound = true; this.bindingContext = bindingContext; this.overrideContext = overrideContext || createOverrideContext(bindingContext); this.resources._invokeHook('beforeBind', this); bindings = this.bindings; for (i = 0, ii = bindings.length; i < ii; ++i) { bindings[i].bind(this); } if (this.viewModelScope !== null) { bindingContext.bind(this.viewModelScope.bindingContext, this.viewModelScope.overrideContext); this.viewModelScope = null; } controllers = this.controllers; for (i = 0, ii = controllers.length; i < ii; ++i) { controllers[i].bind(this); } children = this.children; for (i = 0, ii = children.length; i < ii; ++i) { children[i].bind(bindingContext, overrideContext, true); } if (this.hasSlots) { ShadowDOM.distributeView(this.contentView, this.slots); } } /** * Adds a binding instance to this view. * @param binding The binding instance. */ addBinding(binding: Object): void { this.bindings.push(binding); if (this.isBound) { binding.bind(this); } } /** * Unbinds the view and its children. */ unbind(): void { let controllers; let bindings; let children; let i; let ii; if (this.isBound) { this.isBound = false; this.resources._invokeHook('beforeUnbind', this); if (this.controller !== null) { this.controller.unbind(); } bindings = this.bindings; for (i = 0, ii = bindings.length; i < ii; ++i) { bindings[i].unbind(); } controllers = this.controllers; for (i = 0, ii = controllers.length; i < ii; ++i) { controllers[i].unbind(); } children = this.children; for (i = 0, ii = children.length; i < ii; ++i) { children[i].unbind(); } this.bindingContext = null; this.overrideContext = null; } } /** * Inserts this view's nodes before the specified DOM node. * @param refNode The node to insert this view's nodes before. */ insertNodesBefore(refNode: Node): void { refNode.parentNode.insertBefore(this.fragment, refNode); } /** * Appends this view's to the specified DOM node. * @param parent The parent element to append this view's nodes to. */ appendNodesTo(parent: Element): void { parent.appendChild(this.fragment); } /** * Removes this view's nodes from the DOM. */ removeNodes(): void { let fragment = this.fragment; let current = this.firstChild; let end = this.lastChild; let next; while (current) { next = current.nextSibling; fragment.appendChild(current); if (current === end) { break; } current = next; } } /** * Triggers the attach for the view and its children. */ attached(): void { let controllers; let children; let i; let ii; if (this.isAttached) { return; } this.isAttached = true; if (this.controller !== null) { this.controller.attached(); } controllers = this.controllers; for (i = 0, ii = controllers.length; i < ii; ++i) { controllers[i].attached(); } children = this.children; for (i = 0, ii = children.length; i < ii; ++i) { children[i].attached(); } } /** * Triggers the detach for the view and its children. */ detached(): void { let controllers; let children; let i; let ii; if (this.isAttached) { this.isAttached = false; if (this.controller !== null) { this.controller.detached(); } controllers = this.controllers; for (i = 0, ii = controllers.length; i < ii; ++i) { controllers[i].detached(); } children = this.children; for (i = 0, ii = children.length; i < ii; ++i) { children[i].detached(); } } } }
AshleyGrant/templating
src/view.js
JavaScript
mit
7,895
Ext.define('SlateAdmin.store.progress.terms.Reports', { extend: 'Slate.store.progress.SectionTermReports', config: { autoLoad: false, autoSync: false, remoteFilter: true } });
SlateFoundation/slate-admin
sencha-workspace/SlateAdmin/app/store/progress/terms/Reports.js
JavaScript
mit
214
angular .module('app', [ 'app.core', 'app.startup', 'app.web' ]);
pyoung213/greenLight-starter
src/web/app/app.module.js
JavaScript
mit
98
"use strict"; var helpers = require("../../helpers/helpers"); exports["Africa/Blantyre"] = { "guess:by:offset" : helpers.makeTestGuess("Africa/Blantyre", { offset: true, expect: "Africa/Cairo" }), "guess:by:abbr" : helpers.makeTestGuess("Africa/Blantyre", { abbr: true, expect: "Africa/Khartoum" }), "1903" : helpers.makeTestYear("Africa/Blantyre", [ ["1903-02-28T21:49:39+00:00", "23:59:59", "LMT", -7820 / 60], ["1903-02-28T21:49:40+00:00", "23:49:40", "CAT", -120] ]) };
moment/moment-timezone
tests/zones/africa/blantyre.js
JavaScript
mit
486
/** * @Date 2016-11-10 * @Author xfworld * AmazeUI Upload 模版 * @param true:tableTemplate false:cardTemplate */ var AmazeuiUploadDelegateTemplate = function AmazeuiUploadDelegateTemplate(useDefTemplate) { this.useDefTemplate = useDefTemplate; } AmazeuiUploadDelegateTemplate.prototype.init = function() { if (this.useDefTemplate) { this.initTableTemplate(); } return this; } AmazeuiUploadDelegateTemplate.prototype.initContext = function() { var context = '<div class="am-form-group am-form-file am-upload-toggleBoarder">\ <button type="button" class="am-btn am-btn-primary am-btn-xs">\ <i class="am-icon-cloud-upload"></i>选择要上传的文件\ </button>\ <input id="selectFile" type="file" multiple />\ <div class="am-upload-parse">把文件拖这里试试</div>\ </div>\ <hr/>\ <ul width="100%" class="am-avg-sm-1 am-avg-md-3 am-avg-lg-6 am-thumbnails" id="_uList"></ul>\ <table class="am-table am-table-compact am-table-striped am-table-hover am-text-sm" id="_template"></table>'; return context; } AmazeuiUploadDelegateTemplate.prototype.cardTemplate = function(type) { var imageTpl = '<li>\ <div class="image">\ <img class="am-thumbnail" src="" alt="">\ </div>\ <div class="uploadInfo">\ <table class="am-table am-table-compact am-table-striped am-table-hover am-text-xs">\ <tr><td class="am-text-break"><span style="display:none" class="fileID"></span><span class="fileName"><text>-</text></span></td></tr>\ <tr><td><span class="imageSize">图片尺寸&nbsp;&nbsp;<text>-</text></span></td></tr>\ <tr><td><span class="fileSize"><span class="am-badge">文件大小<text>-</text></span></span></td></tr>\ <tr><td class="am-text-break"><span class="fileType"><span class="am-badge">文件类型<text>-</text></span></span></td></tr>\ <tr><td><span class="speed"><span class="am-badge am-badge-primary">上传速度<text>-</text></span></span></td></tr>\ <tr><td><span class="loaded"><span class="am-badge am-badge-secondary">上传详情<text>-</text></span></span></td></tr>\ <tr><td><div class="stage"><span class="am-badge am-badge-warning">初始化</span></div></td></tr>\ <tr>\ <td><div class="am-progress am-progress-striped am-active" style="display:none">\ <div class="am-progress-bar am-progress-bar-secondary" style="width: 40%;" >40%</div></div>\ </td>\ </tr>\ <tr><td class="am-text-middle"><button type="button" class="am-btn am-btn-danger am-round am-btn-xs"><i class="am-icon-remove"></i>移除</button><button type="button" class="am-btn am-btn-primary am-round am-btn-xs"><i class="am-icon-download"></i>下载</button></td></tr>\ </table>\ </div>\ </li>'; var otherTpl = '<li>\ <div class="uploadInfo">\ <table class="am-table am-table-compact am-table-striped am-table-hover am-text-xs">\ <tr><td class="am-text-break"><span style="display:none" class="fileID"></span><span class="fileName"><text>-</text></span></td></tr>\ <tr><td><span class="fileSize"><span class="am-badge">文件大小<text>-</text></span></span></td></tr>\ <tr><td class="am-text-break"><span class="fileType">文件类型<text>-</text></span></td></tr>\ <tr><td><span class="speed"><span class="am-badge am-badge-primary">上传速度<text>-</text></span></span></td></tr>\ <tr><td><span class="loaded"><span class="am-badge am-badge-secondary">上传详情<text>-</text></span></span></td></tr>\ <tr><td><div class="stage"><span class="am-badge am-badge-warning">初始化</span></div></td></tr>\ <tr>\ <td><div class="am-progress am-progress-striped am-active" style="display:none">\ <div class="am-progress-bar am-progress-bar-secondary" style="width: 40%;" >40%</div></div>\ </td>\ </tr>\ <tr class="am-text-middle"><td><button type="button" class="am-btn am-btn-danger am-round am-btn-xs"><i class="am-icon-remove"></i>移除</button><button type="button" class="am-btn am-btn-primary am-round am-btn-xs"><i class="am-icon-download"></i>下载</button></td></tr>\ </table>\ </div>\ </li>'; if (type == 'image') { return imageTpl; } else if (type == 'other') { return otherTpl; } } AmazeuiUploadDelegateTemplate.prototype.initTableTemplate = function() { var th = '<thead><tr><th>文件信息</th><th>上传情况</th><th>上传状态</th><th>操作项</th></tr></thead><tbody></tbody>'; $('#_template').append(th); } // 设置图片类型文件View模板 AmazeuiUploadDelegateTemplate.prototype.setImageCardTemplate = function(data) { var tpl = this.cardTemplate('image'); // console.log(data.file.name+" :"+data.fileType); $('#_uList').append(tpl); var thisLi = $('#_uList li').last(); //eq(data.file.index); thisLi.find('.image img').attr('src', data.fileReaderiImage.target.result).each(function() { if ($(this).width() > $(this).parent().width()) { $(this).width("100%"); } }); thisLi.find('.fileName text').text(data.file.name); thisLi.find('.imageSize text').text(data.newImage.width + ' X ' + data.newImage.height); thisLi.find('.fileSize text').text(data.fileSize); thisLi.find('.fileType text').text(data.fileType); } // 设置其他文件类型View模板 AmazeuiUploadDelegateTemplate.prototype.setotherCardTemplate = function(data) { // console.log(data.file.name+" :"+data.fileType); var tpl = this.cardTemplate('other'); $('#_uList').append(tpl); var thisLi = $('#_uList li').last(); //.eq(data.file.index); thisLi.find('.fileName text').text(data.file.name); thisLi.find('.fileSize text').text(data.fileSize); thisLi.find('.fileType text').text(data.fileType); } //设定默认模版行 AmazeuiUploadDelegateTemplate.prototype.getTableRowTemplate = function() { var rowTemplate = '<tr>\ <td width="40%">\ <span style="display:none" class="fileID"></span>\ <span class="fileName"><label class="am-text-xs"><text>-</text><label></span><br/>\ <span class="fileSize"><span class="am-badge">文件大小<text>-</text></span></span>\ </td>\ <td width="20%">\ <span class="speed"><span class="am-badge am-badge-primary">速度<text>-</text></span></span><br />\ <span class="loaded"><span class="am-badge am-badge-secondary">详情<text>-</text></span></span>\ </td>\ <td width="30%">\ <div class="stage"><span class="am-badge am-badge-warning">初始化</span></div>\ <div class="am-progress am-progress-striped am-active" style="display:none">\ <div class="am-progress-bar am-progress-bar-secondary" style="width: 10%;" >10%</div>\ </div>\ </td>\ <td width="10%" class="am-text-middle"><button type="button" class="am-btn am-btn-danger am-round am-btn-xs"><i class="am-icon-remove"></i>移除</button><button type="button" class="am-btn am-btn-primary am-round am-btn-xs"><i class="am-icon-download"></i>下载</button></td>\ </tr>'; return rowTemplate; } //创建默认模版行记录 AmazeuiUploadDelegateTemplate.prototype.createTableRowData = function(data) { console.log(data); var tpl = this.getTableRowTemplate(); $('#_template tbody').append(tpl); var thisLi = $('#_template tbody tr').eq(data.file.index); thisLi.find('.fileName text').text(data.file.name); thisLi.find('.fileSize text').text(data.fileSize); thisLi.find('am-btn').hide(); }
cjbi/wetech-cms
wetech-web/src/main/webapp/resources/amazeui/assets/js/amazeui.upload.template2.js
JavaScript
mit
7,531
Package.describe({ name: 'meteorhacks:meteorx', summary: 'Proxy for getting another meteorx fork', version: '1.4.1' }); Package.onUse((api) => { api.export('MeteorX'); api.use([ 'lamhieu:meteorx', ]); });
wekan/wekan
packages/meteorx/package.js
JavaScript
mit
223
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _rule = require('../rule/'); var _rule2 = _interopRequireDefault(_rule); /** * Validates a function. * * @param rule The validation rule. * @param value The value of the field on the source object. * @param callback The callback function. * @param source The source object being validated. * @param options The validation options. * @param options.messages The validation messages. */ function method(rule, value, callback, source, options) { var errors = []; var validate = rule.required || !rule.required && source.hasOwnProperty(rule.field); if (validate) { if (value === undefined && !rule.required) { return callback(); } _rule2['default'].required(rule, value, source, errors, options); if (value !== undefined) { _rule2['default'].type(rule, value, source, errors, options); } } callback(errors); } exports['default'] = method; module.exports = exports['default'];
rekyyang/ArtificalLiverCloud
node_modules/rc-form-validation/node_modules/async-validator/lib/validator/method.js
JavaScript
mit
1,116
import process from 'node:process'; import arrgv from 'arrgv'; export default function normalizeNodeArguments(fromConf = [], fromArgv = '') { let parsedArgv = []; if (fromArgv !== '') { try { parsedArgv = arrgv(fromArgv); } catch { throw new Error('Could not parse `--node-arguments` value. Make sure all strings are closed and backslashes are used correctly.'); } } return [...process.execArgv, ...fromConf, ...parsedArgv]; }
sindresorhus/ava
lib/node-arguments.js
JavaScript
mit
446
import * as SuggestedFeedsActions from 'actions/SuggestedFeeds' function SuggestedFeeds(state = [], action) { switch (action.type) { case SuggestedFeedsActions.LOAD: if (action.response) return [...action.response] return state case SuggestedFeedsActions.FOLLOW: case SuggestedFeedsActions.REMOVE: if (action.data) return state.filter(suggestion => suggestion.id !== action.data.feed_id) return state } return state } export default SuggestedFeeds
mlapierre/Winds
assets/js/reducers/SuggestedFeeds.js
JavaScript
mit
535
'use strict'; describe('Service: RegionRepositoryService', function () { // load the service's module beforeEach(module('troutDashApp')); // instantiate service var RegionRepositoryService; beforeEach(inject(function (_RegionRepositoryService_) { RegionRepositoryService = _RegionRepositoryService_; })); it('should do something', function () { expect(!!RegionRepositoryService).toBe(true); }); });
standersnerdery/trout-dash_frontend
test/spec/services/regionrepositoryservice.js
JavaScript
mit
428
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _trading = require('./trading'); Object.keys(_trading).forEach(function (key) { if (key === "default" || key === "__esModule") return; Object.defineProperty(exports, key, { enumerable: true, get: function get() { return _trading[key]; } }); }); var _classifying = require('./classifying'); Object.keys(_classifying).forEach(function (key) { if (key === "default" || key === "__esModule") return; Object.defineProperty(exports, key, { enumerable: true, get: function get() { return _classifying[key]; } }); }); var _billboard = require('./billboard'); Object.keys(_billboard).forEach(function (key) { if (key === "default" || key === "__esModule") return; Object.defineProperty(exports, key, { enumerable: true, get: function get() { return _billboard[key]; } }); });
EmmaIshta/QUANTAXIS
QUANTAXIS_Webkit/backend/methods/stock/lib/index.js
JavaScript
mit
928
//>>built define({insertEntity:"Masukkan Simbol"});
ycabon/presentations
2020-devsummit/arcgis-js-api-road-ahead/js-api/dojox/editor/plugins/nls/id/InsertEntity.js
JavaScript
mit
51
module.exports = { toHex: function (chinese) { var buf = new Buffer(chinese); var result = ''; for (var i = 0; i < buf.length; i++) { result += buf[i].toString(16); } return result; }, toChinese: function (hex) { if (typeof hex !== 'string') { throw new Error('hex expect a string'); } return new Buffer(hex, 'hex').toString(); } };
tsq-old/hex-chinese
index.js
JavaScript
mit
363
// ToggleDiv window.c.ToggleDiv = (function(m, h){ return { toggler: function() { return h.toggleProp('none', 'block'); }, controller: function(args) { return { vm: { display: args.display } }; }, view: function(ctrl, args) { return m('.toggleDiv', {style: {'transition': 'all .1s ease-out', 'overflow': 'hidden', 'display': ctrl.vm.display()}}, [ args.content]); } }; }(window.m, window.c.h));
rokibulhassan/catarse
vendor/assets/components/catarse.js/src/c/toggle-div.js
JavaScript
mit
483
'use strict'; var path = require('path'), upstreamParse5 = require('parse5'), testUtils = require('../test_utils'); //HACK: https://github.com/bestiejs/benchmark.js/issues/51 /* global upstreamParser, workingCopy, micro, runMicro */ global.upstreamParser = new upstreamParse5.Parser(); global.workingCopy = require('../../lib'); global.micro = testUtils .loadTreeConstructionTestData([path.join(__dirname, '../data/tree_construction')], workingCopy.treeAdapters.default) .filter(function (test) { //NOTE: this test caused stack overflow in parse5 v1.x return test.input !== '<button><p><button>'; }) .map(function (test) { return { html: test.input, fragmentContext: test.fragmentContext }; }); global.runMicro = function (parser, newAPI) { for (var i = 0; i < micro.length; i++) { if (micro[i].fragmentContext) { if (newAPI) parser.parseFragment(micro[i].fragmentContext, micro[i].html); else parser.parseFragment(micro[i].html, micro[i].fragmentContext); } else parser.parse(micro[i].html); } }; module.exports = { name: 'parse5 regression benchmark - MICRO', tests: [ { name: 'Working copy', fn: function () { runMicro(workingCopy, true); } }, { name: 'Upstream', fn: function () { runMicro(upstreamParser); } } ] };
sakagg/parse5
test/benchmark/bench-micro.js
JavaScript
mit
1,560
/* * Copyright 2016-2017 Hewlett Packard Enterprise Development Company, L.P. * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. */ define([ 'underscore', 'backbone', 'find/app/page/search/filters/parametric/filtered-parametric-fields-collection' ], function(_, Backbone, FilteredParametricFieldsCollection) { 'use strict'; const Animal = {CAT: 'CAT', DOG: 'DOG', TIGER: 'TIGER', UNICORN: 'UNICORN'}; const MockCollection = Backbone.Collection.extend({ spy1: function() { }, spy2: function() { }, spy3: function() { } }); describe('Filtered parametric fields collection', function() { beforeEach(function() { spyOn(FilteredParametricFieldsCollection.prototype, 'onAdd').and.callThrough(); spyOn(FilteredParametricFieldsCollection.prototype, 'onRemove').and.callThrough(); spyOn(FilteredParametricFieldsCollection.prototype, 'onChange').and.callThrough(); spyOn(FilteredParametricFieldsCollection.prototype, 'onReset').and.callThrough(); spyOn(FilteredParametricFieldsCollection.prototype, 'filterModels').and.callThrough(); this.parametricFieldsCollection = new MockCollection([ {id: 'Rambo', displayName: 'Rambo', type: 'Parametric'}, {id: 'Millie', displayName: 'Millie', type: 'Parametric'}, {id: 'Maisey', displayName: 'Maisey', type: 'Parametric'}, {id: 'Hobbes', displayName: 'Hobbes', type: 'Parametric'} ]); this.parametricCollection = new Backbone.Collection([ { id: 'Rambo', displayName: 'Rambo', totalValues: 1, values: [{value: Animal.CAT, displayValue: Animal.CAT}], type: 'Parametric' }, { id: 'Millie', displayName: 'Millie', totalValues: 1, values: [{value: Animal.CAT, displayValue: Animal.CAT}], type: 'Parametric' }, { id: 'Maisey', displayName: 'Maisey', totalValues: 1, values: [{value: Animal.DOG, displayValue: Animal.DOG}], type: 'Parametric' }, { id: 'Hobbes', displayName: 'Hobbes', totalValues: 1, values: [{value: Animal.TIGER, displayValue: Animal.TIGER}], type: 'Parametric' } ]); this.filteredParametricCollection = new Backbone.Collection(this.parametricCollection.models); this.filterModel = new Backbone.Model({text: ''}); spyOn(this.parametricFieldsCollection, 'spy1').and.callThrough(); spyOn(this.parametricFieldsCollection, 'spy2').and.callThrough(); spyOn(this.parametricFieldsCollection, 'spy3').and.callThrough(); const queryModel = new Backbone.Model(); queryModel.getIsoDate = _.noop; this.filteredParametricFieldsCollection = new FilteredParametricFieldsCollection([], { queryModel: queryModel, parametricCollection: this.parametricCollection, filteredParametricCollection: this.filteredParametricCollection, collection: this.parametricFieldsCollection, filterModel: this.filterModel, collectionFunctions: ['spy1', 'spy2', 'spy3'] }); }); it('should have 4 elements in the filtered collection', function() { expect(this.filteredParametricFieldsCollection.length).toEqual(4); }); describe('after filtering by the letter "M"', function() { beforeEach(function() { this.filterModel.set({text: 'm'}); this.filteredParametricFieldsCollection.valueRestrictedParametricCollection.trigger('sync'); }); it('should show 3 models when the filter text is set to "m"', function() { expect(this.filteredParametricFieldsCollection.length).toEqual(3); expect(this.filteredParametricFieldsCollection.at(0)) .toBe(this.parametricFieldsCollection.at(0)); expect(this.filteredParametricFieldsCollection.at(1)) .toBe(this.parametricFieldsCollection.at(1)); expect(this.filteredParametricFieldsCollection.at(2)) .toBe(this.parametricFieldsCollection.at(2)); }); it('should set 3 parametric models', function() { expect(this.filteredParametricCollection.length).toEqual(3); }); }); describe('after filtering by the letter "O"', function() { beforeEach(function() { this.filterModel.set({text: 'o'}); this.filteredParametricFieldsCollection.valueRestrictedParametricCollection.set([ { id: 'Maisey', displayName: 'Maisey', totalValues: 1, values: [{value: Animal.DOG, displayValue: Animal.DOG}], type: 'Parametric' } ]); this.filteredParametricFieldsCollection.valueRestrictedParametricCollection.trigger('sync'); }); it('should show 3 models when the filter text is set to "o"', function() { expect(this.filteredParametricFieldsCollection.length).toEqual(3); expect(this.filteredParametricFieldsCollection.at(0)) .toBe(this.parametricFieldsCollection.at(0)); expect(this.filteredParametricFieldsCollection.at(1)) .toBe(this.parametricFieldsCollection.at(2)); expect(this.filteredParametricFieldsCollection.at(2)) .toBe(this.parametricFieldsCollection.at(3)); }); it('should set 3 parametric models', function() { expect(this.filteredParametricCollection.length).toEqual(3); }); describe('after parametric collection update', function() { beforeEach(function() { this.parametricCollection.set([ { id: 'Rambo', displayName: 'Rambo', totalValues: 1, values: [{value: Animal.CAT, displayValue: Animal.CAT}], type: 'Parametric' }, { id: 'Hobbes', displayName: 'Hobbes', totalValues: 1, values: [{value: Animal.TIGER, displayValue: Animal.TIGER}], type: 'Parametric' } ]); this.parametricCollection.trigger('sync'); this.filteredParametricFieldsCollection .valueRestrictedParametricCollection.set([]); this.filteredParametricFieldsCollection .valueRestrictedParametricCollection.trigger('sync'); }); it('should show 2 models', function() { expect(this.filteredParametricFieldsCollection.length).toEqual(2); expect(this.filteredParametricFieldsCollection.at(0)) .toBe(this.parametricFieldsCollection.at(0)); expect(this.filteredParametricFieldsCollection.at(1)) .toBe(this.parametricFieldsCollection.at(3)); }); it('should set 2 parametric models', function() { expect(this.filteredParametricCollection.length).toEqual(2); }); }); }); describe('after filtering by the letters "Hobbes"', function() { beforeEach(function() { this.filterModel.set({text: 'Hobbes'}); this.filteredParametricFieldsCollection.valueRestrictedParametricCollection.trigger('sync'); }); it('should show 1 model when the filter text is set to "Hobbes"', function() { expect(this.filteredParametricFieldsCollection.length).toEqual(1); expect(this.filteredParametricFieldsCollection.at(0)) .toBe(this.parametricFieldsCollection.at(3)); }); it('should set 1 parametric model', function() { expect(this.filteredParametricCollection.length).toEqual(1); }); }); describe('When calling the collection functions', function() { beforeEach(function() { this.filteredParametricFieldsCollection.spy1(); this.filteredParametricFieldsCollection.spy2(1, 2, 3); }); it('should have called the original functions', function() { expect(this.parametricFieldsCollection.spy1) .toHaveBeenCalled(); expect(this.parametricFieldsCollection.spy2) .toHaveBeenCalled(); expect(this.parametricFieldsCollection.spy3) .not.toHaveBeenCalled(); expect(this.parametricFieldsCollection.spy2.calls.argsFor(0)).toEqual([1, 2, 3]); }) }); describe('After adding a model to the original collection', function() { beforeEach(function() { this.parametricFieldsCollection.add(new Backbone.Model({ id: 'Twilight', displayName: 'Twilight', type: 'Parametric' })); }); it('should have 5 models', function() { expect(this.filteredParametricFieldsCollection.length).toEqual(5); }); it('should have called onAdd', function() { expect(FilteredParametricFieldsCollection.prototype.onAdd) .toHaveBeenCalled(); }); }); describe('After removing a model from the original collection', function() { beforeEach(function() { this.parametricFieldsCollection.remove(this.parametricFieldsCollection.at(0)); }); it('filtering collection should have 3 models', function() { expect(this.filteredParametricFieldsCollection.length).toEqual(3); }); it('should have called onRemove', function() { expect(FilteredParametricFieldsCollection.prototype.onRemove) .toHaveBeenCalled(); }); }); describe('After changing a model in the original collection', function() { beforeEach(function() { this.parametricFieldsCollection.findWhere({displayName: 'Rambo'}).set({displayName: 'Rocky'}); }); it('should update the model in the filtering collection', function() { expect(this.filteredParametricFieldsCollection.findWhere({id: 'Rambo'}).get('displayName')) .toEqual('Rocky'); }); it('should have called onChange', function() { expect(FilteredParametricFieldsCollection.prototype.onChange) .toHaveBeenCalled(); }); }); describe('After resetting the original collection', function() { beforeEach(function() { this.parametricFieldsCollection.reset([{ id: 'Luna', displayName: 'Luna', type: 'Parametric' }]); }); it('should have called onReset', function() { expect(FilteredParametricFieldsCollection.prototype.onReset) .toHaveBeenCalled(); }); it('should update the filtering collection', function() { expect(this.filteredParametricFieldsCollection.length).toEqual(1); }); it('should contain the new entry', function() { expect(this.filteredParametricFieldsCollection.at(0)) .toBe(this.parametricFieldsCollection.at(0)); }); }); }); });
hpe-idol/find
webapp/core/src/test/js/spec/app/page/search/filters/parametric/filtered-parametric-fields-collection.js
JavaScript
mit
12,732
export default class Tweet { constructor (tweet) { this._id = tweet._id this.embed_id = tweet.embed_id this.type = 'Tweet' } }
SentiSocial/frontend
src/types/tweet.js
JavaScript
mit
143