code
stringlengths
2
1.05M
const path = require('path') exports.name = 'eject-html' exports.cli = api => { api.cli .command('eject-html [out-file]', 'Eject the default HTML file') .option('--overwrite', 'Overwrite exiting file') .action(async (outFile = 'public/index.html', options) => { const fs = require('fs-extra') if ( !options.overwrite && (await fs.pathExists(api.resolveCwd(outFile))) ) { return api.logger.error( `${outFile} already existing, try --overwrite flag if you want to update it` ) } await fs.copy( path.join(__dirname, '../webpack/default-template.html'), api.resolveCwd(outFile) ) api.logger.done(`Ejected to ${outFile}`) }) }
/* jshint -W097 */// jshint strict:false /*jslint node: true */ "use strict"; var winston = require('winston'); var fs = require('fs'); var path = require('path'); var os = require('os'); //require('winston-syslog').Syslog; var logger = function (level, files, noStdout, prefix) { var userOptions = {}; var options = { transports: [] }; var defaultMaxSize;// = 10 * 1024 * 1024; var dailyRotateFile = null; if (typeof files == 'string') files = [files]; files = files || []; var isNpm = (__dirname.replace(/\\/g, '/').toLowerCase().indexOf('node_modules/iobroker.js-controller') != -1); if (typeof level == 'object') { userOptions = JSON.parse(JSON.stringify(level)); level = userOptions.level; prefix = userOptions.prefix; noStdout = userOptions.noStdout; if (userOptions.prefix !== undefined) delete userOptions.prefix; if (userOptions.transport) { for (var f in userOptions.transport) { if (userOptions.transport[f].type == 'file' && userOptions.transport[f].enabled !== false) { userOptions.transport[f].filename = userOptions.transport[f].filename || 'log/iobroker'; if (!userOptions.transport[f].fileext && userOptions.transport[f].filename.indexOf('.log') == -1) { userOptions.transport[f].fileext = '.log'; } userOptions.transport[f].filename = path.normalize(__dirname + (isNpm ? '/../../../' : '/../') + userOptions.transport[f].filename); userOptions.transport[f].label = prefix || ''; userOptions.transport[f].level = userOptions.transport[f].level || level; userOptions.transport[f].json = (userOptions.transport[f].json !== undefined) ? userOptions.transport[f].json : false; userOptions.transport[f].silent = (userOptions.transport[f].silent !== undefined) ? userOptions.transport[f].silent : false; userOptions.transport[f].colorize = (userOptions.transport[f].colorize !== undefined) ? userOptions.transport[f].colorize : ((userOptions.colorize === undefined) ? true : userOptions.colorize); // userOptions.transport[f].maxsize = (userOptions.transport[f].maxsize !== undefined) ? userOptions.transport[f].maxsize : defaultMaxSize; userOptions.transport[f].timestamp = timestamp; userOptions.transport[f].datePattern = '.yyyy-MM-dd' + (userOptions.transport[f].fileext || '') ; var _dailyRotateFile = new (winston.transports.DailyRotateFile)(userOptions.transport[f]); if (!dailyRotateFile) dailyRotateFile = _dailyRotateFile; options.transports.push(_dailyRotateFile); } } } } else { for (var i = 0; i < files.length; i++) { var _dailyRotateFile = new (winston.transports.DailyRotateFile)({ 'filename': path.normalize(isNpm ? __dirname + '/../../../log/' + files[i] : __dirname + '/../log/' + files[i]), 'datePattern': '.yyyy-MM-dd.log', 'json': false, // If true, messages will be logged as JSON (default true). 'level': level, 'silent': false, 'colorize': (userOptions.colorize === undefined) ? true : userOptions.colorize, 'timestamp': timestamp, 'label': prefix || '', 'maxsize': defaultMaxSize }); if (!dailyRotateFile) dailyRotateFile = _dailyRotateFile; options.transports.push(_dailyRotateFile); } } if (!noStdout) { options.transports.push(new (winston.transports.Console)({ 'level': level, 'silent': false, 'colorize': (userOptions.colorize === undefined) ? true : userOptions.colorize, 'timestamp': timestamp, 'label': prefix ||'' })); } var log = new (winston.Logger)(options); log.getFileName = function () { return dailyRotateFile.dirname + '/' + dailyRotateFile._getFile(); }; log.activateDateChecker = function (isEnabled, daysCount) { if (!isEnabled && this._fileChecker) { clearInterval(this._fileChecker); } else if (isEnabled && !this._fileChecker) { if (!daysCount) daysCount = 3; // Check every hour this._fileChecker = setInterval(function () { if (dailyRotateFile && fs.existsSync(dailyRotateFile.dirname)) { var files = fs.readdirSync(dailyRotateFile.dirname); var for3days = new Date(); for3days.setDate(for3days.getDate() - daysCount); for (var i = 0; i < files.length; i++) { var match = files[i].match(/.+\.(\d+-\d+-\d+)/); if (match) { var date = new Date(match[1]); if (date < for3days) { // delete file try { dailyRotateFile.log('info', 'host.' + os.hostname() + ' Delete log file ' + files[i]); fs.unlinkSync(dailyRotateFile.dirname + '/' + files[i]); } catch (e) { dailyRotateFile.log('error', 'host.' + os.hostname() + ' Cannot delete file "' + path.normalize(dailyRotateFile.dirname + '/' + files[i]) + '": ' + e); } } } } } }, 3600000); // every hour } } return log; }; function timestamp() { var ts = new Date(); var result = ts.getFullYear() + '-'; var value = ts.getMonth() + 1; if (value < 10) value = '0' + value; result += value + '-'; value = ts.getDate(); if (value < 10) value = '0' + value; result += value + ' '; value = ts.getHours(); if (value < 10) value = '0' + value; result += value + ':'; value = ts.getMinutes(); if (value < 10) value = '0' + value; result += value + ':'; value = ts.getSeconds(); if (value < 10) value = '0' + value; result += value + '.'; value = ts.getMilliseconds(); if (value < 10) { value = '00' + value; } else if (value < 100) { value = '0' + value; } result += value + ' '; return result; } module.exports = logger;
module.exports = (event, model) => { const _ = require('lodash'); const sequence = require('../../lib/promise/sequence'); const api = require('../../api'); const apiVersion = model.get('api_version') || 'v2'; const resourceName = event.match(/(\w+)\./)[1]; const docName = `${resourceName}s`; const ops = []; if (Object.keys(model.attributes).length) { ops.push(() => { let frame = {options: {previous: false, context: {user: true}}}; if (['posts', 'pages'].includes(docName)) { frame.options.formats = ['mobiledoc', 'html', 'plaintext']; frame.options.withRelated = ['tags', 'authors']; } return api.shared .serializers .handle .output(model, {docName: docName, method: 'read'}, api[apiVersion].serializers.output, frame) .then(() => { return frame.response[docName][0]; }); }); } else { ops.push(() => { return Promise.resolve({}); }); } if (Object.keys(model._previousAttributes).length) { ops.push(() => { const frame = {options: {previous: true, context: {user: true}}}; if (['posts', 'pages'].includes(docName)) { frame.options.formats = ['mobiledoc', 'html', 'plaintext']; frame.options.withRelated = ['tags', 'authors']; } return api.shared .serializers .handle .output(model, {docName: docName, method: 'read'}, api[apiVersion].serializers.output, frame) .then(() => { return frame.response[docName][0]; }); }); } else { ops.push(() => { return Promise.resolve({}); }); } return sequence(ops) .then((results) => { const current = results[0]; const previous = results[1]; const changed = model._changed ? Object.keys(model._changed) : {}; const payload = { [docName.replace(/s$/, '')]: { current: current, previous: _.pick(previous, changed) } }; // @TODO: remove in v3 // @NOTE: Our webhook format has changed, we still have to support the old format for subscribers events if ('subscriber.added' === event) { payload[docName] = [current]; } if ('subscriber.deleted' === event) { payload[docName] = [previous]; } return payload; }); };
module.exports={A:{A:{"2":"K C G E B A WB"},B:{"2":"D u Y I M H"},C:{"1":"0 1 2 3 5 6 7 z F J K C G E B A D u Y I M H N O P Q R S T U V W X w Z a b c d e f L h i j k l m n o p q r s t y v g SB RB","2":"UB"},D:{"1":"0 1 2 3 5 6 7 F J K C G E B A D u Y I M H N O P Q R S T U V W X w Z a b c d e f L h i j k l m n o p q r s t y v g GB BB DB VB EB"},E:{"1":"J K C G E B A HB IB JB KB LB MB","2":"F FB AB"},F:{"1":"I M H N O P Q R S T U V W X w Z a b c d e f L h i j k l m n o p q r s t","2":"8 9 E A D NB OB PB QB TB x"},G:{"1":"4 G A XB YB ZB aB bB cB dB eB","16":"AB CB"},H:{"2":"fB"},I:{"1":"v kB lB","2":"gB hB iB","132":"4 z F jB"},J:{"1":"B","2":"C"},K:{"1":"L","2":"8 9 B A D x"},L:{"1":"BB"},M:{"1":"g"},N:{"2":"B A"},O:{"1":"mB"},P:{"1":"F J"},Q:{"1":"nB"},R:{"1":"oB"}},B:7,C:"Improved kerning pairs & ligatures"};
'use strict'; /* jshint node:true, undef:true, unused:true */ const Rollup = require('broccoli-rollup'); const Babel = require('broccoli-babel-transpiler'); const merge = require('broccoli-merge-trees'); const uglify = require('broccoli-uglify-js'); const version = require('git-repo-version'); const watchify = require('broccoli-watchify'); const concat = require('broccoli-concat'); const fs = require('fs'); const stew = require('broccoli-stew'); const find = stew.find; const mv = stew.mv; const rename = stew.rename; const env = stew.env; const map = stew.map; const lib = find('lib'); // test stuff const testDir = find('test'); const testFiles = find('test/{index.html,worker.js}'); const json3 = mv(find('node_modules/json3/lib/{json3.js}'), 'node_modules/json3/lib/', 'test/'); // mocha doesn't browserify correctly const mocha = mv(find('node_modules/mocha/mocha.{js,css}'), 'node_modules/mocha/', 'test/'); const testVendor = merge([ json3, mocha ]); const es5 = new Babel(lib, { plugins: [ 'transform-es2015-arrow-functions', 'transform-es2015-computed-properties', 'transform-es2015-shorthand-properties', 'transform-es2015-template-literals', 'transform-es2015-parameters', 'transform-es2015-destructuring', 'transform-es2015-spread', 'transform-es2015-block-scoping', 'transform-es2015-constants', ['transform-es2015-classes', { loose: true }], 'babel6-plugin-strip-class-callcheck' ] }); function rollupConfig(entry) { return new Rollup(es5, { rollup: { input: 'lib/' + entry, output: [ { format: 'umd', name: 'ES6Promise', file: entry, sourcemap: 'inline' } ] } }); } // build RSVP itself const es6Promise = rollupConfig('es6-promise.js') const es6PromiseAuto = rollupConfig('es6-promise.auto.js') const testBundle = watchify(merge([ mv(es6Promise, 'test'), testDir ]), { browserify: { debug: true, entries: ['./test/index.js'] } }); const header = stew.map(find('config/versionTemplate.txt'), content => content.replace(/VERSION_PLACEHOLDER_STRING/, version())); function concatAs(outputFile) { return merge([ concat(merge([es6Promise, header]), { headerFiles: ['config/versionTemplate.txt'], inputFiles: ['es6-promise.js'], outputFile: outputFile }), concat(merge([es6PromiseAuto, header]), { headerFiles: ['config/versionTemplate.txt'], inputFiles: ['es6-promise.auto.js'], outputFile: outputFile.replace('es6-promise', 'es6-promise.auto'), }), ]); } function production() { let result; env('production', () => { result = uglify(concatAs('es6-promise.min.js'), { compress: true, mangle: true, }); }) return result; } function development() { return concatAs('es6-promise.js'); } module.exports = merge([ merge([ production(), development(), ].filter(Boolean)), // test stuff testFiles, testVendor, mv(testBundle, 'test') ]);
"use strict"; /* global describe, it */ var should = require( "should" ); var Postal = require( "../../../lib/common" ); describe( "Match Object:", function () { it( "Constructor - No Config", function () { var postal = new Postal(); var match = postal.match; should.exist( match ); } ); } );
/** * EditorCommands.js * * Copyright, Moxiecode Systems AB * Released under LGPL License. * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ (function(tinymce) { // Added for compression purposes var each = tinymce.each, undef, TRUE = true, FALSE = false; /** * This class enables you to add custom editor commands and it contains * overrides for native browser commands to address various bugs and issues. * * @class tinymce.EditorCommands */ tinymce.EditorCommands = function(editor) { var dom = editor.dom, selection = editor.selection, commands = {state: {}, exec : {}, value : {}}, settings = editor.settings, formatter = editor.formatter, bookmark; /** * Executes the specified command. * * @method execCommand * @param {String} command Command to execute. * @param {Boolean} ui Optional user interface state. * @param {Object} value Optional value for command. * @return {Boolean} true/false if the command was found or not. */ function execCommand(command, ui, value) { var func; command = command.toLowerCase(); if (func = commands.exec[command]) { func(command, ui, value); return TRUE; } return FALSE; }; /** * Queries the current state for a command for example if the current selection is "bold". * * @method queryCommandState * @param {String} command Command to check the state of. * @return {Boolean/Number} true/false if the selected contents is bold or not, -1 if it's not found. */ function queryCommandState(command) { var func; command = command.toLowerCase(); if (func = commands.state[command]) return func(command); return -1; }; /** * Queries the command value for example the current fontsize. * * @method queryCommandValue * @param {String} command Command to check the value of. * @return {Object} Command value of false if it's not found. */ function queryCommandValue(command) { var func; command = command.toLowerCase(); if (func = commands.value[command]) return func(command); return FALSE; }; /** * Adds commands to the command collection. * * @method addCommands * @param {Object} command_list Name/value collection with commands to add, the names can also be comma separated. * @param {String} type Optional type to add, defaults to exec. Can be value or state as well. */ function addCommands(command_list, type) { type = type || 'exec'; each(command_list, function(callback, command) { each(command.toLowerCase().split(','), function(command) { commands[type][command] = callback; }); }); }; // Expose public methods tinymce.extend(this, { execCommand : execCommand, queryCommandState : queryCommandState, queryCommandValue : queryCommandValue, addCommands : addCommands }); // Private methods function execNativeCommand(command, ui, value) { if (ui === undef) ui = FALSE; if (value === undef) value = null; return editor.getDoc().execCommand(command, ui, value); }; function isFormatMatch(name) { return formatter.match(name); }; function toggleFormat(name, value) { formatter.toggle(name, value ? {value : value} : undef); }; function storeSelection(type) { bookmark = selection.getBookmark(type); }; function restoreSelection() { selection.moveToBookmark(bookmark); }; // Add execCommand overrides addCommands({ // Ignore these, added for compatibility 'mceResetDesignMode,mceBeginUndoLevel' : function() {}, // Add undo manager logic 'mceEndUndoLevel,mceAddUndoLevel' : function() { editor.undoManager.add(); }, 'Cut,Copy,Paste' : function(command) { var doc = editor.getDoc(), failed; // Try executing the native command try { execNativeCommand(command); } catch (ex) { // Command failed failed = TRUE; } // Present alert message about clipboard access not being available if (failed || !doc.queryCommandSupported(command)) { if (tinymce.isGecko) { editor.windowManager.confirm(editor.getLang('clipboard_msg'), function(state) { if (state) open('http://www.mozilla.org/editor/midasdemo/securityprefs.html', '_blank'); }); } else editor.windowManager.alert(editor.getLang('clipboard_no_support')); } }, // Override unlink command unlink : function(command) { if (selection.isCollapsed()) selection.select(selection.getNode()); execNativeCommand(command); selection.collapse(FALSE); }, // Override justify commands to use the text formatter engine 'JustifyLeft,JustifyCenter,JustifyRight,JustifyFull' : function(command) { var align = command.substring(7); // Remove all other alignments first each('left,center,right,full'.split(','), function(name) { if (align != name) formatter.remove('align' + name); }); toggleFormat('align' + align); execCommand('mceRepaint'); }, // Override list commands to fix WebKit bug 'InsertUnorderedList,InsertOrderedList' : function(command) { var listElm, listParent; execNativeCommand(command); // WebKit produces lists within block elements so we need to split them // we will replace the native list creation logic to custom logic later on // TODO: Remove this when the list creation logic is removed listElm = dom.getParent(selection.getNode(), 'ol,ul'); if (listElm) { listParent = listElm.parentNode; // If list is within a text block then split that block if (/^(H[1-6]|P|ADDRESS|PRE)$/.test(listParent.nodeName)) { storeSelection(); dom.split(listParent, listElm); restoreSelection(); } } }, // Override commands to use the text formatter engine 'Bold,Italic,Underline,Strikethrough,Superscript,Subscript' : function(command) { toggleFormat(command); }, // Override commands to use the text formatter engine 'ForeColor,HiliteColor,FontName' : function(command, ui, value) { toggleFormat(command, value); }, FontSize : function(command, ui, value) { var fontClasses, fontSizes; // Convert font size 1-7 to styles if (value >= 1 && value <= 7) { fontSizes = tinymce.explode(settings.font_size_style_values); fontClasses = tinymce.explode(settings.font_size_classes); if (fontClasses) value = fontClasses[value - 1] || value; else value = fontSizes[value - 1] || value; } toggleFormat(command, value); }, RemoveFormat : function(command) { formatter.remove(command); }, mceBlockQuote : function(command) { toggleFormat('blockquote'); }, FormatBlock : function(command, ui, value) { return toggleFormat(value || 'p'); }, mceCleanup : function() { var bookmark = selection.getBookmark(); editor.setContent(editor.getContent({cleanup : TRUE}), {cleanup : TRUE}); selection.moveToBookmark(bookmark); }, mceRemoveNode : function(command, ui, value) { var node = value || selection.getNode(); // Make sure that the body node isn't removed if (node != editor.getBody()) { storeSelection(); editor.dom.remove(node, TRUE); restoreSelection(); } }, mceSelectNodeDepth : function(command, ui, value) { var counter = 0; dom.getParent(selection.getNode(), function(node) { if (node.nodeType == 1 && counter++ == value) { selection.select(node); return FALSE; } }, editor.getBody()); }, mceSelectNode : function(command, ui, value) { selection.select(value); }, mceInsertContent : function(command, ui, value) { var parser, serializer, parentNode, rootNode, fragment, args, marker, nodeRect, viewPortRect, rng, node, node2, bookmarkHtml, viewportBodyElement; //selection.normalize(); // Setup parser and serializer parser = editor.parser; serializer = new tinymce.html.Serializer({}, editor.schema); bookmarkHtml = '<span id="mce_marker" data-mce-type="bookmark">\uFEFF</span>'; // Run beforeSetContent handlers on the HTML to be inserted args = {content: value, format: 'html'}; selection.onBeforeSetContent.dispatch(selection, args); value = args.content; // Add caret at end of contents if it's missing if (value.indexOf('{$caret}') == -1) value += '{$caret}'; // Replace the caret marker with a span bookmark element value = value.replace(/\{\$caret\}/, bookmarkHtml); // Insert node maker where we will insert the new HTML and get it's parent if (!selection.isCollapsed()) editor.getDoc().execCommand('Delete', false, null); parentNode = selection.getNode(); // Parse the fragment within the context of the parent node args = {context : parentNode.nodeName.toLowerCase()}; fragment = parser.parse(value, args); // Move the caret to a more suitable location node = fragment.lastChild; if (node.attr('id') == 'mce_marker') { marker = node; for (node = node.prev; node; node = node.walk(true)) { if (node.type == 3 || !dom.isBlock(node.name)) { node.parent.insert(marker, node, node.name === 'br'); break; } } } // If parser says valid we can insert the contents into that parent if (!args.invalid) { value = serializer.serialize(fragment); // Check if parent is empty or only has one BR element then set the innerHTML of that parent node = parentNode.firstChild; node2 = parentNode.lastChild; if (!node || (node === node2 && node.nodeName === 'BR')) dom.setHTML(parentNode, value); else selection.setContent(value); } else { // If the fragment was invalid within that context then we need // to parse and process the parent it's inserted into // Insert bookmark node and get the parent selection.setContent(bookmarkHtml); parentNode = editor.selection.getNode(); rootNode = editor.getBody(); // Opera will return the document node when selection is in root if (parentNode.nodeType == 9) parentNode = node = rootNode; else node = parentNode; // Find the ancestor just before the root element while (node !== rootNode) { parentNode = node; node = node.parentNode; } // Get the outer/inner HTML depending on if we are in the root and parser and serialize that value = parentNode == rootNode ? rootNode.innerHTML : dom.getOuterHTML(parentNode); value = serializer.serialize( parser.parse( // Need to replace by using a function since $ in the contents would otherwise be a problem value.replace(/<span (id="mce_marker"|id=mce_marker).+?<\/span>/i, function() { return serializer.serialize(fragment); }) ) ); // Set the inner/outer HTML depending on if we are in the root or not if (parentNode == rootNode) dom.setHTML(rootNode, value); else dom.setOuterHTML(parentNode, value); } marker = dom.get('mce_marker'); // Scroll range into view scrollIntoView on element can't be used since it will scroll the main view port as well nodeRect = dom.getRect(marker); viewPortRect = dom.getViewPort(editor.getWin()); // Check if node is out side the viewport if it is then scroll to it if ((nodeRect.y + nodeRect.h > viewPortRect.y + viewPortRect.h || nodeRect.y < viewPortRect.y) || (nodeRect.x > viewPortRect.x + viewPortRect.w || nodeRect.x < viewPortRect.x)) { viewportBodyElement = tinymce.isIE ? editor.getDoc().documentElement : editor.getBody(); viewportBodyElement.scrollLeft = nodeRect.x; viewportBodyElement.scrollTop = nodeRect.y - viewPortRect.h + 25; } // Move selection before marker and remove it rng = dom.createRng(); // If previous sibling is a text node set the selection to the end of that node node = marker.previousSibling; if (node && node.nodeType == 3) { rng.setStart(node, node.nodeValue.length); } else { // If the previous sibling isn't a text node or doesn't exist set the selection before the marker node rng.setStartBefore(marker); rng.setEndBefore(marker); } // Remove the marker node and set the new range dom.remove(marker); selection.setRng(rng); // Dispatch after event and add any visual elements needed selection.onSetContent.dispatch(selection, args); editor.addVisual(); }, mceInsertRawHTML : function(command, ui, value) { selection.setContent('tiny_mce_marker'); editor.setContent(editor.getContent().replace(/tiny_mce_marker/g, function() { return value })); }, mceSetContent : function(command, ui, value) { editor.setContent(value); }, 'Indent,Outdent' : function(command) { var intentValue, indentUnit, value; // Setup indent level intentValue = settings.indentation; indentUnit = /[a-z%]+$/i.exec(intentValue); intentValue = parseInt(intentValue); if (!queryCommandState('InsertUnorderedList') && !queryCommandState('InsertOrderedList')) { // If forced_root_blocks is set to false we don't have a block to indent so lets create a div if (!settings.forced_root_block && !dom.getParent(selection.getNode(), dom.isBlock)) { formatter.apply('div'); } each(selection.getSelectedBlocks(), function(element) { if (command == 'outdent') { value = Math.max(0, parseInt(element.style.paddingLeft || 0) - intentValue); dom.setStyle(element, 'paddingLeft', value ? value + indentUnit : ''); } else dom.setStyle(element, 'paddingLeft', (parseInt(element.style.paddingLeft || 0) + intentValue) + indentUnit); }); } else execNativeCommand(command); }, mceRepaint : function() { var bookmark; if (tinymce.isGecko) { try { storeSelection(TRUE); if (selection.getSel()) selection.getSel().selectAllChildren(editor.getBody()); selection.collapse(TRUE); restoreSelection(); } catch (ex) { // Ignore } } }, mceToggleFormat : function(command, ui, value) { formatter.toggle(value); }, InsertHorizontalRule : function() { editor.execCommand('mceInsertContent', false, '<hr />'); }, mceToggleVisualAid : function() { editor.hasVisual = !editor.hasVisual; editor.addVisual(); }, mceReplaceContent : function(command, ui, value) { editor.execCommand('mceInsertContent', false, value.replace(/\{\$selection\}/g, selection.getContent({format : 'text'}))); }, mceInsertLink : function(command, ui, value) { var anchor; if (typeof(value) == 'string') value = {href : value}; anchor = dom.getParent(selection.getNode(), 'a'); // Spaces are never valid in URLs and it's a very common mistake for people to make so we fix it here. value.href = value.href.replace(' ', '%20'); // Remove existing links if there could be child links or that the href isn't specified if (!anchor || !value.href) { formatter.remove('link'); } // Apply new link to selection if (value.href) { formatter.apply('link', value, anchor); } }, selectAll : function() { var root = dom.getRoot(), rng = dom.createRng(); rng.setStart(root, 0); rng.setEnd(root, root.childNodes.length); editor.selection.setRng(rng); } }); // Add queryCommandState overrides addCommands({ // Override justify commands 'JustifyLeft,JustifyCenter,JustifyRight,JustifyFull' : function(command) { var name = 'align' + command.substring(7); var nodes = selection.isCollapsed() ? [dom.getParent(selection.getNode(), dom.isBlock)] : selection.getSelectedBlocks(); var matches = tinymce.map(nodes, function(node) { return !!formatter.matchNode(node, name); }); return tinymce.inArray(matches, TRUE) !== -1; }, 'Bold,Italic,Underline,Strikethrough,Superscript,Subscript' : function(command) { return isFormatMatch(command); }, mceBlockQuote : function() { return isFormatMatch('blockquote'); }, Outdent : function() { var node; if (settings.inline_styles) { if ((node = dom.getParent(selection.getStart(), dom.isBlock)) && parseInt(node.style.paddingLeft) > 0) return TRUE; if ((node = dom.getParent(selection.getEnd(), dom.isBlock)) && parseInt(node.style.paddingLeft) > 0) return TRUE; } return queryCommandState('InsertUnorderedList') || queryCommandState('InsertOrderedList') || (!settings.inline_styles && !!dom.getParent(selection.getNode(), 'BLOCKQUOTE')); }, 'InsertUnorderedList,InsertOrderedList' : function(command) { return dom.getParent(selection.getNode(), command == 'insertunorderedlist' ? 'UL' : 'OL'); } }, 'state'); // Add queryCommandValue overrides addCommands({ 'FontSize,FontName' : function(command) { var value = 0, parent; if (parent = dom.getParent(selection.getNode(), 'span')) { if (command == 'fontsize') value = parent.style.fontSize; else value = parent.style.fontFamily.replace(/, /g, ',').replace(/[\'\"]/g, '').toLowerCase(); } return value; } }, 'value'); // Add undo manager logic addCommands({ Undo : function() { editor.undoManager.undo(); }, Redo : function() { editor.undoManager.redo(); } }); }; })(tinymce);
import { moduleForComponent, test } from 'ember-qunit'; moduleForComponent('credit-card-form', { // specify the other units that are required for this test needs: [ 'component:input-credit-card-number', 'component:input-credit-card-expiration', 'component:input-credit-card-cvc' ] }); test('it renders', function(assert) { assert.expect(2); // creates the component instance var component = this.subject(); assert.equal(component._state, 'preRender'); // renders the component to the page this.render(); assert.equal(component._state, 'inDOM'); });
/* eslint-disable no-console */ function init( _context) { let { Meteor } = _context; return function () { Meteor.methods({ '_books.wipe'() { console.log('<|> <|> (mmks_book/src/server/methods=>_book.wipe) <|> <|> '); return true; } }); }; } const Methods = { new: init, }; export default Methods;
import React from 'react' import { render } from 'react-testing-library' import Header from '../header' describe(`Header`, () => { it(`renders siteTitle`, () => { const siteTitle = `Hello World` const { getByText } = render(<Header siteTitle={siteTitle} />) const title = getByText(siteTitle) expect(title).toBeInTheDocument() }) })
module.exports = function(grunt) { // Project Configuration grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), watch: { sass: { files: ['src/web/assets/feedme/dist/css/*.scss'], tasks: 'css' }, js: { files: ['src/web/assets/feedme/src/js/*.js'], tasks: ['concat', 'uglify:js'] } }, sass: { options: { style: 'compact', unixNewlines: true }, dist: { expand: true, cwd: 'src/web/assets', src: [ '**/*.scss' ], dest: 'src/web/assets', rename: function(dest, src) { // Keep them where they came from return dest + '/' + src; }, ext: '.css' } }, postcss: { options: { map: true, processors: [ require('autoprefixer')({browsers: 'last 2 versions'}) ] }, dist: { expand: true, cwd: 'src/web/assets', src: [ '**/*.css', ], dest: 'src/web/assets' } }, concat: { js: { options: { banner: '/*! <%= pkg.name %> <%= pkg.version %> - <%= grunt.template.today("yyyy-mm-dd") %> */\n' + '(function($){\n\n', footer: '\n})(jQuery);\n' }, src: [ 'src/web/assets/feedme/src/js/_help.js', 'src/web/assets/feedme/src/js/_selectize.js', 'src/web/assets/feedme/src/js/feed-me.js', ], dest: 'src/web/assets/feedme/dist/js/feed-me.js' } }, uglify: { options: { sourceMap: true, preserveComments: 'some', screwIE8: true }, js: { src: 'src/web/assets/feedme/dist/js/feed-me.js', dest: 'src/web/assets/feedme/dist/js/feed-me.min.js' }, }, jshint: { options: { expr: true, laxbreak: true, loopfunc: true, // Supresses "Don't make functions within a loop." errors shadow: true, strict: false, '-W041': true, '-W061': true }, beforeconcat: [ 'gruntfile.js', 'src/web/assets/**/*.js', '!src/web/assets/**/*.min.js', '!src/web/assets/feedme/dist/js/feed-me.js', ], afterconcat: [ 'src/web/assets/feedme/dist/js/feed-me.js' ] } }); //Load NPM tasks grunt.loadNpmTasks('grunt-contrib-sass'); grunt.loadNpmTasks('grunt-postcss'); grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-jshint'); // Default task(s). grunt.registerTask('css', ['sass', 'postcss']); grunt.registerTask('js', ['jshint:beforeconcat', 'concat', 'jshint:afterconcat', 'uglify']); grunt.registerTask('default', ['css', 'js']); };
'use strict' const EventEmitter = require('events') module.exports = class ChildProcessMock extends EventEmitter { constructor() { super() this.stdout = { on() {} } this.stderr = { on() {} } this.stdin = { end: () => { this.emit('exit', 0) } } } }
var test = require('tape'); var defaults = require('../defaults'); test('defaults', function(t) { t.plan(3); t.equal(defaults({}, { a: true }).a, true, 'Property a copied across'); t.equal(defaults({ a: 1 }, { a: 2 }).a, 1, 'Property value not overriden'); t.equal(defaults(undefined, { a: true }).a, true, 'Property pushed to new object'); });
/** * pixi 0.3.1 (a1e2d46) * http://drkibitz.github.io/node-pixi/ * Copyright (c) 2013-2015 Dr. Kibitz, http://drkibitz.com * Super fast 2D rendering engine for browserify, that uses WebGL with a context 2d fallback. * built: Fri May 22 2015 20:31:02 GMT-0700 (PDT) * * Pixi.js - v1.3.0 * Copyright (c) 2012, Mat Groves */ "use strict";var platform=require("../../platform");exports.shader=function(a,b,c){var d=b.join("\n"),e=a.createShader(c);return a.shaderSource(e,d),a.compileShader(e),a.getShaderParameter(e,a.COMPILE_STATUS)?e:(platform.console&&platform.console.error(a.getShaderInfoLog(e)),null)},exports.program=function(a,b,c){var d=exports.shader(a,c,a.FRAGMENT_SHADER),e=exports.shader(a,b,a.VERTEX_SHADER),f=a.createProgram();return a.attachShader(f,e),a.attachShader(f,d),a.linkProgram(f),a.getProgramParameter(f,a.LINK_STATUS)?f:(platform.console&&platform.console.error("Could not initialise shaders"),null)};
'use strict'; angular .module('javascriptNews') .service('indexFactory', ['$resource', function($resource) { this.getHeadlines = function() { return $resource('/api/v1/headlines', null); }; this.getBestArticles = function() { return $resource('/api/v1/articles/top', null); }; this.getArticles = function() { return $resource('/api/v1/articles', null); }; this.getArticle = function(sId) { return $resource('/api/v1/articles/'+sId, null, { 'update': { method:'PUT' } }); }; this.incArticleLink = function(sId) { return $resource('/api/v1/articles/'+sId+'/link', null, { 'update': { method:'PUT' } }); }; this.getPodcasts = function() { return $resource('/api/v1/podcasts', null); }; this.getPodcast = function(sId) { return $resource('/api/v1/podcasts/'+sId, null, { 'update': { method:'PUT' } }); }; this.incPodcastLink = function(sId) { return $resource('/api/v1/podcasts/'+sId+'/link', null, { 'update': { method:'PUT' } }); }; this.getVideos = function() { return $resource('/api/v1/videos', null); }; this.getVideo = function(sId) { return $resource('/api/v1/videos/'+sId, null, { 'update': { method:'PUT' } }); }; this.incVideoLink = function(sId) { return $resource('/api/v1/videos/'+sId+'/link', null, { 'update': { method:'PUT' } }); }; }]) .factory('$localStorage', ['$window', function ($window) { return { store: function (key, value) { $window.localStorage[key] = value; }, get: function (key, defaultValue) { return $window.localStorage[key] || defaultValue; }, remove: function (key) { $window.localStorage.removeItem(key); }, storeObject: function (key, value) { $window.localStorage[key] = JSON.stringify(value); }, getObject: function (key, defaultValue) { return JSON.parse($window.localStorage[key] || defaultValue); } }; }]) .factory('AuthFactory', ['$resource', '$http', '$localStorage', '$rootScope', function($resource, $http, $localStorage, $rootScope){ var authFac = {}; var TOKEN_KEY = 'Token'; var isAuthenticated = false; var isAdmin = false; var username = ''; var email = ''; var authToken; function useCredentials(credentials) { isAuthenticated = true; username = credentials.username; email = credentials.email; authToken = credentials.token; isAdmin = credentials.admin; // Set the token as header for your requests! $http.defaults.headers.common['x-access-token'] = authToken; } function loadUserCredentials() { var credentials = $localStorage.getObject(TOKEN_KEY,'{}'); if (credentials.username) { useCredentials(credentials); } } function storeUserCredentials(credentials) { $localStorage.storeObject(TOKEN_KEY, credentials); useCredentials(credentials); } function destroyUserCredentials() { authToken = ''; username = ''; email = ''; isAuthenticated = false; isAdmin = false; $http.defaults.headers.common['x-access-token'] = authToken; $localStorage.remove(TOKEN_KEY); } authFac.storeUser = function(credentials) { storeUserCredentials(credentials); }; authFac.loginFacebook = function() { window.location = window.location.protocol + '//' + window.location.host + '/api/v1/users/facebook'; }; authFac.login = function(loginData) { $resource('/api/v1/users/login') .save(loginData, function(response) { storeUserCredentials({username:loginData.username, email: loginData.email, admin: response.admin, token: response.token}); $rootScope.$broadcast('login:Successful'); $('#loginModal').modal('hide'); }, function(response){ isAuthenticated = false; $rootScope.loginError=response.data.err.message; //response.data.err.message //response.data.err.name $('#loginAlert').modal('show'); } ); }; authFac.logout = function() { $resource('/api/v1/users/logout').get(function(){ //param response }); destroyUserCredentials(); }; authFac.register = function(registerData) { $resource('/api/v1/users/register') .save(registerData, function() { //param response authFac.login({username:registerData.username, email:registerData.email, password:registerData.password}); if (registerData.rememberMe) { $localStorage.storeObject('userinfo', {username:registerData.username, email:registerData.email, password:registerData.password}); } $rootScope.$broadcast('registration:Successful'); $('#registerModal').modal('hide'); }, function(response){ $rootScope.registrationError=response.data.message; $('#registrationAlert').modal('show'); } ); }; authFac.isAuthenticated = function() { return isAuthenticated; }; authFac.isAdmin = function() { return isAdmin; }; authFac.getUsername = function() { return username; }; loadUserCredentials(); return authFac; }]) .service('messageFactory', ['$resource', function($resource) { this.getMessages = function() { return $resource('/api/v1/messages', null, { 'create': { method:'POST' } }); }; }]) .service('addNewsFactory', ['$resource', function($resource) { this.getArticles = function() { return $resource('/api/v1/articles', null, { 'create': { method:'POST' } }); }; this.getPodcasts = function() { return $resource('/api/v1/podcasts', null, { 'create': { method:'POST' } }); }; this.getVideos = function() { return $resource('/api/v1/videos', null, { 'create': { method:'POST' } }); }; }]) ;
var require = patchRequire(require); var fs = require('fs'); var url = 'http://weibo.com/login.php'; var login_cookies = require('weibo_cookies'); module.exports = function(username, password) { /**************************handler*****************************/ var error_handler = function() { this.die("error: [" + this.getCurrentUrl() + "] login failed! >> no expect selector", 1); // this.capture("error_" + new Date().getTime() + ".png"); }; var check_login_page = function() { return /login\.php$/.test(this.getCurrentUrl()); }; var do_login = function() { casper.waitForSelector('input[name=username]', function() { // this.echo("start login..."); this.evaluate(function(username, password) { var tmp = document.querySelectorAll("input[name=username]"); for (var i = 0; i < tmp.length; i++) { tmp[i].value = username; } var tmp = document.querySelectorAll("input[name=password]"); for (var i = 0; i < tmp.length; i++) { tmp[i].focus(); tmp[i].value = password; } var tmp = document.querySelectorAll("a[action-type=btn_submit]"); for (var i = 0; i < tmp.length; i++) { var oEvent = document.createEvent("MouseEvents"); oEvent.initMouseEvent("click", true, true); tmp[i].dispatchEvent(oEvent); } }, username, password); // casperjs 按钮功能太简单了,捉急啊。。。 // this.click('a[action-type=btn_submit]'); // this.capture("summary.png"); }, error_handler, 10000); }; var weibo_login_handler = function() { // this.echo(this.getCurrentUrl() + " redirect..."); // this.capture("redirect.png"); this.click('p.p1.line a'); casper.then(do_login); }; /************************handler end****************************/ casper.open(url); casper.thenBypassIf(function() { return /^http:\/\/weibo.com\/u/.test(this.getCurrentUrl()); }, 2); casper.waitFor(check_login_page, do_login, weibo_login_handler); casper.then(function() { this.waitWhileSelector('input[name=username]', function() { this.echo("login done..."); login_cookies.writeCookie(username); casper.exit(0); // this.capture("done.png"); }, error_handler, 10000); }); }
var chai = require('chai'); var assert = chai.assert; var sinon = require('sinon'); var fs = require('fs'); var yaml = require('js-yaml'); require('../helpers/globals'); var Config = require('../../lib/config'); describe('Config', function() { var config; var configPath = './tmp-cm-janus-conf.yaml'; context('when single configuration file', function() { before(function() { config = new Config(); sinon.stub(config, '_getValidationSchema').returns({ "id": "/foo", "type": "object", "required": true, "properties": { "foo": { "type": "string", "required": true } } }); }); afterEach(function() { fs.unlinkSync(configPath); }); it('must load valid configs', function() { fs.writeFileSync(configPath, yaml.safeDump({foo: 'bar'})); config.load(configPath); }); it('throw on invalid configs', function() { fs.writeFileSync(configPath, yaml.safeDump({foo: 4})); assert.throws(function() { config.load(configPath); }, 'not of a type'); fs.writeFileSync(configPath, ''); assert.throws(function() { config.load(configPath); }, 'required'); }); }); });
/** * Commands * Pokemon Showdown - https://pokemonshowdown.com/ * * These are commands. For instance, you can define the command 'whois' * here, then use it by typing /whois into Pokemon Showdown. * * A command can be in the form: * ip: 'whois', * This is called an alias: it makes it so /ip does the same thing as * /whois. * * But to actually define a command, it's a function: * * allowchallenges: function (target, room, user) { * user.blockChallenges = false; * this.sendReply("You are available for challenges from now on."); * } * * Commands are actually passed five parameters: * function (target, room, user, connection, cmd, message) * Most of the time, you only need the first three, though. * * target = the part of the message after the command * room = the room object the message was sent to * The room name is room.id * user = the user object that sent the message * The user's name is user.name * connection = the connection that the message was sent from * cmd = the name of the command * message = the entire message sent by the user * * If a user types in "/msg zarel, hello" * target = "zarel, hello" * cmd = "msg" * message = "/msg zarel, hello" * * Commands return the message the user should say. If they don't * return anything or return something falsy, the user won't say * anything. * * Commands have access to the following functions: * * this.sendReply(message) * Sends a message back to the room the user typed the command into. * * this.sendReplyBox(html) * Same as sendReply, but shows it in a box, and you can put HTML in * it. * * this.popupReply(message) * Shows a popup in the window the user typed the command into. * * this.add(message) * Adds a message to the room so that everyone can see it. * This is like this.sendReply, except everyone in the room gets it, * instead of just the user that typed the command. * * this.send(message) * Sends a message to the room so that everyone can see it. * This is like this.add, except it's not logged, and users who join * the room later won't see it in the log, and if it's a battle, it * won't show up in saved replays. * You USUALLY want to use this.add instead. * * this.logEntry(message) * Log a message to the room's log without sending it to anyone. This * is like this.add, except no one will see it. * * this.addModCommand(message) * Like this.add, but also logs the message to the moderator log * which can be seen with /modlog. * * this.logModCommand(message) * Like this.addModCommand, except users in the room won't see it. * * this.can(permission) * this.can(permission, targetUser) * Checks if the user has the permission to do something, or if a * targetUser is passed, check if the user has permission to do * it to that user. Will automatically give the user an "Access * denied" message if the user doesn't have permission: use * user.can() if you don't want that message. * * Should usually be near the top of the command, like: * if (!this.can('potd')) return false; * * this.canBroadcast() * Signifies that a message can be broadcast, as long as the user * has permission to. This will check to see if the user used * "!command" instead of "/command". If so, it will check to see * if the user has permission to broadcast (by default, voice+ can), * and return false if not. Otherwise, it will add the message to * the room, and turn on the flag this.broadcasting, so that * this.sendReply and this.sendReplyBox will broadcast to the room * instead of just the user that used the command. * * Should usually be near the top of the command, like: * if (!this.canBroadcast()) return false; * * this.canBroadcast(suppressMessage) * Functionally the same as this.canBroadcast(). However, it * will look as if the user had written the text suppressMessage. * * this.canTalk() * Checks to see if the user can speak in the room. Returns false * if the user can't speak (is muted, the room has modchat on, etc), * or true otherwise. * * Should usually be near the top of the command, like: * if (!this.canTalk()) return false; * * this.canTalk(message, room) * Checks to see if the user can say the message in the room. * If a room is not specified, it will default to the current one. * If it has a falsy value, the check won't be attached to any room. * In addition to running the checks from this.canTalk(), it also * checks to see if the message has any banned words, is too long, * or was just sent by the user. Returns the filtered message, or a * falsy value if the user can't speak. * * Should usually be near the top of the command, like: * target = this.canTalk(target); * if (!target) return false; * * this.parse(message) * Runs the message as if the user had typed it in. * * Mostly useful for giving help messages, like for commands that * require a target: * if (!target) return this.parse('/help msg'); * * After 10 levels of recursion (calling this.parse from a command * called by this.parse from a command called by this.parse etc) * we will assume it's a bug in your command and error out. * * this.targetUserOrSelf(target, exactName) * If target is blank, returns the user that sent the message. * Otherwise, returns the user with the username in target, or * a falsy value if no user with that username exists. * By default, this will track users across name changes. However, * if exactName is true, it will enforce exact matches. * * this.getLastIdOf(user) * Returns the last userid of an specified user. * * this.splitTarget(target, exactName) * Splits a target in the form "user, message" into its * constituent parts. Returns message, and sets this.targetUser to * the user, and this.targetUsername to the username. * By default, this will track users across name changes. However, * if exactName is true, it will enforce exact matches. * * Remember to check if this.targetUser exists before going further. * * Unless otherwise specified, these functions will return undefined, * so you can return this.sendReply or something to send a reply and * stop the command there. * * @license MIT license */ var commands = exports.commands = { ip: 'whois', rooms: 'whois', alt: 'whois', alts: 'whois', whoare: 'whois', whois: function (target, room, user, connection, cmd) { var targetUser = this.targetUserOrSelf(target, user.group === ' '); if (!targetUser) { return this.sendReply("User " + this.targetUsername + " not found."); } this.sendReply("|raw|User: " + targetUser.name + (!targetUser.connected ? ' <font color="gray"><em>(offline)</em></font>' : '')); if (user.can('alts', targetUser)) { var alts = targetUser.getAlts(true); var output = Object.keys(targetUser.prevNames).join(", "); if (output) this.sendReply("Previous names: " + output); for (var j = 0; j < alts.length; ++j) { var targetAlt = Users.get(alts[j]); if (!targetAlt.named && !targetAlt.connected) continue; if (targetAlt.group === '~' && user.group !== '~') continue; this.sendReply("|raw|Alt: " + targetAlt.name + (!targetAlt.connected ? ' <font color="gray"><em>(offline)</em></font>' : '')); output = Object.keys(targetAlt.prevNames).join(", "); if (output) this.sendReply("Previous names: " + output); } if (targetUser.locked) { switch (targetUser.locked) { case '#dnsbl': this.sendReply("Locked: IP is in a DNS-based blacklist. "); break; case '#range': this.sendReply("Locked: IP or host is in a temporary range-lock."); break; case '#hostfilter': this.sendReply("Locked: host is permanently locked for being a proxy."); break; default: this.sendReply("Locked under the username: " + targetUser.locked); } } } if (Config.groups[targetUser.group] && Config.groups[targetUser.group].name) { this.sendReply("Group: " + Config.groups[targetUser.group].name + " (" + targetUser.group + ")"); } if (targetUser.isSysop) { this.sendReply("(Pok\xE9mon Showdown System Operator)"); } if (!targetUser.authenticated) { this.sendReply("(Unregistered)"); } if ((cmd === 'ip' || cmd === 'whoare') && (user.can('ip', targetUser) || user === targetUser)) { var ips = Object.keys(targetUser.ips); this.sendReply("IP" + ((ips.length > 1) ? "s" : "") + ": " + ips.join(", ") + (user.group !== ' ' && targetUser.latestHost ? "\nHost: " + targetUser.latestHost : "")); } var publicrooms = "In rooms: "; var hiddenrooms = "In hidden rooms: "; var first = true; var hiddencount = 0; for (var i in targetUser.roomCount) { var targetRoom = Rooms.get(i); if (i === 'global' || targetRoom.isPrivate === true) continue; var output = (targetRoom.auth && targetRoom.auth[targetUser.userid] ? targetRoom.auth[targetUser.userid] : '') + '<a href="/' + i + '" room="' + i + '">' + i + '</a>'; if (targetRoom.isPrivate) { if (hiddencount > 0) hiddenrooms += " | "; ++hiddencount; hiddenrooms += output; } else { if (!first) publicrooms += " | "; first = false; publicrooms += output; } } this.sendReply('|raw|' + publicrooms); if (cmd === 'whoare' && user.can('lock') && hiddencount > 0) { this.sendReply('|raw|' + hiddenrooms); } }, ipsearchall: 'ipsearch', ipsearch: function (target, room, user, connection, cmd) { if (!this.can('rangeban')) return; var results = []; this.sendReply("Users with IP " + target + ":"); var isRange; if (target.slice(-1) === '*') { isRange = true; target = target.slice(0, -1); } var isAll = (cmd === 'ipsearchall'); if (isRange) { for (var userid in Users.users) { var curUser = Users.users[userid]; if (curUser.group === '~') continue; if (!curUser.latestIp.startsWith(target)) continue; if (results.push((curUser.connected ? " + " : "-") + " " + curUser.name) > 100 && !isAll) { return this.sendReply("More than 100 users match the specified IP range. Use /ipsearchall to retrieve the full list."); } } } else { for (var userid in Users.users) { var curUser = Users.users[userid]; if (curUser.latestIp === target) { results.push((curUser.connected ? " + " : "-") + " " + curUser.name); } } } if (!results.length) return this.sendReply("No results found."); return this.sendReply(results.join('; ')); }, /********************************************************* * Shortcuts *********************************************************/ invite: function (target, room, user) { target = this.splitTarget(target); if (!this.targetUser) { return this.sendReply("User " + this.targetUsername + " not found."); } var targetRoom = (target ? Rooms.search(target) : room); if (!targetRoom) { return this.sendReply("Room " + target + " not found."); } return this.parse('/msg ' + this.targetUsername + ', /invite ' + targetRoom.id); }, /********************************************************* * Informational commands *********************************************************/ pstats: 'data', stats: 'data', dex: 'data', pokedex: 'data', details: 'data', dt: 'data', data: function (target, room, user, connection, cmd) { if (!this.canBroadcast()) return; var buffer = ''; var targetId = toId(target); if (targetId === '' + parseInt(targetId)) { for (var p in Tools.data.Pokedex) { var pokemon = Tools.getTemplate(p); if (pokemon.num === parseInt(target)) { target = pokemon.species; targetId = pokemon.id; break; } } } var newTargets = Tools.dataSearch(target); var showDetails = (cmd === 'dt' || cmd === 'details'); if (newTargets && newTargets.length) { for (var i = 0; i < newTargets.length; ++i) { if (newTargets[i].id !== targetId && !Tools.data.Aliases[targetId] && !i) { buffer = "No Pokemon, item, move, ability or nature named '" + target + "' was found. Showing the data of '" + newTargets[0].name + "' instead.\n"; } if (newTargets[i].searchType === 'nature') { buffer += "" + newTargets[i].name + " nature: "; if (newTargets[i].plus) { var statNames = {'atk': "Attack", 'def': "Defense", 'spa': "Special Attack", 'spd': "Special Defense", 'spe': "Speed"}; buffer += "+10% " + statNames[newTargets[i].plus] + ", -10% " + statNames[newTargets[i].minus] + "."; } else { buffer += "No effect."; } return this.sendReply(buffer); } else { buffer += '|c|~|/data-' + newTargets[i].searchType + ' ' + newTargets[i].name + '\n'; } } } else { return this.sendReply("No Pokemon, item, move, ability or nature named '" + target + "' was found. (Check your spelling?)"); } if (showDetails) { var details; if (newTargets[0].searchType === 'pokemon') { var pokemon = Tools.getTemplate(newTargets[0].name); var weighthit = 20; if (pokemon.weightkg >= 200) { weighthit = 120; } else if (pokemon.weightkg >= 100) { weighthit = 100; } else if (pokemon.weightkg >= 50) { weighthit = 80; } else if (pokemon.weightkg >= 25) { weighthit = 60; } else if (pokemon.weightkg >= 10) { weighthit = 40; } details = { "Dex#": pokemon.num, "Height": pokemon.heightm + " m", "Weight": pokemon.weightkg + " kg <em>(" + weighthit + " BP)</em>", "Dex Colour": pokemon.color, "Egg Group(s)": pokemon.eggGroups.join(", ") }; if (!pokemon.evos.length) { details["<font color=#585858>Does Not Evolve</font>"] = ""; } else { details["Evolution"] = pokemon.evos.map(function (evo) { evo = Tools.getTemplate(evo); return evo.name + " (" + evo.evoLevel + ")"; }).join(", "); } } else if (newTargets[0].searchType === 'move') { var move = Tools.getMove(newTargets[0].name); details = { "Priority": move.priority }; if (move.secondary || move.secondaries) details["<font color=black>&#10003; Secondary effect</font>"] = ""; if (move.flags['contact']) details["<font color=black>&#10003; Contact</font>"] = ""; if (move.flags['sound']) details["<font color=black>&#10003; Sound</font>"] = ""; if (move.flags['bullet']) details["<font color=black>&#10003; Bullet</font>"] = ""; if (move.flags['pulse']) details["<font color=black>&#10003; Pulse</font>"] = ""; if (move.flags['protect']) details["<font color=black>&#10003; Blocked by Protect</font>"] = ""; if (move.flags['authentic']) details["<font color=black>&#10003; Ignores substitutes</font>"] = ""; if (move.flags['defrost']) details["<font color=black>&#10003; Thaws user</font>"] = ""; if (move.flags['bite']) details["<font color=black>&#10003; Bite</font>"] = ""; if (move.flags['punch']) details["<font color=black>&#10003; Punch</font>"] = ""; if (move.flags['powder']) details["<font color=black>&#10003; Powder</font>"] = ""; if (move.flags['reflectable']) details["<font color=black>&#10003; Bounceable</font>"] = ""; details["Target"] = { 'normal': "One Adjacent Pokemon", 'self': "User", 'adjacentAlly': "One Ally", 'adjacentAllyOrSelf': "User or Ally", 'adjacentFoe': "One Adjacent Opposing Pokemon", 'allAdjacentFoes': "All Adjacent Opponents", 'foeSide': "Opposing Side", 'allySide': "User's Side", 'allyTeam': "User's Side", 'allAdjacent': "All Adjacent Pokemon", 'any': "Any Pokemon", 'all': "All Pokemon" }[move.target] || "Unknown"; } else if (newTargets[0].searchType === 'item') { var item = Tools.getItem(newTargets[0].name); details = {}; if (item.fling) { details["Fling Base Power"] = item.fling.basePower; if (item.fling.status) details["Fling Effect"] = item.fling.status; if (item.fling.volatileStatus) details["Fling Effect"] = item.fling.volatileStatus; if (item.isBerry) details["Fling Effect"] = "Activates the Berry's effect on the target."; if (item.id === 'whiteherb') details["Fling Effect"] = "Restores the target's negative stat stages to 0."; if (item.id === 'mentalherb') details["Fling Effect"] = "Removes the effects of Attract, Disable, Encore, Heal Block, Taunt, and Torment from the target."; } else { details["Fling"] = "This item cannot be used with Fling."; } if (item.naturalGift) { details["Natural Gift Type"] = item.naturalGift.type; details["Natural Gift Base Power"] = item.naturalGift.basePower; } } else { details = {}; } buffer += '|raw|<font size="1">' + Object.keys(details).map(function (detail) { return '<font color=#585858>' + detail + (details[detail] !== '' ? ':</font> ' + details[detail] : '</font>'); }).join("&nbsp;|&ThickSpace;") + '</font>'; } this.sendReply(buffer); }, ds: 'dexsearch', dsearch: 'dexsearch', dexsearch: function (target, room, user) { if (!this.canBroadcast()) return; if (!target) return this.parse('/help dexsearch'); var targets = target.split(','); var searches = {}; var allTiers = {'uber':1, 'ou':1, 'bl':1, 'uu':1, 'bl2':1, 'ru':1, 'bl3':1, 'nu':1, 'bl4':1, 'pu':1, 'nfe':1, 'lc':1, 'cap':1}; var allColours = {'green':1, 'red':1, 'blue':1, 'white':1, 'brown':1, 'yellow':1, 'purple':1, 'pink':1, 'gray':1, 'black':1}; var showAll = false; var megaSearch = null; var recoverySearch = null; var output = 10; for (var i in targets) { var isNotSearch = false; target = targets[i].trim().toLowerCase(); if (target.slice(0, 1) === '!') { isNotSearch = true; target = target.slice(1); } var targetAbility = Tools.getAbility(targets[i]); if (targetAbility.exists) { if (!searches['ability']) searches['ability'] = {}; if (Object.count(searches['ability'], true) === 1 && !isNotSearch) return this.sendReplyBox("Specify only one ability."); if ((searches['ability'][targetAbility.name] && isNotSearch) || (searches['ability'][targetAbility.name] === false && !isNotSearch)) return this.sendReplyBox("A search cannot both exclude and include an ability."); searches['ability'][targetAbility.name] = !isNotSearch; continue; } if (target in allTiers) { if (!searches['tier']) searches['tier'] = {}; if ((searches['tier'][target] && isNotSearch) || (searches['tier'][target] === false && !isNotSearch)) return this.sendReplyBox('A search cannot both exclude and include a tier.'); searches['tier'][target] = !isNotSearch; continue; } if (target in allColours) { if (!searches['color']) searches['color'] = {}; if ((searches['color'][target] && isNotSearch) || (searches['color'][target] === false && !isNotSearch)) return this.sendReplyBox('A search cannot both exclude and include a color.'); searches['color'][target] = !isNotSearch; continue; } var targetInt = parseInt(target); if (0 < targetInt && targetInt < 7) { if (!searches['gen']) searches['gen'] = {}; if ((searches['gen'][target] && isNotSearch) || (searches['gen'][target] === false && !isNotSearch)) return this.sendReplyBox('A search cannot both exclude and include a generation.'); searches['gen'][target] = !isNotSearch; continue; } if (target === 'all') { if (this.broadcasting) { return this.sendReplyBox("A search with the parameter 'all' cannot be broadcast."); } showAll = true; continue; } if (target === 'megas' || target === 'mega') { if ((megaSearch && isNotSearch) || (megaSearch === false && !isNotSearch)) return this.sendReplyBox('A search cannot both exclude and include Mega Evolutions.'); megaSearch = !isNotSearch; continue; } if (target === 'recovery') { if ((recoverySearch && isNotSearch) || (recoverySearch === false && !isNotSearch)) return this.sendReplyBox('A search cannot both exclude and recovery moves.'); if (!searches['recovery']) searches['recovery'] = {}; recoverySearch = !isNotSearch; continue; } var targetMove = Tools.getMove(target); if (targetMove.exists) { if (!searches['moves']) searches['moves'] = {}; if (Object.count(searches['moves'], true) === 4 && !isNotSearch) return this.sendReplyBox("Specify a maximum of 4 moves."); if ((searches['moves'][targetMove.name] && isNotSearch) || (searches['moves'][targetMove.name] === false && !isNotSearch)) return this.sendReplyBox("A search cannot both exclude and include a move."); searches['moves'][targetMove.name] = !isNotSearch; continue; } if (target.indexOf(' type') > -1) { target = target.charAt(0).toUpperCase() + target.slice(1, target.indexOf(' type')); if (target in Tools.data.TypeChart) { if (!searches['types']) searches['types'] = {}; if (Object.count(searches['types'], true) === 2 && !isNotSearch) return this.sendReplyBox("Specify a maximum of two types."); if ((searches['types'][target] && isNotSearch) || (searches['types'][target] === false && !isNotSearch)) return this.sendReplyBox("A search cannot both exclude and include a type."); searches['types'][target] = !isNotSearch; continue; } } return this.sendReplyBox("'" + Tools.escapeHTML(target) + "' could not be found in any of the search categories."); } if (showAll && Object.size(searches) === 0 && megaSearch === null) return this.sendReplyBox("No search parameters other than 'all' were found. Try '/help dexsearch' for more information on this command."); var dex = {}; for (var pokemon in Tools.data.Pokedex) { var template = Tools.getTemplate(pokemon); var megaSearchResult = (megaSearch === null || (megaSearch === true && template.isMega) || (megaSearch === false && !template.isMega)); if (template.tier !== 'Unreleased' && template.tier !== 'Illegal' && (template.tier !== 'CAP' || (searches['tier'] && searches['tier']['cap'])) && megaSearchResult) { dex[pokemon] = template; } } for (var search in {'moves':1, 'recovery':1, 'types':1, 'ability':1, 'tier':1, 'gen':1, 'color':1}) { if (!searches[search]) continue; switch (search) { case 'types': for (var mon in dex) { if (Object.count(searches[search], true) === 2) { if (!(searches[search][dex[mon].types[0]]) || !(searches[search][dex[mon].types[1]])) delete dex[mon]; } else { if (searches[search][dex[mon].types[0]] === false || searches[search][dex[mon].types[1]] === false || (Object.count(searches[search], true) > 0 && (!(searches[search][dex[mon].types[0]]) && !(searches[search][dex[mon].types[1]])))) delete dex[mon]; } } break; case 'tier': for (var mon in dex) { if ('lc' in searches[search]) { // some LC legal Pokemon are stored in other tiers (Ferroseed/Murkrow etc) // this checks for LC legality using the going criteria, instead of dex[mon].tier var isLC = (dex[mon].evos && dex[mon].evos.length > 0) && !dex[mon].prevo && Tools.data.Formats['lc'].banlist.indexOf(dex[mon].species) === -1; if ((searches[search]['lc'] && !isLC) || (!searches[search]['lc'] && isLC)) { delete dex[mon]; continue; } } if (searches[search][String(dex[mon][search]).toLowerCase()] === false) { delete dex[mon]; } else if (Object.count(searches[search], true) > 0 && !searches[search][String(dex[mon][search]).toLowerCase()]) delete dex[mon]; } break; case 'gen': case 'color': for (var mon in dex) { if (searches[search][String(dex[mon][search]).toLowerCase()] === false) { delete dex[mon]; } else if (Object.count(searches[search], true) > 0 && !searches[search][String(dex[mon][search]).toLowerCase()]) delete dex[mon]; } break; case 'ability': for (var mon in dex) { for (var ability in searches[search]) { var needsAbility = searches[search][ability]; var hasAbility = Object.count(dex[mon].abilities, ability) > 0; if (hasAbility !== needsAbility) { delete dex[mon]; break; } } } break; case 'moves': for (var mon in dex) { var template = Tools.getTemplate(dex[mon].id); if (!template.learnset) template = Tools.getTemplate(template.baseSpecies); if (!template.learnset) continue; for (var i in searches[search]) { var move = Tools.getMove(i); if (!move.exists) return this.sendReplyBox("'" + move + "' is not a known move."); var prevoTemp = Tools.getTemplate(template.id); while (prevoTemp.prevo && prevoTemp.learnset && !(prevoTemp.learnset[move.id])) { prevoTemp = Tools.getTemplate(prevoTemp.prevo); } var canLearn = (prevoTemp.learnset.sketch && !(move.id in {'chatter':1, 'struggle':1, 'magikarpsrevenge':1})) || prevoTemp.learnset[move.id]; if ((!canLearn && searches[search][i]) || (searches[search][i] === false && canLearn)) delete dex[mon]; } } break; case 'recovery': for (var mon in dex) { var template = Tools.getTemplate(dex[mon].id); if (!template.learnset) template = Tools.getTemplate(template.baseSpecies); if (!template.learnset) continue; var recoveryMoves = ["recover", "roost", "moonlight", "morningsun", "synthesis", "milkdrink", "slackoff", "softboiled", "wish", "healorder"]; var canLearn = false; for (var i = 0; i < recoveryMoves.length; i++) { var prevoTemp = Tools.getTemplate(template.id); while (prevoTemp.prevo && prevoTemp.learnset && !(prevoTemp.learnset[recoveryMoves[i]])) { prevoTemp = Tools.getTemplate(prevoTemp.prevo); } canLearn = (prevoTemp.learnset.sketch) || prevoTemp.learnset[recoveryMoves[i]]; if (canLearn) break; } if ((!canLearn && searches[search]) || (searches[search] === false && canLearn)) delete dex[mon]; } break; default: return this.sendReplyBox("Something broke! PM TalkTakesTime here or on the Smogon forums with the command you tried."); } } var results = Object.keys(dex).map(function (speciesid) {return dex[speciesid].species;}); results = results.filter(function (species) { var template = Tools.getTemplate(species); return !(species !== template.baseSpecies && results.indexOf(template.baseSpecies) > -1); }); var resultsStr = ""; if (results.length > 0) { if (showAll || results.length <= output) { results.sort(); resultsStr = results.join(", "); } else { results.randomize(); resultsStr = results.slice(0, 10).join(", ") + ", and " + string(results.length - output) + " more. Redo the search with 'all' as a search parameter to show all results."; } } else { resultsStr = "No Pokémon found."; } return this.sendReplyBox(resultsStr); }, learnset: 'learn', learnall: 'learn', learn5: 'learn', g6learn: 'learn', rbylearn: 'learn', gsclearn: 'learn', advlearn: 'learn', dpplearn: 'learn', bw2learn: 'learn', learn: function (target, room, user, connection, cmd) { if (!target) return this.parse('/help learn'); if (!this.canBroadcast()) return; var lsetData = {set:{}}; var targets = target.split(','); var template = Tools.getTemplate(targets[0]); var move = {}; var problem; var format = {rby:'gen1ou', gsc:'gen2ou', adv:'gen3oubeta', dpp:'gen4ou', bw2:'gen5ou'}[cmd.substring(0, 3)]; var all = (cmd === 'learnall'); if (cmd === 'learn5') lsetData.set.level = 5; if (cmd === 'g6learn') lsetData.format = {noPokebank: true}; if (!template.exists) { return this.sendReply("Pokemon '" + template.id + "' not found."); } if (targets.length < 2) { return this.sendReply("You must specify at least one move."); } for (var i = 1, len = targets.length; i < len; ++i) { move = Tools.getMove(targets[i]); if (!move.exists) { return this.sendReply("Move '" + move.id + "' not found."); } problem = TeamValidator.checkLearnsetSync(format, move, template.species, lsetData); if (problem) break; } var buffer = template.name + (problem ? " <span class=\"message-learn-cannotlearn\">can't</span> learn " : " <span class=\"message-learn-canlearn\">can</span> learn ") + (targets.length > 2 ? "these moves" : move.name); if (format) buffer += ' on ' + cmd.substring(0, 3).toUpperCase(); if (!problem) { var sourceNames = {E:"egg", S:"event", D:"dream world"}; if (lsetData.sources || lsetData.sourcesBefore) buffer += " only when obtained from:<ul class=\"message-learn-list\">"; if (lsetData.sources) { var sources = lsetData.sources.sort(); var prevSource; var prevSourceType; var prevSourceCount = 0; for (var i = 0, len = sources.length; i < len; ++i) { var source = sources[i]; if (source.substr(0, 2) === prevSourceType) { if (prevSourceCount < 0) { buffer += ": " + source.substr(2); } else if (all || prevSourceCount < 3) { buffer += ", " + source.substr(2); } else if (prevSourceCount === 3) { buffer += ", ..."; } ++prevSourceCount; continue; } prevSourceType = source.substr(0, 2); prevSourceCount = source.substr(2) ? 0 : -1; buffer += "<li>gen " + source.substr(0, 1) + " " + sourceNames[source.substr(1, 1)]; if (prevSourceType === '5E' && template.maleOnlyHidden) buffer += " (cannot have hidden ability)"; if (source.substr(2)) buffer += ": " + source.substr(2); } } if (lsetData.sourcesBefore) { if (!(cmd.substring(0, 3) in {'rby':1, 'gsc':1})) { buffer += "<li>any generation before " + (lsetData.sourcesBefore + 1); } else if (!lsetData.sources) { buffer += "<li>gen " + lsetData.sourcesBefore; } } buffer += "</ul>"; } this.sendReplyBox(buffer); }, weak: 'weakness', resist: 'weakness', weakness: function (target, room, user) { if (!this.canBroadcast()) return; var targets = target.split(/[ ,\/]/); var pokemon = Tools.getTemplate(target); var type1 = Tools.getType(targets[0]); var type2 = Tools.getType(targets[1]); if (pokemon.exists) { target = pokemon.species; } else if (type1.exists && type2.exists) { pokemon = {types: [type1.id, type2.id]}; target = type1.id + "/" + type2.id; } else if (type1.exists) { pokemon = {types: [type1.id]}; target = type1.id; } else { return this.sendReplyBox("" + Tools.escapeHTML(target) + " isn't a recognized type or pokemon."); } var weaknesses = []; var resistances = []; var immunities = []; Object.keys(Tools.data.TypeChart).forEach(function (type) { var notImmune = Tools.getImmunity(type, pokemon); if (notImmune) { var typeMod = Tools.getEffectiveness(type, pokemon); switch (typeMod) { case 1: weaknesses.push(type); break; case 2: weaknesses.push("<b>" + type + "</b>"); break; case -1: resistances.push(type); break; case -2: resistances.push("<b>" + type + "</b>"); break; } } else { immunities.push(type); } }); var buffer = []; buffer.push(pokemon.exists ? "" + target + ' (ignoring abilities):' : '' + target + ':'); buffer.push('<span class=\"message-effect-weak\">Weaknesses</span>: ' + (weaknesses.join(', ') || 'None')); buffer.push('<span class=\"message-effect-resist\">Resistances</span>: ' + (resistances.join(', ') || 'None')); buffer.push('<span class=\"message-effect-immune\">Immunities</span>: ' + (immunities.join(', ') || 'None')); this.sendReplyBox(buffer.join('<br>')); }, eff: 'effectiveness', type: 'effectiveness', matchup: 'effectiveness', effectiveness: function (target, room, user) { var targets = target.split(/[,/]/).slice(0, 2); if (targets.length !== 2) return this.sendReply("Attacker and defender must be separated with a comma."); var searchMethods = {'getType':1, 'getMove':1, 'getTemplate':1}; var sourceMethods = {'getType':1, 'getMove':1}; var targetMethods = {'getType':1, 'getTemplate':1}; var source; var defender; var foundData; var atkName; var defName; for (var i = 0; i < 2; ++i) { var method; for (method in searchMethods) { foundData = Tools[method](targets[i]); if (foundData.exists) break; } if (!foundData.exists) return this.parse('/help effectiveness'); if (!source && method in sourceMethods) { if (foundData.type) { source = foundData; atkName = foundData.name; } else { source = foundData.id; atkName = foundData.id; } searchMethods = targetMethods; } else if (!defender && method in targetMethods) { if (foundData.types) { defender = foundData; defName = foundData.species + " (not counting abilities)"; } else { defender = {types: [foundData.id]}; defName = foundData.id; } searchMethods = sourceMethods; } } if (!this.canBroadcast()) return; var factor = 0; if (Tools.getImmunity(source.type || source, defender)) { var totalTypeMod = 0; if (source.effectType !== 'Move' || source.basePower || source.basePowerCallback) { for (var i = 0; i < defender.types.length; i++) { var baseMod = Tools.getEffectiveness(source, defender.types[i]); var moveMod = source.onEffectiveness && source.onEffectiveness.call(Tools, baseMod, defender.types[i], source); totalTypeMod += typeof moveMod === 'number' ? moveMod : baseMod; } } factor = Math.pow(2, totalTypeMod); } this.sendReplyBox("" + atkName + " is " + factor + "x effective against " + defName + "."); }, uptime: function (target, room, user) { if (!this.canBroadcast()) return; var uptime = process.uptime(); var uptimeText; if (uptime > 24 * 60 * 60) { var uptimeDays = Math.floor(uptime / (24 * 60 * 60)); uptimeText = uptimeDays + " " + (uptimeDays === 1 ? "day" : "days"); var uptimeHours = Math.floor(uptime / (60 * 60)) - uptimeDays * 24; if (uptimeHours) uptimeText += ", " + uptimeHours + " " + (uptimeHours === 1 ? "hour" : "hours"); } else { uptimeText = uptime.seconds().duration(); } this.sendReplyBox("Uptime: <b>" + uptimeText + "</b>"); }, groups: function (target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox( "+ <b>Voice</b> - They can use ! commands like !groups, and talk during moderated chat<br />" + "% <b>Driver</b> - The above, and they can mute. Global % can also lock users and check for alts<br />" + "@ <b>Moderator</b> - The above, and they can ban users<br />" + "&amp; <b>Leader</b> - The above, and they can promote to moderator and force ties<br />" + "# <b>Room Owner</b> - They are leaders of the room and can almost totally control it<br />" + "~ <b>Administrator</b> - They can do anything, like change what this message says" ); }, git: 'opensource', opensource: function (target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox( "Pokemon Showdown is open source:<br />" + "- Language: JavaScript (Node.js)<br />" + "- <a href=\"https://github.com/Zarel/Pokemon-Showdown/commits/master\">What's new?</a><br />" + "- <a href=\"https://github.com/Zarel/Pokemon-Showdown\">Server source code</a><br />" + "- <a href=\"https://github.com/Zarel/Pokemon-Showdown-Client\">Client source code</a>" ); }, staff: function (target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox("<a href=\"https://www.smogon.com/sim/staff_list\">Pokemon Showdown Staff List</a>"); }, avatars: function (target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('You can <button name="avatars">change your avatar</button> by clicking on it in the <button name="openOptions"><i class="icon-cog"></i> Options</button> menu in the upper right. Custom avatars are only obtainable by staff.'); }, bofrocket: function (target, room, user) { if (room.id !== 'bof') return this.sendReply("The command '/bofrocket' was unrecognized. To send a message starting with '/bofrocket', type '//bofrocket'."); if (!this.can('modchat', null, room)) return; target = this.splitTarget(target); if (!this.targetUser) return this.sendReply("User not found"); if (!room.users[this.targetUser.userid]) return this.sendReply("Not in bof"); this.targetUser.avatar = '#bofrocket'; room.add("" + user.name + " applied bofrocket to " + this.targetUser.name); }, showtan: function (target, room, user) { if (room.id !== 'showderp') return this.sendReply("The command '/showtan' was unrecognized. To send a message starting with '/showtan', type '//showtan'."); if (!this.can('modchat', null, room)) return; target = this.splitTarget(target); if (!this.targetUser) return this.sendReply("User not found"); if (!room.users[this.targetUser.userid]) return this.sendReply("Not a showderper"); this.targetUser.avatar = '#showtan'; room.add("" + user.name + " applied showtan to affected area of " + this.targetUser.name); }, cpgtan: function (target, room, user) { if (room.id !== 'cpg') return this.sendReply("The command '/cpgtan' was unrecognized. To send a message starting with '/cpgtan', type '//cpgtan'."); if (!this.can('modchat', null, room)) return; target = this.splitTarget(target); if (!this.targetUser) return this.sendReply("User not found"); if (!room.users[this.targetUser.userid]) return this.sendReply("Not a cpger"); this.targetUser.avatar = '#cpgtan'; room.add("" + user.name + " applied cpgtan to affected area of " + this.targetUser.name); }, introduction: 'intro', intro: function (target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox( "New to competitive pokemon?<br />" + "- <a href=\"https://www.smogon.com/sim/ps_guide\">Beginner's Guide to Pokémon Showdown</a><br />" + "- <a href=\"https://www.smogon.com/dp/articles/intro_comp_pokemon\">An introduction to competitive Pokémon</a><br />" + "- <a href=\"https://www.smogon.com/bw/articles/bw_tiers\">What do 'OU', 'UU', etc mean?</a><br />" + "- <a href=\"https://www.smogon.com/xyhub/tiers\">What are the rules for each format? What is 'Sleep Clause'?</a>" ); }, mentoring: 'smogintro', smogonintro: 'smogintro', smogintro: function (target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox( "Welcome to Smogon's official simulator! Here are some useful links to <a href=\"https://www.smogon.com/mentorship/\">Smogon\'s Mentorship Program</a> to help you get integrated into the community:<br />" + "- <a href=\"https://www.smogon.com/mentorship/primer\">Smogon Primer: A brief introduction to Smogon's subcommunities</a><br />" + "- <a href=\"https://www.smogon.com/mentorship/introductions\">Introduce yourself to Smogon!</a><br />" + "- <a href=\"https://www.smogon.com/mentorship/profiles\">Profiles of current Smogon Mentors</a><br />" + "- <a href=\"http://mibbit.com/#mentor@irc.synirc.net\">#mentor: the Smogon Mentorship IRC channel</a>" ); }, calculator: 'calc', calc: function (target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox( "Pokemon Showdown! damage calculator. (Courtesy of Honko)<br />" + "- <a href=\"https://pokemonshowdown.com/damagecalc/\">Damage Calculator</a>" ); }, cap: function (target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox( "An introduction to the Create-A-Pokemon project:<br />" + "- <a href=\"https://www.smogon.com/cap/\">CAP project website and description</a><br />" + "- <a href=\"https://www.smogon.com/forums/showthread.php?t=48782\">What Pokemon have been made?</a><br />" + "- <a href=\"https://www.smogon.com/forums/forums/311\">Talk about the metagame here</a><br />" + "- <a href=\"https://www.smogon.com/forums/threads/3512318/#post-5594694\">Sample XY CAP teams</a>" ); }, gennext: function (target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox( "NEXT (also called Gen-NEXT) is a mod that makes changes to the game:<br />" + "- <a href=\"https://github.com/Zarel/Pokemon-Showdown/blob/master/mods/gennext/README.md\">README: overview of NEXT</a><br />" + "Example replays:<br />" + "- <a href=\"https://replay.pokemonshowdown.com/gennextou-120689854\">Zergo vs Mr Weegle Snarf</a><br />" + "- <a href=\"https://replay.pokemonshowdown.com/gennextou-130756055\">NickMP vs Khalogie</a>" ); }, om: 'othermetas', othermetas: function (target, room, user) { if (!this.canBroadcast()) return; target = toId(target); var buffer = ""; var matched = false; if (target === 'all' && this.broadcasting) { return this.sendReplyBox("You cannot broadcast informatiom about all Other Metagames at once."); } if (!target || target === 'all') { matched = true; buffer += "- <a href=\"https://www.smogon.com/tiers/om/\">Other Metagames Hub</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3505031/\">Other Metagames Index</a><br />"; } if (target === 'all' || target === 'smogondoublesuu' || target === 'doublesuu') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3516968/\">Doubles UU</a><br />"; } if (target === 'all' || target === 'smogontriples' || target === 'triples') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3511522/\">Smogon Triples</a><br />"; } if (target === 'all' || target === 'omofthemonth' || target === 'omotm' || target === 'month') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3481155/\">Other Metagame of the Month</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3521887/\">Current OMotM: Classic Hackmons</a><br />"; } if (target === 'all' || target === 'seasonal') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3491902/\">Seasonal Ladder</a><br />"; } if (target === 'all' || target === 'balancedhackmons' || target === 'bh') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3489849/\">Balanced Hackmons</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3515725/\">Balanced Hackmons Suspect Discussion</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3525676/\">Balanced Hackmons Viability Rankings</a><br />"; } if (target === 'all' || target === '1v1') { matched = true; if (target !== 'all') buffer += "Bring three Pokémon to Team Preview and choose one to battle.<br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3496773/\">1v1</a><br />"; } if (target === 'all' || target === 'monotype') { matched = true; if (target !== 'all') buffer += "All Pokémon on a team must share a type.<br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3493087/\">Monotype</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3517737/\">Monotype Viability Rankings</a><br />"; } if (target === 'all' || target === 'tiershift' || target === 'ts') { matched = true; if (target !== 'all') buffer += "Pokémon below OU get all their stats boosted. BL/UU get +5, BL2/RU get +10, and BL3/NU or lower get +15.<br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3508369/\">Tier Shift</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3514386/\">Tier Shift Viability Rankings</a><br />"; } if (target === 'all' || target === 'pu') { matched = true; if (target !== 'all') buffer += "The unofficial tier below NU.<br />"; buffer += "- <a href=\"http://www.smogon.com/forums/forums/pu.327/\">PU</a><br />"; } if (target === 'all' || target === 'inversebattle' || target === 'inverse') { matched = true; if (target !== 'all') buffer += "Battle with an inverted type chart.<br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3518146/\">Inverse Battle</a><br />"; } if (target === 'all' || target === 'almostanyability' || target === 'aaa') { matched = true; if (target !== 'all') buffer += "Pokémon can use any ability, barring the few that are banned.<br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3528058/\">Almost Any Ability</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3517258/\">Almost Any Ability Viability Rankings</a><br />"; } if (target === 'all' || target === 'stabmons') { matched = true; if (target !== 'all') buffer += "Pokémon can use any move of their typing, in addition to the moves they can normally learn.<br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3493081/\">STABmons</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3512215/\">STABmons Viability Rankings</a><br />"; } if (target === 'all' || target === 'lcuu') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3523929/\">LC UU</a><br />"; } if (target === 'all' || target === '350cup') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3512945/\">350 Cup</a><br />"; } if (target === 'all' || target === 'averagemons') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3526481/\">Averagemons</a><br />"; } if (target === 'all' || target === 'classichackmons' || target === 'hackmons') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3521887/\">Classic Hackmons</a><br />"; } if (target === 'all' || target === 'hiddentype') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3516349/\">Hidden Type</a><br />"; } if (target === 'all' || target === 'middlecup' || target === 'mc') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3524287/\">Middle Cup</a><br />"; } if (target === 'all' || target === 'skybattle') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3493601/\">Sky Battle</a><br />"; } if (!matched) { return this.sendReply("The Other Metas entry '" + target + "' was not found. Try /othermetas or /om for general help."); } this.sendReplyBox(buffer); }, /*formats: 'formathelp', formatshelp: 'formathelp', formathelp: function (target, room, user) { if (!this.canBroadcast()) return; if (this.broadcasting && (room.id === 'lobby' || room.battle)) return this.sendReply("This command is too spammy to broadcast in lobby/battles"); var buf = []; var showAll = (target === 'all'); for (var id in Tools.data.Formats) { var format = Tools.data.Formats[id]; if (!format) continue; if (format.effectType !== 'Format') continue; if (!format.challengeShow) continue; if (!showAll && !format.searchShow) continue; buf.push({ name: format.name, gameType: format.gameType || 'singles', mod: format.mod, searchShow: format.searchShow, desc: format.desc || 'No description.' }); } this.sendReplyBox( "Available Formats: (<strong>Bold</strong> formats are on ladder.)<br />" + buf.map(function (data) { var str = ""; // Bold = Ladderable. str += (data.searchShow ? "<strong>" + data.name + "</strong>" : data.name) + ": "; str += "(" + (!data.mod || data.mod === 'base' ? "" : data.mod + " ") + data.gameType + " format) "; str += data.desc; return str; }).join("<br />") ); },*/ roomhelp: function (target, room, user) { if (room.id === 'lobby' || room.battle) return this.sendReply("This command is too spammy for lobby/battles."); if (!this.canBroadcast()) return; this.sendReplyBox( "Room drivers (%) can use:<br />" + "- /warn OR /k <em>username</em>: warn a user and show the Pokemon Showdown rules<br />" + "- /mute OR /m <em>username</em>: 7 minute mute<br />" + "- /hourmute OR /hm <em>username</em>: 60 minute mute<br />" + "- /unmute <em>username</em>: unmute<br />" + "- /announce OR /wall <em>message</em>: make an announcement<br />" + "- /modlog <em>username</em>: search the moderator log of the room<br />" + "- /modnote <em>note</em>: adds a moderator note that can be read through modlog<br />" + "<br />" + "Room moderators (@) can also use:<br />" + "- /roomban OR /rb <em>username</em>: bans user from the room<br />" + "- /roomunban <em>username</em>: unbans user from the room<br />" + "- /roomvoice <em>username</em>: appoint a room voice<br />" + "- /roomdevoice <em>username</em>: remove a room voice<br />" + "- /modchat <em>[off/autoconfirmed/+]</em>: set modchat level<br />" + "<br />" + "Room owners (#) can also use:<br />" + "- /roomintro <em>intro</em>: sets the room introduction that will be displayed for all users joining the room<br />" + "- /rules <em>rules link</em>: set the room rules link seen when using /rules<br />" + "- /roommod, /roomdriver <em>username</em>: appoint a room moderator/driver<br />" + "- /roomdemod, /roomdedriver <em>username</em>: remove a room moderator/driver<br />" + "- /modchat <em>[%/@/#]</em>: set modchat level<br />" + "- /declare <em>message</em>: make a large blue declaration to the room<br />" + "- !htmlbox <em>HTML code</em>: broadcasts a box of HTML code to the room<br />" + "- !showimage <em>[url], [width], [height]</em>: shows an image to the room<br />" + "<br />" + "More detailed help can be found in the <a href=\"https://www.smogon.com/sim/roomauth_guide\">roomauth guide</a><br />" + "</div>" ); }, restarthelp: function (target, room, user) { if (room.id === 'lobby' && !this.can('lockdown')) return false; if (!this.canBroadcast()) return; this.sendReplyBox( "The server is restarting. Things to know:<br />" + "- We wait a few minutes before restarting so people can finish up their battles<br />" + "- The restart itself will take around 0.6 seconds<br />" + "- Your ladder ranking and teams will not change<br />" + "- We are restarting to update Pokémon Showdown to a newer version" ); }, rule: 'rules', rules: function (target, room, user) { if (!target) { if (!this.canBroadcast()) return; this.sendReplyBox("Please follow the rules:<br />" + (room.rulesLink ? "- <a href=\"" + Tools.escapeHTML(room.rulesLink) + "\">" + Tools.escapeHTML(room.title) + " room rules</a><br />" : "") + "- <a href=\"https://pokemonshowdown.com/rules\">" + (room.rulesLink ? "Global rules" : "Rules") + "</a>"); return; } if (!this.can('roommod', null, room)) return; if (target.length > 100) { return this.sendReply("Error: Room rules link is too long (must be under 100 characters). You can use a URL shortener to shorten the link."); } room.rulesLink = target.trim(); this.sendReply("(The room rules link is now: " + target + ")"); if (room.chatRoomData) { room.chatRoomData.rulesLink = room.rulesLink; Rooms.global.writeChatRoomData(); } }, faq: function (target, room, user) { if (!this.canBroadcast()) return; target = target.toLowerCase(); var buffer = ""; var matched = false; if (target === 'all' && this.broadcasting) { return this.sendReplyBox("You cannot broadcast all FAQs at once."); } if (!target || target === 'all') { matched = true; buffer += "<a href=\"https://www.smogon.com/sim/faq\">Frequently Asked Questions</a><br />"; } if (target === 'all' || target === 'elo') { matched = true; buffer += "<a href=\"https://www.smogon.com/sim/faq#elo\">Why did this user gain or lose so many points?</a><br />"; } if (target === 'all' || target === 'doubles' || target === 'triples' || target === 'rotation') { matched = true; buffer += "<a href=\"https://www.smogon.com/sim/faq#doubles\">Can I play doubles/triples/rotation battles here?</a><br />"; } if (target === 'all' || target === 'restarts') { matched = true; buffer += "<a href=\"https://www.smogon.com/sim/faq#restarts\">Why is the server restarting?</a><br />"; } if (target === 'all' || target === 'star' || target === 'player') { matched = true; buffer += '<a href="http://www.smogon.com/sim/faq#star">Why is there this star (&starf;) in front of my username?</a><br />'; } if (target === 'all' || target === 'staff') { matched = true; buffer += "<a href=\"https://www.smogon.com/sim/staff_faq\">Staff FAQ</a><br />"; } if (target === 'all' || target === 'autoconfirmed' || target === 'ac') { matched = true; buffer += "A user is autoconfirmed when they have won at least one rated battle and have been registered for a week or longer.<br />"; } if (target === 'all' || target === 'customavatar' || target === 'ca') { matched = true; buffer += "<a href=\"https://www.smogon.com/sim/faq#customavatar\">How can I get a custom avatar?</a><br />"; } if (target === 'all' || target === 'pm') { matched = true; buffer += "<a href=\"https://www.smogon.com/sim/faq#pm\">How can I send a user a private message?</a><br />"; } if (target === 'all' || target === 'challenge') { matched = true; buffer += "<a href=\"https://www.smogon.com/sim/faq#challenge\">How can I battle a specific user?</a><br />"; } if (target === 'all' || target === 'gxe') { matched = true; buffer += "<a href=\"https://www.smogon.com/sim/faq#gxe\">What does GXE mean?</a><br />"; } if (!matched) { return this.sendReply("The FAQ entry '" + target + "' was not found. Try /faq for general help."); } this.sendReplyBox(buffer); }, banlists: 'tiers', tier: 'tiers', tiers: function (target, room, user) { if (!this.canBroadcast()) return; target = toId(target); var buffer = ""; var matched = false; if (target === 'all' && this.broadcasting) { return this.sendReplyBox("You cannot broadcast information about all tiers at once."); } if (!target || target === 'all') { matched = true; buffer += "- <a href=\"https://www.smogon.com/tiers/\">Smogon Tiers</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/tiering-faq.3498332/\">Tiering FAQ</a><br />"; buffer += "- <a href=\"https://www.smogon.com/xyhub/tiers\">The banlists for each tier</a><br />"; } if (target === 'all' || target === 'overused' || target === 'ou') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3521201/\">OU Metagame Discussion</a><br />"; buffer += "- <a href=\"https://www.smogon.com/dex/xy/tags/ou/\">OU Banlist</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3526596/\">OU Viability Rankings</a><br />"; } if (target === 'all' || target === 'ubers' || target === 'uber') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3522911/\">Ubers Metagame Discussion</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3523419/\">Ubers Viability Rankings</a><br />"; } if (target === 'all' || target === 'underused' || target === 'uu') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3528903/\">np: UU Stage 2</a><br />"; buffer += "- <a href=\"https://www.smogon.com/dex/xy/tags/uu/\">UU Banlist</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3523649/\">UU Viability Rankings</a><br />"; } if (target === 'all' || target === 'rarelyused' || target === 'ru') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3527140/\">np: RU Stage 6</a><br />"; buffer += "- <a href=\"https://www.smogon.com/dex/xy/tags/ru/\">RU Banlist</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3523627/\">RU Viability Rankings</a><br />"; } if (target === 'all' || target === 'neverused' || target === 'nu') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3528871/\">np: NU Stage 4</a><br />"; buffer += "- <a href=\"https://www.smogon.com/dex/xy/tags/nu/\">NU Banlist</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3523692/\">NU Viability Rankings</a><br />"; } if (target === 'all' || target === 'littlecup' || target === 'lc') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3505710/\">LC Metagame Discussion</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3490462/\">LC Banlist</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3496013/\">LC Viability Rankings</a><br />"; } if (target === 'all' || target === 'smogondoubles' || target === 'doubles') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3525739/\">np: Doubles Stage 1.5</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3498688/\">Doubles Banlist</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3522814/\">Doubles Viability Rankings</a><br />"; } if (target === 'all' || target === 'anythinggoes' || target === 'ag') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3523229/\">Anything Goes</a><br />"; } if (!matched) { return this.sendReply("The Tiers entry '" + target + "' was not found. Try /tiers for general help."); } this.sendReplyBox(buffer); }, analysis: 'smogdex', strategy: 'smogdex', smogdex: function (target, room, user) { if (!this.canBroadcast()) return; var targets = target.split(','); if (toId(targets[0]) === 'previews') return this.sendReplyBox("<a href=\"https://www.smogon.com/forums/threads/sixth-generation-pokemon-analyses-index.3494918/\">Generation 6 Analyses Index</a>, brought to you by <a href=\"https://www.smogon.com\">Smogon University</a>"); var pokemon = Tools.getTemplate(targets[0]); var item = Tools.getItem(targets[0]); var move = Tools.getMove(targets[0]); var ability = Tools.getAbility(targets[0]); var atLeastOne = false; var generation = (targets[1] || 'xy').trim().toLowerCase(); var genNumber = 6; // var doublesFormats = {'vgc2012':1, 'vgc2013':1, 'vgc2014':1, 'doubles':1}; var doublesFormats = {}; var doublesFormat = (!targets[2] && generation in doublesFormats) ? generation : (targets[2] || '').trim().toLowerCase(); var doublesText = ''; if (generation === 'xy' || generation === 'xy' || generation === '6' || generation === 'six') { generation = 'xy'; } else if (generation === 'bw' || generation === 'bw2' || generation === '5' || generation === 'five') { generation = 'bw'; genNumber = 5; } else if (generation === 'dp' || generation === 'dpp' || generation === '4' || generation === 'four') { generation = 'dp'; genNumber = 4; } else if (generation === 'adv' || generation === 'rse' || generation === 'rs' || generation === '3' || generation === 'three') { generation = 'rs'; genNumber = 3; } else if (generation === 'gsc' || generation === 'gs' || generation === '2' || generation === 'two') { generation = 'gs'; genNumber = 2; } else if (generation === 'rby' || generation === 'rb' || generation === '1' || generation === 'one') { generation = 'rb'; genNumber = 1; } else { generation = 'xy'; } if (doublesFormat !== '') { // Smogon only has doubles formats analysis from gen 5 onwards. if (!(generation in {'bw':1, 'xy':1}) || !(doublesFormat in doublesFormats)) { doublesFormat = ''; } else { doublesText = {'vgc2012':"VGC 2012", 'vgc2013':"VGC 2013", 'vgc2014':"VGC 2014", 'doubles':"Doubles"}[doublesFormat]; doublesFormat = '/' + doublesFormat; } } // Pokemon if (pokemon.exists) { atLeastOne = true; if (genNumber < pokemon.gen) { return this.sendReplyBox("" + pokemon.name + " did not exist in " + generation.toUpperCase() + "!"); } // if (pokemon.tier === 'CAP') generation = 'cap'; if (pokemon.tier === 'CAP') return this.sendReply("CAP is not currently supported by Smogon Strategic Pokedex."); var illegalStartNums = {'351':1, '421':1, '487':1, '493':1, '555':1, '647':1, '648':1, '649':1, '681':1}; if (pokemon.isMega || pokemon.num in illegalStartNums) pokemon = Tools.getTemplate(pokemon.baseSpecies); var poke = pokemon.name.toLowerCase().replace(/\ /g, '_').replace(/[^a-z0-9\-\_]+/g, ''); this.sendReplyBox("<a href=\"https://www.smogon.com/dex/" + generation + "/pokemon/" + poke + doublesFormat + "\">" + generation.toUpperCase() + " " + doublesText + " " + pokemon.name + " analysis</a>, brought to you by <a href=\"https://www.smogon.com\">Smogon University</a>"); } // Item if (item.exists && genNumber > 1 && item.gen <= genNumber) { atLeastOne = true; var itemName = item.name.toLowerCase().replace(' ', '_'); this.sendReplyBox("<a href=\"https://www.smogon.com/dex/" + generation + "/items/" + itemName + "\">" + generation.toUpperCase() + " " + item.name + " item analysis</a>, brought to you by <a href=\"https://www.smogon.com\">Smogon University</a>"); } // Ability if (ability.exists && genNumber > 2 && ability.gen <= genNumber) { atLeastOne = true; var abilityName = ability.name.toLowerCase().replace(' ', '_'); this.sendReplyBox("<a href=\"https://www.smogon.com/dex/" + generation + "/abilities/" + abilityName + "\">" + generation.toUpperCase() + " " + ability.name + " ability analysis</a>, brought to you by <a href=\"https://www.smogon.com\">Smogon University</a>"); } // Move if (move.exists && move.gen <= genNumber) { atLeastOne = true; var moveName = move.name.toLowerCase().replace(' ', '_'); this.sendReplyBox("<a href=\"https://www.smogon.com/dex/" + generation + "/moves/" + moveName + "\">" + generation.toUpperCase() + " " + move.name + " move analysis</a>, brought to you by <a href=\"https://www.smogon.com\">Smogon University</a>"); } if (!atLeastOne) { return this.sendReplyBox("Pokemon, item, move, or ability not found for generation " + generation.toUpperCase() + "."); } }, /********************************************************* * Miscellaneous commands *********************************************************/ potd: function (target, room, user) { if (!this.can('potd')) return false; Config.potd = target; Simulator.SimulatorProcess.eval('Config.potd = \'' + toId(target) + '\''); if (target) { if (Rooms.lobby) Rooms.lobby.addRaw("<div class=\"broadcast-blue\"><b>The Pokemon of the Day is now " + target + "!</b><br />This Pokemon will be guaranteed to show up in random battles.</div>"); this.logModCommand("The Pokemon of the Day was changed to " + target + " by " + user.name + "."); } else { if (Rooms.lobby) Rooms.lobby.addRaw("<div class=\"broadcast-blue\"><b>The Pokemon of the Day was removed!</b><br />No pokemon will be guaranteed in random battles.</div>"); this.logModCommand("The Pokemon of the Day was removed by " + user.name + "."); } }, spammode: function (target, room, user) { if (!this.can('ban')) return false; // NOTE: by default, spammode does nothing; it's up to you to set stricter filters // in config for chatfilter/hostfilter. Put this above the spammode filters: /* if (!Config.spammode) return; if (Config.spammode < Date.now()) { delete Config.spammode; return; } */ if (target === 'off' || target === 'false') { if (Config.spammode) { delete Config.spammode; this.privateModCommand("(" + user.name + " turned spammode OFF.)"); } else { this.sendReply("Spammode is already off."); } } else if (!target || target === 'on' || target === 'true') { if (Config.spammode) { this.privateModCommand("(" + user.name + " renewed spammode for half an hour.)"); } else { this.privateModCommand("(" + user.name + " turned spammode ON for half an hour.)"); } Config.spammode = Date.now() + 30 * 60 * 1000; } else { this.sendReply("Unrecognized spammode setting."); } }, roll: 'dice', dice: function (target, room, user) { if (!target) return this.parse('/help dice'); if (!this.canBroadcast()) return; var d = target.indexOf("d"); if (d >= 0) { var num = parseInt(target.substring(0, d)); var faces; if (target.length > d) faces = parseInt(target.substring(d + 1)); if (isNaN(num)) num = 1; if (isNaN(faces)) return this.sendReply("The number of faces must be a valid integer."); if (faces < 1 || faces > 1000) return this.sendReply("The number of faces must be between 1 and 1000"); if (num < 1 || num > 20) return this.sendReply("The number of dice must be between 1 and 20"); var rolls = []; var total = 0; for (var i = 0; i < num; ++i) { rolls[i] = (Math.floor(faces * Math.random()) + 1); total += rolls[i]; } return this.sendReplyBox("Random number " + num + "x(1 - " + faces + "): " + rolls.join(", ") + "<br />Total: " + total); } if (target && isNaN(target) || target.length > 21) return this.sendReply("The max roll must be a number under 21 digits."); var maxRoll = (target) ? target : 6; var rand = Math.floor(maxRoll * Math.random()) + 1; return this.sendReplyBox("Random number (1 - " + maxRoll + "): " + rand); }, pr: 'pickrandom', pick: 'pickrandom', pickrandom: function (target, room, user) { var options = target.split(','); if (options.length < 2) return this.parse('/help pick'); if (!this.canBroadcast()) return false; return this.sendReplyBox('<em>We randomly picked:</em> ' + Tools.escapeHTML(options.sample().trim())); }, register: function () { if (!this.canBroadcast()) return; this.sendReplyBox('You will be prompted to register upon winning a rated battle. Alternatively, there is a register button in the <button name="openOptions"><i class="icon-cog"></i> Options</button> menu in the upper right.'); }, lobbychat: function (target, room, user, connection) { if (!Rooms.lobby) return this.popupReply("This server doesn't have a lobby."); target = toId(target); if (target === 'off') { user.leaveRoom(Rooms.lobby, connection.socket); connection.send('|users|'); this.sendReply("You are now blocking lobby chat."); } else { user.joinRoom(Rooms.lobby, connection); this.sendReply("You are now receiving lobby chat."); } }, showimage: function (target, room, user) { if (!target) return this.parse('/help showimage'); if (!this.can('declare', null, room)) return false; if (!this.canBroadcast()) return; var targets = target.split(','); if (targets.length !== 3) { return this.parse('/help showimage'); } this.sendReply('|raw|<img src="' + Tools.escapeHTML(targets[0]) + '" alt="" width="' + toId(targets[1]) + '" height="' + toId(targets[2]) + '" />'); }, htmlbox: function (target, room, user) { if (!target) return this.parse('/help htmlbox'); if (!this.can('declare', null, room)) return; if (!this.canHTML(target)) return; if (!this.canBroadcast('!htmlbox')) return; this.sendReplyBox(target); }, a: function (target, room, user) { if (!this.can('rawpacket')) return false; // secret sysop command room.add(target); }, /********************************************************* * Help commands *********************************************************/ commands: 'help', h: 'help', '?': 'help', help: function (target, room, user) { target = target.toLowerCase(); var matched = false; if (target === 'msg' || target === 'pm' || target === 'whisper' || target === 'w') { matched = true; this.sendReply("/msg OR /whisper OR /w [username], [message] - Send a private message."); } if (target === 'r' || target === 'reply') { matched = true; this.sendReply("/reply OR /r [message] - Send a private message to the last person you received a message from, or sent a message to."); } if (target === 'avatar') { matched = true; this.sendReply("/avatar [new avatar number] - Change your trainer sprite."); } if (target === 'whois' || target === 'alts' || target === 'ip' || target === 'rooms') { matched = true; this.sendReply("/whois - Get details on yourself: alts, group, IP address, and rooms."); this.sendReply("/whois [username] - Get details on a username: alts (Requires: % @ & ~), group, IP address (Requires: @ & ~), and rooms."); } if (target === 'data') { matched = true; this.sendReply("/data [pokemon/item/move/ability] - Get details on this pokemon/item/move/ability/nature."); this.sendReply("!data [pokemon/item/move/ability] - Show everyone these details. Requires: + % @ & ~"); } if (target === 'details' || target === 'dt') { matched = true; this.sendReply("/details [pokemon] - Get additional details on this pokemon/item/move/ability/nature."); this.sendReply("!details [pokemon] - Show everyone these details. Requires: + % @ & ~"); } if (target === 'analysis') { matched = true; this.sendReply("/analysis [pokemon], [generation] - Links to the Smogon University analysis for this Pokemon in the given generation."); this.sendReply("!analysis [pokemon], [generation] - Shows everyone this link. Requires: + % @ & ~"); } if (target === 'groups') { matched = true; this.sendReply("/groups - Explains what the + % @ & next to people's names mean."); this.sendReply("!groups - Show everyone that information. Requires: + % @ & ~"); } if (target === 'opensource') { matched = true; this.sendReply("/opensource - Links to PS's source code repository."); this.sendReply("!opensource - Show everyone that information. Requires: + % @ & ~"); } if (target === 'avatars') { matched = true; this.sendReply("/avatars - Explains how to change avatars."); this.sendReply("!avatars - Show everyone that information. Requires: + % @ & ~"); } if (target === 'intro') { matched = true; this.sendReply("/intro - Provides an introduction to competitive pokemon."); this.sendReply("!intro - Show everyone that information. Requires: + % @ & ~"); } if (target === 'cap') { matched = true; this.sendReply("/cap - Provides an introduction to the Create-A-Pokemon project."); this.sendReply("!cap - Show everyone that information. Requires: + % @ & ~"); } if (target === 'om') { matched = true; this.sendReply("/om - Provides links to information on the Other Metagames."); this.sendReply("!om - Show everyone that information. Requires: + % @ & ~"); } if (target === 'learn' || target === 'learnset' || target === 'learnall') { matched = true; this.sendReply("/learn [pokemon], [move, move, ...] - Displays how a Pokemon can learn the given moves, if it can at all."); this.sendReply("!learn [pokemon], [move, move, ...] - Show everyone that information. Requires: + % @ & ~"); } if (target === 'calc' || target === 'calculator') { matched = true; this.sendReply("/calc - Provides a link to a damage calculator"); this.sendReply("!calc - Shows everyone a link to a damage calculator. Requires: + % @ & ~"); } if (target === 'blockchallenges' || target === 'away' || target === 'idle') { matched = true; this.sendReply("/away - Blocks challenges so no one can challenge you. Deactivate it with /back."); } if (target === 'allowchallenges' || target === 'back') { matched = true; this.sendReply("/back - Unlocks challenges so you can be challenged again. Deactivate it with /away."); } if (target === 'faq') { matched = true; this.sendReply("/faq [theme] - Provides a link to the FAQ. Add deviation, doubles, randomcap, restart, or staff for a link to these questions. Add all for all of them."); this.sendReply("!faq [theme] - Shows everyone a link to the FAQ. Add deviation, doubles, randomcap, restart, or staff for a link to these questions. Add all for all of them. Requires: + % @ & ~"); } if (target === 'effectiveness' || target === 'matchup' || target === 'eff' || target === 'type') { matched = true; this.sendReply("/effectiveness OR /matchup OR /eff OR /type [attack], [defender] - Provides the effectiveness of a move or type on another type or a Pokémon."); this.sendReply("!effectiveness OR !matchup OR !eff OR !type [attack], [defender] - Shows everyone the effectiveness of a move or type on another type or a Pokémon."); } if (target === 'dexsearch' || target === 'dsearch' || target === 'ds') { matched = true; this.sendReply("/dexsearch [type], [move], [move], ... - Searches for Pokemon that fulfill the selected criteria."); this.sendReply("Search categories are: type, tier, color, moves, ability, gen."); this.sendReply("Valid colors are: green, red, blue, white, brown, yellow, purple, pink, gray and black."); this.sendReply("Valid tiers are: Uber/OU/BL/UU/BL2/RU/BL3/NU/PU/NFE/LC/CAP."); this.sendReply("Types must be followed by ' type', e.g., 'dragon type'."); this.sendReply("Parameters can be excluded through the use of '!', e.g., '!water type' excludes all water types."); this.sendReply("The parameter 'mega' can be added to search for Mega Evolutions only, and the parameters 'FE' or 'NFE' can be added to search fully or not-fully evolved Pokemon only."); this.sendReply("The order of the parameters does not matter."); } if (target === 'dice' || target === 'roll') { matched = true; this.sendReply("/dice [optional max number] - Randomly picks a number between 1 and 6, or between 1 and the number you choose."); this.sendReply("/dice [number of dice]d[number of sides] - Simulates rolling a number of dice, e.g., /dice 2d4 simulates rolling two 4-sided dice."); } if (target === 'pick' || target === 'pickrandom') { matched = true; this.sendReply("/pick [option], [option], ... - Randomly selects an item from a list containing 2 or more elements."); } if (target === 'invite') { matched = true; this.sendReply("/invite [username], [roomname] - Invites the player [username] to join the room [roomname]."); } // driver commands if (target === 'lock' || target === 'l') { matched = true; this.sendReply("/lock OR /l [username], [reason] - Locks the user from talking in all chats. Requires: % @ & ~"); } if (target === 'unlock') { matched = true; this.sendReply("/unlock [username] - Unlocks the user. Requires: % @ & ~"); } if (target === 'redirect' || target === 'redir') { matched = true; this.sendReply("/redirect OR /redir [username], [roomname] - Attempts to redirect the user [username] to the room [roomname]. Requires: % @ & ~"); } if (target === 'modnote') { matched = true; this.sendReply("/modnote [note] - Adds a moderator note that can be read through modlog. Requires: % @ & ~"); } if (target === 'forcerename' || target === 'fr') { matched = true; this.sendReply("/forcerename OR /fr [username], [reason] - Forcibly change a user's name and shows them the [reason]. Requires: % @ & ~"); } if (target === 'kickbattle') { matched = true; this.sendReply("/kickbattle [username], [reason] - Kicks a user from a battle with reason. Requires: % @ & ~"); } if (target === 'warn' || target === 'k') { matched = true; this.sendReply("/warn OR /k [username], [reason] - Warns a user showing them the Pokemon Showdown Rules and [reason] in an overlay. Requires: % @ & ~"); } if (target === 'modlog') { matched = true; this.sendReply("/modlog [roomid|all], [n] - Roomid defaults to current room. If n is a number or omitted, display the last n lines of the moderator log. Defaults to 15. If n is not a number, search the moderator log for 'n' on room's log [roomid]. If you set [all] as [roomid], searches for 'n' on all rooms's logs. Requires: % @ & ~"); } if (target === 'mute' || target === 'm') { matched = true; this.sendReply("/mute OR /m [username], [reason] - Mutes a user with reason for 7 minutes. Requires: % @ & ~"); } if (target === 'hourmute' || target === 'hm') { matched = true; this.sendReply("/hourmute OR /hm [username], [reason] - Mutes a user with reason for an hour. Requires: % @ & ~"); } if (target === 'unmute' || target === 'um') { matched = true; this.sendReply("/unmute [username] - Removes mute from user. Requires: % @ & ~"); } // mod commands if (target === 'roomban' || target === 'rb') { matched = true; this.sendReply("/roomban [username] - Bans the user from the room you are in. Requires: @ & ~"); } if (target === 'roomunban') { matched = true; this.sendReply("/roomunban [username] - Unbans the user from the room you are in. Requires: @ & ~"); } if (target === 'ban' || target === 'b') { matched = true; this.sendReply("/ban OR /b [username], [reason] - Kick user from all rooms and ban user's IP address with reason. Requires: @ & ~"); } if (target === 'unban') { matched = true; this.sendReply("/unban [username] - Unban a user. Requires: @ & ~"); } // RO commands if (target === 'showimage') { matched = true; this.sendReply("/showimage [url], [width], [height] - Show an image. Requires: # & ~"); } if (target === 'roompromote') { matched = true; this.sendReply("/roompromote [username], [group] - Promotes the user to the specified group or next ranked group. Requires: @ # & ~"); } if (target === 'roomdemote') { matched = true; this.sendReply("/roomdemote [username], [group] - Demotes the user to the specified group or previous ranked group. Requires: @ # & ~"); } // leader commands if (target === 'banip') { matched = true; this.sendReply("/banip [ip] - Kick users on this IP or IP range from all rooms and bans it. Accepts wildcards to ban ranges. Requires: & ~"); } if (target === 'unbanip') { matched = true; this.sendReply("/unbanip [ip] - Kick users on this IP or IP range from all rooms and bans it. Accepts wildcards to ban ranges. Requires: & ~"); } if (target === 'unbanall') { matched = true; this.sendReply("/unbanall - Unban all IP addresses. Requires: & ~"); } if (target === 'promote') { matched = true; this.sendReply("/promote [username], [group] - Promotes the user to the specified group or next ranked group. Requires: & ~"); } if (target === 'demote') { matched = true; this.sendReply("/demote [username], [group] - Demotes the user to the specified group or previous ranked group. Requires: & ~"); } if (target === 'forcetie') { matched = true; this.sendReply("/forcetie - Forces the current match to tie. Requires: & ~"); } if (target === 'declare') { matched = true; this.sendReply("/declare [message] - Anonymously announces a message. Requires: & ~"); } // admin commands if (target === 'chatdeclare' || target === 'cdeclare') { matched = true; this.sendReply("/cdeclare [message] - Anonymously announces a message to all chatrooms on the server. Requires: ~"); } if (target === 'globaldeclare' || target === 'gdeclare') { matched = true; this.sendReply("/globaldeclare [message] - Anonymously announces a message to every room on the server. Requires: ~"); } if (target === 'htmlbox') { matched = true; this.sendReply("/htmlbox [message] - Displays a message, parsing HTML code contained. Requires: ~ # with global authority"); } if (target === 'announce' || target === 'wall') { matched = true; this.sendReply("/announce OR /wall [message] - Makes an announcement. Requires: % @ & ~"); } if (target === 'modchat') { matched = true; this.sendReply("/modchat [off/autoconfirmed/+/%/@/&/~] - Set the level of moderated chat. Requires: @ for off/autoconfirmed/+ options, & ~ for all the options"); } if (target === 'hotpatch') { matched = true; this.sendReply("Hot-patching the game engine allows you to update parts of Showdown without interrupting currently-running battles. Requires: ~"); this.sendReply("Hot-patching has greater memory requirements than restarting."); this.sendReply("/hotpatch chat - reload chat-commands.js"); this.sendReply("/hotpatch battles - spawn new simulator processes"); this.sendReply("/hotpatch formats - reload the tools.js tree, rebuild and rebroad the formats list, and also spawn new simulator processes"); } if (target === 'lockdown') { matched = true; this.sendReply("/lockdown - locks down the server, which prevents new battles from starting so that the server can eventually be restarted. Requires: ~"); } if (target === 'kill') { matched = true; this.sendReply("/kill - kills the server. Can't be done unless the server is in lockdown state. Requires: ~"); } if (target === 'loadbanlist') { matched = true; this.sendReply("/loadbanlist - Loads the bans located at ipbans.txt. The command is executed automatically at startup. Requires: ~"); } if (target === 'makechatroom') { matched = true; this.sendReply("/makechatroom [roomname] - Creates a new room named [roomname]. Requires: ~"); } if (target === 'deregisterchatroom') { matched = true; this.sendReply("/deregisterchatroom [roomname] - Deletes room [roomname] after the next server restart. Requires: ~"); } if (target === 'roomowner') { matched = true; this.sendReply("/roomowner [username] - Appoints [username] as a room owner. Removes official status. Requires: ~"); } if (target === 'roomdeowner') { matched = true; this.sendReply("/roomdeowner [username] - Removes [username]'s status as a room owner. Requires: ~"); } if (target === 'privateroom' || target === 'hiddenroom') { matched = true; this.sendReply("/privateroom [on/off] - Makes or unmakes a room private. Requires: ~"); this.sendReply("/hiddenroom [on/off] - Makes or unmakes a room hidden. Hidden rooms will maintain global ranks of users. Requires: \u2605 ~"); } // overall if (target === 'help' || target === 'h' || target === '?' || target === 'commands') { matched = true; this.sendReply("/help OR /h OR /? - Gives you help."); } if (!target) { this.sendReply("COMMANDS: /nick, /avatar, /rating, /whois, /msg, /reply, /ignore, /away, /back, /timestamps, /highlight"); this.sendReply("INFORMATIONAL COMMANDS: /data, /dexsearch, /groups, /opensource, /avatars, /faq, /rules, /intro, /tiers, /othermetas, /learn, /analysis, /calc (replace / with ! to broadcast. Broadcasting requires: + % @ & ~)"); if (user.group !== Config.groupsranking[0]) { this.sendReply("DRIVER COMMANDS: /warn, /mute, /unmute, /alts, /forcerename, /modlog, /lock, /unlock, /announce, /redirect"); this.sendReply("MODERATOR COMMANDS: /ban, /unban, /ip"); this.sendReply("LEADER COMMANDS: /declare, /forcetie, /forcewin, /promote, /demote, /banip, /unbanall"); } this.sendReply("For an overview of room commands, use /roomhelp"); this.sendReply("For details of a specific command, use something like: /help data"); } else if (!matched) { this.sendReply("Help for the command '" + target + "' was not found. Try /help for general help"); } } };
import React, { Component } from 'react'; import moment from 'moment'; import glamorous from 'glamorous'; moment.locale('it'); const Time = glamorous.div({ fontSize: '48px', color: '#fff', fontFamily: 'LeroyMerlinSans Bold', textTransform: 'uppercase' }); export default class DateBadge extends Component { constructor(props) { super(props); this.state = { currentTime: '', intID: '' }; } componentWillMount() { const intID = this.updateTime(); this.setState({ intID }); } shouldComponentUpdate(nextProps, nextState) { return nextState.currentTime !== this.state.currentTime; } componentWillUnmount() { const { intID } = this.state; clearInterval(intID); } updateTime() { return setInterval(() => { const currentTime = moment().format('ddd HH:mm'); this.setState({ currentTime }); }, 1000); } render() { const { currentTime } = this.state; return ( <Time> {currentTime} </Time> ); } }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as nls from '../../../nls.js'; import { Color, RGBA } from '../../../base/common/color.js'; import { activeContrastBorder, editorBackground, editorForeground, registerColor } from '../../../platform/theme/common/colorRegistry.js'; import { registerThemingParticipant } from '../../../platform/theme/common/themeService.js'; /** * Definition of the editor colors */ export var editorLineHighlight = registerColor('editor.lineHighlightBackground', { dark: null, light: null, hc: null }, nls.localize('lineHighlight', 'Background color for the highlight of line at the cursor position.')); export var editorLineHighlightBorder = registerColor('editor.lineHighlightBorder', { dark: '#282828', light: '#eeeeee', hc: '#f38518' }, nls.localize('lineHighlightBorderBox', 'Background color for the border around the line at the cursor position.')); export var editorRangeHighlight = registerColor('editor.rangeHighlightBackground', { dark: '#ffffff0b', light: '#fdff0033', hc: null }, nls.localize('rangeHighlight', 'Background color of highlighted ranges, like by quick open and find features. The color must not be opaque so as not to hide underlying decorations.'), true); export var editorRangeHighlightBorder = registerColor('editor.rangeHighlightBorder', { dark: null, light: null, hc: activeContrastBorder }, nls.localize('rangeHighlightBorder', 'Background color of the border around highlighted ranges.'), true); export var editorCursorForeground = registerColor('editorCursor.foreground', { dark: '#AEAFAD', light: Color.black, hc: Color.white }, nls.localize('caret', 'Color of the editor cursor.')); export var editorCursorBackground = registerColor('editorCursor.background', null, nls.localize('editorCursorBackground', 'The background color of the editor cursor. Allows customizing the color of a character overlapped by a block cursor.')); export var editorWhitespaces = registerColor('editorWhitespace.foreground', { dark: '#e3e4e229', light: '#33333333', hc: '#e3e4e229' }, nls.localize('editorWhitespaces', 'Color of whitespace characters in the editor.')); export var editorIndentGuides = registerColor('editorIndentGuide.background', { dark: editorWhitespaces, light: editorWhitespaces, hc: editorWhitespaces }, nls.localize('editorIndentGuides', 'Color of the editor indentation guides.')); export var editorActiveIndentGuides = registerColor('editorIndentGuide.activeBackground', { dark: editorWhitespaces, light: editorWhitespaces, hc: editorWhitespaces }, nls.localize('editorActiveIndentGuide', 'Color of the active editor indentation guides.')); export var editorLineNumbers = registerColor('editorLineNumber.foreground', { dark: '#858585', light: '#237893', hc: Color.white }, nls.localize('editorLineNumbers', 'Color of editor line numbers.')); var deprecatedEditorActiveLineNumber = registerColor('editorActiveLineNumber.foreground', { dark: '#c6c6c6', light: '#0B216F', hc: activeContrastBorder }, nls.localize('editorActiveLineNumber', 'Color of editor active line number'), false, nls.localize('deprecatedEditorActiveLineNumber', 'Id is deprecated. Use \'editorLineNumber.activeForeground\' instead.')); export var editorActiveLineNumber = registerColor('editorLineNumber.activeForeground', { dark: deprecatedEditorActiveLineNumber, light: deprecatedEditorActiveLineNumber, hc: deprecatedEditorActiveLineNumber }, nls.localize('editorActiveLineNumber', 'Color of editor active line number')); export var editorRuler = registerColor('editorRuler.foreground', { dark: '#5A5A5A', light: Color.lightgrey, hc: Color.white }, nls.localize('editorRuler', 'Color of the editor rulers.')); export var editorCodeLensForeground = registerColor('editorCodeLens.foreground', { dark: '#999999', light: '#999999', hc: '#999999' }, nls.localize('editorCodeLensForeground', 'Foreground color of editor code lenses')); export var editorBracketMatchBackground = registerColor('editorBracketMatch.background', { dark: '#0064001a', light: '#0064001a', hc: '#0064001a' }, nls.localize('editorBracketMatchBackground', 'Background color behind matching brackets')); export var editorBracketMatchBorder = registerColor('editorBracketMatch.border', { dark: '#888', light: '#B9B9B9', hc: '#fff' }, nls.localize('editorBracketMatchBorder', 'Color for matching brackets boxes')); export var editorOverviewRulerBorder = registerColor('editorOverviewRuler.border', { dark: '#7f7f7f4d', light: '#7f7f7f4d', hc: '#7f7f7f4d' }, nls.localize('editorOverviewRulerBorder', 'Color of the overview ruler border.')); export var editorGutter = registerColor('editorGutter.background', { dark: editorBackground, light: editorBackground, hc: editorBackground }, nls.localize('editorGutter', 'Background color of the editor gutter. The gutter contains the glyph margins and the line numbers.')); export var editorErrorForeground = registerColor('editorError.foreground', { dark: '#ea4646', light: '#d60a0a', hc: null }, nls.localize('errorForeground', 'Foreground color of error squigglies in the editor.')); export var editorErrorBorder = registerColor('editorError.border', { dark: null, light: null, hc: Color.fromHex('#E47777').transparent(0.8) }, nls.localize('errorBorder', 'Border color of error squigglies in the editor.')); export var editorWarningForeground = registerColor('editorWarning.foreground', { dark: '#4d9e4d', light: '#117711', hc: null }, nls.localize('warningForeground', 'Foreground color of warning squigglies in the editor.')); export var editorWarningBorder = registerColor('editorWarning.border', { dark: null, light: null, hc: Color.fromHex('#71B771').transparent(0.8) }, nls.localize('warningBorder', 'Border color of warning squigglies in the editor.')); export var editorInfoForeground = registerColor('editorInfo.foreground', { dark: '#008000', light: '#008000', hc: null }, nls.localize('infoForeground', 'Foreground color of info squigglies in the editor.')); export var editorInfoBorder = registerColor('editorInfo.border', { dark: null, light: null, hc: Color.fromHex('#71B771').transparent(0.8) }, nls.localize('infoBorder', 'Border color of info squigglies in the editor.')); export var editorHintForeground = registerColor('editorHint.foreground', { dark: Color.fromHex('#eeeeee').transparent(0.7), light: '#6c6c6c', hc: null }, nls.localize('hintForeground', 'Foreground color of hint squigglies in the editor.')); export var editorHintBorder = registerColor('editorHint.border', { dark: null, light: null, hc: Color.fromHex('#eeeeee').transparent(0.8) }, nls.localize('hintBorder', 'Border color of hint squigglies in the editor.')); export var editorUnnecessaryCodeBorder = registerColor('editorUnnecessaryCode.border', { dark: null, light: null, hc: Color.fromHex('#fff').transparent(0.8) }, nls.localize('unnecessaryCodeBorder', 'Border color of unnecessary (unused) source code in the editor.')); export var editorUnnecessaryCodeOpacity = registerColor('editorUnnecessaryCode.opacity', { dark: Color.fromHex('#000a'), light: Color.fromHex('#0007'), hc: null }, nls.localize('unnecessaryCodeOpacity', 'Opacity of unnecessary (unused) source code in the editor. For example, "#000000c0" will render the code with 75% opacity. For high contrast themes, use the \'editorUnnecessaryCode.border\' theme color to underline unnecessary code instead of fading it out.')); export var overviewRulerError = registerColor('editorOverviewRuler.errorForeground', { dark: new Color(new RGBA(255, 18, 18, 0.7)), light: new Color(new RGBA(255, 18, 18, 0.7)), hc: new Color(new RGBA(255, 50, 50, 1)) }, nls.localize('overviewRuleError', 'Overview ruler marker color for errors.')); export var overviewRulerWarning = registerColor('editorOverviewRuler.warningForeground', { dark: new Color(new RGBA(18, 136, 18, 0.7)), light: new Color(new RGBA(18, 136, 18, 0.7)), hc: new Color(new RGBA(50, 255, 50, 1)) }, nls.localize('overviewRuleWarning', 'Overview ruler marker color for warnings.')); export var overviewRulerInfo = registerColor('editorOverviewRuler.infoForeground', { dark: new Color(new RGBA(18, 18, 136, 0.7)), light: new Color(new RGBA(18, 18, 136, 0.7)), hc: new Color(new RGBA(50, 50, 255, 1)) }, nls.localize('overviewRuleInfo', 'Overview ruler marker color for infos.')); // contains all color rules that used to defined in editor/browser/widget/editor.css registerThemingParticipant(function (theme, collector) { var background = theme.getColor(editorBackground); if (background) { collector.addRule(".monaco-editor, .monaco-editor-background, .monaco-editor .inputarea.ime-input { background-color: " + background + "; }"); } var foreground = theme.getColor(editorForeground); if (foreground) { collector.addRule(".monaco-editor, .monaco-editor .inputarea.ime-input { color: " + foreground + "; }"); } var gutter = theme.getColor(editorGutter); if (gutter) { collector.addRule(".monaco-editor .margin { background-color: " + gutter + "; }"); } var rangeHighlight = theme.getColor(editorRangeHighlight); if (rangeHighlight) { collector.addRule(".monaco-editor .rangeHighlight { background-color: " + rangeHighlight + "; }"); } var rangeHighlightBorder = theme.getColor(editorRangeHighlightBorder); if (rangeHighlightBorder) { collector.addRule(".monaco-editor .rangeHighlight { border: 1px " + (theme.type === 'hc' ? 'dotted' : 'solid') + " " + rangeHighlightBorder + "; }"); } var invisibles = theme.getColor(editorWhitespaces); if (invisibles) { collector.addRule(".vs-whitespace { color: " + invisibles + " !important; }"); } });
'use strict'; var $npm = { con: require('manakin').local, result: require('./result'), special: require('./special'), context: require('./cnContext'), events: require('./events'), utils: require('./utils'), connect: require('./connect'), query: require('./query'), task: require('./task') }; var $arr = require('./array'); /** * @class Database * @description * * Represents the database protocol, extensible via event {@link event:extend extend}. * This type is not available directly, it can only be created via the library's base call. * * **IMPORTANT:** * * For any given connection, you should only create a single {@link Database} object in a separate module, * to be shared in your application (see the code example below). If instead you keep creating the {@link Database} * object dynamically, your application will suffer from loss in performance, and will be getting a warning in a * development environment (when `NODE_ENV` = `development`): * * `WARNING: Creating a duplicate database object for the same connection.` * * If you ever see this warning, rectify your {@link Database} object initialization, so there is only one object * per connection details. See the example provided below. * * See also: property `noWarnings` in {@link module:pg-promise Initialization Options}. * * @param {String|Object} cn * Database connection details, which can be: * * - a configuration object * - a connection string * * For details see {@link https://github.com/vitaly-t/pg-promise/wiki/Connection-Syntax Connection Syntax}. * * @param {} [dc] * Database Context. * * Any object or value to be propagated through the protocol, to allow implementations * and event handling that depend on the database context. * * This is mainly to facilitate the use of multiple databases which may need separate protocol * extensions, or different implementations within a single task / transaction callback, * depending on the database context. * * @returns {Database} * * @see * * {@link Database.query query}, * {@link Database.none none}, * {@link Database.one one}, * {@link Database.oneOrNone oneOrNone}, * {@link Database.many many}, * {@link Database.manyOrNone manyOrNone}, * {@link Database.any any}, * {@link Database.func func}, * {@link Database.proc proc}, * {@link Database.result result}, * {@link Database.map map}, * {@link Database.each each}, * {@link Database.stream stream}, * {@link Database.task task}, * {@link Database.tx tx}, * {@link Database.connect connect}, * {@link Database.$config $config}, * {@link event:extend extend} * * @example * // Proper way to initialize and share the Database object * * // Loading and initializing the library: * var pgp = require('pg-promise')({ * // Initialization Options * }); * * // Preparing the connection details: * var cn = "postgres://username:password@host:port/database"; * * // Creating a new database instance from the connection details: * var db = pgp(cn); * * // Exporting the database object for shared use: * module.exports = db; */ function Database(cn, dc, config) { checkForDuplicates(cn, config); setErrorHandler(config); var $p = config.promise; /** * @method Database.connect * * @description * Acquires a new or existing connection, based on the current connection parameters. * * This method creates a shared connection for executing a chain of queries against it. * The connection must be released in the end of the chain by calling method `done()` on the connection object. * * This is an older, low-level approach to chaining queries on the same connection. * A newer and safer approach is via methods {@link Database.task task} and {@link Database.tx tx} (for transactions), * which allocate and release the shared connection automatically. * * **NOTE:** Even though this method exposes a {@link external:Client Client} object via property `client`, * you cannot call `client.end()` directly, or it will print an error into the console: * `Abnormal client.end() call, due to invalid code or failed server connection.` * You should only call method `done()` to release the connection. * * @param {object} [options] * @param {boolean} [options.direct=false] * Creates the connection directly, through the {@link external:Client Client}, bypassing the connection pool. * * By default, all connections are acquired from the connection pool. If you set this option, the library will instead * create a new {@link external:Client Client} object directly (separately from the pool), and then call its `connect` method. * * **WARNING:** * * Do not use this option for regular query execution, because it exclusively occupies one physical connection, * and therefore cannot scale. This option is only suitable for global connection usage, such as database event listeners. * * @returns {external:Promise} * A promise object that represents the connection result: * - resolves with the complete {@link Database} protocol, extended with: * - property `client` of type {@link external:Client Client} that represents the open connection * - method `done()` that must be called in the end, in order to release the connection * - rejects with a connection-related error when it fails to connect. * * @see * {@link Database.task}, * {@link Database.tx} * * @example * * var sco; // shared connection object; * * db.connect() * .then(function (obj) { * // obj.client = new connected Client object; * * sco = obj; // save the connection object; * * // execute all the queries you need: * return sco.any('SELECT * FROM Users'); * }) * .then(function (data) { * // success * }) * .catch(function (error) { * // error * }) * .finally(function () { * // release the connection, if it was successful: * if (sco) { * sco.done(); * } * }); * */ this.connect = function (options) { var ctx = createContext(); var self = { // Generic query method; query: function (query, values, qrm) { if (!ctx.db) { throw new Error("Cannot execute a query on a disconnected client."); } return config.$npm.query.call(this, ctx, query, values, qrm); }, // Connection release method; done: function () { if (!ctx.db) { throw new Error("Cannot invoke done() on a disconnected client."); } ctx.disconnect(); } }; var method = (options && options.direct) ? 'direct' : 'pool'; return config.$npm.connect[method](ctx) .then(function (db) { ctx.connect(db); self.client = db.client; extend(ctx, self); return self; }); }; /** * @method Database.query * * @description * Executes a generic query request that expects the return data according to parameter `qrm`. * * @param {String|Object} query * Query to be executed, which can any of the following types: * - A non-empty query string * - Prepared Statement `{name, text, values, ...}` or {@link PreparedStatement} object * - Parameterized Query `{text, values, ...}` or {@link ParameterizedQuery} object * - {@link QueryFile} object * * @param {array|value} [values] * Query formatting parameters. * * When `query` is of type `string` or a {@link QueryFile} object, the `values` can be: * - a single value - to replace all `$1` occurrences * - an array of values - to replace all `$1`, `$2`, ... variables * - an object - to apply $[Named Parameters] formatting * * When `query` is a Prepared Statement or a Parameterized Query (or their class types), * and `values` is not `null` or `undefined`, it is automatically set within such object, * as an override for its internal `values`. * * @param {queryResult} [qrm=queryResult.any] * {@link queryResult Query Result Mask} * * @returns {external:Promise} * A promise object that represents the query result. * * When the query result is an array, it is extended with a hidden property `duration` * - query duration in milliseconds. */ this.query = function (query, values, qrm) { var self = this, ctx = createContext(); return config.$npm.connect.pool(ctx) .then(function (db) { ctx.connect(db); return config.$npm.query.call(self, ctx, query, values, qrm); }) .then(function (data) { ctx.disconnect(); return data; }) .catch(function (error) { ctx.disconnect(); return $p.reject(error); }); }; /** * @member {object} Database.$config * @readonly * @description * This is a hidden property, to help integrating type {@link Database} directly with third-party libraries. * * Properties available in the object: * - `pgp` - instance of the entire library after initialization * - `options` - the library's {@link module:pg-promise Initialization Options} object * - `promiseLib` - instance of the promise library that's used * - `promise` - generic promise interface that uses `promiseLib` via 3 basic methods: * - `promise((resolve, reject)=>{})` - to create a new promise * - `promise.resolve(value)` - to resolve with a value * - `promise.reject(value)` - to reject with a value * - `version` - this library's version * - `$npm` _(hidden property)_ - internal module cache * * @example * * // Using the promise protocol as configured by pg-promise: * * var $p = db.$config.promise; * * var resolvedPromise = $p.resolve('some data'); * var rejectedPromise = $p.reject('some reason'); * * var newPromise = $p(function(resolve, reject) { * // call either resolve(data) or reject(reason) here * }); */ $npm.utils.addReadProp(this, '$config', config, true); extend(createContext(), this); // extending root protocol; function createContext() { return new $npm.context(cn, dc, config.options); } function transform(value, cb, thisArg) { if (typeof cb === 'function') { value = value.then(function (data) { return cb.call(thisArg, data); }); } return value; } //////////////////////////////////////////////////// // Injects additional methods into an access object, // extending the protocol's base method 'query'. function extend(ctx, obj) { /** * @method Database.none * @description * Executes a query that expects no data to be returned. * If the query returns any kind of data, the method rejects. * * @param {String|Object} query * Query to be executed, which can any of the following types: * - A non-empty query string * - Prepared Statement `{name, text, values, ...}` or {@link PreparedStatement} object * - Parameterized Query `{text, values, ...}` or {@link ParameterizedQuery} object * - {@link QueryFile} object * * @param {array|value} [values] * Query formatting parameters. * * When `query` is of type `string` or a {@link QueryFile} object, the `values` can be: * - a single value - to replace all `$1` occurrences * - an array of values - to replace all `$1`, `$2`, ... variables * - an object - to apply $[Named Parameters] formatting * * When `query` is a Prepared Statement or a Parameterized Query (or their class types), * and `values` is not `null` or `undefined`, it is automatically set within such object, * as an override for its internal `values`. * * @returns {external:Promise} * A promise object that represents the query result: * - when no records are returned, it resolves with `null` * - when any data is returned, it rejects with {@link errors.QueryResultError QueryResultError} * = `No return data was expected.` */ obj.none = function (query, values) { return obj.query.call(this, query, values, $npm.result.none); }; /** * @method Database.one * @description * Executes a query that expects exactly one row of data. * When 0 or more than 1 rows are returned, the method rejects. * * @param {String|Object} query * Query to be executed, which can any of the following types: * - A non-empty query string * - Prepared Statement `{name, text, values, ...}` or {@link PreparedStatement} object * - Parameterized Query `{text, values, ...}` or {@link ParameterizedQuery} object * - {@link QueryFile} object * * @param {array|value} [values] * Query formatting parameters. * * When `query` is of type `string` or a {@link QueryFile} object, the `values` can be: * - a single value - to replace all `$1` occurrences * - an array of values - to replace all `$1`, `$2`, ... variables * - an object - to apply $[Named Parameters] formatting * * When `query` is a Prepared Statement or a Parameterized Query (or their class types), * and `values` is not `null` or `undefined`, it is automatically set within such object, * as an override for its internal `values`. * * @param {function} [cb] * Value transformation callback, to allow in-line value change. * When specified, the return value replaces the original resolved value. * * The function takes only one parameter - value resolved from the query. * * @param {} [thisArg] * Value to use as `this` when executing the transformation callback. * * @returns {external:Promise} * A promise object that represents the query result: * - when 1 row is returned, it resolves with that row as a single object; * - when no rows are returned, it rejects with {@link errors.QueryResultError QueryResultError} * = `No data returned from the query.` * - when multiple rows are returned, it rejects with {@link errors.QueryResultError QueryResultError} * = `Multiple rows were not expected.` * * @example * * // a query with in-line value transformation: * db.one('INSERT INTO Events VALUES($1) RETURNING id', [123], event => event.id) * .then(data=> { * // data = a new event id, rather than an object with it * }); * * @example * * // a query with in-line value transformation + conversion: * db.one('SELECT count(*) FROM Users', null, c => +c.count) * .then(count=> { * // count = a proper integer value, rather than an object with a string * }); * */ obj.one = function (query, values, cb, thisArg) { var v = obj.query.call(this, query, values, $npm.result.one); return transform(v, cb, thisArg); }; /** * @method Database.many * @description * Executes a query that expects one or more rows. * When the query returns no data, the method rejects. * * @param {String|Object} query * Query to be executed, which can any of the following types: * - A non-empty query string * - Prepared Statement `{name, text, values, ...}` or {@link PreparedStatement} object * - Parameterized Query `{text, values, ...}` or {@link ParameterizedQuery} object * - {@link QueryFile} object * * @param {array|value} [values] * Query formatting parameters. * * When `query` is of type `string` or a {@link QueryFile} object, the `values` can be: * - a single value - to replace all `$1` occurrences * - an array of values - to replace all `$1`, `$2`, ... variables * - an object - to apply $[Named Parameters] formatting * * When `query` is a Prepared Statement or a Parameterized Query (or their class types), * and `values` is not `null` or `undefined`, it is automatically set within such object, * as an override for its internal `values`. * * @returns {external:Promise} * A promise object that represents the query result: * - when 1 or more rows are returned, it resolves with the array of rows * - when no rows are returned, it rejects with {@link errors.QueryResultError QueryResultError} * = `No data returned from the query.` */ obj.many = function (query, values) { return obj.query.call(this, query, values, $npm.result.many); }; /** * @method Database.oneOrNone * @description * Executes a query that expects 0 or 1 rows. * When the query returns more than 1 row, the method rejects. * * @param {String|Object} query * Query to be executed, which can any of the following types: * - A non-empty query string * - Prepared Statement `{name, text, values, ...}` or {@link PreparedStatement} object * - Parameterized Query `{text, values, ...}` or {@link ParameterizedQuery} object * - {@link QueryFile} object * * @param {array|value} [values] * Query formatting parameters. * * When `query` is of type `string` or a {@link QueryFile} object, the `values` can be: * - a single value - to replace all `$1` occurrences * - an array of values - to replace all `$1`, `$2`, ... variables * - an object - to apply $[Named Parameters] formatting * * When `query` is a Prepared Statement or a Parameterized Query (or their class types), * and `values` is not `null` or `undefined`, it is automatically set within such object, * as an override for its internal `values`. * * @param {function} [cb] * Value transformation callback, to allow in-line value change. * When specified, the return value replaces the original resolved value. * * The function takes only one parameter - value resolved from the query. * * @param {} [thisArg] * Value to use as `this` when executing the transformation callback. * * @returns {external:Promise} * A promise object that represents the query result: * - when no rows are returned, it resolves with `null` * - when 1 row is returned, it resolves with that row as a single object * - when multiple rows are returned, it rejects with {@link errors.QueryResultError QueryResultError} * = `Multiple rows were not expected.` * * @see * {@link Database.one one}, * {@link Database.none none} * * @example * * // a query with in-line value transformation: * db.oneOrNone('SELECT id FROM Events WHERE type = $1', ['entry'], e => e && e.id) * .then(data=> { * // data = the event id or null (rather than object or null) * }); * */ obj.oneOrNone = function (query, values, cb, thisArg) { var v = obj.query.call(this, query, values, $npm.result.one | $npm.result.none); return transform(v, cb, thisArg); }; /** * @method Database.manyOrNone * @description * Executes a query that expects any number of rows. * * @param {String|Object} query * Query to be executed, which can any of the following types: * - A non-empty query string * - Prepared Statement `{name, text, values, ...}` or {@link PreparedStatement} object * - Parameterized Query `{text, values, ...}` or {@link ParameterizedQuery} object * - {@link QueryFile} object * * @param {array|value} [values] * Query formatting parameters. * * When `query` is of type `string` or a {@link QueryFile} object, the `values` can be: * - a single value - to replace all `$1` occurrences * - an array of values - to replace all `$1`, `$2`, ... variables * - an object - to apply $[Named Parameters] formatting * * When `query` is a Prepared Statement or a Parameterized Query (or their class types), * and `values` is not `null` or `undefined`, it is automatically set within such object, * as an override for its internal `values`. * * @returns {external:Promise} * A promise object that represents the query result: * - when no rows are returned, it resolves with an empty array * - when 1 or more rows are returned, it resolves with the array of rows. * * @see {@link Database.any any} * */ obj.manyOrNone = function (query, values) { return obj.query.call(this, query, values, $npm.result.many | $npm.result.none); }; /** * @method Database.any * @description * Executes a query that expects any number of rows. * This is simply a shorter alias for method {@link Database.manyOrNone manyOrNone}. * * @param {String|Object} query * Query to be executed, which can any of the following types: * - A non-empty query string * - Prepared Statement `{name, text, values, ...}` or {@link PreparedStatement} object * - Parameterized Query `{text, values, ...}` or {@link ParameterizedQuery} object * - {@link QueryFile} object * * @param {array|value} [values] * Query formatting parameters. * * When `query` is of type `string` or a {@link QueryFile} object, the `values` can be: * - a single value - to replace all `$1` occurrences * - an array of values - to replace all `$1`, `$2`, ... variables * - an object - to apply $[Named Parameters] formatting * * When `query` is a Prepared Statement or a Parameterized Query (or their class types), * and `values` is not `null` or `undefined`, it is automatically set within such object, * as an override for its internal `values`. * * @returns {external:Promise} * A promise object that represents the query result: * - when no rows are returned, it resolves with an empty array * - when 1 or more rows are returned, it resolves with the array of rows. * * @see * {@link Database.manyOrNone manyOrNone}, * {@link Database.map map}, * {@link Database.each each} * */ obj.any = function (query, values) { return obj.query.call(this, query, values, $npm.result.any); }; /** * @method Database.result * @description * Executes a query without any expectation for the return data, to resolve with the * original $[Result] object when successful. * * @param {String|Object} query * Query to be executed, which can any of the following types: * - A non-empty query string * - Prepared Statement `{name, text, values, ...}` or {@link PreparedStatement} object * - Parameterized Query `{text, values, ...}` or {@link ParameterizedQuery} object * - {@link QueryFile} object * * @param {array|value} [values] * Query formatting parameters. * * When `query` is of type `string` or a {@link QueryFile} object, the `values` can be: * - a single value - to replace all `$1` occurrences * - an array of values - to replace all `$1`, `$2`, ... variables * - an object - to apply $[Named Parameters] formatting * * When `query` is a Prepared Statement or a Parameterized Query (or their class types), * and `values` is not `null` or `undefined`, it is automatically set within such object, * as an override for its internal `values`. * * @param {function} [cb] * Value transformation callback, to allow in-line value change. * When specified, the return value replaces the original resolved value. * * The function takes only one parameter - value resolved from the query. * * @param {} [thisArg] * Value to use as `this` when executing the transformation callback. * * @returns {external:Promise} * A promise object that represents the query result: * - resolves with the original $[Result] object, extended with * property `duration` - query duration in milliseconds. * * @example * * // use of value transformation: * // deleting rows and returning the number of rows deleted * db.result('DELETE FROM Events WHERE id = $1', [123], r=>r.rowCount) * .then(data=> { * // data = number of rows that were deleted * }); * * @example * * // use of value transformation: * // getting only column details from a table * db.result('SELECT * FROM Users LIMIT 0', null, r=>r.fields) * .then(data=> { * // data = array of column descriptors * }); * */ obj.result = function (query, values, cb, thisArg) { var v = obj.query.call(this, query, values, $npm.special.cache.resultQuery); return transform(v, cb, thisArg); }; /** * @method Database.stream * @description * Custom data streaming, with the help of $[pg-query-stream]. * * This method doesn't work with the $[Native Bindings], and if option `pgNative` * is set, it will reject with `Streaming doesn't work with Native Bindings.` * * @param {QueryStream} qs * Stream object of type $[QueryStream]. * * @param {Database.streamInitCB} initCB * Stream initialization callback. * * It is invoked with the same `this` context as the calling method. * * @returns {external:Promise} * Result of the streaming operation. * * Once the streaming has finished successfully, the method resolves with * `{processed, duration}`: * - `processed` - total number of rows processed; * - `duration` - streaming duration, in milliseconds. * * Possible rejections messages: * - `Invalid or missing stream object.` * - `Invalid stream state.` * - `Invalid or missing stream initialization callback.` */ obj.stream = function (qs, init) { return obj.query.call(this, qs, init, $npm.special.cache.streamQuery); }; /** * @method Database.func * @description * Executes a query against a database function by its name: `SELECT * FROM funcName(values)`. * * @param {string} funcName * Name of the function to be executed. * * @param {array|value} [values] * Parameters for the function - one value or an array of values. * * @param {queryResult} [qrm=queryResult.any] - {@link queryResult Query Result Mask}. * * @returns {external:Promise} * Result of the query call, according to parameter `qrm`. * * @see * {@link Database.query query}, * {@link Database.proc proc} */ obj.func = function (funcName, values, qrm) { return obj.query.call(this, { funcName: funcName }, values, qrm); }; /** * @method Database.proc * @description * Executes a query against a stored procedure via its name: `select * from procName(values)`, * expecting back 0 or 1 rows. * * The method simply forwards into {@link Database.func func}`(procName, values, queryResult.one|queryResult.none)`. * * @param {string} procName * Name of the stored procedure to be executed. * * @param {array|value} [values] * Parameters for the procedure - one value or an array of values. * * @param {function} [cb] * Value transformation callback, to allow in-line value change. * When specified, the return value replaces the original resolved value. * * The function takes only one parameter - value resolved from the query. * * @param {} [thisArg] * Value to use as `this` when executing the transformation callback. * * @returns {external:Promise} * The same result as method {@link Database.oneOrNone oneOrNone}. * * @see * {@link Database.oneOrNone oneOrNone}, * {@link Database.func func} */ obj.proc = function (procName, values, cb, thisArg) { var v = obj.func.call(this, procName, values, $npm.result.one | $npm.result.none); return transform(v, cb, thisArg); }; /** * @method Database.map * @description * Creates a new array with the results of calling a provided function on every element in the array of rows * resolved by method {@link Database.any any}. * * It is a convenience method to reduce the following code: * * ```js * db.any(query, values) * .then(function(data) { * return data.map(function(row, index, data) { * // return a new element * }); * }); * ``` * * In addition to much shorter code, it offers the following benefits: * * - Use of a custom iterator has a much better performance than the standard {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map Array.map} * - Automatic `this` context through the database protocol * * @param {String|Object} query * Query to be executed, which can any of the following types: * - A non-empty query string * - Prepared Statement `{name, text, values, ...}` or {@link PreparedStatement} object * - Parameterized Query `{text, values, ...}` or {@link ParameterizedQuery} object * - {@link QueryFile} object * * @param {array|value} values * Query formatting parameters. * * When `query` is of type `string` or a {@link QueryFile} object, the `values` can be: * - a single value - to replace all `$1` occurrences * - an array of values - to replace all `$1`, `$2`, ... variables * - an object - to apply $[Named Parameters] formatting * * When `query` is a Prepared Statement or a Parameterized Query (or their class types), * and `values` is not `null` or `undefined`, it is automatically set within such object, * as an override for its internal `values`. * * @param {function} cb * Function that produces an element of the new array, taking three arguments: * - `row` - the current row object being processed in the array * - `index` - the index of the current row being processed in the array * - `data` - the original array of rows resolved by method {@link Database.any any} * * @param {} [thisArg] * Value to use as `this` when executing the callback. * * @returns {external:Promise} * Resolves with the new array of values returned from the callback. * * @see * {@link Database.any any}, * {@link Database.each each}, * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map Array.map} * * @example * * db.map('SELECT id FROM Users WHERE status = $1', ['active'], row => row.id) * .then(data => { * // data = array of active user id-s * }) * .catch(error => { * // error * }); * * @example * * db.tx(t => { * return t.map('SELECT id FROM Users WHERE status = $1', ['active'], row => { * return t.none('UPDATE Events SET checked = $1 WHERE userId = $2', [true, row.id]); * }).then(t.batch); * }) * .then(data => { * // success * }) * .catch(error => { * // error * }); * * @example * * // Build a list of active users, each with the list of user events: * db.task(t => { * return t.map('SELECT id FROM Users WHERE status = $1', ['active'], user => { * return t.any('SELECT * FROM Events WHERE userId = $1', user.id) * .then(events=> { * user.events = events; * return user; * }); * }).then(t.batch); * }) * .then(data => { * // success * }) * .catch(error => { * // error * }); * */ obj.map = function (query, values, cb, thisArg) { return obj.any.call(this, query, values) .then(function (data) { return $arr.map(data, cb, thisArg); }); }; /** * @method Database.each * @description * Executes a provided function once per array element, for an array of rows resolved by method {@link Database.any any}. * * It is a convenience method to reduce the following code: * * ```js * db.any(query, values) * .then(function(data) { * data.forEach(function(row, index, data) { * // process the row * }); * return data; * }); * ``` * * In addition to much shorter code, it offers the following benefits: * * - Use of a custom iterator has a much better performance than the regular {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach Array.forEach} * - Automatic `this` context through the database protocol * * @param {String|Object} query * Query to be executed, which can any of the following types: * - A non-empty query string * - Prepared Statement `{name, text, values, ...}` or {@link PreparedStatement} object * - Parameterized Query `{text, values, ...}` or {@link ParameterizedQuery} object * - {@link QueryFile} object * * @param {array|value} [values] * Query formatting parameters. * * When `query` is of type `string` or a {@link QueryFile} object, the `values` can be: * - a single value - to replace all `$1` occurrences * - an array of values - to replace all `$1`, `$2`, ... variables * - an object - to apply $[Named Parameters] formatting * * When `query` is a Prepared Statement or a Parameterized Query (or their class types), * and `values` is not `null` or `undefined`, it is automatically set within such object, * as an override for its internal `values`. * * @param {function} cb * Function to execute for each row, taking three arguments: * - `row` - the current row object being processed in the array * - `index` - the index of the current row being processed in the array * - `data` - the array of rows resolved by method {@link Database.any any} * * @param {} [thisArg] * Value to use as `this` when executing the callback. * * @returns {external:Promise} * Resolves with the original array of rows. * * @see * {@link Database.any any}, * {@link Database.map map}, * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach Array.forEach} * * @example * * db.each('SELECT id, code, name FROM Events', [], row => { * row.code = +row.code; // leading `+` is short for `parseInt()` * }) * .then(data => { * // data = array of events, with 'code' converted into integer * }) * .catch(error => { * // error * }); * */ obj.each = function (query, values, cb, thisArg) { return obj.any.call(this, query, values) .then(function (data) { $arr.forEach(data, cb, thisArg); return data; }); }; /** * @method Database.task * @description * Executes a callback function (or $[ES6 generator]) with an automatically managed connection. * * This method should be used whenever executing more than one query at once, so the allocated connection * is reused between all queries, and released only after the task has finished. * * The callback function is called with one parameter - database protocol (same as `this`), extended with methods * {@link Task.batch batch}, {@link Task.page page}, {@link Task.sequence sequence}, plus property {@link Task.ctx ctx} - * the task context object. * * See class {@link Task} for more details. * * @param {} tag/cb * When the method takes only one parameter, it must be the callback function (or $[ES6 generator]) for the task. * However, when calling the method with 2 parameters, the first one is always the `tag` - traceable context for the * task (see $[tags]). * * @param {function|generator} [cb] * Task callback function (or $[ES6 generator]), if it is not `undefined`, or else the callback is expected to * be passed in as the first parameter. * * @returns {external:Promise} * Result from the callback function. * * @see * {@link Task}, * {@link Database.tx tx}, * $[tags] * * @example * * // using the regular callback syntax: * db.task(function(t) { * // t = this * // t.ctx = task context object * * return t.one('SELECT id FROM Users WHERE name = $1', 'John') * .then(user=> { * return t.any('SELECT * FROM Events WHERE userId = $1', user.id); * }); * }) * .then(function(data) { * // success * // data = as returned from the task's callback * }) * .catch(function(error) { * // error * }); * * @example * * // using the ES6 arrow syntax: * db.task(t=> { * // t.ctx = task context object * * return t.one('SELECT id FROM Users WHERE name = $1', 'John') * .then(user=> { * return t.any('SELECT * FROM Events WHERE userId = $1', user.id); * }); * }) * .then(data=> { * // success * // data = as returned from the task's callback * }) * .catch(error=> { * // error * }); * * @example * * // using an ES6 generator for the callback: * db.task(function*(t) { * // t = this * // t.ctx = task context object * * let user = yield t.one('SELECT id FROM Users WHERE name = $1', 'John'); * return yield t.any('SELECT * FROM Events WHERE userId = $1', user.id); * }) * .then(function(data) { * // success * // data = as returned from the task's callback * }) * .catch(function(error) { * // error * }); * */ obj.task = function (p1, p2) { return taskProcessor.call(this, p1, p2, false); }; /** * @method Database.tx * @description * Executes a callback function (or $[ES6 generator]) as a transaction. * * A transaction simply wraps a regular {@link Database.task task} in automatic queries: * - it executes `BEGIN` just before invoking the callback function * - it executes `COMMIT`, if the callback didn't throw any error or return a rejected promise * - it executes `ROLLBACK`, if the callback did throw an error or return a rejected promise * * The callback function is called with one parameter - database protocol (same as `this`), extended with methods * {@link Task.batch batch}, {@link Task.page page}, {@link Task.sequence sequence}, plus property {@link Task.ctx ctx} - * the transaction context object. * * See class {@link Task} for more details. * * Note that transactions should be chosen over tasks only where they are necessary, because unlike regular tasks, * transactions are blocking operations, and must be used with caution. * * @param {} tag/cb * When the method takes only one parameter, it must be the callback function (or $[ES6 generator]) for the transaction. * However, when calling the method with 2 parameters, the first one is always the `tag` - traceable context for the * transaction (see $[tags]). * * @param {function|generator} [cb] * Transaction callback function (or $[ES6 generator]), if it is not `undefined`, or else the callback is expected to be * passed in as the first parameter. * * @returns {external:Promise} * Result from the callback function. * * @see * {@link Task}, * {@link Database.task}, * $[tags] * * @example * * // using the regular callback syntax: * db.tx(function(t) { * // t = this * // t.ctx = transaction context object * * return t.one('INSERT INTO Users(name, age) VALUES($1, $2) RETURNING id', ['Mike', 25]) * .then(user=> { * return t.none('INSERT INTO Events(userId, name) VALUES($1, $2)', [user.id, 'created']); * }); * }) * .then(function(data) { * // success * // data = as returned from the transaction's callback * }) * .catch(function(error) { * // error * }); * * @example * * // using the ES6 arrow syntax: * db.tx(t=> { * // t.ctx = transaction context object * * return t.one('INSERT INTO Users(name, age) VALUES($1, $2) RETURNING id', ['Mike', 25]) * .then(user=> { * return t.batch([ * t.none('INSERT INTO Events(userId, name) VALUES($1, $2)', [user.id, 'created']), * t.none('INSERT INTO Events(userId, name) VALUES($1, $2)', [user.id, 'login']) * ]); * }); * }) * .then(data=> { * // success * // data = as returned from the transaction's callback * }) * .catch(error=> { * // error * }); * * @example * * // using an ES6 generator for the callback: * db.tx(function*(t) { * // t = this * // t.ctx = transaction context object * * let user = yield t.one('INSERT INTO Users(name, age) VALUES($1, $2) RETURNING id', ['Mike', 25]); * return yield t.none('INSERT INTO Events(userId, name) VALUES($1, $2)', [user.id, 'created']); * }) * .then(function(data) { * // success * // data = as returned from the transaction's callback * }) * .catch(function(error) { * // error * }); * */ obj.tx = function (p1, p2) { return taskProcessor.call(this, p1, p2, true); }; // Task method; // Resolves with result from the callback function; function taskProcessor(p1, p2, isTX) { var tag, // tag object/value; taskCtx = ctx.clone(); // task context object; if (isTX) { taskCtx.txLevel = taskCtx.txLevel >= 0 ? (taskCtx.txLevel + 1) : 0; } if (this !== obj) { taskCtx.context = this; // calling context object; } taskCtx.cb = p1; // callback function; // allow inserting a tag in front of the callback // function, for better code readability; if (p2 !== undefined) { tag = p1; // overriding any default tag; taskCtx.cb = p2; } var cb = taskCtx.cb; if (typeof cb !== 'function') { return $p.reject(new TypeError("Callback function is required for the " + (isTX ? "transaction." : "task."))); } if (tag === undefined) { if (cb.tag !== undefined) { // use the default tag associated with the task: tag = cb.tag; } else { if (cb.name) { tag = cb.name; // use the function name as tag; } } } var tsk = new config.$npm.task(taskCtx, tag, isTX, config); extend(taskCtx, tsk); if (taskCtx.db) { // reuse existing connection; $npm.utils.addReadProp(tsk.ctx, 'isFresh', taskCtx.db.isFresh); return config.$npm.task.exec(taskCtx, tsk, isTX, config); } // connection required; return config.$npm.connect.pool(taskCtx) .then(function (db) { taskCtx.connect(db); $npm.utils.addReadProp(tsk.ctx, 'isFresh', db.isFresh); return config.$npm.task.exec(taskCtx, tsk, isTX, config); }) .then(function (data) { taskCtx.disconnect(); return data; }) .catch(function (error) { taskCtx.disconnect(); return $p.reject(error); }); } // lock all default properties to read-only, // to prevent override by the client. $npm.utils.lock(obj, false, ctx.options); // extend the protocol; $npm.events.extend(ctx.options, obj, ctx.dc); // freeze the protocol permanently; $npm.utils.lock(obj, true, ctx.options); } } var jsHandled, nativeHandled, dbObjects = {}; function checkForDuplicates(cn, config) { var cnKey = JSON.stringify(cn); if (cnKey in dbObjects) { if (!config.options.noWarnings) { $npm.con.warn("WARNING: Creating a duplicate database object for the same connection.\n%s\n", $npm.utils.getLocalStack(5)); } } else { dbObjects[cnKey] = true; } } function setErrorHandler(config) { // we do not do code coverage specific to Native Bindings: // istanbul ignore if if (config.options.pgNative) { if (!nativeHandled) { config.pgp.pg.on('error', onError); nativeHandled = true; } } else { if (!jsHandled) { config.pgp.pg.on('error', onError); jsHandled = true; } } } // this event only happens when the connection is lost physically, // which cannot be tested automatically; removing from coverage: // istanbul ignore next function onError(err, client) { var ctx = client.$ctx; $npm.events.error(ctx.options, err, { cn: $npm.utils.getSafeConnection(ctx.cn), dc: ctx.dc }); } module.exports = function (config) { var npm = config.$npm; npm.connect = npm.connect || $npm.connect(config); npm.query = npm.query || $npm.query(config); npm.task = npm.task || $npm.task(config); return Database; }; /** * @callback Database.streamInitCB * @description * Stream initialization callback, used by {@link Database.stream}. * * @param {external:Stream} stream * Stream object to initialize streaming. * * @example * var QueryStream = require('pg-query-stream'); * var JSONStream = require('JSONStream'); * * // you can also use pgp.as.format(query, values, options) * // to format queries properly, via pg-promise; * var qs = new QueryStream('select * from users'); * * db.stream(qs, function (stream) { * // initiate streaming into the console: * stream.pipe(JSONStream.stringify()).pipe(process.stdout); * }) * .then(function (data) { * console.log("Total rows processed:", data.processed, * "Duration in milliseconds:", data.duration); * }) * .catch(function (error) { * // error; * }); */ /** * @external Stream * @see https://nodejs.org/api/stream.html */
/** * Created by Florin Chelaru ( florin [dot] chelaru [at] gmail [dot] com ) * Date: 8/27/2015 * Time: 9:42 AM */ goog.require('vs.ui.VisualizationFactory'); goog.exportSymbol('vs.ui.VisualizationFactory', vs.ui.VisualizationFactory); goog.exportProperty(vs.ui.VisualizationFactory.prototype, 'createNew', vs.ui.VisualizationFactory.prototype.createNew);
/* * Copyright 2013 The Polymer Authors. All rights reserved. * Use of this source code is governed by a BSD-style * license that can be found in the LICENSE file. */ module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), yuidoc: { compile: { name: '<%= pkg.name %>', description: '<%= pkg.description %>', version: '<%= pkg.version %>', url: '<%= pkg.homepage %>', options: { exclude: 'docs', extension: '.js,.html', paths: '.', outdir: 'docs', linkNatives: 'true', tabtospace: 2, themedir: 'tools/doc/themes/polymerase' } } } }); // plugins grunt.loadNpmTasks('grunt-contrib-yuidoc'); // tasks grunt.registerTask('default', ['yuidoc']); grunt.registerTask('docs', ['yuidoc']); };
export default function loadInfo() { return new Promise((resolve) => { resolve({ message: '这来自API服务器', time: Date.now() }); }); }
'use strict'; module.exports = { client: { lib: { css: [ 'public/lib/bootstrap/dist/css/bootstrap.css', 'public/lib/bootstrap/dist/css/bootstrap-theme.css' ], js: [ 'public/lib/angular/angular.js', 'public/lib/angular-resource/angular-resource.js', 'public/lib/angular-animate/angular-animate.js', 'public/lib/angular-messages/angular-messages.js', 'public/lib/angular-strap/dist/angular-strap.min.js', 'public/lib/angular-strap/dist/angular-strap.tpl.min.js', 'public/lib/angular-ui-router/release/angular-ui-router.js', 'public/lib/angular-ui-utils/ui-utils.js', 'public/lib/angular-bootstrap/ui-bootstrap-tpls.js', 'public/lib/angular-file-upload/angular-file-upload.js', 'public/lib/owasp-password-strength-test/owasp-password-strength-test.js' ], tests: ['public/lib/angular-mocks/angular-mocks.js'] }, css: [ 'modules/*/client/css/*.css' ], less: [ 'modules/*/client/less/*.less' ], sass: [ 'modules/*/client/scss/*.scss' ], js: [ 'modules/core/client/app/config.js', 'modules/core/client/app/init.js', 'modules/*/client/*.js', 'modules/*/client/**/*.js' ], views: ['modules/*/client/views/**/*.html'], templates: ['build/templates.js'] }, server: { gruntConfig: 'gruntfile.js', gulpConfig: 'gulpfile.js', allJS: ['server.js', 'config/**/*.js', 'modules/*/server/**/*.js'], models: 'modules/*/server/models/**/*.js', routes: ['modules/!(core)/server/routes/**/*.js', 'modules/core/server/routes/**/*.js'], sockets: 'modules/*/server/sockets/**/*.js', config: 'modules/*/server/config/*.js', policies: 'modules/*/server/policies/*.js', views: 'modules/*/server/views/*.html' } };
import React from 'react'; import ReactDOM from 'react-dom'; import Profile from './components/Profile'; import { StyleSheet, css } from 'aphrodite'; const styles = StyleSheet.create({ wrapper: { display: 'flex', justifyContent: 'center', alignItems: 'center', width: '100%', height: '100%', }, }); ReactDOM.render( <div className={css(styles.wrapper)}> <style>{` html, body, #root { width: 100%; height: 100%; background-color: #f4f7f9; overflow: hidden; margin: 0; padding: 0; } `}</style> <Profile avatarUrl="https://pbs.twimg.com/profile_images/681114454029942784/PwhopfmU.jpg" firstName="Max" lastName="Stoiber" username="mxstbr" bio="I travel around the world, brew coffee, ski mountains and make stuff on the web. Open source developer advocate (@KeystoneJS @ElementalUI), part of @reactvienna." // eslint-disable-line max-len /> </div>, document.getElementById('root') );
'use strict'; /** * Enable dubug mode * This allow to console.log in a firefox default configuration */ require('sdk/preferences/service').set('extensions.sdk.console.logLevel', 'debug'); var data = require('sdk/self').data; var { ToggleButton } = require('sdk/ui/button/toggle');<% if (contentscript) { %> var { PageMod } = require('sdk/page-mod');<% } if (popup) { %> var { Panel } = require('sdk/panel'); var popup = Panel({ contentURL: data.url('popup.html'), onHide: function () { button.state('window', {checked: false}); } }); // Show the popup when the user clicks the button. function handleClick(state) { if (state.checked) { popup.show({ position: button, width: 600, height: 400 }); } } <% } %> // Create a button var button = ToggleButton({ id: 'show-popup', label: 'RSS Lector', icon: { '16': './images/icon-16.png', '32': './images/icon-32.png', '64': './images/icon-64.png' }<% if (popup) { %>, onClick: handleClick <% } %> }); <% if (contentscript) { %> // Create a content script var pageMod = PageMod({ include: ['*'], // all urls contentScriptFile: [data.url('contentscript.js')], contentStyleFile: [data.url('contentstyle.css')] }); <% } %>
var _ = require('lodash'); var FieldType = require('../Type'); var https = require('https'); var keystone = require('../../../'); var querystring = require('querystring'); var util = require('util'); var utils = require('keystone-utils'); var RADIUS_KM = 6371; var RADIUS_MILES = 3959; /** * Location FieldType Constructor */ function location (list, path, options) { this._underscoreMethods = ['format', 'googleLookup', 'kmFrom', 'milesFrom']; this._fixedSize = 'full'; this._properties = ['enableMapsAPI']; this.enableMapsAPI = (options.geocodeGoogle === true || (options.geocodeGoogle !== false && keystone.get('google server api key'))) ? true : false; if (!options.defaults) { options.defaults = {}; } if (options.required) { if (Array.isArray(options.required)) { // required can be specified as an array of paths this.requiredPaths = options.required; } else if (typeof options.required === 'string') { // or it can be specified as a comma-delimited list this.requiredPaths = options.required.replace(/,/g, ' ').split(/\s+/); } // options.required should always be simplified to a boolean options.required = true; } // default this.requiredPaths if (!this.requiredPaths) { this.requiredPaths = ['street1', 'suburb']; } location.super_.call(this, list, path, options); } location.properName = 'Location'; util.inherits(location, FieldType); /** * Registers the field on the List's Mongoose Schema. */ location.prototype.addToSchema = function () { var field = this; var schema = this.list.schema; var options = this.options; var paths = this.paths = { number: this._path.append('.number'), name: this._path.append('.name'), street1: this._path.append('.street1'), street2: this._path.append('.street2'), suburb: this._path.append('.suburb'), state: this._path.append('.state'), postcode: this._path.append('.postcode'), country: this._path.append('.country'), geo: this._path.append('.geo'), geo_lat: this._path.append('.geo_lat'), geo_lng: this._path.append('.geo_lng'), serialised: this._path.append('.serialised'), improve: this._path.append('_improve'), overwrite: this._path.append('_improve_overwrite'), }; var getFieldDef = function (type, key) { var def = { type: type }; if (options.defaults[key]) { def.default = options.defaults[key]; } return def; }; schema.nested[this.path] = true; schema.add({ number: getFieldDef(String, 'number'), name: getFieldDef(String, 'name'), street1: getFieldDef(String, 'street1'), street2: getFieldDef(String, 'street2'), street3: getFieldDef(String, 'street3'), suburb: getFieldDef(String, 'suburb'), state: getFieldDef(String, 'state'), postcode: getFieldDef(String, 'postcode'), country: getFieldDef(String, 'country'), geo: { type: [Number], index: '2dsphere' }, }, this.path + '.'); schema.virtual(paths.serialised).get(function () { return _.compact([ this.get(paths.number), this.get(paths.name), this.get(paths.street1), this.get(paths.street2), this.get(paths.suburb), this.get(paths.state), this.get(paths.postcode), this.get(paths.country), ]).join(', '); }); // pre-save hook to fix blank geo fields // see http://stackoverflow.com/questions/16388836/does-applying-a-2dsphere-index-on-a-mongoose-schema-force-the-location-field-to schema.pre('save', function (next) { var obj = field._path.get(this); var geo = (obj.geo || []).map(Number).filter(_.isFinite); obj.geo = (geo.length === 2) ? geo : undefined; next(); }); this.bindUnderscoreMethods(); }; /** * Add filters to a query */ var FILTER_PATH_MAP = { street: 'street1', city: 'suburb', state: 'state', code: 'postcode', country: 'country', }; location.prototype.addFilterToQuery = function (filter) { var query = {}; var field = this; ['street', 'city', 'state', 'code', 'country'].forEach(function (i) { if (!filter[i]) return; var value = utils.escapeRegExp(filter[i]); value = new RegExp(value, 'i'); query[field.paths[FILTER_PATH_MAP[i]]] = filter.inverted ? { $not: value } : value; }); return query; }; /** * Formats a list of the values stored by the field. Only paths that * have values will be included. * * Optionally provide a space-separated list of values to include. * * Delimiter defaults to `', '`. */ location.prototype.format = function (item, values, delimiter) { if (!values) { return item.get(this.paths.serialised); } var paths = this.paths; values = values.split(' ').map(function (i) { return item.get(paths[i]); }); return _.compact(values).join(delimiter || ', '); }; /** * Detects whether the field has been modified */ location.prototype.isModified = function (item) { return item.isModified(this.paths.number) || item.isModified(this.paths.name) || item.isModified(this.paths.street1) || item.isModified(this.paths.street2) || item.isModified(this.paths.suburb) || item.isModified(this.paths.state) || item.isModified(this.paths.postcode) || item.isModified(this.paths.country) || item.isModified(this.paths.geo); }; /** * Validates that a value for this field has been provided in a data object * * options.required specifies an array or space-delimited list of paths that * are required (defaults to street1, suburb) * * Deprecated */ location.prototype.inputIsValid = function (data, required, item) { if (!required) return true; var paths = this.paths; var nested = this._path.get(data); var values = nested || data; var valid = true; this.requiredPaths.forEach(function (path) { if (nested) { if (!(path in values) && item && item.get(paths[path])) { return; } if (!values[path]) { valid = false; } } else { if (!(paths[path] in values) && item && item.get(paths[path])) { return; } if (!values[paths[path]]) { valid = false; } } }); return valid; }; /** * Updates the value for this field in the item from a data object */ location.prototype.updateItem = function (item, data, callback) { var paths = this.paths; var fieldKeys = ['number', 'name', 'street1', 'street2', 'suburb', 'state', 'postcode', 'country']; var geoKeys = ['geo', 'geo_lat', 'geo_lng']; var valueKeys = fieldKeys.concat(geoKeys); var valuePaths = valueKeys; var values = this._path.get(data); if (!values) { // Handle flattened values valuePaths = valueKeys.map(function (i) { return paths[i]; }); values = _.pick(data, valuePaths); } // convert valuePaths to a map for easier usage valuePaths = _.zipObject(valueKeys, valuePaths); var setValue = function (key) { if (valuePaths[key] in values && values[valuePaths[key]] !== item.get(paths[key])) { item.set(paths[key], values[valuePaths[key]] || null); } }; _.forEach(fieldKeys, setValue); if (valuePaths.geo in values) { var oldGeo = item.get(paths.geo) || []; if (oldGeo.length > 1) { oldGeo[0] = item.get(paths.geo)[1]; oldGeo[1] = item.get(paths.geo)[0]; } var newGeo = values[valuePaths.geo]; if (!Array.isArray(newGeo) || newGeo.length !== 2) { newGeo = []; } if (newGeo[0] !== oldGeo[0] || newGeo[1] !== oldGeo[1]) { item.set(paths.geo, newGeo); } } else if (valuePaths.geo_lat in values && valuePaths.geo_lng in values) { var lat = utils.number(values[valuePaths.geo_lat]); var lng = utils.number(values[valuePaths.geo_lng]); item.set(paths.geo, (lat && lng) ? [lng, lat] : undefined); } process.nextTick(callback); }; /** * Returns a callback that handles a standard form submission for the field * * Handles: * - `field.paths.improve` in `req.body` - improves data via `.googleLookup()` * - `field.paths.overwrite` in `req.body` - in conjunction with `improve`, overwrites existing data */ location.prototype.getRequestHandler = function (item, req, paths, callback) { var field = this; if (utils.isFunction(paths)) { callback = paths; paths = field.paths; } else if (!paths) { paths = field.paths; } callback = callback || function () {}; return function () { var update = req.body[paths.overwrite] ? 'overwrite' : true; if (req.body && req.body[paths.improve]) { field.googleLookup(item, false, update, function () { callback(); }); } else { callback(); } }; }; /** * Immediately handles a standard form submission for the field (see `getRequestHandler()`) */ location.prototype.handleRequest = function (item, req, paths, callback) { this.getRequestHandler(item, req, paths, callback)(); }; /** * Internal Google geocode request method */ function doGoogleGeocodeRequest (address, region, callback) { // https://developers.google.com/maps/documentation/geocoding/ // Use of the Google Geocoding API is subject to a query limit of 2,500 geolocation requests per day, except with an enterprise license. // Note: the Geocoding API may only be used in conjunction with a Google map; geocoding results without displaying them on a map is prohibited. // Please make sure your Keystone app complies with the Google Maps API License. var options = { sensor: false, language: 'en', address: address, }; if (arguments.length === 2 && _.isFunction(region)) { callback = region; region = null; } if (region) { options.region = region; } if (keystone.get('google server api key')) { options.key = keystone.get('google server api key'); } var endpoint = 'https://maps.googleapis.com/maps/api/geocode/json?' + querystring.stringify(options); https.get(endpoint, function (res) { var data = []; res.on('data', function (chunk) { data.push(chunk); }) .on('end', function () { var dataBuff = data.join('').trim(); var result; try { result = JSON.parse(dataBuff); } catch (exp) { result = { status_code: 500, status_text: 'JSON Parse Failed', status: 'UNKNOWN_ERROR', }; } callback(null, result); }); }) .on('error', function (err) { callback(err); }); } /** * Autodetect the full address and lat, lng from the stored value. * * Uses Google's Maps API and may only be used in conjunction with a Google map. * Geocoding results without displaying them on a map is prohibited. * Please make sure your Keystone app complies with the Google Maps API License. * * Internal status codes mimic the Google API status codes. */ location.prototype.googleLookup = function (item, region, update, callback) { if (_.isFunction(update)) { callback = update; update = false; } var field = this; var stored = item.get(this.path); var address = item.get(this.paths.serialised); if (address.length === 0) { return callback({ status_code: 500, status_text: 'No address to geocode', status: 'NO_ADDRESS', }); } doGoogleGeocodeRequest(address, region || keystone.get('default region'), function (err, geocode) { if (err || geocode.status !== 'OK') { return callback(err || new Error(geocode.status + ': ' + geocode.error_message)); } // use the first result // if there were no results in the array, status would be ZERO_RESULTS var result = geocode.results[0]; // parse the address components into a location object var location = {}; _.forEach(result.address_components, function (val) { if (_.indexOf(val.types, 'street_number') >= 0) { location.street1 = location.street1 || []; location.street1.push(val.long_name); } if (_.indexOf(val.types, 'route') >= 0) { location.street1 = location.street1 || []; location.street1.push(val.short_name); } // in some cases, you get suburb, city as locality - so only use the first if (_.indexOf(val.types, 'locality') >= 0 && !location.suburb) { location.suburb = val.long_name; } if (_.indexOf(val.types, 'administrative_area_level_1') >= 0) { location.state = val.short_name; } if (_.indexOf(val.types, 'country') >= 0) { location.country = val.long_name; } if (_.indexOf(val.types, 'postal_code') >= 0) { location.postcode = val.short_name; } }); if (Array.isArray(location.street1)) { location.street1 = location.street1.join(' '); } location.geo = [ result.geometry.location.lng, result.geometry.location.lat, ]; // console.log('------ Google Geocode Results ------'); // console.log(address); // console.log(result); // console.log(location); if (update === 'overwrite') { item.set(field.path, location); } else if (update) { _.forEach(location, function (value, key) { if (key === 'geo') { return; } if (!stored[key]) { item.set(field.paths[key], value); } }); if (!Array.isArray(stored.geo) || !stored.geo[0] || !stored.geo[1]) { item.set(field.paths.geo, location.geo); } } callback(null, location, result); }); }; /** * Internal Distance calculation function * * See http://en.wikipedia.org/wiki/Haversine_formula */ function calculateDistance (point1, point2) { var dLng = (point2[0] - point1[0]) * Math.PI / 180; var dLat = (point2[1] - point1[1]) * Math.PI / 180; var lat1 = (point1[1]) * Math.PI / 180; var lat2 = (point2[1]) * Math.PI / 180; /* eslint-disable space-infix-ops */ var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.sin(dLng/2) * Math.sin(dLng/2) * Math.cos(lat1) * Math.cos(lat2); var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); /* eslint-enable space-infix-ops */ return c; } /** * Returns the distance from a [lat, lng] point in kilometres */ location.prototype.kmFrom = function (item, point) { return calculateDistance(this.get(this.paths.geo), point) * RADIUS_KM; }; /** * Returns the distance from a [lat, lng] point in miles */ location.prototype.milesFrom = function (item, point) { return calculateDistance(this.get(this.paths.geo), point) * RADIUS_MILES; }; /* Export Field Type */ module.exports = location;
/** * A string representing a [CSS font]{@link https://developer.mozilla.org/en-US/docs/Web/CSS/font}. * @typedef {String} Font * @example var sansSerif = '12px sans-serif', * bigBoldArial = '700 24px Arial', * italicSmallCaps = 'italic small-caps 16px Times New Roman'; */
module.exports = function (notes, length, dynamics) { this.stack.push({ notes: notes, length: length, dynamics: dynamics }); };
import Promise from 'bluebird' import _ from 'lodash/fp' export const idAsync = value => new Promise(resolve => setImmediate(resolve, value)) export const getBooksReadAsync = () => new Promise(resolve => resolve(['Moby Dick', 'A Tale of Two Cities'])) export const calculateTasteScoreAsync = () => new Promise(resolve => resolve(_.random(1, 10)))
Ext.ns('iwage.image.tools.glfx'); Ext.define('iwage.image.tools.glfx.TiltShift', { toolLabel: 'Tilt Shift', extend: 'iwage.image.tools.glfx.NubFilter', createControls: function() { return [ { xtype: 'slider', fieldLabel: 'Blur radius', itemId: 'blurRadius', width: 350, value: 0, minValue: 0, maxValue: 255 }, { xtype: 'slider', fieldLabel: 'Gradient radius', itemId: 'gradientRadius', width: 350, value: 0, minValue: 0, maxValue: 255 } ]; }, previewFilter: function(values, nubs) { this.fxCanvas.draw(this.texture).tiltShift( nubs.start.x, nubs.start.y, nubs.end.x, nubs.end.y, values.blurRadius, values.gradientRadius ).update(); }, use: function(options) { this.addNub('start', 0.25, 0.5); this.addNub('end', 0.75, 0.5); this.callParent(arguments); // setup nubs this.createNubs(); } });
'use strict'; /** * Commands module. * @module command */ module.exports = [ require('./add'), require('./remove'), require('./reset'), require('./list'), require('./pokedex'), require('./start'), require('./stop') ];
'use strict'; ////////////////////////////// // Requires ////////////////////////////// var paths = require('compass-options').paths(), browserSync = require('browser-sync'), reload = browserSync.reload; ////////////////////////////// // Internal Vars ////////////////////////////// var workPaths = [ paths.css + '/**/*.css' ]; module.exports = function (gulp, devPaths) { gulp.task('dev-css', function () { devPaths = devPaths || workPaths; return gulp.src(devPaths) .pipe(reload({stream: true})); }); }
import { ref, computed, watch, nextTick } from 'vue' function samePagination (oldPag, newPag) { for (const prop in newPag) { if (newPag[ prop ] !== oldPag[ prop ]) { return false } } return true } function fixPagination (p) { if (p.page < 1) { p.page = 1 } if (p.rowsPerPage !== void 0 && p.rowsPerPage < 1) { p.rowsPerPage = 0 } return p } export const useTablePaginationProps = { pagination: Object, rowsPerPageOptions: { type: Array, default: () => [ 5, 7, 10, 15, 20, 25, 50, 0 ] }, 'onUpdate:pagination': [ Function, Array ] } export function useTablePaginationState (vm, getCellValue) { const { props, emit } = vm const innerPagination = ref( Object.assign({ sortBy: null, descending: false, page: 1, rowsPerPage: props.rowsPerPageOptions.length > 0 ? props.rowsPerPageOptions[ 0 ] : 5 }, props.pagination) ) const computedPagination = computed(() => { const pag = props[ 'onUpdate:pagination' ] !== void 0 ? { ...innerPagination.value, ...props.pagination } : innerPagination.value return fixPagination(pag) }) const isServerSide = computed(() => computedPagination.value.rowsNumber !== void 0) function sendServerRequest (pagination) { requestServerInteraction({ pagination, filter: props.filter }) } function requestServerInteraction (prop = {}) { nextTick(() => { emit('request', { pagination: prop.pagination || computedPagination.value, // FIXME: 'props.filter' is string/object, but 'prop.filter' can be controlled by the user, and the docs are suggesting 'prop.filter' is a function // So, value of 'filter' becomes function/string/object, which makes a lot of things unpredictable and can break things // Either update the docs to say 'prop.filter' should be a string/object, or use 'prop.filter || props.filterMethod' or maybe get 'computedFilterFunction' here and use that instead of 'props.filterMethod' // The examples on our docs are using 'filter' as a string in onRequest handler, but the JSON API is saying 'filter' is a function filter: prop.filter || props.filter, getCellValue }) }) } function setPagination (val, forceServerRequest) { const newPagination = fixPagination({ ...computedPagination.value, ...val }) if (samePagination(computedPagination.value, newPagination) === true) { if (isServerSide.value === true && forceServerRequest === true) { sendServerRequest(newPagination) } return } if (isServerSide.value === true) { sendServerRequest(newPagination) return } if ( props.pagination !== void 0 && props[ 'onUpdate:pagination' ] !== void 0 ) { emit('update:pagination', newPagination) } else { innerPagination.value = newPagination } } return { innerPagination, computedPagination, isServerSide, requestServerInteraction, setPagination } } export function useTablePagination (vm, innerPagination, computedPagination, isServerSide, setPagination, filteredSortedRowsNumber) { const { props, emit, proxy: { $q } } = vm const computedRowsNumber = computed(() => ( isServerSide.value === true ? computedPagination.value.rowsNumber || 0 : filteredSortedRowsNumber.value )) const firstRowIndex = computed(() => { const { page, rowsPerPage } = computedPagination.value return (page - 1) * rowsPerPage }) const lastRowIndex = computed(() => { const { page, rowsPerPage } = computedPagination.value return page * rowsPerPage }) const isFirstPage = computed(() => computedPagination.value.page === 1) const pagesNumber = computed(() => ( computedPagination.value.rowsPerPage === 0 ? 1 : Math.max( 1, Math.ceil(computedRowsNumber.value / computedPagination.value.rowsPerPage) ) )) const isLastPage = computed(() => ( lastRowIndex.value === 0 ? true : computedPagination.value.page >= pagesNumber.value )) const computedRowsPerPageOptions = computed(() => { const opts = props.rowsPerPageOptions.includes(innerPagination.value.rowsPerPage) ? props.rowsPerPageOptions : [ innerPagination.value.rowsPerPage ].concat(props.rowsPerPageOptions) return opts.map(count => ({ label: count === 0 ? $q.lang.table.allRows : '' + count, value: count })) }) watch(pagesNumber, (lastPage, oldLastPage) => { if (lastPage === oldLastPage) { return } const currentPage = computedPagination.value.page if (lastPage && !currentPage) { setPagination({ page: 1 }) } else if (lastPage < currentPage) { setPagination({ page: lastPage }) } }) function firstPage () { setPagination({ page: 1 }) } function prevPage () { const { page } = computedPagination.value if (page > 1) { setPagination({ page: page - 1 }) } } function nextPage () { const { page, rowsPerPage } = computedPagination.value if (lastRowIndex.value > 0 && page * rowsPerPage < computedRowsNumber.value) { setPagination({ page: page + 1 }) } } function lastPage () { setPagination({ page: pagesNumber.value }) } if (props[ 'onUpdate:pagination' ] !== void 0) { emit('update:pagination', { ...computedPagination.value }) } return { firstRowIndex, lastRowIndex, isFirstPage, isLastPage, pagesNumber, computedRowsPerPageOptions, computedRowsNumber, firstPage, prevPage, nextPage, lastPage } }
#!/usr/bin/env node const electronPath = require('electron'); const childProcess = require('child_process'); const args = process.argv.slice(2); args.unshift(__dirname); childProcess.spawn(electronPath, args, { stdio: 'inherit' });
/** * node-shopify-api * * Copyright (c) 2014 Chris Talkington, contributors. * Licensed under the MIT license. * https://github.com/ctalkington/node-shopify-api/blob/master/LICENSE-MIT */ var Resource = require('../resource'); module.exports = Resource.extend({ path: '/admin/', create: Resource.method({ method: 'POST', path: '/themes.json' }), destroy: Resource.method({ method: 'DELETE', path: '/themes/{id}.json', urlParams: ['id'] }), list: Resource.method({ method: 'GET', path: '/themes.json' }), retrieve: Resource.method({ method: 'GET', path: '/themes/{id}.json', urlParams: ['id'] }), update: Resource.method({ method: 'PUT', path: '/themes/{id}.json', urlParams: ['id'] }) });
import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import withFB from 'common/withFB'; import MessageBoard from '../../components/ExperienceDetail/MessageBoard'; import { login } from '../../actions/auth'; import { statusSelector, } from '../../selectors/authSelector'; const mapStateToProps = state => ({ authStatus: statusSelector(state), }); const mapDispatchToProps = dispatch => bindActionCreators({ login }, dispatch); export default connect(mapStateToProps, mapDispatchToProps)(withFB(MessageBoard));
var searchData= [ ['write_5ffinish_5ffn',['write_finish_fn',['../struct__esp__tcp.html#ae885dafd86eabefcff4ead713c21eb82',1,'_esp_tcp']]] ];
//------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. //------------------------------------------------------------------------------------------------------- // Functional WeakMap tests -- verifies the APIs work correctly // Note however this does not verify the GC semantics of WeakMap WScript.LoadScriptFile("..\\UnitTestFramework\\UnitTestFramework.js"); var tests = [ { name: "WeakMap constructor called on undefined or WeakMap.prototype returns new WeakMap object (and throws on null, non-extensible object)", body: function () { // WeakMap is no longer allowed to be called as a function unless the object it is given // for its this argument already has the [[WeakMapData]] property on it. // // For IE11 we simply throw if WeakMap() is called as a function instead of in a new expression assert.throws(function () { WeakMap.call(undefined); }, TypeError, "WeakMap.call() throws TypeError given undefined"); assert.throws(function () { WeakMap.call(null); }, TypeError, "WeakMap.call() throws TypeError given null"); assert.throws(function () { WeakMap.call(WeakMap.prototype); }, TypeError, "WeakMap.call() throws TypeError given WeakMap.prototype"); /* var weakmap1 = WeakMap.call(undefined); assert.isTrue(weakmap1 !== null && weakmap1 !== undefined && weakmap1 !== WeakMap.prototype, "WeakMap constructor creates new WeakMap object when this is undefined"); var weakmap2 = WeakMap.call(WeakMap.prototype); assert.isTrue(weakmap2 !== null && weakmap2 !== undefined && weakmap2 !== WeakMap.prototype, "WeakMap constructor creates new WeakMap object when this is equal to WeakMap.prototype"); var o = { }; Object.preventExtensions(o); assert.throws(function () { WeakMap.call(null); }, TypeError, "WeakMap constructor throws on null"); assert.throws(function () { WeakMap.call(o); }, TypeError, "WeakMap constructor throws on non-extensible object"); */ } }, { name: "WeakMap constructor throws when called on already initialized WeakMap object", body: function () { var weakmap = new WeakMap(); assert.throws(function () { WeakMap.call(weakmap); }, TypeError); // WeakMap is no longer allowed to be called as a function unless the object it is given // for its this argument already has the [[WeakMapData]] property on it. /* var obj = {}; WeakMap.call(obj); assert.throws(function () { WeakMap.call(obj); }, TypeError); function MyWeakMap() { WeakMap.call(this); } MyWeakMap.prototype = new WeakMap(); MyWeakMap.prototype.constructor = MyWeakMap; var myweakmap = new MyWeakMap(); assert.throws(function () { WeakMap.call(myweakmap); }, TypeError); assert.throws(function () { MyWeakMap.call(myweakmap); }, TypeError); */ } }, { name: "WeakMap constructor populates the weakmap with key-values pairs from given optional iterable argument", body: function () { var keys = [ { }, { }, { }, { } ]; var wm = new WeakMap([ [keys[0], 1], [keys[1], 2], [keys[2], 3] ]); assert.areEqual(1, wm.get(keys[0]), "wm has key keys[0] mapping to value 1"); assert.areEqual(2, wm.get(keys[1]), "wm has key keys[1] mapping to value 2"); assert.areEqual(3, wm.get(keys[2]), "wm has key keys[2] mapping to value 3"); var customIterable = { [Symbol.iterator]: function () { var i = 0; return { next: function () { return { done: i > 3, value: [ keys[i], ++i * 2 ] }; } }; } }; wm = new WeakMap(customIterable); assert.areEqual(2, wm.get(keys[0]), "wm has key keys[0] mapping to value 2"); assert.areEqual(4, wm.get(keys[1]), "wm has key keys[1] mapping to value 4"); assert.areEqual(6, wm.get(keys[2]), "wm has key keys[2] mapping to value 6"); assert.areEqual(8, wm.get(keys[3]), "wm has key keys[3] mapping to value 8"); } }, { name: "WeakMap constructor throws exceptions for non- and malformed iterable arguments", body: function () { var iterableNoIteratorMethod = { [Symbol.iterator]: 123 }; var iterableBadIteratorMethod = { [Symbol.iterator]: function () { } }; var iterableNoIteratorNextMethod = { [Symbol.iterator]: function () { return { }; } }; var iterableBadIteratorNextMethod = { [Symbol.iterator]: function () { return { next: 123 }; } }; var iterableNoIteratorResultObject = { [Symbol.iterator]: function () { return { next: function () { } }; } }; assert.throws(function () { new WeakMap(123); }, TypeError, "new WeakMap() throws on non-object", "Function expected"); assert.throws(function () { new WeakMap({ }); }, TypeError, "new WeakMap() throws on non-iterable object", "Function expected"); assert.throws(function () { new WeakMap(iterableNoIteratorMethod); }, TypeError, "new WeakMap() throws on non-iterable object where @@iterator property is not a function", "Function expected"); assert.throws(function () { new WeakMap(iterableBadIteratorMethod); }, TypeError, "new WeakMap() throws on non-iterable object where @@iterator function doesn't return an iterator", "Object expected"); assert.throws(function () { new WeakMap(iterableNoIteratorNextMethod); }, TypeError, "new WeakMap() throws on iterable object where iterator object does not have next property", "Function expected"); assert.throws(function () { new WeakMap(iterableBadIteratorNextMethod); }, TypeError, "new WeakMap() throws on iterable object where iterator object's next property is not a function", "Function expected"); assert.throws(function () { new WeakMap(iterableNoIteratorResultObject); }, TypeError, "new WeakMap() throws on iterable object where iterator object's next method doesn't return an iterator result", "Object expected"); } }, { name: "APIs throw TypeError where specified", body: function () { function MyWeakMapImposter() { } MyWeakMapImposter.prototype = new WeakMap(); MyWeakMapImposter.prototype.constructor = MyWeakMapImposter; var o = new MyWeakMapImposter(); assert.throws(function () { o.delete(o); }, TypeError, "delete should throw if this doesn't have WeakMapData property"); assert.throws(function () { o.get(o); }, TypeError, "get should throw if this doesn't have WeakMapData property"); assert.throws(function () { o.has(o); }, TypeError, "has should throw if this doesn't have WeakMapData property"); assert.throws(function () { o.set(o, o); }, TypeError, "set should throw if this doesn't have WeakMapData property"); assert.throws(function () { WeakMap.prototype.delete.call(); }, TypeError, "delete should throw if called with no arguments"); assert.throws(function () { WeakMap.prototype.get.call(); }, TypeError, "get should throw if called with no arguments"); assert.throws(function () { WeakMap.prototype.has.call(); }, TypeError, "has should throw if called with no arguments"); assert.throws(function () { WeakMap.prototype.set.call(); }, TypeError, "set should throw if called with no arguments"); assert.throws(function () { WeakMap.prototype.delete.call(null, o); }, TypeError, "delete should throw if this is null"); assert.throws(function () { WeakMap.prototype.get.call(null, o); }, TypeError, "get should throw if this is null"); assert.throws(function () { WeakMap.prototype.has.call(null, o); }, TypeError, "has should throw if this is null"); assert.throws(function () { WeakMap.prototype.set.call(null, o, o); }, TypeError, "set should throw if this is null"); assert.throws(function () { WeakMap.prototype.delete.call(undefined, o); }, TypeError, "delete should throw if this is undefined"); assert.throws(function () { WeakMap.prototype.get.call(undefined, o); }, TypeError, "get should throw if this is undefined"); assert.throws(function () { WeakMap.prototype.has.call(undefined, o); }, TypeError, "has should throw if this is undefined"); assert.throws(function () { WeakMap.prototype.set.call(undefined, o, o); }, TypeError, "set should throw if this is undefined"); var weakmap = new WeakMap(); assert.throws(function () { weakmap.set(null, o); }, TypeError, "set should throw if key is not an object, e.g. null"); assert.throws(function () { weakmap.set(undefined, o); }, TypeError, "set should throw if key is not an object, e.g. undefined"); assert.throws(function () { weakmap.set(true, o); }, TypeError, "set should throw if key is not an object, e.g. a boolean"); assert.throws(function () { weakmap.set(10, o); }, TypeError, "set should throw if key is not an object, e.g. a number"); assert.throws(function () { weakmap.set("hello", o); }, TypeError, "set should throw if key is not an object, e.g. a string"); } }, { name: "Non-object key argument silent fails delete, get, and has", body: function () { var weakmap = new WeakMap(); assert.isTrue(weakmap.get(null) === undefined, "null is not an object and cannot be a key in a WeakMap; get returns undefined"); assert.isTrue(weakmap.get(undefined) === undefined, "undefined is not an object and cannot be a key in a WeakMap; get returns undefined"); assert.isTrue(weakmap.get(true) === undefined, "boolean is not an object and cannot be a key in a WeakMap; get returns undefined"); assert.isTrue(weakmap.get(10) === undefined, "number is not an object and cannot be a key in a WeakMap; get returns undefined"); assert.isTrue(weakmap.get("hello") === undefined, "string is not an object and cannot be a key in a WeakMap; get returns undefined"); assert.isFalse(weakmap.has(null), "null is not an object and cannot be a key in a WeakMap; has returns false"); assert.isFalse(weakmap.has(undefined), "undefined is not an object and cannot be a key in a WeakMap; has returns false"); assert.isFalse(weakmap.has(true), "boolean is not an object and cannot be a key in a WeakMap; has returns false"); assert.isFalse(weakmap.has(10), "number is not an object and cannot be a key in a WeakMap; has returns false"); assert.isFalse(weakmap.has("hello"), "string is not an object and cannot be a key in a WeakMap; has returns false"); assert.isFalse(weakmap.delete(null), "null is not an object and cannot be a key in a WeakMap; delete returns false"); assert.isFalse(weakmap.delete(undefined), "undefined is not an object and cannot be a key in a WeakMap; delete returns false"); assert.isFalse(weakmap.delete(true), "boolean is not an object and cannot be a key in a WeakMap; delete returns false"); assert.isFalse(weakmap.delete(10), "number is not an object and cannot be a key in a WeakMap; delete returns false"); assert.isFalse(weakmap.delete("hello"), "string is not an object and cannot be a key in a WeakMap; delete returns false"); var booleanObject = new Boolean(true); var numberObject = new Number(10); var stringObject = new String("hello"); weakmap.set(booleanObject, null); weakmap.set(numberObject, null); weakmap.set(stringObject, null); assert.isTrue(weakmap.get(true) === undefined, "boolean is not an object and cannot be a key in a WeakMap; get returns undefined"); assert.isTrue(weakmap.get(10) === undefined, "number is not an object and cannot be a key in a WeakMap; get returns undefined"); assert.isTrue(weakmap.get("hello") === undefined, "string is not an object and cannot be a key in a WeakMap; get returns undefined"); assert.isFalse(weakmap.has(true), "boolean is not an object and cannot be a key in a WeakMap; has returns false"); assert.isFalse(weakmap.has(10), "number is not an object and cannot be a key in a WeakMap; has returns false"); assert.isFalse(weakmap.has("hello"), "string is not an object and cannot be a key in a WeakMap; has returns false"); assert.isFalse(weakmap.delete(true), "boolean is not an object and cannot be a key in a WeakMap; delete returns false"); assert.isFalse(weakmap.delete(10), "number is not an object and cannot be a key in a WeakMap; delete returns false"); assert.isFalse(weakmap.delete("hello"), "string is not an object and cannot be a key in a WeakMap; delete returns false"); } }, { name: "Basic usage, delete, get, has, set", body: function () { var weakmap = new WeakMap(); var o = { }; var p = { }; var q = { }; weakmap.set(o, 10); weakmap.set(p, o); weakmap.set(q, q); assert.isTrue(weakmap.has(o), "Should contain key o"); assert.isTrue(weakmap.has(p), "Should contain key p"); assert.isTrue(weakmap.has(q), "Should contain key q"); assert.isFalse(weakmap.has(weakmap), "Should not contain other keys, 'weakmap'"); assert.isFalse(weakmap.has({ }), "Should not contain other keys, '{ }'"); assert.isTrue(weakmap.get(o) === 10, "Should weakmap o to 10"); assert.isTrue(weakmap.get(p) === o, "Should weakmap p to o"); assert.isTrue(weakmap.get(q) === q, "Should weakmap q to q"); assert.isTrue(weakmap.get(weakmap) === undefined, "Should return undefined for non-existant key, 'weakmap'"); assert.isTrue(weakmap.get({ }) === undefined, "Should return undefined for non-existant key, '{ }'"); assert.isTrue(weakmap.delete(p), "Should return true after deleting key p"); assert.isTrue(weakmap.has(o), "Should still contain key o"); assert.isFalse(weakmap.has(p), "Should no longer contain key p"); assert.isTrue(weakmap.has(q), "Should still contain key q"); assert.isFalse(weakmap.delete(p), "Should return false, p is no longer a key"); assert.isTrue(weakmap.delete(o), "Should return true after deleting key o"); assert.isTrue(weakmap.delete(q), "Should return true after deleting key q"); assert.isFalse(weakmap.has(o), "Should no longer contain key o"); assert.isFalse(weakmap.has(p), "Should still not contain key p"); assert.isFalse(weakmap.has(q), "Should no longer contain key q"); } }, { name: "Not specifying arguments should default them to undefined", body: function () { var weakmap = new WeakMap(); assert.isFalse(weakmap.has(), "Should return false for implicit undefined; has"); assert.isTrue(weakmap.get() === undefined, "Should return undefined for implicit undefined; get"); assert.isFalse(weakmap.delete(), "Should return false for implicit undefined; delete"); assert.throws(function () { weakmap.set(); }, TypeError, "Should throw TypeError for implicit undefined; set"); } }, { name: "Extra arguments should be ignored", body: function () { var weakmap = new WeakMap(); var o = { }; var p = { }; var q = { }; assert.isFalse(weakmap.has(o, p, q), "Looks for o, ignores p and q, weak weakmap is empty and has should return false"); assert.isTrue(weakmap.get(o, p, q) === undefined, "Looks for o, ignores p and q, weak weakmap is empty and get should return false"); assert.isFalse(weakmap.delete(o, p, q), "Looks for o, ignores p and q, weak weakmap is empty and delete should return false"); weakmap.set(o, p, q); assert.isTrue(weakmap.has(o), "Should contain o"); assert.isFalse(weakmap.has(p), "Should not contain p"); assert.isFalse(weakmap.has(q), "Should not contain q"); assert.isTrue(weakmap.has(o, p, q), "Ignores p and q, does have o"); assert.isTrue(weakmap.has(o, q, p), "Order of extra arguments has no affect, still has o"); assert.isFalse(weakmap.has(p, o), "Ignores o, does not have p"); assert.isTrue(weakmap.get(o) === p, "Should contain o and return p"); assert.isTrue(weakmap.get(p) === undefined, "Should not contain p and return undefined"); assert.isTrue(weakmap.get(q) === undefined, "Should not contain q and return undefined"); assert.isTrue(weakmap.get(o, p, q) === p, "Ignores p and q, does have o, returns p"); assert.isTrue(weakmap.get(o, q, p) === p, "Order of extra arguments has no affect, still has o, still returns p"); assert.isTrue(weakmap.get(p, o) === undefined, "Ignores o, does not have p and returns undefined"); assert.isFalse(weakmap.delete(p, o, q), "p is not found so should return false, ignores o and q"); assert.isFalse(weakmap.delete(q, o), "q is not found so should return false, ignores o"); assert.isTrue(weakmap.delete(o, p, q), "o is found and deleted, so should return true, ignores p and q"); } }, { name: "Delete should return true if item was in the WeakMap, false if not", body: function () { var weakmap = new WeakMap(); var o = { }; var p = { }; weakmap.set(o, p); assert.isFalse(weakmap.delete(p), "p is not a key in the weakmap, delete should return false"); assert.isTrue(weakmap.delete(o), "o is a key in the weakmap, delete should remove it and return true"); assert.isFalse(weakmap.delete(o), "o is no longer a key in the weakmap, delete should now return false"); } }, { name: "Setting the same key twice is valid, and should modify the value", body: function () { var weakmap = new WeakMap(); var o = { }; var p = { }; weakmap.set(o); weakmap.set(o); weakmap.set(p); weakmap.delete(o); weakmap.set(p); weakmap.set(o); weakmap.set(o); weakmap.delete(o); weakmap.delete(p); weakmap.set(o, 3); assert.isTrue(weakmap.get(o) === 3, "o maps to 3"); weakmap.set(o, 4); assert.isTrue(weakmap.get(o) === 4, "o maps to 4"); weakmap.set(p, 5); assert.isTrue(weakmap.get(o) === 4, "o still maps to 4"); assert.isTrue(weakmap.get(p) === 5, "p maps to 5"); weakmap.delete(o); assert.isTrue(weakmap.get(o) === undefined, "o is no longer in the weakmap"); assert.isTrue(weakmap.get(p) === 5, "p still maps to 5"); weakmap.set(p, 6); assert.isTrue(weakmap.get(p) === 6, "p maps to 6"); } }, { name: "set returns the weakmap instance itself", body: function () { var weakmap = new WeakMap(); var o = { }; assert.areEqual(weakmap, weakmap.set(o, o), "Setting new key should return WeakMap instance"); assert.areEqual(weakmap, weakmap.set(o, o), "Setting existing key should return WeakMap instance"); } }, { name: "Adding and removing keys from one WeakMap shouldn't affect other WeakMaps", body: function () { var wm1 = new WeakMap(); var wm2 = new WeakMap(); var wm3 = new WeakMap(); var o = { }; var p = { }; var q = { }; wm1.set(o, o); wm1.set(p, q); wm2.set(q, o); assert.isTrue(wm1.has(o), "wm1 has o"); assert.isFalse(wm2.has(o), "wm2 does not have o"); assert.isFalse(wm3.has(o), "wm3 does not have o"); assert.isTrue(wm1.get(o) === o, "wm1 has o map to o"); assert.isTrue(wm2.get(o) === undefined, "wm2 does not have o and get returns undefined"); assert.isTrue(wm3.get(o) === undefined, "wm3 does not have o and get returns undefined"); assert.isTrue(wm1.has(p), "wm1 has p"); assert.isTrue(wm2.has(q), "wm2 has q"); assert.isFalse(wm1.has(q), "wm1 does not have q"); assert.isFalse(wm2.has(p), "wm2 does not have p"); assert.isFalse(wm3.has(p), "wm3 does not have p"); assert.isFalse(wm3.has(q), "wm3 does not have q"); assert.isTrue(wm1.get(p) === q, "wm1 has p map to q"); assert.isTrue(wm2.get(q) === o, "wm2 has q map to o"); assert.isTrue(wm1.get(q) === undefined, "wm1 does not have q and get returns undefined"); assert.isTrue(wm2.get(p) === undefined, "wm2 does not have p and get returns undefined"); assert.isTrue(wm3.get(p) === undefined, "wm3 does not have p and get returns undefined"); assert.isTrue(wm3.get(q) === undefined, "wm3 does not have q and get returns undefined"); wm3.set(p, o); wm3.set(q, p); assert.isTrue(wm3.has(p), "wm3 now has p"); assert.isTrue(wm3.has(q), "wm3 now has q"); assert.isTrue(wm1.has(p), "wm1 still has p"); assert.isFalse(wm2.has(p), "wm2 still does not have p"); assert.isFalse(wm1.has(q), "wm1 still does not have q"); assert.isTrue(wm2.has(q), "wm2 still has q"); assert.isTrue(wm1.delete(p), "p is removed from wm1"); assert.isFalse(wm1.has(p), "wm1 no longer has p"); assert.isTrue(wm3.has(p), "wm3 still has p"); wm3.delete(p); wm3.delete(q); assert.isFalse(wm3.has(p), "wm3 no longer has p"); assert.isFalse(wm3.has(q), "wm3 no longer has q"); assert.isTrue(wm1.has(o), "wm1 still has o"); assert.isTrue(wm2.has(q), "wm2 still has q"); } }, { name: "Number, Boolean, and String and other special objects should all as keys", body: function () { var weakmap = new WeakMap(); var n = new Number(1); var b = new Boolean(2); var s = new String("Hi"); /* Fast DOM and HostDispatch objects are tested in the mshtml test weakmap_DOMkey.html WinRT objects are still an open issue; they are CustomExternalObjects so they work, but they are proxied and the proxies are not kept alive by the outside object, only by internal JS references. Further, allowing objects to be linked to the lifetime of a WinJS object can cause cycles between JS GC objects and WinRT COM ref counted objects, which are not deducible by the GC. Therefore using WinRT objects with WeakMap is prone to subtle easy to make memory leak bugs. var fd = new FastDOM(); var hd = new HostDispatch(); var wrt = new WinRT(); */ var ab = new ArrayBuffer(32); weakmap.set(n, 1); weakmap.set(b, 2); weakmap.set(s, 3); weakmap.set(ab, 4); assert.isTrue(weakmap.has(n), "weakmap has key n which is a Number instance"); assert.isTrue(weakmap.has(b), "weakmap has key b which is a Boolean instance"); assert.isTrue(weakmap.has(s), "weakmap has key s which is a String instance"); assert.isTrue(weakmap.has(ab), "weakmap has key ab which is an ArrayBuffer instance"); assert.isTrue(weakmap.get(n) === 1, "weakmap has key n which is a Number instance and maps it to 1"); assert.isTrue(weakmap.get(b) === 2, "weakmap has key b which is a Boolean instance and maps it to 2"); assert.isTrue(weakmap.get(s) === 3, "weakmap has key s which is a String instance and maps it to 3"); assert.isTrue(weakmap.get(ab) === 4, "weakmap has key ab which is an ArrayBuffer instance and maps it to 4"); assert.isTrue(weakmap.delete(n), "Successfully delete key n which is a Number instance from weakmap"); assert.isTrue(weakmap.delete(b), "Successfully delete key b which is a Boolean instance from weakmap"); assert.isTrue(weakmap.delete(s), "Successfully delete key s which is a String instance from weakmap"); assert.isTrue(weakmap.delete(ab), "Successfully delete key ab which is an ArrayBuffer instance from weakmap"); assert.isFalse(weakmap.has(n), "weakmap no longer has key n"); assert.isFalse(weakmap.has(b), "weakmap no longer has key b"); assert.isFalse(weakmap.has(s), "weakmap no longer has key s"); assert.isFalse(weakmap.has(ab), "weakmap no longer has key ab"); } }, { name: "WeakMap can add keys that are sealed and frozen (testworthy because WeakMap implementation sets internal property on key objects)", body: function () { var wm = new WeakMap(); var sealedObj = Object.seal({ }); var frozenObj = Object.freeze({ }); wm.set(sealedObj, 1248); wm.set(frozenObj, 3927); assert.isTrue(wm.has(sealedObj), "WeakMap has sealed object as key"); assert.isTrue(wm.has(frozenObj), "WeakMap has frozen object as key"); assert.areEqual(1248, wm.get(sealedObj), "WeakMap maps sealed object key to corresponding mapped value"); assert.areEqual(3927, wm.get(frozenObj), "WeakMap maps frozen object key to corresponding mapped value"); var wm2 = new WeakMap(); assert.isFalse(wm2.has(sealedObj), "Second WeakMap does not have sealed object key"); assert.isFalse(wm2.has(frozenObj), "Second WeakMap does not have frozen object key"); wm2.set(sealedObj, 42); wm2.set(frozenObj, 68); assert.isTrue(wm2.has(sealedObj), "Second WeakMap now has sealed object key"); assert.isTrue(wm2.has(frozenObj), "Second WeakMap now has frozen object key"); assert.isTrue(wm.has(sealedObj), "First WeakMap still has sealed object as key"); assert.isTrue(wm.has(frozenObj), "First WeakMap still has frozen object as key"); wm.delete(sealedObj); wm2.delete(frozenObj); assert.isTrue(wm2.has(sealedObj), "Second WeakMap still has sealed object key"); assert.isFalse(wm2.has(frozenObj), "Second WeakMap no longer has frozen object key"); assert.isFalse(wm.has(sealedObj), "First WeakMap no longer has sealed object as key"); assert.isTrue(wm.has(frozenObj), "First WeakMap still has frozen object as key"); } }, ]; testRunner.runTests(tests, { verbose: WScript.Arguments[0] != "summary" });
class Globals { constructor() { "ngInject"; this.globals = {} } } export default Globals;
module('JSHint - routes'); test('routes/contact.js should pass jshint', function() { ok(true, 'routes/contact.js should pass jshint.'); });
export const open = (component) => ({ type: 'OPEN', component }) export const close = () => ({ type: 'CLOSE' }) export const clear = () => ({ type: 'CLEAR' })
'use strict'; require('../../modules/core.number.iterator'); var get = require('../../modules/$.iterators').Number; module.exports = function (it) { return get.call(it); }; //# sourceMappingURL=iterator-compiled.js.map
import { EventDispatcher } from '../core/EventDispatcher.js'; import { Texture } from '../textures/Texture.js'; import { LinearFilter } from '../constants.js'; import { Vector4 } from '../math/Vector4.js'; /* In options, we can specify: * Texture parameters for an auto-generated target texture * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers */ class WebGLRenderTarget extends EventDispatcher { constructor( width, height, options ) { super(); this.width = width; this.height = height; this.depth = 1; this.scissor = new Vector4( 0, 0, width, height ); this.scissorTest = false; this.viewport = new Vector4( 0, 0, width, height ); options = options || {}; this.texture = new Texture( undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding ); this.texture.image = {}; this.texture.image.width = width; this.texture.image.height = height; this.texture.image.depth = 1; this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false; this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter; this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true; this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : false; this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null; } setTexture( texture ) { texture.image = { width: this.width, height: this.height, depth: this.depth }; this.texture = texture; } setSize( width, height, depth = 1 ) { if ( this.width !== width || this.height !== height || this.depth !== depth ) { this.width = width; this.height = height; this.depth = depth; this.texture.image.width = width; this.texture.image.height = height; this.texture.image.depth = depth; this.dispose(); } this.viewport.set( 0, 0, width, height ); this.scissor.set( 0, 0, width, height ); } clone() { return new this.constructor().copy( this ); } copy( source ) { this.width = source.width; this.height = source.height; this.depth = source.depth; this.viewport.copy( source.viewport ); this.texture = source.texture.clone(); this.depthBuffer = source.depthBuffer; this.stencilBuffer = source.stencilBuffer; this.depthTexture = source.depthTexture; return this; } dispose() { this.dispatchEvent( { type: 'dispose' } ); } } WebGLRenderTarget.prototype.isWebGLRenderTarget = true; export { WebGLRenderTarget };
var searchData= [ ['viewrules',['viewrules',['../quest_8c.html#a33504d3cfa7980c5646061494f95132b',1,'viewrules():&#160;quest.c'],['../quest_8h.html#a33504d3cfa7980c5646061494f95132b',1,'viewrules():&#160;quest.c']]] ];
'use strict'; /* * This test makes sure that `writeFile()` always writes from the current * position of the file, instead of truncating the file. */ const common = require('../common'); const assert = require('assert'); const path = require('path'); const { readFileSync } = require('fs'); const { open } = require('fs').promises; const tmpdir = require('../common/tmpdir'); tmpdir.refresh(); const fn = path.join(tmpdir.path, 'test.txt'); async function writeFileTest() { const handle = await open(fn, 'w'); /* Write only five bytes, so that the position moves to five. */ const buf = Buffer.from('Hello'); const { bytesWritten } = await handle.write(buf, 0, 5, null); assert.strictEqual(bytesWritten, 5); /* Write some more with writeFile(). */ await handle.writeFile('World'); /* New content should be written at position five, instead of zero. */ assert.deepStrictEqual(readFileSync(fn).toString(), 'HelloWorld'); await handle.close(); } writeFileTest() .then(common.mustCall());
(function () { 'use strict'; function GroupsBuilderDirective(contentTypeHelper, contentTypeResource, mediaTypeResource, dataTypeHelper, dataTypeResource, $filter, iconHelper, $q, $timeout, notificationsService, localizationService, editorService, eventsService, overlayService) { function link(scope, el, attr, ctrl) { var eventBindings = []; var validationTranslated = ""; var tabNoSortOrderTranslated = ""; scope.dataTypeHasChanged = false; scope.sortingMode = false; scope.toolbar = []; scope.sortableOptionsGroup = {}; scope.sortableOptionsProperty = {}; scope.sortingButtonKey = "general_reorder"; scope.compositionsButtonState = "init"; function activate() { setSortingOptions(); // set placeholder property on each group if (scope.model.groups.length !== 0) { angular.forEach(scope.model.groups, function (group) { addInitProperty(group); }); } // add init tab addInitGroup(scope.model.groups); activateFirstGroup(scope.model.groups); // localize texts localizationService.localize("validation_validation").then(function (value) { validationTranslated = value; }); localizationService.localize("contentTypeEditor_tabHasNoSortOrder").then(function (value) { tabNoSortOrderTranslated = value; }); } function setSortingOptions() { scope.sortableOptionsGroup = { axis: 'y', distance: 10, tolerance: "pointer", opacity: 0.7, scroll: true, cursor: "move", placeholder: "umb-group-builder__group-sortable-placeholder", zIndex: 6000, handle: ".umb-group-builder__group-handle", items: ".umb-group-builder__group-sortable", start: function (e, ui) { ui.placeholder.height(ui.item.height()); }, stop: function (e, ui) { updateTabsSortOrder(); } }; scope.sortableOptionsProperty = { axis: 'y', distance: 10, tolerance: "pointer", connectWith: ".umb-group-builder__properties", opacity: 0.7, scroll: true, cursor: "move", placeholder: "umb-group-builder__property_sortable-placeholder", zIndex: 6000, handle: ".umb-group-builder__property-handle", items: ".umb-group-builder__property-sortable", start: function (e, ui) { ui.placeholder.height(ui.item.height()); }, stop: function (e, ui) { updatePropertiesSortOrder(); } }; } function updateTabsSortOrder() { var first = true; var prevSortOrder = 0; scope.model.groups.map(function (group) { var index = scope.model.groups.indexOf(group); if (group.tabState !== "init") { // set the first not inherited tab to sort order 0 if (!group.inherited && first) { // set the first tab sort order to 0 if prev is 0 if (prevSortOrder === 0) { group.sortOrder = 0; // when the first tab is inherited and sort order is not 0 } else { group.sortOrder = prevSortOrder + 1; } first = false; } else if (!group.inherited && !first) { // find next group var nextGroup = scope.model.groups[index + 1]; // if a groups is dropped in the middle of to groups with // same sort order. Give it the dropped group same sort order if (prevSortOrder === nextGroup.sortOrder) { group.sortOrder = prevSortOrder; } else { group.sortOrder = prevSortOrder + 1; } } // store this tabs sort order as reference for the next prevSortOrder = group.sortOrder; } }); } function filterAvailableCompositions(selectedContentType, selecting) { //selecting = true if the user has check the item, false if the user has unchecked the item var selectedContentTypeAliases = selecting ? //the user has selected the item so add to the current list _.union(scope.compositionsDialogModel.compositeContentTypes, [selectedContentType.alias]) : //the user has unselected the item so remove from the current list _.reject(scope.compositionsDialogModel.compositeContentTypes, function (i) { return i === selectedContentType.alias; }); //get the currently assigned property type aliases - ensure we pass these to the server side filer var propAliasesExisting = _.filter(_.flatten(_.map(scope.model.groups, function (g) { return _.map(g.properties, function (p) { return p.alias; }); })), function (f) { return f !== null && f !== undefined; }); //use a different resource lookup depending on the content type type var resourceLookup = scope.contentType === "documentType" ? contentTypeResource.getAvailableCompositeContentTypes : mediaTypeResource.getAvailableCompositeContentTypes; return resourceLookup(scope.model.id, selectedContentTypeAliases, propAliasesExisting).then(function (filteredAvailableCompositeTypes) { scope.compositionsDialogModel.availableCompositeContentTypes.forEach(current => { //reset first current.allowed = true; //see if this list item is found in the response (allowed) list var found = filteredAvailableCompositeTypes.find(f => current.contentType.alias === f.contentType.alias); //allow if the item was found in the response (allowed) list - // and ensure its set to allowed if it is currently checked, // DO not allow if it's a locked content type. current.allowed = scope.model.lockedCompositeContentTypes.includes(current.contentType.alias) && (selectedContentTypeAliases.includes(current.contentType.alias)) || (found ? found.allowed : false); }); }); } function updatePropertiesSortOrder() { angular.forEach(scope.model.groups, function (group) { if (group.tabState !== "init") { group.properties = contentTypeHelper.updatePropertiesSortOrder(group.properties); } }); } function setupAvailableContentTypesModel(result) { scope.compositionsDialogModel.availableCompositeContentTypes = result; //iterate each one and set it up scope.compositionsDialogModel.availableCompositeContentTypes.forEach(c => { //enable it if it's part of the selected model if (scope.compositionsDialogModel.compositeContentTypes.includes(c.contentType.alias)) { c.allowed = true; } //set the inherited flags c.inherited = false; if (scope.model.lockedCompositeContentTypes.includes(c.contentType.alias)) { c.inherited = true; } // convert icons for composite content types iconHelper.formatContentTypeIcons([c.contentType]); }); } /* ---------- DELETE PROMT ---------- */ scope.togglePrompt = function (object) { object.deletePrompt = !object.deletePrompt; }; scope.hidePrompt = function (object) { object.deletePrompt = false; }; /* ---------- TOOLBAR ---------- */ scope.toggleSortingMode = function (tool) { if (scope.sortingMode === true) { var sortOrderMissing = false; for (var i = 0; i < scope.model.groups.length; i++) { var group = scope.model.groups[i]; if (group.tabState !== "init" && group.sortOrder === undefined) { sortOrderMissing = true; group.showSortOrderMissing = true; notificationsService.error(validationTranslated + ": " + group.name + " " + tabNoSortOrderTranslated); } } if (!sortOrderMissing) { scope.sortingMode = false; scope.sortingButtonKey = "general_reorder"; } } else { scope.sortingMode = true; scope.sortingButtonKey = "general_reorderDone"; } }; scope.openCompositionsDialog = function () { scope.compositionsDialogModel = { contentType: scope.model, compositeContentTypes: scope.model.compositeContentTypes, view: "views/common/infiniteeditors/compositions/compositions.html", size: "small", submit: function () { // make sure that all tabs has an init property if (scope.model.groups.length !== 0) { angular.forEach(scope.model.groups, function (group) { addInitProperty(group); }); } // remove overlay editorService.close(); }, close: function (oldModel) { // reset composition changes scope.model.groups = oldModel.contentType.groups; scope.model.compositeContentTypes = oldModel.contentType.compositeContentTypes; // remove overlay editorService.close(); }, selectCompositeContentType: function (selectedContentType) { var deferred = $q.defer(); //first check if this is a new selection - we need to store this value here before any further digests/async // because after that the scope.model.compositeContentTypes will be populated with the selected value. var newSelection = scope.model.compositeContentTypes.indexOf(selectedContentType.alias) === -1; if (newSelection) { //merge composition with content type //use a different resource lookup depending on the content type type var resourceLookup = scope.contentType === "documentType" ? contentTypeResource.getById : mediaTypeResource.getById; resourceLookup(selectedContentType.id).then(function (composition) { //based on the above filtering we shouldn't be able to select an invalid one, but let's be safe and // double check here. var overlappingAliases = contentTypeHelper.validateAddingComposition(scope.model, composition); if (overlappingAliases.length > 0) { //this will create an invalid composition, need to uncheck it scope.compositionsDialogModel.compositeContentTypes.splice( scope.compositionsDialogModel.compositeContentTypes.indexOf(composition.alias), 1); //dissallow this until something else is unchecked selectedContentType.allowed = false; } else { contentTypeHelper.mergeCompositeContentType(scope.model, composition); } //based on the selection, we need to filter the available composite types list filterAvailableCompositions(selectedContentType, newSelection).then(function () { deferred.resolve({ selectedContentType, newSelection }); // TODO: Here we could probably re-enable selection if we previously showed a throbber or something }, function () { deferred.reject(); }); }); } else { // split composition from content type contentTypeHelper.splitCompositeContentType(scope.model, selectedContentType); //based on the selection, we need to filter the available composite types list filterAvailableCompositions(selectedContentType, newSelection).then(function () { deferred.resolve({ selectedContentType, newSelection }); // TODO: Here we could probably re-enable selection if we previously showed a throbber or something }, function () { deferred.reject(); }); } return deferred.promise; } }; //select which resource methods to use, eg document Type or Media Type versions var availableContentTypeResource = scope.contentType === "documentType" ? contentTypeResource.getAvailableCompositeContentTypes : mediaTypeResource.getAvailableCompositeContentTypes; var whereUsedContentTypeResource = scope.contentType === "documentType" ? contentTypeResource.getWhereCompositionIsUsedInContentTypes : mediaTypeResource.getWhereCompositionIsUsedInContentTypes; var countContentTypeResource = scope.contentType === "documentType" ? contentTypeResource.getCount : mediaTypeResource.getCount; //get the currently assigned property type aliases - ensure we pass these to the server side filer var propAliasesExisting = _.filter(_.flatten(_.map(scope.model.groups, function (g) { return _.map(g.properties, function (p) { return p.alias; }); })), function (f) { return f !== null && f !== undefined; }); scope.compositionsButtonState = "busy"; $q.all([ //get available composite types availableContentTypeResource(scope.model.id, [], propAliasesExisting, scope.model.isElement).then(function (result) { setupAvailableContentTypesModel(result); }), //get where used document types whereUsedContentTypeResource(scope.model.id).then(function (whereUsed) { //pass to the dialog model the content type eg documentType or mediaType scope.compositionsDialogModel.section = scope.contentType; //pass the list of 'where used' document types scope.compositionsDialogModel.whereCompositionUsed = whereUsed; }), //get content type count countContentTypeResource().then(function (result) { scope.compositionsDialogModel.totalContentTypes = parseInt(result, 10); }) ]).then(function () { //resolves when both other promises are done, now show it editorService.open(scope.compositionsDialogModel); scope.compositionsButtonState = "init"; }); }; scope.openDocumentType = function (documentTypeId) { const editor = { id: documentTypeId, submit: function (model) { const args = { node: scope.model }; eventsService.emit("editors.documentType.reload", args); editorService.close(); }, close: function () { editorService.close(); } }; editorService.documentTypeEditor(editor); }; /* ---------- GROUPS ---------- */ scope.addGroup = function (group) { // set group sort order var index = scope.model.groups.indexOf(group); var prevGroup = scope.model.groups[index - 1]; if (index > 0) { // set index to 1 higher than the previous groups sort order group.sortOrder = prevGroup.sortOrder + 1; } else { // first group - sort order will be 0 group.sortOrder = 0; } // activate group scope.activateGroup(group); // push new init tab to the scope addInitGroup(scope.model.groups); }; scope.activateGroup = function (selectedGroup) { // set all other groups that are inactive to active angular.forEach(scope.model.groups, function (group) { // skip init tab if (group.tabState !== "init") { group.tabState = "inActive"; } }); selectedGroup.tabState = "active"; }; scope.canRemoveGroup = function (group) { return group.inherited !== true && _.find(group.properties, function (property) { return property.locked === true; }) == null; } scope.removeGroup = function (groupIndex) { scope.model.groups.splice(groupIndex, 1); }; scope.updateGroupTitle = function (group) { if (group.properties.length === 0) { addInitProperty(group); } }; scope.changeSortOrderValue = function (group) { if (group.sortOrder !== undefined) { group.showSortOrderMissing = false; } scope.model.groups = $filter('orderBy')(scope.model.groups, 'sortOrder'); }; function addInitGroup(groups) { // check i init tab already exists var addGroup = true; angular.forEach(groups, function (group) { if (group.tabState === "init") { addGroup = false; } }); if (addGroup) { groups.push({ properties: [], parentTabContentTypes: [], parentTabContentTypeNames: [], name: "", tabState: "init" }); } return groups; } function activateFirstGroup(groups) { if (groups && groups.length > 0) { var firstGroup = groups[0]; if (!firstGroup.tabState || firstGroup.tabState === "inActive") { firstGroup.tabState = "active"; } } } /* ---------- PROPERTIES ---------- */ scope.addPropertyToActiveGroup = function () { var group = _.find(scope.model.groups, group => group.tabState === "active"); if (!group && scope.model.groups.length) { group = scope.model.groups[0]; } if (!group || !group.name) { return; } var property = _.find(group.properties, property => property.propertyState === "init"); if (!property) { return; } scope.addProperty(property, group); } scope.addProperty = function (property, group) { // set property sort order var index = group.properties.indexOf(property); var prevProperty = group.properties[index - 1]; if (index > 0) { // set index to 1 higher than the previous property sort order property.sortOrder = prevProperty.sortOrder + 1; } else { // first property - sort order will be 0 property.sortOrder = 0; } // open property settings dialog scope.editPropertyTypeSettings(property, group); }; scope.editPropertyTypeSettings = function (property, group) { if (!property.inherited) { var oldPropertyModel = Utilities.copy(property); if (oldPropertyModel.allowCultureVariant === undefined) { // this is necessary for comparison when detecting changes to the property oldPropertyModel.allowCultureVariant = scope.model.allowCultureVariant; oldPropertyModel.alias = ""; } var propertyModel = Utilities.copy(property); var propertySettings = { title: "Property settings", property: propertyModel, contentType: scope.contentType, contentTypeName: scope.model.name, contentTypeAllowCultureVariant: scope.model.allowCultureVariant, contentTypeAllowSegmentVariant: scope.model.allowSegmentVariant, view: "views/common/infiniteeditors/propertysettings/propertysettings.html", size: "small", submit: function (model) { property.inherited = false; property.dialogIsOpen = false; property.propertyState = "active"; // apply all property changes property.label = propertyModel.label; property.alias = propertyModel.alias; property.description = propertyModel.description; property.config = propertyModel.config; property.editor = propertyModel.editor; property.view = propertyModel.view; property.dataTypeId = propertyModel.dataTypeId; property.dataTypeIcon = propertyModel.dataTypeIcon; property.dataTypeName = propertyModel.dataTypeName; property.validation.mandatory = propertyModel.validation.mandatory; property.validation.mandatoryMessage = propertyModel.validation.mandatoryMessage; property.validation.pattern = propertyModel.validation.pattern; property.validation.patternMessage = propertyModel.validation.patternMessage; property.showOnMemberProfile = propertyModel.showOnMemberProfile; property.memberCanEdit = propertyModel.memberCanEdit; property.isSensitiveData = propertyModel.isSensitiveData; property.isSensitiveValue = propertyModel.isSensitiveValue; property.allowCultureVariant = propertyModel.allowCultureVariant; property.allowSegmentVariant = propertyModel.allowSegmentVariant; property.labelOnTop = propertyModel.labelOnTop; // update existing data types if (model.updateSameDataTypes) { updateSameDataTypes(property); } // close the editor editorService.close(); // push new init property to group addInitProperty(group); // set focus on init property var numberOfProperties = group.properties.length; group.properties[numberOfProperties - 1].focus = true; notifyChanged(); }, close: function () { if (_.isEqual(oldPropertyModel, propertyModel) === false) { localizationService.localizeMany(["general_confirm", "contentTypeEditor_propertyHasChanges", "general_cancel", "general_ok"]).then(function (data) { const overlay = { title: data[0], content: data[1], closeButtonLabel: data[2], submitButtonLabel: data[3], submitButtonStyle: "danger", close: function () { overlayService.close(); }, submit: function () { // close the confirmation overlayService.close(); // close the editor editorService.close(); } }; overlayService.open(overlay); }); } else { // remove the editor editorService.close(); } } }; // open property settings editor editorService.open(propertySettings); // set property states property.dialogIsOpen = true; } }; scope.deleteProperty = function (tab, propertyIndex) { // remove property tab.properties.splice(propertyIndex, 1); notifyChanged(); }; function notifyChanged() { eventsService.emit("editors.groupsBuilder.changed"); } function addInitProperty(group) { var addInitPropertyBool = true; var initProperty = { label: null, alias: null, propertyState: "init", validation: { mandatory: false, mandatoryMessage: null, pattern: null, patternMessage: null }, labelOnTop: false }; // check if there already is an init property angular.forEach(group.properties, function (property) { if (property.propertyState === "init") { addInitPropertyBool = false; } }); if (addInitPropertyBool) { group.properties.push(initProperty); } return group; } function updateSameDataTypes(newProperty) { // find each property angular.forEach(scope.model.groups, function (group) { angular.forEach(group.properties, function (property) { if (property.dataTypeId === newProperty.dataTypeId) { // update property data property.config = newProperty.config; property.editor = newProperty.editor; property.view = newProperty.view; property.dataTypeId = newProperty.dataTypeId; property.dataTypeIcon = newProperty.dataTypeIcon; property.dataTypeName = newProperty.dataTypeName; } }); }); } function hasPropertyOfDataTypeId(dataTypeId) { // look at each property var result = _.filter(scope.model.groups, function (group) { return _.filter(group.properties, function (property) { return (property.dataTypeId === dataTypeId); }); }); return (result.length > 0); } eventBindings.push(scope.$watch('model', function (newValue, oldValue) { if (newValue !== undefined && newValue.groups !== undefined) { activate(); } })); // clean up eventBindings.push(eventsService.on("editors.dataTypeSettings.saved", function (name, args) { if (hasPropertyOfDataTypeId(args.dataType.id)) { scope.dataTypeHasChanged = true; } })); // clean up eventBindings.push(scope.$on('$destroy', function () { for (var e in eventBindings) { eventBindings[e](); } // if a dataType has changed, we want to notify which properties that are affected by this dataTypeSettings change if (scope.dataTypeHasChanged === true) { var args = { documentType: scope.model }; eventsService.emit("editors.documentType.saved", args); } })); } var directive = { restrict: "E", replace: true, templateUrl: "views/components/umb-groups-builder.html", scope: { model: "=", compositions: "=", sorting: "=", contentType: "@" }, link: link }; return directive; } angular.module('umbraco.directives').directive('umbGroupsBuilder', GroupsBuilderDirective); })();
/* * Copyright (c) 2017. MIT-license for Jari Van Melckebeke * Note that there was a lot of educational work in this project, * this project was (or is) used for an assignment from Realdolmen in Belgium. * Please just don't abuse my work */ define(function () { // Slovak // use text for the numbers 2 through 4 var smallNumbers = { 2: function (masc) { return (masc ? 'dva' : 'dve'); }, 3: function () { return 'tri'; }, 4: function () { return 'štyri'; } }; return { inputTooLong: function (args) { var overChars = args.input.length - args.maximum; if (overChars == 1) { return 'Prosím, zadajte o jeden znak menej'; } else if (overChars >= 2 && overChars <= 4) { return 'Prosím, zadajte o ' + smallNumbers[overChars](true) + ' znaky menej'; } else { return 'Prosím, zadajte o ' + overChars + ' znakov menej'; } }, inputTooShort: function (args) { var remainingChars = args.minimum - args.input.length; if (remainingChars == 1) { return 'Prosím, zadajte ešte jeden znak'; } else if (remainingChars <= 4) { return 'Prosím, zadajte ešte ďalšie ' + smallNumbers[remainingChars](true) + ' znaky'; } else { return 'Prosím, zadajte ešte ďalších ' + remainingChars + ' znakov'; } }, loadingMore: function () { return 'Loading more results…'; }, maximumSelected: function (args) { if (args.maximum == 1) { return 'Môžete zvoliť len jednu položku'; } else if (args.maximum >= 2 && args.maximum <= 4) { return 'Môžete zvoliť najviac ' + smallNumbers[args.maximum](false) + ' položky'; } else { return 'Môžete zvoliť najviac ' + args.maximum + ' položiek'; } }, noResults: function () { return 'Nenašli sa žiadne položky'; }, searching: function () { return 'Vyhľadávanie…'; } }; });
(function(){Template.formItem.customerMeasurement = function(item) { customerId = Session.get('currentCustomer'); customerMeasurements = Customers.findOne({_id: customerId}).measurements; if(!_.isUndefined(customerMeasurements)) { return 'Currently: ' + customerMeasurements[item] } return 'No Measurement Taken Yet' } })();
'use strict'; const isGeneratorFn = require('is-generator-fn'); const co = require('co-with-promise'); const concordance = require('concordance'); const observableToPromise = require('observable-to-promise'); const isPromise = require('is-promise'); const isObservable = require('is-observable'); const plur = require('plur'); const assert = require('./assert'); const globals = require('./globals'); const concordanceOptions = require('./concordance-options').default; function formatErrorValue(label, error) { const formatted = concordance.format(error, concordanceOptions); return {label, formatted}; } class SkipApi { constructor(test) { this._test = test; } } const captureStack = start => { const limitBefore = Error.stackTraceLimit; Error.stackTraceLimit = 1; const obj = {}; Error.captureStackTrace(obj, start); Error.stackTraceLimit = limitBefore; return obj.stack; }; class ExecutionContext { constructor(test) { Object.defineProperties(this, { _test: {value: test}, skip: {value: new SkipApi(test)} }); } plan(ct) { this._test.plan(ct, captureStack(this.plan)); } get end() { const end = this._test.bindEndCallback(); const endFn = err => end(err, captureStack(endFn)); return endFn; } get title() { return this._test.title; } get context() { const contextRef = this._test.contextRef; return contextRef && contextRef.context; } set context(context) { const contextRef = this._test.contextRef; if (!contextRef) { this._test.saveFirstError(new Error(`\`t.context\` is not available in ${this._test.metadata.type} tests`)); return; } contextRef.context = context; } _throwsArgStart(assertion, file, line) { this._test.trackThrows({assertion, file, line}); } _throwsArgEnd() { this._test.trackThrows(null); } } { const assertions = assert.wrapAssertions({ log(executionContext, text) { executionContext._test.addLog(text); }, pass(executionContext) { executionContext._test.countPassedAssertion(); }, pending(executionContext, promise) { executionContext._test.addPendingAssertion(promise); }, fail(executionContext, error) { executionContext._test.addFailedAssertion(error); } }); Object.assign(ExecutionContext.prototype, assertions); function skipFn() { this._test.countPassedAssertion(); } Object.keys(assertions).forEach(el => { SkipApi.prototype[el] = skipFn; }); } class Test { constructor(options) { this.contextRef = options.contextRef; this.failWithoutAssertions = options.failWithoutAssertions; this.fn = isGeneratorFn(options.fn) ? co.wrap(options.fn) : options.fn; this.metadata = options.metadata; this.onResult = options.onResult; this.title = options.title; this.logs = []; this.snapshotInvocationCount = 0; this.compareWithSnapshot = assertionOptions => { const belongsTo = assertionOptions.id || this.title; const expected = assertionOptions.expected; const index = assertionOptions.id ? 0 : this.snapshotInvocationCount++; const label = assertionOptions.id ? '' : assertionOptions.message || `Snapshot ${this.snapshotInvocationCount}`; return options.compareTestSnapshot({belongsTo, expected, index, label}); }; this.assertCount = 0; this.assertError = undefined; this.calledEnd = false; this.duration = null; this.endCallbackFinisher = null; this.finishDueToAttributedError = null; this.finishDueToInactivity = null; this.finishing = false; this.pendingAssertionCount = 0; this.pendingThrowsAssertion = null; this.planCount = null; this.startedAt = 0; } bindEndCallback() { if (this.metadata.callback) { return (err, stack) => { this.endCallback(err, stack); }; } throw new Error('`t.end()`` is not supported in this context. To use `t.end()` as a callback, you must use "callback mode" via `test.cb(testName, fn)`'); } endCallback(err, stack) { if (this.calledEnd) { this.saveFirstError(new Error('`t.end()` called more than once')); return; } this.calledEnd = true; if (err) { this.saveFirstError(new assert.AssertionError({ actual: err, message: 'Callback called with an error', stack, values: [formatErrorValue('Callback called with an error:', err)] })); } if (this.endCallbackFinisher) { this.endCallbackFinisher(); } } createExecutionContext() { return new ExecutionContext(this); } countPassedAssertion() { if (this.finishing) { this.saveFirstError(new Error('Assertion passed, but test has already finished')); } this.assertCount++; } addLog(text) { this.logs.push(text); } addPendingAssertion(promise) { if (this.finishing) { this.saveFirstError(new Error('Assertion passed, but test has already finished')); } this.assertCount++; this.pendingAssertionCount++; promise .catch(err => this.saveFirstError(err)) .then(() => this.pendingAssertionCount--); } addFailedAssertion(error) { if (this.finishing) { this.saveFirstError(new Error('Assertion failed, but test has already finished')); } this.assertCount++; this.saveFirstError(error); } saveFirstError(err) { if (!this.assertError) { this.assertError = err; } } plan(count, planStack) { if (typeof count !== 'number') { throw new TypeError('Expected a number'); } this.planCount = count; // In case the `planCount` doesn't match `assertCount, we need the stack of // this function to throw with a useful stack. this.planStack = planStack; } verifyPlan() { if (!this.assertError && this.planCount !== null && this.planCount !== this.assertCount) { this.saveFirstError(new assert.AssertionError({ assertion: 'plan', message: `Planned for ${this.planCount} ${plur('assertion', this.planCount)}, but got ${this.assertCount}.`, operator: '===', stack: this.planStack })); } } verifyAssertions() { if (!this.assertError) { if (this.failWithoutAssertions && !this.calledEnd && this.planCount === null && this.assertCount === 0) { this.saveFirstError(new Error('Test finished without running any assertions')); } else if (this.pendingAssertionCount > 0) { this.saveFirstError(new Error('Test finished, but an assertion is still pending')); } } } trackThrows(pending) { this.pendingThrowsAssertion = pending; } detectImproperThrows(err) { if (!this.pendingThrowsAssertion) { return false; } const pending = this.pendingThrowsAssertion; this.pendingThrowsAssertion = null; const values = []; if (err) { values.push(formatErrorValue(`The following error was thrown, possibly before \`t.${pending.assertion}()\` could be called:`, err)); } this.saveFirstError(new assert.AssertionError({ assertion: pending.assertion, fixedSource: {file: pending.file, line: pending.line}, improperUsage: true, message: `Improper usage of \`t.${pending.assertion}()\` detected`, stack: err instanceof Error && err.stack, values })); return true; } waitForPendingThrowsAssertion() { return new Promise(resolve => { this.finishDueToAttributedError = () => { resolve(this.finishPromised()); }; this.finishDueToInactivity = () => { this.detectImproperThrows(); resolve(this.finishPromised()); }; // Wait up to a second to see if an error can be attributed to the // pending assertion. globals.setTimeout(() => this.finishDueToInactivity(), 1000).unref(); }); } attributeLeakedError(err) { if (!this.detectImproperThrows(err)) { return false; } this.finishDueToAttributedError(); return true; } callFn() { try { return { ok: true, retval: this.fn(this.createExecutionContext()) }; } catch (err) { return { ok: false, error: err }; } } run() { this.startedAt = globals.now(); const result = this.callFn(); if (!result.ok) { if (!this.detectImproperThrows(result.error)) { this.saveFirstError(new assert.AssertionError({ message: 'Error thrown in test', stack: result.error instanceof Error && result.error.stack, values: [formatErrorValue('Error thrown in test:', result.error)] })); } return this.finish(); } const returnedObservable = isObservable(result.retval); const returnedPromise = isPromise(result.retval); let promise; if (returnedObservable) { promise = observableToPromise(result.retval); } else if (returnedPromise) { // `retval` can be any thenable, so convert to a proper promise. promise = Promise.resolve(result.retval); } if (this.metadata.callback) { if (returnedObservable || returnedPromise) { const asyncType = returnedObservable ? 'observables' : 'promises'; this.saveFirstError(new Error(`Do not return ${asyncType} from tests declared via \`test.cb(...)\`, if you want to return a promise simply declare the test via \`test(...)\``)); return this.finish(); } if (this.calledEnd) { return this.finish(); } return new Promise(resolve => { this.endCallbackFinisher = () => { resolve(this.finishPromised()); }; this.finishDueToAttributedError = () => { resolve(this.finishPromised()); }; this.finishDueToInactivity = () => { this.saveFirstError(new Error('`t.end()` was never called')); resolve(this.finishPromised()); }; }); } if (promise) { return new Promise(resolve => { this.finishDueToAttributedError = () => { resolve(this.finishPromised()); }; this.finishDueToInactivity = () => { const err = returnedObservable ? new Error('Observable returned by test never completed') : new Error('Promise returned by test never resolved'); this.saveFirstError(err); resolve(this.finishPromised()); }; promise .catch(err => { if (!this.detectImproperThrows(err)) { this.saveFirstError(new assert.AssertionError({ message: 'Rejected promise returned by test', stack: err instanceof Error && err.stack, values: [formatErrorValue('Rejected promise returned by test. Reason:', err)] })); } }) .then(() => resolve(this.finishPromised())); }); } return this.finish(); } finish() { this.finishing = true; if (!this.assertError && this.pendingThrowsAssertion) { return this.waitForPendingThrowsAssertion(); } this.verifyPlan(); this.verifyAssertions(); this.duration = globals.now() - this.startedAt; let reason = this.assertError; let passed = !reason; if (this.metadata.failing) { passed = !passed; if (passed) { reason = undefined; } else { reason = new Error('Test was expected to fail, but succeeded, you should stop marking the test as failing'); } } this.onResult({ passed, result: this, reason }); return passed; } finishPromised() { return new Promise(resolve => { resolve(this.finish()); }); } } module.exports = Test;
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /** * @name: S11.8.1_A4.12_T2; * @section: 11.8.1, 11.8.5; * @assertion: If neither x, nor y is a prefix of each other, returned result of strings comparison applies a simple lexicographic ordering to the sequences of code point value values; * @description: x and y are string primitives; */ //CHECK#1 if (("0" < "x") !== true) { $ERROR('#1: ("0" < "x") !== true'); } //CHECK#2 if (("-" < "0") !== true) { $ERROR('#2: ("-" < "0") !== true'); } //CHECK#3 if (("." < "0") !== true) { $ERROR('#3: ("." < "0") !== true'); } //CHECK#4 if (("+" < "-") !== true) { $ERROR('#4: ("+" < "-") !== true'); } //CHECK#5 if (("-0" < "-1") !== true) { $ERROR('#5: ("-0" < "-1") !== true'); } //CHECK#6 if (("+1" < "-1") !== true) { $ERROR('#6: ("+1" < "-1") !== true'); } //CHECK#7 if (("1" < "1e-10") !== true) { $ERROR('#7: ("1" < "1e-10") !== true'); }
import { Meteor } from 'meteor/meteor'; const nextTick = Meteor.bindEnvironment( fct => Meteor.defer(() => fct()), ); export default nextTick;
"use strict"; function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _defaults(subClass, superClass); } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } var Declaration = require('../declaration'); var utils = require('../utils'); var BackgroundClip = /*#__PURE__*/ function (_Declaration) { _inheritsLoose(BackgroundClip, _Declaration); function BackgroundClip(name, prefixes, all) { var _this; _this = _Declaration.call(this, name, prefixes, all) || this; if (_this.prefixes) { _this.prefixes = utils.uniq(_this.prefixes.map(function (i) { if (i === '-ms-') { return '-webkit-'; } else { return i; } })); } return _this; } var _proto = BackgroundClip.prototype; _proto.check = function check(decl) { return decl.value.toLowerCase() === 'text'; }; return BackgroundClip; }(Declaration); _defineProperty(BackgroundClip, "names", ['background-clip']); module.exports = BackgroundClip;
//= require redactor-rails/redactor.min //= require redactor-rails/langs/pt_br //= require ./redactor-rails/config.js
var expect = require('chai').expect var request = require('request') var local_enduro = require('../index').quick_init() var test_utilities = require('./libs/test_utilities') describe('Development server', function () { this.timeout(5000) before(function () { return test_utilities.before(local_enduro, 'devserver', 'minimalistic') .then(() => { return enduro.actions.developer_start({ norefresh: true, nowatch: true }) }) .delay(150) }) it('should serve something on port 3000', function (done) { request('http://localhost:3000/', function (error, response, body) { if (error) { console.log(error) } expect(body).to.contain('body') expect(body).to.contain('head') expect(body).to.contain('title') done() }) }) it('should serve something on port 5000', function (done) { request('http://localhost:5000/', function (error, response, body) { if (error) { console.log(error) } expect(body).to.contain('body') expect(body).to.contain('head') expect(body).to.contain('title') done() }) }) it('should serve admin interface', function (done) { request('http://localhost:5000/admin', function (error, response, body) { if (error) { console.log(error) } expect(body).to.contain('body') expect(body).to.contain('head') expect(body).to.contain('ng-view ng-cloak') done() }) }) after(function () { return enduro.actions.stop_server() .then(() => { return test_utilities.after() }) }) })
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M7 5h10v2h2V3c0-1.1-.9-1.99-2-1.99L7 1c-1.1 0-2 .9-2 2v4h2V5zm8.41 11.59L20 12l-4.59-4.59L14 8.83 17.17 12 14 15.17l1.41 1.42zM10 15.17L6.83 12 10 8.83 8.59 7.41 4 12l4.59 4.59L10 15.17zM17 19H7v-2H5v4c0 1.1.9 2 2 2h10c1.1 0 2-.9 2-2v-4h-2v2z" /> , 'DeveloperModeTwoTone');
function flip( fn ) { return function () { return fn.apply( fn, Array.prototype.slice.call( arguments ).reverse() ); }; }
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M17 12h2L12 2 5.05 12H7l-3.9 6h6.92v4h3.96v-4H21z" }), 'ParkSharp'); exports.default = _default;
cordova.define('cordova/plugin_list', function(require, exports, module) { module.exports = [ { "file": "plugins/org.apache.cordova.geolocation/src/firefoxos/GeolocationProxy.js", "id": "org.apache.cordova.geolocation.GeolocationProxy", "runs": true }, { "file": "plugins/org.apache.cordova.geolocation/www/Coordinates.js", "id": "org.apache.cordova.geolocation.Coordinates", "clobbers": [ "Coordinates" ] }, { "file": "plugins/org.apache.cordova.geolocation/www/PositionError.js", "id": "org.apache.cordova.geolocation.PositionError", "clobbers": [ "PositionError" ] }, { "file": "plugins/org.apache.cordova.geolocation/www/Position.js", "id": "org.apache.cordova.geolocation.Position", "clobbers": [ "Position" ] }, { "file": "plugins/org.apache.cordova.geolocation/www/geolocation.js", "id": "org.apache.cordova.geolocation.geolocation", "clobbers": [ "navigator.geolocation" ] }, { "file": "plugins/org.apache.cordova.device/www/device.js", "id": "org.apache.cordova.device.device", "clobbers": [ "device" ] }, { "file": "plugins/org.apache.cordova.device/src/firefoxos/DeviceProxy.js", "id": "org.apache.cordova.device.DeviceProxy", "runs": true }, { "file": "plugins/org.apache.cordova.contacts/www/contacts.js", "id": "org.apache.cordova.contacts.contacts", "clobbers": [ "navigator.contacts" ] }, { "file": "plugins/org.apache.cordova.contacts/www/Contact.js", "id": "org.apache.cordova.contacts.Contact", "clobbers": [ "Contact" ] }, { "file": "plugins/org.apache.cordova.contacts/www/ContactAddress.js", "id": "org.apache.cordova.contacts.ContactAddress", "clobbers": [ "ContactAddress" ] }, { "file": "plugins/org.apache.cordova.contacts/www/ContactError.js", "id": "org.apache.cordova.contacts.ContactError", "clobbers": [ "ContactError" ] }, { "file": "plugins/org.apache.cordova.contacts/www/ContactField.js", "id": "org.apache.cordova.contacts.ContactField", "clobbers": [ "ContactField" ] }, { "file": "plugins/org.apache.cordova.contacts/www/ContactFindOptions.js", "id": "org.apache.cordova.contacts.ContactFindOptions", "clobbers": [ "ContactFindOptions" ] }, { "file": "plugins/org.apache.cordova.contacts/www/ContactName.js", "id": "org.apache.cordova.contacts.ContactName", "clobbers": [ "ContactName" ] }, { "file": "plugins/org.apache.cordova.contacts/www/ContactOrganization.js", "id": "org.apache.cordova.contacts.ContactOrganization", "clobbers": [ "ContactOrganization" ] }, { "file": "plugins/org.apache.cordova.contacts/src/firefoxos/ContactsProxy.js", "id": "org.apache.cordova.contacts.ContactsProxy", "runs": true }, { "file": "plugins/org.apache.cordova.camera/www/CameraConstants.js", "id": "org.apache.cordova.camera.Camera", "clobbers": [ "Camera" ] }, { "file": "plugins/org.apache.cordova.camera/www/CameraPopoverOptions.js", "id": "org.apache.cordova.camera.CameraPopoverOptions", "clobbers": [ "CameraPopoverOptions" ] }, { "file": "plugins/org.apache.cordova.camera/www/Camera.js", "id": "org.apache.cordova.camera.camera", "clobbers": [ "navigator.camera" ] }, { "file": "plugins/org.apache.cordova.camera/src/firefoxos/CameraProxy.js", "id": "org.apache.cordova.camera.CameraProxy", "runs": true } ]; module.exports.metadata = // TOP OF METADATA { "org.apache.cordova.geolocation": "0.3.6", "org.apache.cordova.device": "0.2.8", "org.apache.cordova.contacts": "0.2.8", "org.apache.cordova.camera": "0.2.7" } // BOTTOM OF METADATA });
new Test.Unit.Runner({ 'setup': function() { scrollTo(0,0); Position.prepare(); Position.includeScrollOffsets = false; }, 'teardown': function() { scrollTo(0,0); Position.prepare(); Position.includeScrollOffsets = false; }, 'testPrepare': function() { Position.prepare(); this.assertEqual(0, Position.deltaX); this.assertEqual(0, Position.deltaY); scrollTo(20,30); Position.prepare(); this.assertEqual(20, Position.deltaX); this.assertEqual(30, Position.deltaY); }, 'testWithin': function() { Fuse.List(true, false).each(function(withScrollOffsets) { Position.includeScrollOffsets = withScrollOffsets; this.assert(Position.within($('body_absolute'), 10, 10), 'left/top corner'); this.assert(Position.within($('body_absolute'), 10, 19), 'left/bottom corner'); this.assert(!Position.within($('body_absolute'), 9, 9), 'outside left/top'); this.assert(!Position.within($('body_absolute'), 10, 20), 'outside bottom'); }, this); scrollTo(20,30); Position.prepare(); Position.includeScrollOffsets = true; this.assert(Position.within($('body_absolute'), 10, 10), 'left/top corner'); this.assert(Position.within($('body_absolute'), 10, 19), 'left/bottom corner'); this.assert(!Position.within($('body_absolute'), 9, 9), 'outside left/top'); this.assert(!Position.within($('body_absolute'), 10, 20), 'outside bottom'); } });
// // Autogenerated by Thrift Compiler (0.9.1) // // DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING // if (typeof kibitz === 'undefined') { kibitz = {}; } kibitz.Item = function(args) { this.attributes = null; this.kibitz_generated_id = null; if (args) { if (args.attributes !== undefined) { this.attributes = args.attributes; } if (args.kibitz_generated_id !== undefined) { this.kibitz_generated_id = args.kibitz_generated_id; } } }; kibitz.Item.prototype = {}; kibitz.Item.prototype.read = function(input) { input.readStructBegin(); while (true) { var ret = input.readFieldBegin(); var fname = ret.fname; var ftype = ret.ftype; var fid = ret.fid; if (ftype == Thrift.Type.STOP) { break; } switch (fid) { case 1: if (ftype == Thrift.Type.MAP) { var _size0 = 0; var _rtmp34; this.attributes = {}; var _ktype1 = 0; var _vtype2 = 0; _rtmp34 = input.readMapBegin(); _ktype1 = _rtmp34.ktype; _vtype2 = _rtmp34.vtype; _size0 = _rtmp34.size; for (var _i5 = 0; _i5 < _size0; ++_i5) { if (_i5 > 0 ) { if (input.rstack.length > input.rpos[input.rpos.length -1] + 1) { input.rstack.pop(); } } var key6 = null; var val7 = null; key6 = input.readString().value; val7 = input.readString().value; this.attributes[key6] = val7; } input.readMapEnd(); } else { input.skip(ftype); } break; case 2: if (ftype == Thrift.Type.I64) { this.kibitz_generated_id = input.readI64().value; } else { input.skip(ftype); } break; default: input.skip(ftype); } input.readFieldEnd(); } input.readStructEnd(); return; }; kibitz.Item.prototype.write = function(output) { output.writeStructBegin('Item'); if (this.attributes !== null && this.attributes !== undefined) { output.writeFieldBegin('attributes', Thrift.Type.MAP, 1); output.writeMapBegin(Thrift.Type.STRING, Thrift.Type.STRING, Thrift.objectLength(this.attributes)); for (var kiter8 in this.attributes) { if (this.attributes.hasOwnProperty(kiter8)) { var viter9 = this.attributes[kiter8]; output.writeString(kiter8); output.writeString(viter9); } } output.writeMapEnd(); output.writeFieldEnd(); } if (this.kibitz_generated_id !== null && this.kibitz_generated_id !== undefined) { output.writeFieldBegin('kibitz_generated_id', Thrift.Type.I64, 2); output.writeI64(this.kibitz_generated_id); output.writeFieldEnd(); } output.writeFieldStop(); output.writeStructEnd(); return; }; kibitz.Recommender = function(args) { this.username = null; this.recommenderName = null; this.clientKey = null; this.homepage = null; this.repoName = null; this.title = null; this.description = null; this.image = null; this.video = null; this.itemTypes = null; this.displayItems = null; this.numRecs = null; this.maxRatingVal = null; this.ratingsColumn = null; this.primaryKey = null; if (args) { if (args.username !== undefined) { this.username = args.username; } if (args.recommenderName !== undefined) { this.recommenderName = args.recommenderName; } if (args.clientKey !== undefined) { this.clientKey = args.clientKey; } if (args.homepage !== undefined) { this.homepage = args.homepage; } if (args.repoName !== undefined) { this.repoName = args.repoName; } if (args.title !== undefined) { this.title = args.title; } if (args.description !== undefined) { this.description = args.description; } if (args.image !== undefined) { this.image = args.image; } if (args.video !== undefined) { this.video = args.video; } if (args.itemTypes !== undefined) { this.itemTypes = args.itemTypes; } if (args.displayItems !== undefined) { this.displayItems = args.displayItems; } if (args.numRecs !== undefined) { this.numRecs = args.numRecs; } if (args.maxRatingVal !== undefined) { this.maxRatingVal = args.maxRatingVal; } if (args.ratingsColumn !== undefined) { this.ratingsColumn = args.ratingsColumn; } if (args.primaryKey !== undefined) { this.primaryKey = args.primaryKey; } } }; kibitz.Recommender.prototype = {}; kibitz.Recommender.prototype.read = function(input) { input.readStructBegin(); while (true) { var ret = input.readFieldBegin(); var fname = ret.fname; var ftype = ret.ftype; var fid = ret.fid; if (ftype == Thrift.Type.STOP) { break; } switch (fid) { case 1: if (ftype == Thrift.Type.STRING) { this.username = input.readString().value; } else { input.skip(ftype); } break; case 2: if (ftype == Thrift.Type.STRING) { this.recommenderName = input.readString().value; } else { input.skip(ftype); } break; case 3: if (ftype == Thrift.Type.STRING) { this.clientKey = input.readString().value; } else { input.skip(ftype); } break; case 4: if (ftype == Thrift.Type.STRING) { this.homepage = input.readString().value; } else { input.skip(ftype); } break; case 5: if (ftype == Thrift.Type.STRING) { this.repoName = input.readString().value; } else { input.skip(ftype); } break; case 6: if (ftype == Thrift.Type.STRING) { this.title = input.readString().value; } else { input.skip(ftype); } break; case 7: if (ftype == Thrift.Type.STRING) { this.description = input.readString().value; } else { input.skip(ftype); } break; case 8: if (ftype == Thrift.Type.STRING) { this.image = input.readString().value; } else { input.skip(ftype); } break; case 9: if (ftype == Thrift.Type.STRING) { this.video = input.readString().value; } else { input.skip(ftype); } break; case 10: if (ftype == Thrift.Type.MAP) { var _size10 = 0; var _rtmp314; this.itemTypes = {}; var _ktype11 = 0; var _vtype12 = 0; _rtmp314 = input.readMapBegin(); _ktype11 = _rtmp314.ktype; _vtype12 = _rtmp314.vtype; _size10 = _rtmp314.size; for (var _i15 = 0; _i15 < _size10; ++_i15) { if (_i15 > 0 ) { if (input.rstack.length > input.rpos[input.rpos.length -1] + 1) { input.rstack.pop(); } } var key16 = null; var val17 = null; key16 = input.readString().value; val17 = input.readString().value; this.itemTypes[key16] = val17; } input.readMapEnd(); } else { input.skip(ftype); } break; case 11: if (ftype == Thrift.Type.LIST) { var _size18 = 0; var _rtmp322; this.displayItems = []; var _etype21 = 0; _rtmp322 = input.readListBegin(); _etype21 = _rtmp322.etype; _size18 = _rtmp322.size; for (var _i23 = 0; _i23 < _size18; ++_i23) { var elem24 = null; elem24 = input.readString().value; this.displayItems.push(elem24); } input.readListEnd(); } else { input.skip(ftype); } break; case 12: if (ftype == Thrift.Type.I64) { this.numRecs = input.readI64().value; } else { input.skip(ftype); } break; case 13: if (ftype == Thrift.Type.I64) { this.maxRatingVal = input.readI64().value; } else { input.skip(ftype); } break; case 14: if (ftype == Thrift.Type.STRING) { this.ratingsColumn = input.readString().value; } else { input.skip(ftype); } break; case 15: if (ftype == Thrift.Type.STRING) { this.primaryKey = input.readString().value; } else { input.skip(ftype); } break; default: input.skip(ftype); } input.readFieldEnd(); } input.readStructEnd(); return; }; kibitz.Recommender.prototype.write = function(output) { output.writeStructBegin('Recommender'); if (this.username !== null && this.username !== undefined) { output.writeFieldBegin('username', Thrift.Type.STRING, 1); output.writeString(this.username); output.writeFieldEnd(); } if (this.recommenderName !== null && this.recommenderName !== undefined) { output.writeFieldBegin('recommenderName', Thrift.Type.STRING, 2); output.writeString(this.recommenderName); output.writeFieldEnd(); } if (this.clientKey !== null && this.clientKey !== undefined) { output.writeFieldBegin('clientKey', Thrift.Type.STRING, 3); output.writeString(this.clientKey); output.writeFieldEnd(); } if (this.homepage !== null && this.homepage !== undefined) { output.writeFieldBegin('homepage', Thrift.Type.STRING, 4); output.writeString(this.homepage); output.writeFieldEnd(); } if (this.repoName !== null && this.repoName !== undefined) { output.writeFieldBegin('repoName', Thrift.Type.STRING, 5); output.writeString(this.repoName); output.writeFieldEnd(); } if (this.title !== null && this.title !== undefined) { output.writeFieldBegin('title', Thrift.Type.STRING, 6); output.writeString(this.title); output.writeFieldEnd(); } if (this.description !== null && this.description !== undefined) { output.writeFieldBegin('description', Thrift.Type.STRING, 7); output.writeString(this.description); output.writeFieldEnd(); } if (this.image !== null && this.image !== undefined) { output.writeFieldBegin('image', Thrift.Type.STRING, 8); output.writeString(this.image); output.writeFieldEnd(); } if (this.video !== null && this.video !== undefined) { output.writeFieldBegin('video', Thrift.Type.STRING, 9); output.writeString(this.video); output.writeFieldEnd(); } if (this.itemTypes !== null && this.itemTypes !== undefined) { output.writeFieldBegin('itemTypes', Thrift.Type.MAP, 10); output.writeMapBegin(Thrift.Type.STRING, Thrift.Type.STRING, Thrift.objectLength(this.itemTypes)); for (var kiter25 in this.itemTypes) { if (this.itemTypes.hasOwnProperty(kiter25)) { var viter26 = this.itemTypes[kiter25]; output.writeString(kiter25); output.writeString(viter26); } } output.writeMapEnd(); output.writeFieldEnd(); } if (this.displayItems !== null && this.displayItems !== undefined) { output.writeFieldBegin('displayItems', Thrift.Type.LIST, 11); output.writeListBegin(Thrift.Type.STRING, this.displayItems.length); for (var iter27 in this.displayItems) { if (this.displayItems.hasOwnProperty(iter27)) { iter27 = this.displayItems[iter27]; output.writeString(iter27); } } output.writeListEnd(); output.writeFieldEnd(); } if (this.numRecs !== null && this.numRecs !== undefined) { output.writeFieldBegin('numRecs', Thrift.Type.I64, 12); output.writeI64(this.numRecs); output.writeFieldEnd(); } if (this.maxRatingVal !== null && this.maxRatingVal !== undefined) { output.writeFieldBegin('maxRatingVal', Thrift.Type.I64, 13); output.writeI64(this.maxRatingVal); output.writeFieldEnd(); } if (this.ratingsColumn !== null && this.ratingsColumn !== undefined) { output.writeFieldBegin('ratingsColumn', Thrift.Type.STRING, 14); output.writeString(this.ratingsColumn); output.writeFieldEnd(); } if (this.primaryKey !== null && this.primaryKey !== undefined) { output.writeFieldBegin('primaryKey', Thrift.Type.STRING, 15); output.writeString(this.primaryKey); output.writeFieldEnd(); } output.writeFieldStop(); output.writeStructEnd(); return; };
import gulp from 'gulp'; import co from 'co'; import path from 'path'; import plumber from 'gulp-plumber'; import rm from 'greasebox/rm'; import { paths } from './config'; gulp.task('clean', (cb) => { rm(paths.build) .then(cb) .catch(cb); }); gulp.task('clean:bundle', (cb) => { rm(paths.bundle) .then(cb) .catch(cb); });
define(['durandal/app','lib/pagelayout','lib/prettify'], function (app, pagelayout, prettify) { var activePage = ko.observable(), hash = "", oc; var availablePoints = ko.observableArray([ 'up-1', 'up-2', 'up-3','up-4','up-5','up-6', 'down-1', 'down-2', 'down-3','down-4','down-5','down-6', 'right-1', 'right-2', 'right-3','right-4','right-5','right-6', 'left-1', 'left-2', 'left-3','left-4','left-5','left-6' ]); var sample1 = ko.observable({ pointA : "", pointB : "", image : "#image-1" }); var sample2 = ko.observable({ pointA : "", pointB : "", image : "#image-2" }); var sample3 = ko.observable({ pointA : "", pointB : "", image : "#image-3" }); var sample4 = ko.observable({ pointA : "", pointB : "", image : "#image-4", customimage : ko.observable("http://t2.gstatic.com/images?q=tbn:ANd9GcQh6lYnW0E-HTU0WtfJV0cl1UZVS2Ng0D03lu4lIHCOMdVS90SLeg") }); var sampleOn = function(data, event) { Stashy.FocalPoint(data.image).on(data.pointA,data.pointB); } var sampleOff = function(data, event) { Stashy.FocalPoint(data.image).off(); } var sampleUpdate = function(data, event) { Stashy.FocalPoint(data.image).update(data.pointA, data.pointB); } var samplesOff = function() { Stashy.FocalPoint("#sample-1").off(); Stashy.FocalPoint("#sample-2").off(); } return { compositionComplete : function() { var that = this; oc= Stashy.OffCanvas("#focalpoint", { enableTouch : true }) pagelayout.offcanvasLayout(oc); prettyPrint(); Stashy.FocalPoint("#sample-1").on("top-3", "right-3"); Stashy.FocalPoint("#sample-2").on("top-2", "right-2"); Stashy.Utils.ScrollTo('#' + that.hash); }, activePage : activePage, activate: function (page) { var that = this; if (page != undefined) { that.hash = page; Stashy.Utils.ScrollTo('#focalpoint #' + that.hash); } ga('send', 'pageview'); }, sample1 : sample1, sample2 : sample2, sample3 : sample3, sample4 : sample4, sampleOn : sampleOn, sampleOff : sampleOff, sampleUpdate : sampleUpdate, samplesOff : samplesOff, availablePoints : availablePoints }; });
function WaitForRegistration(cmdController) { "use strict"; var handlerRegister = function () { cmdController.log('handlerRegister invoked...'); }, handlerSubmitSMS = function () { cmdController.log('handlerSubmitSMS invoked...'); }, validateInputs = function () { cmdController.log('validateInputs invoked...'); }, checkServerConfig = function () { cmdController.log('checkServerConfig invoked...'); }, sendOK = function () { cmdController.log('sendOK invoked...'); }, sendSENDSMS = function () { cmdController.log('sendSENDSMS invoked...'); }; this.handlerRegister = handlerRegister; this.handlerSubmitSMS = handlerSubmitSMS; this.validateInputs = validateInputs; this.checkServerConfig = checkServerConfig; this.sendOK = sendOK; this.sendSENDSMS = sendSENDSMS; } module.exports = WaitForRegistration;
// IMPORTANT!!! // The native getBBox() on text elements isn't always accurate in the decimals. // Therefore sometimes some rounding is used to make test work as expected. describe('Text', function() { var text beforeEach(function() { text = draw.text(loremIpsum).size(5) }) afterEach(function() { draw.clear() }) describe('x()', function() { it('returns the value of x without an argument', function() { expect(text.x()).toBe(0) }) it('sets the value of x with the first argument', function() { text.x(123) var box = text.bbox() expect(box.x).toBe(123) }) it('sets the value of x based on the anchor with the first argument', function() { text.x(123, true) var box = text.bbox() expect(box.x).toBe(123) }) }) describe('y()', function() { it('returns the value of y without an argument', function() { expect(text.y(0).y()).toBe(0) }) it('sets the value of y with the first argument', function() { text.y(345) var box = text.bbox() expect(box.y).toBe(345) }) it('sets the value of y based on the anchor with the first argument', function() { text.y(345, true) var box = text.bbox() expect(box.y).toBe(345) }) }) describe('cx()', function() { it('returns the value of cx without an argument', function() { var box = text.bbox() expect(text.cx()).toBe(box.width / 2) }) it('sets the value of cx with the first argument', function() { text.cx(123) var box = text.bbox() expect(box.cx).toBe(123) }) it('sets the value of cx based on the anchor with the first argument', function() { text.cx(123, true) var box = text.bbox() expect(box.cx).toBe(123) }) }) describe('cy()', function() { it('returns the value of cy without an argument', function() { var box = text.bbox() expect(text.cy()).toBe(box.cy) }) it('sets the value of cy with the first argument', function() { text.cy(345) var box = text.bbox() expect(Math.round(box.cy * 10) / 10).toBe(345) }) }) describe('move()', function() { it('sets the x and y position', function() { text.move(123,456) var box = text.bbox() expect(box.x).toBe(123) expect(box.y).toBe(456) }) }) describe('center()', function() { it('sets the cx and cy position', function() { text.center(321,567) var box = text.bbox() expect(box.cx).toBe(321) expect(Math.round(box.cy * 10) / 10).toBe(567) }) }) describe('size()', function() { it('should define the width and height of the element', function() { text.size(50) expect(text.attr('font-size').valueOf()).toBe(50) }) }) describe('translate()', function() { it('sets the translation of an element', function() { text.transform({ x: 12, y: 12 }) expect(text.node.getAttribute('transform')).toBe('translate(12 12)') }) }) describe('text()', function() { it('adds content in a nested tspan', function() { text.text('It is a bear!') expect(text.node.childNodes[0].nodeType).toBe(1) expect(text.node.childNodes[0].childNodes[0].nodeValue).toBe('It is a bear!') }) it('creates multiple lines with a newline separated string', function() { text.text('It is\nJUST\na bear!') expect(text.node.childNodes.length).toBe(3) }) it('stores a reference to the tspan nodes in a set', function() { text.text('It is\nJUST\na bear!') expect(text.lines instanceof SVG.Set).toBe(true) expect(text.lines.members.length).toBe(3) }) it('stores the text value in the content reference', function() { text.text('It is\nJUST\na bear!') expect(text.content).toBe('It is\nJUST\na bear!') }) it('gets the given content of a text element without an argument', function() { text.text('It is another bear!') expect(text.node.childNodes[0].nodeType).toBe(1) expect(text.text()).toMatch('It is another bear!') }) it('accepts a block as first arguments', function() { text.text(function(add) { add.tspan('mastaba') add.plain('hut') }) expect(text.node.childNodes[0].nodeType).toBe(1) expect(text.node.childNodes[0].childNodes[0].nodeValue).toBe('mastaba') expect(text.node.childNodes[1].nodeType).toBe(3) expect(text.node.childNodes[1].nodeValue).toBe('hut') }) }) describe('plain()', function() { it('adds content without a tspan', function() { text.plain('It is a bear!') expect(text.node.childNodes[0].nodeType).toBe(3) expect(text.node.childNodes[0].nodeValue).toBe('It is a bear!') }) it('clears content before adding new content', function() { text.plain('It is not a bear!') expect(text.node.childNodes.length).toBe(1) expect(text.node.childNodes[0].nodeValue).toBe('It is not a bear!') }) it('stores the text value in the content reference', function() { text.plain('Just plain text!') expect(text.content).toBe('Just plain text!') }) }) describe('tspan()', function() { it('adds content in a tspan', function() { text.tspan('It is a bear!') expect(text.node.childNodes[0].nodeType).toBe(1) expect(text.node.childNodes[0].childNodes[0].nodeValue).toBe('It is a bear!') }) it('clears content before adding new content', function() { text.tspan('It is not a bear!') expect(text.node.childNodes.length).toBe(1) expect(text.node.childNodes[0].childNodes[0].nodeValue).toBe('It is not a bear!') }) }) describe('clear()', function() { it('removes all content', function() { text.text(function(add) { add.tspan('The first.') add.tspan('The second.') add.tspan('The third.') }) expect(text.node.childNodes.length).toBe(3) text.clear() expect(text.node.childNodes.length).toBe(0) }) it('initializes a new set for the lines reference', function() { var lines = text.lines text.clear() expect(text.lines instanceof SVG.Set).toBe(true) expect(text.lines).not.toBe(lines) }) it('clears the stored content value', function() { text.text('Stored locally.') expect(text.content).toBe('Stored locally.') text.clear() expect(text.content).toBe('') }) }) describe('build()', function() { it('enables adding multiple plain text nodes when given true', function() { text.clear().build(true) text.plain('A great piece!') text.plain('Another great piece!') expect(text.node.childNodes[0].nodeValue).toBe('A great piece!') expect(text.node.childNodes[1].nodeValue).toBe('Another great piece!') }) it('enables adding multiple tspan nodes when given true', function() { text.clear().build(true) text.tspan('A great piece!') text.tspan('Another great piece!') expect(text.node.childNodes[0].childNodes[0].nodeValue).toBe('A great piece!') expect(text.node.childNodes[1].childNodes[0].nodeValue).toBe('Another great piece!') }) it('disables adding multiple plain text nodes when given false', function() { text.clear().build(true) text.plain('A great piece!') text.build(false).plain('Another great piece!') expect(text.node.childNodes[0].nodeValue).toBe('Another great piece!') expect(text.node.childNodes[1]).toBe(undefined) }) it('disables adding multiple tspan nodes when given false', function() { text.clear().build(true) text.tspan('A great piece!') text.build(false).tspan('Another great piece!') expect(text.node.childNodes[0].childNodes[0].nodeValue).toBe('Another great piece!') expect(text.node.childNodes[1]).toBe(undefined) }) }) })
// @flow const sum = (acc, next) => acc + next; /** * Calculates the average of multiple vectors (x, y values) */ const getVectorAvg = (vectors: Array<Object>): Object => ({ x: vectors.map(v => (v.x)).reduce(sum) / vectors.length, y: vectors.map(v => (v.y)).reduce(sum) / vectors.length, }); const getElement = (type: string) => (el: EventTarget): number => ( (el instanceof HTMLImageElement) ? el[type] : 1 ); /** * isWithin - Check if value is between two values * * @param { Number } scale current scale value * @param { Object } minPinch, maxPinh * @return { Boolean } **/ export const isWithin = (scale: number, opts: Object): boolean => { const { maxScale, minScale } = opts; return (scale >= minScale) && (scale <= maxScale); }; /** * addOffset - Combine current offset with old offset and returns a new offset * * @param { Object } lastOffset last offset * @param { Object } offset, new offset * @return { Object } **/ export const addOffset = (lastOffset: Object, offset: Object): Object => ({ x: lastOffset.x + offset.x, y: lastOffset.y + offset.y, }); export const getX = getElement('offsetWidth'); export const getY = getElement('offsetHeight'); /** * getScale - Check if value is between two values * * @param { Node } el current scale value * @return { Number } **/ export const getInitialScale = (el: EventTarget, image: HTMLElement): number => ( (el instanceof HTMLImageElement) ? getX(el) / image.offsetWidth : 1 ); /** * Scales the zoom factor relative to current state * * @param scale * @return the actual scale (can differ because of max min zoom factor) */ export const getScaleFactor = (scale: number, factor: number, opts: Object): number => { const { maxScaleTimes, minScaleTimes } = opts; const zoomFactor = Math.min(maxScaleTimes, Math.max(factor * scale, minScaleTimes)); return zoomFactor / factor; }; /** * Scales the zoom factor relative to current state * * @param scale * @return the actual scale (can differ because of max min zoom factor) */ export const getZoomFactor = (scale: number, factor: number, opts: Object): number => { const { maxScaleTimes, minScaleTimes } = opts; return Math.min(maxScaleTimes, Math.max(factor * scale, minScaleTimes)); }; export const getTouchCenter = (touches: Array<Object>) => getVectorAvg(touches); export const calcNewScale = (to: number, lastScale: number = 1): number => ( to / lastScale );
var replace = require('cli-util').pedantic; module.exports = function middleware(meta) { if(!meta.pedantic) { return; } return function pedantic(token, tokens, next) { if(!arguments.length) { return; } var types = ['paragraph', 'text']; if(token.text && ~types.indexOf(token.type)) { token.text = replace(token.text); } next(); } }
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /** * @name: S7.8.5_A2.2_T2; * @section: 7.8.5; * @assertion: RegularExpressionChar :: \ or / is incorrect; * @description: /; * @negative */ //CHECK#1 /a//.source;
{ "name": "gradx.js", "url": "https://github.com/PhilippeAssis/gradx.git" }
/** * Tas.js * (c) 2017 Owen Luke * https://github.com/tasjs/tas * Released under the MIT License. */ var tas = require('../../../../../tas'); var tasks = function(){ tas(function t9(){ a ++; // 36 log('wait...'); setTimeout(function(){ a ++; // 37 log('continue...'); tas.next(); }, timeout); }); }; var exports = { do: function(){ tas.load(tasks); } }; module.exports = exports;
'use strict'; // From : https://github.com/twisterghost/react-mocha-jsdom-example/blob/master/test/setup.js import jsdom from 'jsdom'; // Define some html to be our basic document // JSDOM will consume this and act as if we were in a browser const DEFAULT_HTML = '<html><body></body></html>'; // Define some variables to make it look like we're a browser // First, use JSDOM's fake DOM as the document global.document = jsdom.jsdom(DEFAULT_HTML); // Set up a mock window global.window = document.defaultView; // Allow for things like window.location global.navigator = window.navigator;
export default { unknown: "未知", anonymous: "匿名", activeCall: "使用中通話" }; // @key: @#@"unknown"@#@ @source: @#@"Unknown"@#@ // @key: @#@"anonymous"@#@ @source: @#@"Anonymous"@#@ // @key: @#@"activeCall"@#@ @source: @#@"Active Call"@#@
/* eslint-disable react/no-unused-prop-types */ /* @flow */ import React from 'react'; import type { Node } from 'react'; import cn from 'classnames'; export type Props = { children: Node, value?: any, onClick?: Function, onSelect?: Function, setHighlighted?: Function, index?: number, disabled?: boolean, active?: boolean, highlighted?: boolean, className?: string, title?: string, }; export default class DropdownOption extends React.PureComponent<Props, *> { props: Props; onClick: Function = (event: SyntheticEvent<>): void => { const { onSelect, onClick, value, disabled } = this.props; if (!disabled) { if (onSelect) { onSelect(value); } if (onClick) { event.stopPropagation(); onClick(value); } } }; setHighlighted: Function = (): void => { const { setHighlighted, index } = this.props; setHighlighted(index); }; resetHighlighted: Function = (): void => { const { setHighlighted } = this.props; setHighlighted(-1); }; render(): Node { const { children, active, highlighted, title, disabled } = this.props; return ( <li className={cn('be-dd__opt--default', { 'be-dd__opt--active': active, 'be-dd__opt--highlight': highlighted, 'be-dd__opt--disabled': disabled, })} onMouseEnter={this.setHighlighted} onMouseLeave={this.resetHighlighted} onClick={this.onClick} onKeyDown={this.onClick} aria-selected={active} title={title}> {children} </li> ); } }
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import invokeGuardedCallbackImpl from './invokeGuardedCallbackImpl'; // Used by Fiber to simulate a try-catch. let hasError: boolean = false; let caughtError: mixed = null; // Used by event system to capture/rethrow the first error. let hasRethrowError: boolean = false; let rethrowError: mixed = null; const reporter = { onError(error: mixed) { hasError = true; caughtError = error; }, }; /** * Call a function while guarding against errors that happens within it. * Returns an error if it throws, otherwise null. * * In production, this is implemented using a try-catch. The reason we don't * use a try-catch directly is so that we can swap out a different * implementation in DEV mode. * * @param {String} name of the guard to use for logging or debugging * @param {Function} func The function to invoke * @param {*} context The context to use when calling the function * @param {...*} args Arguments for function */ export function invokeGuardedCallback<A, B, C, D, E, F, Context>( name: string | null, func: (a: A, b: B, c: C, d: D, e: E, f: F) => mixed, context: Context, a: A, b: B, c: C, d: D, e: E, f: F, ): void { hasError = false; caughtError = null; invokeGuardedCallbackImpl.apply(reporter, arguments); } /** * Same as invokeGuardedCallback, but instead of returning an error, it stores * it in a global so it can be rethrown by `rethrowCaughtError` later. * TODO: See if caughtError and rethrowError can be unified. * * @param {String} name of the guard to use for logging or debugging * @param {Function} func The function to invoke * @param {*} context The context to use when calling the function * @param {...*} args Arguments for function */ export function invokeGuardedCallbackAndCatchFirstError< A, B, C, D, E, F, Context, >( name: string | null, func: (a: A, b: B, c: C, d: D, e: E, f: F) => void, context: Context, a: A, b: B, c: C, d: D, e: E, f: F, ): void { invokeGuardedCallback.apply(this, arguments); if (hasError) { const error = clearCaughtError(); if (!hasRethrowError) { hasRethrowError = true; rethrowError = error; } } } /** * During execution of guarded functions we will capture the first error which * we will rethrow to be handled by the top level error handler. */ export function rethrowCaughtError() { if (hasRethrowError) { const error = rethrowError; hasRethrowError = false; rethrowError = null; throw error; } } export function hasCaughtError() { return hasError; } export function clearCaughtError() { if (hasError) { const error = caughtError; hasError = false; caughtError = null; return error; } else { throw new Error( 'clearCaughtError was called but no error was captured. This error ' + 'is likely caused by a bug in React. Please file an issue.', ); } }
module.exports=(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ // all ti calls will cache when appropriate var _tmpdir; exports.tmpdir = function() { return _tmpdir || (_tmpdir = Ti.Filesystem.tempDirectory); }; exports.endianness = function() { return 'LE'; }; var _hostname; exports.hostname = function() { return typeof _hostname !== 'undefined' ? _hostname : (_hostname = Ti.Platform.address || ''); }; var _type; exports.type = function() { return _type || (_type = Ti.Platform.osname); }; var _platform; exports.platform = function() { return _platform || (_platform = Ti.Platform.name); }; var _arch; exports.arch = function() { return _arch || (_arch = Ti.Platform.architecture); }; var _release; exports.release = function() { return _release || (_release = Ti.Platform.version); }; exports.uptime = function () { return 0; }; exports.loadavg = function () { return []; }; exports.freemem = function () { var avail = Ti.Platform.availableMemory; if (avail) { return exports.platform === 'iPhone OS' ? Math.floor(avail/1024) : avail; } else { return Number.MAX_VALUE; } }; exports.totalmem = function () { return Number.MAX_VALUE; }; exports.cpus = function () { return []; }; exports.networkInterfaces = exports.getNetworkInterfaces = function () { return {}; }; exports.EOL = '\n'; },{}]},{},[1])(1);
if (typeof(VisualWebGL) == 'undefined' ){ VisualWebGL = {}; } var VisualWebGL = (function(VisualWebGL){ var scene, camera, projector, plane, Model; var stats, renderer; // init(); // animate(); var _initialized = false; var _height; var _width; VisualWebGL.init = function(width, height){ _width = width; _height = height; if ( Detector.webgl ){ renderer = new THREE.WebGLRenderer({ antialias: true }); renderer.setClearColorHex( 0xf9f9f9, 1 ); } else{ renderer = new THREE.CanvasRenderer(); } renderer.setSize(_width, _height); renderer.domElement.style.width = "100%"; renderer.domElement.style.height = "100%"; renderer.domElement.id = "VisualWebGLCanvas"; document.getElementById('VisualWebGLContent').appendChild(renderer.domElement); scene = new THREE.Scene(); camera = new THREE.PerspectiveCamera(75, _width / _height, 1, 10000); camera.position.z = 1600; scene.add( camera ); projector = new THREE.Projector(); /* stats = new Stats(); stats.getDomElement().style.position = 'absolute'; stats.getDomElement().style.left = '0px'; stats.getDomElement().style.top = '0px'; document.body.appendChild( stats.getDomElement() ); */ var light; scene.add( new THREE.AmbientLight( 0x404040 ) ); light = new THREE.DirectionalLight( 0xffffff ); light.position.set( 0, 0, 1 ); scene.add( light ); Model = new THREE.Object3D(); scene.add(Model); plane = new THREE.Mesh( new THREE.PlaneGeometry( 2000, 2000, 10, 10 ), new THREE.MeshBasicMaterial( { color: 0x555555, wireframe: true } ) ); plane.rotation.z = - 90 * Math.PI / 180; plane.position.x = 0; plane.position.y = 0; Model.add( plane ); CreateUI(); GetUsers(); //$("#VisualWebGLContent").click(clickHandler); $("#VisualWebGLContent").mousedown(mousedownHandler).bind('touchstart', mousedownHandler); $("#VisualWebGLContent").mousemove(mousemoveHandler).bind('touchmove', mousemoveHandler); $("#VisualWebGLContent").mouseup(mouseupHandler).bind('touchend', mouseupHandler); _initialized = true; } VisualWebGL.initialized = function(){ return _initialized; } var _id; var _animating; VisualWebGL.animate = function(){ _id =requestAnimationFrame( VisualWebGL.animate ); render(); //stats.update(); _animating = true; } VisualWebGL.stopAnimate = function(){ cancelAnimationFrame(_id); _animating = false; } VisualWebGL.animating = function(){ return _animating; } var render = function(){ Model.rotation.y += ( ModelRotationY - Model.rotation.y ) * 0.05; Model.rotation.x += ( ModelRotationX - Model.rotation.x ) * 0.05; for ( var i in objects ){ if ( objects.hasOwnProperty(i) ){ if ( objects[i].material.map.visualrestdata && objects[i].material.map.visualrestdatatype == "video" ){ if ( objects[i].material.map.visualrestdata.readyState === objects[i].material.map.visualrestdata.HAVE_ENOUGH_DATA ) { if ( objects[i].material.map ) objects[i].material.map.needsUpdate = true; } } } } renderer.render(scene, camera); } var GetUsers = function(){ $.ajax({ url:"http://visualrest.cs.tut.fi/users", data: {'user': "", 'qoption[format]': 'json'}, dataType: 'jsonp', jsonp: "qoption[json_callback]", jsonpCallback: 'VisualWebGL.DisplayUsers' }); UIObjects[1].VisualRestFunc = UIObjects[1].PrevVisualRestFunc; UIObjects[1].PrevVisualRestFunc = function(){ GetUsers(); } } var DoQuery = function(query){ var data = {'qoption[format]': 'json'}; for ( var attr in query){ data[attr] = query[attr]; } $.ajax({ url:"http://visualrest.cs.tut.fi/files", data: data, dataType: 'jsonp', jsonp: "qoption[json_callback]", jsonpCallback: 'VisualWebGL.DisplayResults' }); UIObjects[1].VisualRestFunc = UIObjects[1].PrevVisualRestFunc; UIObjects[1].PrevVisualRestFunc = function(){ DoQuery(query); } } var objects = []; var findPos = function(obj) { var curleft = curtop = 0; if (obj.offsetParent) { do { curleft += obj.offsetLeft; curtop += obj.offsetTop; } while (obj = obj.offsetParent); return { x: curleft, y: curtop }; } } var clickHandler = function(event, that){ var mouse = new THREE.Vector2(); var pos = findPos(that); mouse.x = ( (event.pageX-pos.x) / $("#VisualWebGLCanvas").width() ) * 2 - 1; mouse.y = - ( (event.pageY-pos.y) / $("#VisualWebGLCanvas").height() ) * 2 + 1; var vector = new THREE.Vector3(mouse.x, mouse.y, 0.5); projector.unprojectVector(vector, camera); var ray = new THREE.Ray( camera.position, vector.subSelf( camera.position ).normalize() ); var planeCollision = ray.intersectObject(plane); var intersectsUI = ray.intersectObjects(UIObjects); if ( intersectsUI.length > 0 ){ for ( var i in objects ){ if ( objects.hasOwnProperty(i) ){ Model.remove(objects[i]); } } objects = []; intersectsUI[0].object.VisualRestFunc(); } var intersects = ray.intersectObjects(objects); if ( intersects.length == 1 ){ for ( var i in objects ){ if ( objects.hasOwnProperty(i) ){ Model.remove(objects[i]); } } objects = []; if ( intersects[0].object.user ){ console.log(intersects[0].object.user); DoQuery({'q[user]': intersects[0].object.user }); } else if ( intersects[0].object.visualrestdata ){ LoadImage(intersects[0].object.visualrestdata); } } } var MouseClickStart; var MouseClickEvent; var RotateObjects = false; var MouseClickLocation; var ModelRotationY = 0; var ModelRotationOnMousedownY; var ModelRotationX = 0; var ModelRotationOnMousedownX; var mousedownHandler = function(event){ event.preventDefault(); var e = event.originalEvent; if ( e.touches ){ e = e.touches[0]; } RotateObjects = true; var pos = findPos(this); MouseClickLocation = new THREE.Vector2((e.pageX - pos.x) - ($("#VisualWebGLCanvas").width() / 2), (e.pageY-pos.y) - ($("#VisualWebGLCanvas").height() / 2)); ModelRotationOnMousedownY = ModelRotationY; ModelRotationOnMousedownX = ModelRotationX; MouseClickStart = new Date(); MouseClickEvent = e; return false; } var mouseupHandler = function(event){ event.preventDefault(); var e = event.originalEvent; if ( e.touches ){ e = e.touches[0]; } RotateObjects = false; console.log(new Date() - MouseClickStart); if ( (new Date() - MouseClickStart) < 200 ){ clickHandler(MouseClickEvent, this); } } var mousemoveHandler = function(event){ event.preventDefault(); var e = event.originalEvent; if ( e.touches ){ e = e.touches[0]; } if (RotateObjects){ var pos = findPos(this); var mouse = new THREE.Vector2((e.pageX - pos.x) - ($("#VisualWebGLCanvas").width() / 2), (e.pageY-pos.y) - ($("#VisualWebGLCanvas").height() / 2)); ModelRotationY = ModelRotationOnMousedownY + ( mouse.x - MouseClickLocation.x ) * 0.02; ModelRotationX = ModelRotationOnMousedownX + ( mouse.y - MouseClickLocation.y ) * 0.02; } } VisualWebGL.DisplayUsers = function(data){ console.log(data); var x = -900; var y = 900; for ( var i in data ){ if ( data.hasOwnProperty(i) ){ var url = data[i].thumbnail_uri; var texture = THREE.ImageUtils.loadTexture(url+ '?access-control-allow-origin=true'); var geometry = new THREE.CubeGeometry(150,150,30); var mesh = new THREE.Mesh( geometry, new THREE.MeshLambertMaterial( { ambient: 0xbbbbbb, map: texture } )); mesh.position.x = x; mesh.position.y = y; mesh.user = data[i].username; objects.push(mesh); x += 200; if ( x >= 1100 ){ x = -900; y -= 200; if ( y <= -900 ){ y = 900; } } Model.add(mesh); } } } VisualWebGL.DisplayResults = function(data){ console.log(data); var x = -900; var y = 900; for ( var i in data ){ if ( data.hasOwnProperty(i) ){ for ( var j in data[i] ){ if ( data[i].hasOwnProperty(j) ){ if ( data[i][j].filetype == "image/jpeg" || data[i][j].filetype == "video/vnd.objectvideo" || data[i][j].filetype == "image/gif" || data[i][j].filetype == "video/ogg"){ var url = data[i][j].thumbnail; url = url.replace("thumbnails", "allowthumbnails"); var texture = THREE.ImageUtils.loadTexture(url); var geometry = new THREE.CubeGeometry(150,150,30); var mesh = new THREE.Mesh( geometry, new THREE.MeshLambertMaterial( { ambient: 0xbbbbbb, map: texture } )); mesh.position.x = x; mesh.position.y = y; mesh.user = data[i].username; mesh.visualrestdata = data[i][j]; objects.push(mesh); x += 200; if ( x >= 1100 ){ x = -900; y -= 200; if ( y <= -900 ){ y = 900; } } Model.add(mesh); } } } } } } var UIObjects = []; var CreateUI = function(){ var geometry = new THREE.CubeGeometry(150,150,30); var homeTexture = THREE.ImageUtils.loadTexture("img/home.png"); var home = new THREE.Mesh(geometry, new THREE.MeshLambertMaterial( { ambient: 0xbbbbbb, map: homeTexture } )); home.position.x = -1250; home.position.y = 500; home.VisualRestFunc = function(){ GetUsers(); } scene.add(home); UIObjects.push(home); var backTexture = THREE.ImageUtils.loadTexture("img/back.png"); var back = new THREE.Mesh(geometry, new THREE.MeshLambertMaterial( { ambient: 0xbbbbbb, map: backTexture } )); back.position.x = -1250; back.position.y = 300; back.VisualRestFunc = function(){ } back.PrevVisualRestFunc = function(){ GetUsers(); } scene.add(back); UIObjects.push(back); } var LoadImage = function(visualrestdata){ if ( visualrestdata.filetype.match(/image.*/) ){ var texture = THREE.ImageUtils.loadTexture(visualrestdata.essence_uri + '?access-control-allow-origin=true'); } else if ( visualrestdata.filetype == "video/vnd.objectvideo" ){ var video = document.createElement('video'); video.autoplay = true; video.loop = true; var source = document.createElement('source'); source.crossorigin = 'anonymous'; source.src = visualrestdata.essence_uri + '?access-control-allow-origin=true'; //source.src = "../sintel.mp4"; source.type = 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"'; video.appendChild(source); var texture = new THREE.Texture(video); texture.minFilter = THREE.LinearFilter; texture.magFilter = THREE.LinearFilter; texture.format = THREE.RGBFormat; texture.visualrestdata = video; texture.visualrestdatatype = "video"; //document.body.appendChild(video); } else if ( visualrestdata.filetype == "video/ogg" ){ var video = document.createElement('video'); video.autoplay = true; video.loop = true; var source = document.createElement('source'); video.crossorigin = 'anonymous'; source.src = visualrestdata.essence_uri + '?access-control-allow-origin=true'; //source.src = "../sintel.mp4"; source.type = 'video/ogg'; video.appendChild(source); var texture = new THREE.Texture(video); texture.minFilter = THREE.LinearFilter; texture.magFilter = THREE.LinearFilter; texture.format = THREE.RGBFormat; texture.visualrestdata = video; texture.visualrestdatatype = "video"; //document.body.appendChild(video); } var geometry = new THREE.CubeGeometry(2000,2000,30); var mesh = new THREE.Mesh( geometry, new THREE.MeshLambertMaterial({map: texture})); Model.add(mesh); objects.push(mesh); UIObjects[1].VisualRestFunc = UIObjects[1].PrevVisualRestFunc; UIObjects[1].PrevVisualRestFunc = function(){ LoadImage(visualrestdata); } } return VisualWebGL; })(VisualWebGL);
define([ "require", "./abstract" ], function (require, AbstractView) { "use strict"; var _ = require("underscore"); var GridView = function () { }; GridView.prototype = new AbstractView(); _.extend(GridView.prototype, { _options: { step: 10, strokeStyle: "#c0c0c0" }, draw: function (context) { this._draw(context, 1); this._draw(context, 10); }, _draw: function (context, distance) { context.save(); context.beginPath(); // vertical _.range(this._options.step * distance, context.canvas.width, this._options.step * distance).forEach(function (i) { context.moveTo(0, i); context.lineTo(context.canvas.height, i); }, this); // horizontal _.range(this._options.step * distance, context.canvas.height, this._options.step * distance).forEach(function (i) { context.moveTo(i, 0); context.lineTo(i, context.canvas.width); }, this); // move to the beginning before close path context.moveTo(0, 0); context.strokeStyle = this._options.strokeStyle; context.closePath(); context.stroke(); context.restore(); } }); return new GridView(); });
var searchData= [ ['_7ecqlex',['~Cqlex',['../classCqlex.html#a15bc5b23d36df0a995e0a340f0372cc9',1,'Cqlex']]], ['_7ecregarray',['~Cregarray',['../classCregarray.html#a12f4b61c0fa17913e9076d0748de9210',1,'Cregarray']]] ];
import styled from 'styled-components' const InfoString = styled.span` font-size: 13px; letter-spacing: 0.8px; color: ${props => props.theme.text}; ` export default InfoString
angular.module('app').config(function($locationProvider, $routeProvider) { $locationProvider.html5Mode(true); $routeProvider.otherwise({redirectTo: '/'}); });
var protractor = require('protractor'); var firebase = require('firebase'); require('../../initialize-node.js'); // Various messages sent to demo const MESSAGES_PREFAB = [ { from: "Default Guest 1", content: 'Hey there!' }, { from: "Default Guest 2", content: 'Oh Hi, how are you?' }, { from: "Default Guest 1", content: "Pretty fantastic!" } ]; describe('Chat App', function () { // Reference to the Firebase which stores the data for this demo var firebaseRef; // Boolean used to load the page on the first test only var isPageLoaded = false; // Reference to the messages repeater var messages = element.all(by.repeater('message in messages')); var flow = protractor.promise.controlFlow(); function waitOne() { return protractor.promise.delayed(500); } function sleep() { flow.execute(waitOne); } function clearFirebaseRef() { var deferred = protractor.promise.defer(); firebaseRef.remove(function(err) { if (err) { deferred.reject(err); } else { deferred.fulfill(); } }); return deferred.promise; } beforeEach(function (done) { if (!isPageLoaded) { isPageLoaded = true; browser.get('chat/chat.html').then(function () { return browser.waitForAngular() }).then(function() { return element(by.id('url')).evaluate('url'); }).then(function (url) { // Get the random push ID where the data is being stored return firebase.database().refFromURL(url); }).then(function(ref) { // Update the Firebase ref to point to the random push ID firebaseRef = ref; // Clear the Firebase ref return clearFirebaseRef(); }).then(done) } else { done() } }); it('loads', function () { expect(browser.getTitle()).toEqual('AngularFire Chat e2e Test'); }); it('starts with an empty list of messages', function () { expect(messages.count()).toBe(0); }); it('adds new messages', function () { // Add three new messages by typing into the input and pressing enter var usernameInput = element(by.model('username')); var newMessageInput = element(by.model('message')); MESSAGES_PREFAB.forEach(function (msg) { usernameInput.clear(); usernameInput.sendKeys(msg.from); newMessageInput.sendKeys(msg.content + '\n'); }); sleep(); // We should only have two messages in the repeater since we did a limit query expect(messages.count()).toBe(2); }); it('updates upon new remote messages', function (done) { var message = { from: 'Guest 2000', content: 'Remote message detected' }; flow.execute(function() { var def = protractor.promise.defer(); // Simulate a message being added remotely firebaseRef.child('messages').push(message, function(err) { if( err ) { def.reject(err); } else { def.fulfill(); } }); return def.promise; }).then(function () { return messages.get(1).getText(); }).then(function (text) { expect(text).toBe(message.from + ": " + message.content); done(); }) // We should only have two messages in the repeater since we did a limit query expect(messages.count()).toBe(2); }); it('updates upon removed remote messages', function (done) { flow.execute(function() { var def = protractor.promise.defer(); // Simulate a message being deleted remotely var onCallback = firebaseRef.child('messages').limitToLast(1).on('child_added', function(childSnapshot) { firebaseRef.child('messages').off('child_added', onCallback); childSnapshot.ref.remove(function(err) { if( err ) { def.reject(err); } else { def.fulfill(); } }); }); return def.promise; }).then(function () { return messages.get(1).getText(); }).then(function (text) { expect(text).toBe(MESSAGES_PREFAB[2].from + ": " + MESSAGES_PREFAB[2].content); done(); }); // We should only have two messages in the repeater since we did a limit query expect(messages.count()).toBe(2); }); it('stops updating once the AngularFire bindings are destroyed', function () { // Destroy the AngularFire bindings $('#destroyButton').click(); sleep(); expect(messages.count()).toBe(0); }); });
var test = async_test("Calling a Web Page URL from an Injected Script Process should return null"); function getHandler() { return function(evt) { test.step(function() { assert_equals(evt.data, "success", "Calling a Web Page URL from an Injected Script Process returns null"); }); test.done(); } } ext.onmessage = getHandler(); // Injectable Interface Test createTab({url: 'http://team.opera.com/testbed/generic/blank.html?resourceload_010', focused: true});
export default function (a, v) { return !!~a.indexOf(v); }
import { getOwner } from '@ember/-internals/owner'; import { scheduleOnce } from '@ember/runloop'; import { get, objectAt, addArrayObserver, removeArrayObserver } from '@ember/-internals/metal'; import { dasherize } from '@ember/string'; import { Namespace, Object as EmberObject, A as emberA } from '@ember/-internals/runtime'; /** @module @ember/debug */ /** The `DataAdapter` helps a data persistence library interface with tools that debug Ember such as the [Ember Inspector](https://github.com/emberjs/ember-inspector) for Chrome and Firefox. This class will be extended by a persistence library which will override some of the methods with library-specific code. The methods likely to be overridden are: * `getFilters` * `detect` * `columnsForType` * `getRecords` * `getRecordColumnValues` * `getRecordKeywords` * `getRecordFilterValues` * `getRecordColor` * `observeRecord` The adapter will need to be registered in the application's container as `dataAdapter:main`. Example: ```javascript Application.initializer({ name: "data-adapter", initialize: function(application) { application.register('data-adapter:main', DS.DataAdapter); } }); ``` @class DataAdapter @extends EmberObject @public */ export default EmberObject.extend({ init() { this._super(...arguments); this.releaseMethods = emberA(); }, /** The container-debug-adapter which is used to list all models. @property containerDebugAdapter @default undefined @since 1.5.0 @public **/ containerDebugAdapter: undefined, /** The number of attributes to send as columns. (Enough to make the record identifiable). @private @property attributeLimit @default 3 @since 1.3.0 */ attributeLimit: 3, /** Ember Data > v1.0.0-beta.18 requires string model names to be passed around instead of the actual factories. This is a stamp for the Ember Inspector to differentiate between the versions to be able to support older versions too. @public @property acceptsModelName */ acceptsModelName: true, /** Stores all methods that clear observers. These methods will be called on destruction. @private @property releaseMethods @since 1.3.0 */ releaseMethods: emberA(), /** Specifies how records can be filtered. Records returned will need to have a `filterValues` property with a key for every name in the returned array. @public @method getFilters @return {Array} List of objects defining filters. The object should have a `name` and `desc` property. */ getFilters() { return emberA(); }, /** Fetch the model types and observe them for changes. @public @method watchModelTypes @param {Function} typesAdded Callback to call to add types. Takes an array of objects containing wrapped types (returned from `wrapModelType`). @param {Function} typesUpdated Callback to call when a type has changed. Takes an array of objects containing wrapped types. @return {Function} Method to call to remove all observers */ watchModelTypes(typesAdded, typesUpdated) { let modelTypes = this.getModelTypes(); let releaseMethods = emberA(); let typesToSend; typesToSend = modelTypes.map(type => { let klass = type.klass; let wrapped = this.wrapModelType(klass, type.name); releaseMethods.push(this.observeModelType(type.name, typesUpdated)); return wrapped; }); typesAdded(typesToSend); let release = () => { releaseMethods.forEach(fn => fn()); this.releaseMethods.removeObject(release); }; this.releaseMethods.pushObject(release); return release; }, _nameToClass(type) { if (typeof type === 'string') { let owner = getOwner(this); let Factory = owner.factoryFor(`model:${type}`); type = Factory && Factory.class; } return type; }, /** Fetch the records of a given type and observe them for changes. @public @method watchRecords @param {String} modelName The model name. @param {Function} recordsAdded Callback to call to add records. Takes an array of objects containing wrapped records. The object should have the following properties: columnValues: {Object} The key and value of a table cell. object: {Object} The actual record object. @param {Function} recordsUpdated Callback to call when a record has changed. Takes an array of objects containing wrapped records. @param {Function} recordsRemoved Callback to call when a record has removed. Takes the following parameters: index: The array index where the records were removed. count: The number of records removed. @return {Function} Method to call to remove all observers. */ watchRecords(modelName, recordsAdded, recordsUpdated, recordsRemoved) { let releaseMethods = emberA(); let klass = this._nameToClass(modelName); let records = this.getRecords(klass, modelName); let release; function recordUpdated(updatedRecord) { recordsUpdated([updatedRecord]); } let recordsToSend = records.map(record => { releaseMethods.push(this.observeRecord(record, recordUpdated)); return this.wrapRecord(record); }); let contentDidChange = (array, idx, removedCount, addedCount) => { for (let i = idx; i < idx + addedCount; i++) { let record = objectAt(array, i); let wrapped = this.wrapRecord(record); releaseMethods.push(this.observeRecord(record, recordUpdated)); recordsAdded([wrapped]); } if (removedCount) { recordsRemoved(idx, removedCount); } }; let observer = { didChange: contentDidChange, willChange() { return this; }, }; addArrayObserver(records, this, observer); release = () => { releaseMethods.forEach(fn => fn()); removeArrayObserver(records, this, observer); this.releaseMethods.removeObject(release); }; recordsAdded(recordsToSend); this.releaseMethods.pushObject(release); return release; }, /** Clear all observers before destruction @private @method willDestroy */ willDestroy() { this._super(...arguments); this.releaseMethods.forEach(fn => fn()); }, /** Detect whether a class is a model. Test that against the model class of your persistence library. @private @method detect @return boolean Whether the class is a model class or not. */ detect() { return false; }, /** Get the columns for a given model type. @private @method columnsForType @return {Array} An array of columns of the following format: name: {String} The name of the column. desc: {String} Humanized description (what would show in a table column name). */ columnsForType() { return emberA(); }, /** Adds observers to a model type class. @private @method observeModelType @param {String} modelName The model type name. @param {Function} typesUpdated Called when a type is modified. @return {Function} The function to call to remove observers. */ observeModelType(modelName, typesUpdated) { let klass = this._nameToClass(modelName); let records = this.getRecords(klass, modelName); function onChange() { typesUpdated([this.wrapModelType(klass, modelName)]); } let observer = { didChange(array, idx, removedCount, addedCount) { // Only re-fetch records if the record count changed // (which is all we care about as far as model types are concerned). if (removedCount > 0 || addedCount > 0) { scheduleOnce('actions', this, onChange); } }, willChange() { return this; }, }; addArrayObserver(records, this, observer); let release = () => removeArrayObserver(records, this, observer); return release; }, /** Wraps a given model type and observes changes to it. @private @method wrapModelType @param {Class} klass A model class. @param {String} modelName Name of the class. @return {Object} Contains the wrapped type and the function to remove observers Format: type: {Object} The wrapped type. The wrapped type has the following format: name: {String} The name of the type. count: {Integer} The number of records available. columns: {Columns} An array of columns to describe the record. object: {Class} The actual Model type class. release: {Function} The function to remove observers. */ wrapModelType(klass, name) { let records = this.getRecords(klass, name); let typeToSend; typeToSend = { name, count: get(records, 'length'), columns: this.columnsForType(klass), object: klass, }; return typeToSend; }, /** Fetches all models defined in the application. @private @method getModelTypes @return {Array} Array of model types. */ getModelTypes() { let containerDebugAdapter = this.get('containerDebugAdapter'); let types; if (containerDebugAdapter.canCatalogEntriesByType('model')) { types = containerDebugAdapter.catalogEntriesByType('model'); } else { types = this._getObjectsOnNamespaces(); } // New adapters return strings instead of classes. types = emberA(types).map(name => { return { klass: this._nameToClass(name), name, }; }); types = emberA(types).filter(type => this.detect(type.klass)); return emberA(types); }, /** Loops over all namespaces and all objects attached to them. @private @method _getObjectsOnNamespaces @return {Array} Array of model type strings. */ _getObjectsOnNamespaces() { let namespaces = emberA(Namespace.NAMESPACES); let types = emberA(); namespaces.forEach(namespace => { for (let key in namespace) { if (!namespace.hasOwnProperty(key)) { continue; } // Even though we will filter again in `getModelTypes`, // we should not call `lookupFactory` on non-models if (!this.detect(namespace[key])) { continue; } let name = dasherize(key); types.push(name); } }); return types; }, /** Fetches all loaded records for a given type. @private @method getRecords @return {Array} An array of records. This array will be observed for changes, so it should update when new records are added/removed. */ getRecords() { return emberA(); }, /** Wraps a record and observers changes to it. @private @method wrapRecord @param {Object} record The record instance. @return {Object} The wrapped record. Format: columnValues: {Array} searchKeywords: {Array} */ wrapRecord(record) { let recordToSend = { object: record }; recordToSend.columnValues = this.getRecordColumnValues(record); recordToSend.searchKeywords = this.getRecordKeywords(record); recordToSend.filterValues = this.getRecordFilterValues(record); recordToSend.color = this.getRecordColor(record); return recordToSend; }, /** Gets the values for each column. @private @method getRecordColumnValues @return {Object} Keys should match column names defined by the model type. */ getRecordColumnValues() { return {}; }, /** Returns keywords to match when searching records. @private @method getRecordKeywords @return {Array} Relevant keywords for search. */ getRecordKeywords() { return emberA(); }, /** Returns the values of filters defined by `getFilters`. @private @method getRecordFilterValues @param {Object} record The record instance. @return {Object} The filter values. */ getRecordFilterValues() { return {}; }, /** Each record can have a color that represents its state. @private @method getRecordColor @param {Object} record The record instance @return {String} The records color. Possible options: black, red, blue, green. */ getRecordColor() { return null; }, /** Observes all relevant properties and re-sends the wrapped record when a change occurs. @private @method observerRecord @return {Function} The function to call to remove all observers. */ observeRecord() { return function() {}; }, });
/* * grunt-string-replace * https://github.com/eruizdechavez/grunt-string-replace * * Copyright (c) 2016 Erick Ruiz de Chavez * Licensed under the MIT license. */ module.exports = function(grunt) { 'use strict'; grunt.initConfig({ base: { env: { test: 'replaced!' } }, package: { replacement: 'replaced!' }, jshint: { options: { curly: true, eqeqeq: true, immed: true, latedef: true, newcap: true, noarg: true, sub: true, undef: true, boss: true, eqnull: true, node: true }, lint: ['Gruntfile.js', 'tasks/**/*.js', 'test/**/*.js'] }, clean: ['tmp/', 'tmp_baz/'], nodeunit: { files: ['test/**/*.js'] }, watch: { files: '<%= jshint.lint %>', tasks: ['jshint', 'test'] }, copy: { fixtures: { files: [{ dest: 'tmp/foo/1.txt', src: 'test/fixtures/foo.txt' }, { dest: 'tmp/foo/2.txt', src: 'test/fixtures/foo.txt' }, { dest: 'tmp/bar/1.txt', src: 'test/fixtures/foo.txt' }, { dest: 'tmp/bar/2.txt', src: 'test/fixtures/foo.txt' }] } }, 'string-replace': { single_file: { files: { 'tmp/foo.txt': 'test/fixtures/foo.txt', 'tmp/baz.txt': 'test/fixtures/baz.txt' }, options: { replacements: [{ pattern: '[test:string]', replacement: 'replaced!' }, { pattern: /\[test a:regex \d{3,}\]/, replacement: 'replaced!' }, { pattern: /\[test b:regex \d{3,}\]/g, replacement: 'replaced!' }, { pattern: /\[test c:regex \d{3,}\]/g, replacement: 'replaced!' }, { pattern: /\[test d:regex \d{3,}\]/ig, replacement: 'replaced!' }, { pattern: /\[test e:regex \d{3,}\]/ig, replacement: '<%= package.replacement %>' }, { pattern: /\[test f:regex \d{3,}\]/g, replacement: function(match, p1) { var env = grunt.option('env').toLowerCase(); return grunt.config.get(['base', 'env', env]); } }] } }, mutli_same_path: { files: { 'tmp/foo/': 'tmp/foo/*.txt' }, options: { replacements: [{ pattern: '[test:string]', replacement: 'replaced!' }, { pattern: /\[test a:regex \d{3,}\]/, replacement: 'replaced!' }, { pattern: /\[test b:regex \d{3,}\]/g, replacement: 'replaced!' }, { pattern: /\[test c:regex \d{3,}\]/g, replacement: 'replaced!' }, { pattern: /\[test d:regex \d{3,}\]/ig, replacement: 'replaced!' }, { pattern: /\[test e:regex \d{3,}\]/ig, replacement: '<%= package.replacement %>' }, { pattern: /\[test f:regex \d{3,}\]/g, replacement: function(match, p1) { var env = grunt.option('env').toLowerCase(); return grunt.config.get(['base', 'env', env]); } }] } }, mutli_diff_path: { files: { 'tmp_baz/': 'tmp/bar/*.txt' }, options: { replacements: [{ pattern: '[test:string]', replacement: 'replaced!' }, { pattern: /\[test a:regex \d{3,}\]/, replacement: 'replaced!' }, { pattern: /\[test b:regex \d{3,}\]/g, replacement: 'replaced!' }, { pattern: /\[test c:regex \d{3,}\]/g, replacement: 'replaced!' }, { pattern: /\[test d:regex \d{3,}\]/ig, replacement: 'replaced!' }, { pattern: /\[test e:regex \d{3,}\]/ig, replacement: '<%= package.replacement %>' }, { pattern: /\[test f:regex \d{3,}\]/g, replacement: function(match, p1) { var env = grunt.option('env').toLowerCase(); return grunt.config.get(['base', 'env', env]); } }] } } } }); // Load nom tasks. grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-contrib-nodeunit'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-copy'); // Load local tasks. grunt.loadTasks('tasks'); grunt.registerTask('test', ['clean', 'copy', 'string-replace', 'nodeunit']); grunt.registerTask('default', ['jshint', 'test']); };
/** * jQuery Unveil * A very lightweight jQuery plugin to lazy load images * http://luis-almeida.github.com/unveil * * Licensed under the MIT license. * Copyright 2013 Luís Almeida * https://github.com/luis-almeida * * Modifications by Yong Chen */ (function(factory) { if(typeof define === 'function' && define.amd) { // AMD (Register as an anonymous module) define('unveil',['jquery', 'underscore', 'utils/window-size'], factory); } else if(typeof exports === 'object') { // Node/CommonJS module.exports = factory(require('jquery'), require('underscore'), require('utils/window-size')); } else { // Browser globals factory(jQuery, _, windowInfo); } }(function($, _, Win) { $.fn.unveil = function(options) { var defaults = { threshold: 200, horizontal: false, context: '' }; options = _.extend({}, defaults, options); var $w = $(window), ch = options.horizontal, th = options.threshold, // retina = window.devicePixelRatio > 1, size, // reusable window attributes, defined once per 'unveil' call // instead of once per every filtered item wt, wh, wb, wl, wr, // attrib = retina? "data-src-retina" : "data-src", attrib, images = this, loaded = $(), to_load = $(), suffix = '.unveil' + (options.context !== '' ? '.delegate' + options.context : '') ; // however image size is determined, set data attribute to use here function resetSize() { // size = window.getComputedStyle(document.body,':after').getPropertyValue('content'); size = Win.size(); switch(size) { case Win.sizes.desktop: attrib = 'data-high'; break; case Win.sizes.tablet: attrib = 'data-medium'; break; case Win.sizes.global: default: attrib = 'data-lower'; break; } // request portrait specific lower render if(attrib === 'data-lower' && Win.orientation() === Win.orientations.portrait) { attrib = 'data-lower-portrait'; } } function replace(_callback) { var source = this.getAttribute(attrib); // in case portrait specific lower render is unavailable, use default landscape render if(attrib === 'data-lower-portrait' && source === null) { source = this.getAttribute('data-lower'); } source = source || this.getAttribute('data-src'); // if(typeof _callback === "function") { // console.log('unveil: ' + source); // } if(this.tagName === 'IMG') { if(source && source !== this.getAttribute('src')) { // console.log('unveil: setting source to ' + source); this.setAttribute('src', source); if(typeof _callback === 'function') _callback.call(this); if(typeof callback === 'function') callback.call(this); } } else { // check background image source instead if(source && source !== parseBackgroundImageUrl(this.style.backgroundImage)) { this.style.backgroundImage = 'url(' + source + ')'; if(typeof _callback === 'function') _callback.call(this); if(typeof callback === 'function') callback.call(this); } } } function parseBackgroundImageUrl(string) { return string.replace(/url\(([^)]*)\)/, '$1'); } // unveil each image once this.not('.unveiled').one('unveil', function() { replace.call(this, function() { $(this).addClass('unveiled'); }); }); function getWindowPosition() { wt = $w.scrollTop(); wh = $w.height(); wb = wt + wh; if(ch) { wl = $w.scrollLeft(); wr = wl + $w.width(); } // recheck window innerHeight if height is reported as 0 if(wh === 0) { wh = window.innerHeight; wb = wt + wh; } } function filter_inview() { var $e = $(this); var et = $e.offset().top, eb = et + $e.height(); if(!(eb >= wt - th && et <= wb + th)) { return false; } if(!ch) { return true; } // check horizontal constraint as well var el = $e.offset().left, er = el + $e.width(); return er >= wl - th && el <= wr + th; } function unveil() { if(images.length === 0) { return; } getWindowPosition(); // since :visible is expensive, filter by in view first, // then by visible var inview = images.filter(filter_inview).filter(':visible'); to_load = inview.trigger('unveil'); // console.log('[jQuery.unveil] calling unveil with context %o on set %o', options.context, images.length); to_load.off('reset').on('reset', function() { // console.log('resetting unveil for ' + this.src); replace.call(this); }); images = images.not(to_load); loaded = loaded.add(to_load); } $w .on('scroll' + suffix + ' lookup' + suffix, function() { unveil(); }) // on resize, re-examine src to ensure proper size utilized .on('resize' + suffix, _.throttle(function() { resetSize(); loaded.trigger('reset'); // console.log('unveil: throttled unveil'); }, 200)) // allow manual call to force reset the unveiled images .on('forcereset' + suffix, function() { resetSize(); loaded.trigger('reset'); }); resetSize(); unveil(); return this; }; }));
import { get, set } from 'ember';
/** * @providesModule HasteModule */ module.exports = 'HasteModule';
var imgurGallery = require('./imgurGallery'); var imgurSearch = require('./imgurSearch'); var imgurServiceErrors = require('./imgurServiceErrors'); module.exports = { imgur: { serviceError: { apiKey: JSON.stringify(imgurServiceErrors.apiKey), emptySearch: JSON.stringify(imgurServiceErrors.emptySearch), albumNotFound: JSON.stringify(imgurServiceErrors.albumNotFound) }, album: JSON.stringify(imgurGallery), search: JSON.stringify(imgurSearch) } };
{ "ADP_currencyISO" : "peseta andorrana", "ADP_currencyPlural" : "pesetas andorranas", "ADP_currencySingular" : "peseta andorrana", "ADP_currencySymbol" : "ADP", "AED_currencyISO" : "dírham de los Emiratos Árabes Unidos", "AED_currencyPlural" : "dirhams de los Emiratos Árabes Unidos", "AED_currencySingular" : "dirham de los Emiratos Árabes Unidos", "AED_currencySymbol" : "AED", "AFA_currencyISO" : "afgani (1927-2002)", "AFA_currencyPlural" : "dirhams de los Emiratos Árabes Unidos", "AFA_currencySingular" : "dirham de los Emiratos Árabes Unidos", "AFA_currencySymbol" : "AFA", "AFN_currencyISO" : "afgani", "AFN_currencyPlural" : "afganis afganos", "AFN_currencySingular" : "afgani afgano", "AFN_currencySymbol" : "Af", "ALK_currencyISO" : "afgani", "ALK_currencyPlural" : "afganis afganos", "ALK_currencySingular" : "afgani afgano", "ALK_currencySymbol" : "Af", "ALL_currencyISO" : "lek albanés", "ALL_currencyPlural" : "lekë albaneses", "ALL_currencySingular" : "lek albanés", "ALL_currencySymbol" : "ALL", "AMD_currencyISO" : "dram armenio", "AMD_currencyPlural" : "dram armenios", "AMD_currencySingular" : "dram armenio", "AMD_currencySymbol" : "AMD", "ANG_currencyISO" : "florín de las Antillas Neerlandesas", "ANG_currencyPlural" : "florines de las Antillas Neerlandesas", "ANG_currencySingular" : "florín de las Antillas Neerlandesas", "ANG_currencySymbol" : "NAf.", "AOA_currencyISO" : "kwanza angoleño", "AOA_currencyPlural" : "kwanzas angoleños", "AOA_currencySingular" : "kwanza angoleño", "AOA_currencySymbol" : "Kz", "AOK_currencyISO" : "kwanza angoleño (1977-1990)", "AOK_currencyPlural" : "kwanzas angoleños", "AOK_currencySingular" : "kwanza angoleño", "AOK_currencySymbol" : "AOK", "AON_currencyISO" : "nuevo kwanza angoleño (1990-2000)", "AON_currencyPlural" : "kwanzas angoleños", "AON_currencySingular" : "kwanza angoleño", "AON_currencySymbol" : "AON", "AOR_currencyISO" : "kwanza reajustado angoleño (1995-1999)", "AOR_currencyPlural" : "kwanzas angoleños", "AOR_currencySingular" : "kwanza angoleño", "AOR_currencySymbol" : "AOR", "ARA_currencyISO" : "austral argentino", "ARA_currencyPlural" : "australes argentinos", "ARA_currencySingular" : "austral argentino", "ARA_currencySymbol" : "₳", "ARL_currencyISO" : "ARL", "ARL_currencyPlural" : "australes argentinos", "ARL_currencySingular" : "austral argentino", "ARL_currencySymbol" : "$L", "ARM_currencyISO" : "ARM", "ARM_currencyPlural" : "australes argentinos", "ARM_currencySingular" : "austral argentino", "ARM_currencySymbol" : "m$n", "ARP_currencyISO" : "peso argentino (1983-1985)", "ARP_currencyPlural" : "pesos argentinos (ARP)", "ARP_currencySingular" : "peso argentino (ARP)", "ARP_currencySymbol" : "ARP", "ARS_currencyISO" : "peso argentino", "ARS_currencyPlural" : "pesos argentinos", "ARS_currencySingular" : "peso argentino", "ARS_currencySymbol" : "AR$", "ATS_currencyISO" : "chelín austriaco", "ATS_currencyPlural" : "chelines austriacos", "ATS_currencySingular" : "chelín austriaco", "ATS_currencySymbol" : "ATS", "AUD_currencyISO" : "dólar australiano", "AUD_currencyPlural" : "dólares australianos", "AUD_currencySingular" : "dólar australiano", "AUD_currencySymbol" : "AU$", "AWG_currencyISO" : "florín de Aruba", "AWG_currencyPlural" : "florines de Aruba", "AWG_currencySingular" : "florín de Aruba", "AWG_currencySymbol" : "Afl.", "AZM_currencyISO" : "manat azerí (1993-2006)", "AZM_currencyPlural" : "florines de Aruba", "AZM_currencySingular" : "florín de Aruba", "AZM_currencySymbol" : "AZM", "AZN_currencyISO" : "manat azerí", "AZN_currencyPlural" : "manat azeríes", "AZN_currencySingular" : "manat azerí", "AZN_currencySymbol" : "man.", "BAD_currencyISO" : "dinar bosnio", "BAD_currencyPlural" : "dinares bosnios", "BAD_currencySingular" : "dinar bosnio", "BAD_currencySymbol" : "BAD", "BAM_currencyISO" : "marco convertible de Bosnia-Herzegovina", "BAM_currencyPlural" : "marcos convertibles de Bosnia-Herzegovina", "BAM_currencySingular" : "marco convertible de Bosnia-Herzegovina", "BAM_currencySymbol" : "KM", "BAN_currencyISO" : "marco convertible de Bosnia-Herzegovina", "BAN_currencyPlural" : "marcos convertibles de Bosnia-Herzegovina", "BAN_currencySingular" : "marco convertible de Bosnia-Herzegovina", "BAN_currencySymbol" : "KM", "BBD_currencyISO" : "dólar de Barbados", "BBD_currencyPlural" : "dólares de Barbados", "BBD_currencySingular" : "dólar de Barbados", "BBD_currencySymbol" : "Bds$", "BDT_currencyISO" : "taka de Bangladesh", "BDT_currencyPlural" : "taka de Bangladesh", "BDT_currencySingular" : "taka de Bangladesh", "BDT_currencySymbol" : "Tk", "BEC_currencyISO" : "franco belga (convertible)", "BEC_currencyPlural" : "francos belgas (convertibles)", "BEC_currencySingular" : "franco belga (convertible)", "BEC_currencySymbol" : "BEC", "BEF_currencyISO" : "franco belga", "BEF_currencyPlural" : "francos belgas", "BEF_currencySingular" : "franco belga", "BEF_currencySymbol" : "BF", "BEL_currencyISO" : "franco belga (financiero)", "BEL_currencyPlural" : "francos belgas (financieros)", "BEL_currencySingular" : "franco belga (financiero)", "BEL_currencySymbol" : "BEL", "BGL_currencyISO" : "lev fuerte búlgaro", "BGL_currencyPlural" : "leva fuertes búlgaros", "BGL_currencySingular" : "lev fuerte búlgaro", "BGL_currencySymbol" : "BGL", "BGM_currencyISO" : "lev fuerte búlgaro", "BGM_currencyPlural" : "leva fuertes búlgaros", "BGM_currencySingular" : "lev fuerte búlgaro", "BGM_currencySymbol" : "BGL", "BGN_currencyISO" : "nuevo lev búlgaro", "BGN_currencyPlural" : "nuevos leva búlgaros", "BGN_currencySingular" : "nuevo lev búlgaro", "BGN_currencySymbol" : "BGN", "BGO_currencyISO" : "nuevo lev búlgaro", "BGO_currencyPlural" : "nuevos leva búlgaros", "BGO_currencySingular" : "nuevo lev búlgaro", "BGO_currencySymbol" : "BGN", "BHD_currencyISO" : "dinar bahreiní", "BHD_currencyPlural" : "dinares bahreiníes", "BHD_currencySingular" : "dinar bahreiní", "BHD_currencySymbol" : "BD", "BIF_currencyISO" : "franco de Burundi", "BIF_currencyPlural" : "francos de Burundi", "BIF_currencySingular" : "franco de Burundi", "BIF_currencySymbol" : "FBu", "BMD_currencyISO" : "dólar de Bermudas", "BMD_currencyPlural" : "dólares de Bermudas", "BMD_currencySingular" : "dólar de Bermudas", "BMD_currencySymbol" : "BD$", "BND_currencyISO" : "dólar de Brunéi", "BND_currencyPlural" : "dólares de Brunéi", "BND_currencySingular" : "dólar de Brunéi", "BND_currencySymbol" : "BN$", "BOB_currencyISO" : "boliviano", "BOB_currencyPlural" : "bolivianos", "BOB_currencySingular" : "boliviano", "BOB_currencySymbol" : "Bs", "BOL_currencyISO" : "boliviano", "BOL_currencyPlural" : "bolivianos", "BOL_currencySingular" : "boliviano", "BOL_currencySymbol" : "Bs", "BOP_currencyISO" : "peso boliviano", "BOP_currencyPlural" : "pesos bolivianos", "BOP_currencySingular" : "peso boliviano", "BOP_currencySymbol" : "$b.", "BOV_currencyISO" : "MVDOL boliviano", "BOV_currencyPlural" : "MVDOL bolivianos", "BOV_currencySingular" : "MVDOL boliviano", "BOV_currencySymbol" : "BOV", "BRB_currencyISO" : "nuevo cruceiro brasileño (1967-1986)", "BRB_currencyPlural" : "nuevos cruzados brasileños (BRB)", "BRB_currencySingular" : "nuevo cruzado brasileño (BRB)", "BRB_currencySymbol" : "BRB", "BRC_currencyISO" : "cruzado brasileño", "BRC_currencyPlural" : "cruzados brasileños", "BRC_currencySingular" : "cruzado brasileño", "BRC_currencySymbol" : "BRC", "BRE_currencyISO" : "cruceiro brasileño (1990-1993)", "BRE_currencyPlural" : "cruceiros brasileños (BRE)", "BRE_currencySingular" : "cruceiro brasileño (BRE)", "BRE_currencySymbol" : "BRE", "BRL_currencyISO" : "real brasileño", "BRL_currencyPlural" : "reales brasileños", "BRL_currencySingular" : "real brasileño", "BRL_currencySymbol" : "R$", "BRN_currencyISO" : "nuevo cruzado brasileño", "BRN_currencyPlural" : "nuevos cruzados brasileños", "BRN_currencySingular" : "nuevo cruzado brasileño", "BRN_currencySymbol" : "BRN", "BRR_currencyISO" : "cruceiro brasileño", "BRR_currencyPlural" : "cruceiros brasileños", "BRR_currencySingular" : "cruceiro brasileño", "BRR_currencySymbol" : "BRR", "BRZ_currencyISO" : "cruceiro brasileño", "BRZ_currencyPlural" : "cruceiros brasileños", "BRZ_currencySingular" : "cruceiro brasileño", "BRZ_currencySymbol" : "BRR", "BSD_currencyISO" : "dólar de las Bahamas", "BSD_currencyPlural" : "dólares de las Bahamas", "BSD_currencySingular" : "dólar de las Bahamas", "BSD_currencySymbol" : "BS$", "BTN_currencyISO" : "ngultrum butanés", "BTN_currencyPlural" : "ngultrum butaneses", "BTN_currencySingular" : "ngultrum butanés", "BTN_currencySymbol" : "Nu.", "BUK_currencyISO" : "kyat birmano", "BUK_currencyPlural" : "kyat birmanos", "BUK_currencySingular" : "kyat birmano", "BUK_currencySymbol" : "BUK", "BWP_currencyISO" : "pula botsuano", "BWP_currencyPlural" : "pula botsuanas", "BWP_currencySingular" : "pula botsuana", "BWP_currencySymbol" : "BWP", "BYB_currencyISO" : "nuevo rublo bielorruso (1994-1999)", "BYB_currencyPlural" : "nuevos rublos bielorrusos", "BYB_currencySingular" : "nuevo rublo bielorruso", "BYB_currencySymbol" : "BYB", "BYR_currencyISO" : "rublo bielorruso", "BYR_currencyPlural" : "rublos bielorrusos", "BYR_currencySingular" : "rublo bielorruso", "BYR_currencySymbol" : "BYR", "BZD_currencyISO" : "dólar de Belice", "BZD_currencyPlural" : "dólares de Belice", "BZD_currencySingular" : "dólar de Belice", "BZD_currencySymbol" : "BZ$", "CAD_currencyISO" : "dólar canadiense", "CAD_currencyPlural" : "dólares canadienses", "CAD_currencySingular" : "dólar canadiense", "CAD_currencySymbol" : "CA$", "CDF_currencyISO" : "franco congoleño", "CDF_currencyPlural" : "francos congoleños", "CDF_currencySingular" : "franco congoleño", "CDF_currencySymbol" : "CDF", "CHE_currencyISO" : "euro WIR", "CHE_currencyPlural" : "euros WIR", "CHE_currencySingular" : "euro WIR", "CHE_currencySymbol" : "CHE", "CHF_currencyISO" : "franco suizo", "CHF_currencyPlural" : "francos suizos", "CHF_currencySingular" : "franco suizo", "CHF_currencySymbol" : "CHF", "CHW_currencyISO" : "franco WIR", "CHW_currencyPlural" : "francos WIR", "CHW_currencySingular" : "franco WIR", "CHW_currencySymbol" : "CHW", "CLE_currencyISO" : "CLE", "CLE_currencyPlural" : "francos WIR", "CLE_currencySingular" : "franco WIR", "CLE_currencySymbol" : "Eº", "CLF_currencyISO" : "unidad de fomento chilena", "CLF_currencyPlural" : "unidades de fomento chilenas", "CLF_currencySingular" : "unidad de fomento chilena", "CLF_currencySymbol" : "CLF", "CLP_currencyISO" : "peso chileno", "CLP_currencyPlural" : "pesos chilenos", "CLP_currencySingular" : "peso chileno", "CLP_currencySymbol" : "$", "CNX_currencyISO" : "peso chileno", "CNX_currencyPlural" : "pesos chilenos", "CNX_currencySingular" : "peso chileno", "CNX_currencySymbol" : "$", "CNY_currencyISO" : "yuan renminbi chino", "CNY_currencyPlural" : "pesos chilenos", "CNY_currencySingular" : "yuan renminbi chino", "CNY_currencySymbol" : "CN¥", "COP_currencyISO" : "peso colombiano", "COP_currencyPlural" : "pesos colombianos", "COP_currencySingular" : "peso colombiano", "COP_currencySymbol" : "CO$", "COU_currencyISO" : "unidad de valor real colombiana", "COU_currencyPlural" : "unidades de valor reales", "COU_currencySingular" : "unidad de valor real", "COU_currencySymbol" : "COU", "CRC_currencyISO" : "colón costarricense", "CRC_currencyPlural" : "colones costarricenses", "CRC_currencySingular" : "colón costarricense", "CRC_currencySymbol" : "₡", "CSD_currencyISO" : "antiguo dinar serbio", "CSD_currencyPlural" : "antiguos dinares serbios", "CSD_currencySingular" : "antiguo dinar serbio", "CSD_currencySymbol" : "CSD", "CSK_currencyISO" : "corona fuerte checoslovaca", "CSK_currencyPlural" : "coronas fuertes checoslovacas", "CSK_currencySingular" : "corona fuerte checoslovaca", "CSK_currencySymbol" : "CSK", "CUC_currencyISO" : "CUC", "CUC_currencyPlural" : "coronas fuertes checoslovacas", "CUC_currencySingular" : "corona fuerte checoslovaca", "CUC_currencySymbol" : "CUC$", "CUP_currencyISO" : "peso cubano", "CUP_currencyPlural" : "pesos cubanos", "CUP_currencySingular" : "peso cubano", "CUP_currencySymbol" : "CU$", "CVE_currencyISO" : "escudo de Cabo Verde", "CVE_currencyPlural" : "escudos de Cabo Verde", "CVE_currencySingular" : "escudo de Cabo Verde", "CVE_currencySymbol" : "CV$", "CYP_currencyISO" : "libra chipriota", "CYP_currencyPlural" : "libras chipriotas", "CYP_currencySingular" : "libra chipriota", "CYP_currencySymbol" : "CY£", "CZK_currencyISO" : "corona checa", "CZK_currencyPlural" : "coronas checas", "CZK_currencySingular" : "corona checa", "CZK_currencySymbol" : "Kč", "DDM_currencyISO" : "ostmark de Alemania del Este", "DDM_currencyPlural" : "marcos de la República Democrática Alemana", "DDM_currencySingular" : "marco de la República Democrática Alemana", "DDM_currencySymbol" : "DDM", "DEM_currencyISO" : "marco alemán", "DEM_currencyPlural" : "marcos alemanes", "DEM_currencySingular" : "marco alemán", "DEM_currencySymbol" : "DM", "DJF_currencyISO" : "franco de Yibuti", "DJF_currencyPlural" : "marcos alemanes", "DJF_currencySingular" : "marco alemán", "DJF_currencySymbol" : "Fdj", "DKK_currencyISO" : "corona danesa", "DKK_currencyPlural" : "coronas danesas", "DKK_currencySingular" : "corona danesa", "DKK_currencySymbol" : "Dkr", "DOP_currencyISO" : "peso dominicano", "DOP_currencyPlural" : "pesos dominicanos", "DOP_currencySingular" : "peso dominicano", "DOP_currencySymbol" : "RD$", "DZD_currencyISO" : "dinar argelino", "DZD_currencyPlural" : "dinares argelinos", "DZD_currencySingular" : "dinar argelino", "DZD_currencySymbol" : "DA", "ECS_currencyISO" : "sucre ecuatoriano", "ECS_currencyPlural" : "sucres ecuatorianos", "ECS_currencySingular" : "sucre ecuatoriano", "ECS_currencySymbol" : "ECS", "ECV_currencyISO" : "unidad de valor constante (UVC) ecuatoriana", "ECV_currencyPlural" : "unidades de valor constante (UVC) ecuatorianas", "ECV_currencySingular" : "unidad de valor constante (UVC) ecuatoriana", "ECV_currencySymbol" : "ECV", "EEK_currencyISO" : "corona estonia", "EEK_currencyPlural" : "coronas estonias", "EEK_currencySingular" : "corona estonia", "EEK_currencySymbol" : "Ekr", "EGP_currencyISO" : "libra egipcia", "EGP_currencyPlural" : "libras egipcias", "EGP_currencySingular" : "libra egipcia", "EGP_currencySymbol" : "EG£", "ERN_currencyISO" : "nakfa eritreo", "ERN_currencyPlural" : "libras egipcias", "ERN_currencySingular" : "libra egipcia", "ERN_currencySymbol" : "Nfk", "ESA_currencyISO" : "peseta española (cuenta A)", "ESA_currencyPlural" : "pesetas españolas (cuenta A)", "ESA_currencySingular" : "peseta española (cuenta A)", "ESA_currencySymbol" : "ESA", "ESB_currencyISO" : "peseta española (cuenta convertible)", "ESB_currencyPlural" : "pesetas españolas (cuenta convertible)", "ESB_currencySingular" : "peseta española (cuenta convertible)", "ESB_currencySymbol" : "ESB", "ESP_currencyISO" : "peseta española", "ESP_currencyPlural" : "pesetas españolas", "ESP_currencySingular" : "peseta española", "ESP_currencySymbol" : "₧", "ETB_currencyISO" : "birr etíope", "ETB_currencyPlural" : "pesetas españolas", "ETB_currencySingular" : "peseta española", "ETB_currencySymbol" : "Br", "EUR_currencyISO" : "euro", "EUR_currencyPlural" : "euros", "EUR_currencySingular" : "euro", "EUR_currencySymbol" : "€", "FIM_currencyISO" : "marco finlandés", "FIM_currencyPlural" : "marcos finlandeses", "FIM_currencySingular" : "marco finlandés", "FIM_currencySymbol" : "mk", "FJD_currencyISO" : "dólar de las Islas Fiyi", "FJD_currencyPlural" : "marcos finlandeses", "FJD_currencySingular" : "marco finlandés", "FJD_currencySymbol" : "FJ$", "FKP_currencyISO" : "libra de las Islas Malvinas", "FKP_currencyPlural" : "libras de las Islas Malvinas", "FKP_currencySingular" : "libra de las Islas Malvinas", "FKP_currencySymbol" : "FK£", "FRF_currencyISO" : "franco francés", "FRF_currencyPlural" : "francos franceses", "FRF_currencySingular" : "franco francés", "FRF_currencySymbol" : "₣", "GBP_currencyISO" : "libra esterlina británica", "GBP_currencyPlural" : "libras esterlinas británicas", "GBP_currencySingular" : "libra esterlina británica", "GBP_currencySymbol" : "£", "GEK_currencyISO" : "kupon larit georgiano", "GEK_currencyPlural" : "libras esterlinas británicas", "GEK_currencySingular" : "libra esterlina británica", "GEK_currencySymbol" : "GEK", "GEL_currencyISO" : "lari georgiano", "GEL_currencyPlural" : "libras esterlinas británicas", "GEL_currencySingular" : "libra esterlina británica", "GEL_currencySymbol" : "GEL", "GHC_currencyISO" : "cedi ghanés (1979-2007)", "GHC_currencyPlural" : "libras esterlinas británicas", "GHC_currencySingular" : "libra esterlina británica", "GHC_currencySymbol" : "₵", "GHS_currencyISO" : "GHS", "GHS_currencyPlural" : "libras esterlinas británicas", "GHS_currencySingular" : "libra esterlina británica", "GHS_currencySymbol" : "GH₵", "GIP_currencyISO" : "libra de Gibraltar", "GIP_currencyPlural" : "libras gibraltareñas", "GIP_currencySingular" : "libra gibraltareña", "GIP_currencySymbol" : "GI£", "GMD_currencyISO" : "dalasi gambiano", "GMD_currencyPlural" : "libras gibraltareñas", "GMD_currencySingular" : "libra gibraltareña", "GMD_currencySymbol" : "GMD", "GNF_currencyISO" : "franco guineano", "GNF_currencyPlural" : "francos guineanos", "GNF_currencySingular" : "franco guineano", "GNF_currencySymbol" : "FG", "GNS_currencyISO" : "syli guineano", "GNS_currencyPlural" : "francos guineanos", "GNS_currencySingular" : "franco guineano", "GNS_currencySymbol" : "GNS", "GQE_currencyISO" : "ekuele de Guinea Ecuatorial", "GQE_currencyPlural" : "ekueles de Guinea Ecuatorial", "GQE_currencySingular" : "ekuele de Guinea Ecuatorial", "GQE_currencySymbol" : "GQE", "GRD_currencyISO" : "dracma griego", "GRD_currencyPlural" : "dracmas griegos", "GRD_currencySingular" : "dracma griego", "GRD_currencySymbol" : "₯", "GTQ_currencyISO" : "quetzal guatemalteco", "GTQ_currencyPlural" : "quetzales guatemaltecos", "GTQ_currencySingular" : "quetzal guatemalteco", "GTQ_currencySymbol" : "GTQ", "GWE_currencyISO" : "escudo de Guinea Portuguesa", "GWE_currencyPlural" : "quetzales guatemaltecos", "GWE_currencySingular" : "quetzal guatemalteco", "GWE_currencySymbol" : "GWE", "GWP_currencyISO" : "peso de Guinea-Bissáu", "GWP_currencyPlural" : "quetzales guatemaltecos", "GWP_currencySingular" : "quetzal guatemalteco", "GWP_currencySymbol" : "GWP", "GYD_currencyISO" : "dólar guyanés", "GYD_currencyPlural" : "quetzales guatemaltecos", "GYD_currencySingular" : "quetzal guatemalteco", "GYD_currencySymbol" : "GY$", "HKD_currencyISO" : "dólar de Hong Kong", "HKD_currencyPlural" : "dólares de Hong Kong", "HKD_currencySingular" : "dólar de Hong Kong", "HKD_currencySymbol" : "HK$", "HNL_currencyISO" : "lempira hondureño", "HNL_currencyPlural" : "lempiras hondureños", "HNL_currencySingular" : "lempira hondureño", "HNL_currencySymbol" : "HNL", "HRD_currencyISO" : "dinar croata", "HRD_currencyPlural" : "dinares croatas", "HRD_currencySingular" : "dinar croata", "HRD_currencySymbol" : "HRD", "HRK_currencyISO" : "kuna croata", "HRK_currencyPlural" : "kunas croatas", "HRK_currencySingular" : "kuna croata", "HRK_currencySymbol" : "kn", "HTG_currencyISO" : "gourde haitiano", "HTG_currencyPlural" : "kunas croatas", "HTG_currencySingular" : "kuna croata", "HTG_currencySymbol" : "HTG", "HUF_currencyISO" : "florín húngaro", "HUF_currencyPlural" : "florines húngaros", "HUF_currencySingular" : "florín húngaro", "HUF_currencySymbol" : "Ft", "IDR_currencyISO" : "rupia indonesia", "IDR_currencyPlural" : "rupias indonesias", "IDR_currencySingular" : "rupia indonesia", "IDR_currencySymbol" : "Rp", "IEP_currencyISO" : "libra irlandesa", "IEP_currencyPlural" : "libras irlandesas", "IEP_currencySingular" : "libra irlandesa", "IEP_currencySymbol" : "IR£", "ILP_currencyISO" : "libra israelí", "ILP_currencyPlural" : "libras israelíes", "ILP_currencySingular" : "libra israelí", "ILP_currencySymbol" : "I£", "ILR_currencyISO" : "libra israelí", "ILR_currencyPlural" : "libras israelíes", "ILR_currencySingular" : "libra israelí", "ILR_currencySymbol" : "I£", "ILS_currencyISO" : "nuevo sheqel israelí", "ILS_currencyPlural" : "libras israelíes", "ILS_currencySingular" : "libra israelí", "ILS_currencySymbol" : "₪", "INR_currencyISO" : "rupia india", "INR_currencyPlural" : "rupias indias", "INR_currencySingular" : "rupia india", "INR_currencySymbol" : "Rs", "IQD_currencyISO" : "dinar iraquí", "IQD_currencyPlural" : "dinares iraquíes", "IQD_currencySingular" : "dinar iraquí", "IQD_currencySymbol" : "IQD", "IRR_currencyISO" : "rial iraní", "IRR_currencyPlural" : "dinares iraquíes", "IRR_currencySingular" : "dinar iraquí", "IRR_currencySymbol" : "IRR", "ISJ_currencyISO" : "rial iraní", "ISJ_currencyPlural" : "dinares iraquíes", "ISJ_currencySingular" : "dinar iraquí", "ISJ_currencySymbol" : "IRR", "ISK_currencyISO" : "corona islandesa", "ISK_currencyPlural" : "coronas islandesas", "ISK_currencySingular" : "corona islandesa", "ISK_currencySymbol" : "Ikr", "ITL_currencyISO" : "lira italiana", "ITL_currencyPlural" : "liras italianas", "ITL_currencySingular" : "lira italiana", "ITL_currencySymbol" : "IT₤", "JMD_currencyISO" : "dólar de Jamaica", "JMD_currencyPlural" : "dólares de Jamaica", "JMD_currencySingular" : "dólar de Jamaica", "JMD_currencySymbol" : "J$", "JOD_currencyISO" : "dinar jordano", "JOD_currencyPlural" : "dinares jordanos", "JOD_currencySingular" : "dinar jordano", "JOD_currencySymbol" : "JD", "JPY_currencyISO" : "yen japonés", "JPY_currencyPlural" : "yenes japoneses", "JPY_currencySingular" : "yen japonés", "JPY_currencySymbol" : "JP¥", "KES_currencyISO" : "chelín keniata", "KES_currencyPlural" : "yenes japoneses", "KES_currencySingular" : "yen japonés", "KES_currencySymbol" : "Ksh", "KGS_currencyISO" : "som kirguís", "KGS_currencyPlural" : "yenes japoneses", "KGS_currencySingular" : "yen japonés", "KGS_currencySymbol" : "KGS", "KHR_currencyISO" : "riel camboyano", "KHR_currencyPlural" : "yenes japoneses", "KHR_currencySingular" : "yen japonés", "KHR_currencySymbol" : "KHR", "KMF_currencyISO" : "franco comorense", "KMF_currencyPlural" : "yenes japoneses", "KMF_currencySingular" : "yen japonés", "KMF_currencySymbol" : "CF", "KPW_currencyISO" : "won norcoreano", "KPW_currencyPlural" : "yenes japoneses", "KPW_currencySingular" : "yen japonés", "KPW_currencySymbol" : "KPW", "KRH_currencyISO" : "won norcoreano", "KRH_currencyPlural" : "yenes japoneses", "KRH_currencySingular" : "yen japonés", "KRH_currencySymbol" : "KPW", "KRO_currencyISO" : "won norcoreano", "KRO_currencyPlural" : "yenes japoneses", "KRO_currencySingular" : "yen japonés", "KRO_currencySymbol" : "KPW", "KRW_currencyISO" : "won surcoreano", "KRW_currencyPlural" : "yenes japoneses", "KRW_currencySingular" : "yen japonés", "KRW_currencySymbol" : "₩", "KWD_currencyISO" : "dinar kuwaití", "KWD_currencyPlural" : "yenes japoneses", "KWD_currencySingular" : "yen japonés", "KWD_currencySymbol" : "KD", "KYD_currencyISO" : "dólar de las Islas Caimán", "KYD_currencyPlural" : "dólares de las Islas Caimán", "KYD_currencySingular" : "dólar de las Islas Caimán", "KYD_currencySymbol" : "KY$", "KZT_currencyISO" : "tenge kazako", "KZT_currencyPlural" : "dólares de las Islas Caimán", "KZT_currencySingular" : "dólar de las Islas Caimán", "KZT_currencySymbol" : "KZT", "LAK_currencyISO" : "kip laosiano", "LAK_currencyPlural" : "dólares de las Islas Caimán", "LAK_currencySingular" : "dólar de las Islas Caimán", "LAK_currencySymbol" : "₭", "LBP_currencyISO" : "libra libanesa", "LBP_currencyPlural" : "libras libanesas", "LBP_currencySingular" : "libra libanesa", "LBP_currencySymbol" : "LB£", "LKR_currencyISO" : "rupia de Sri Lanka", "LKR_currencyPlural" : "rupias de Sri Lanka", "LKR_currencySingular" : "rupia de Sri Lanka", "LKR_currencySymbol" : "SLRs", "LRD_currencyISO" : "dólar liberiano", "LRD_currencyPlural" : "dólares liberianos", "LRD_currencySingular" : "dólar liberiano", "LRD_currencySymbol" : "L$", "LSL_currencyISO" : "loti lesothense", "LSL_currencyPlural" : "dólares liberianos", "LSL_currencySingular" : "dólar liberiano", "LSL_currencySymbol" : "LSL", "LTL_currencyISO" : "litas lituano", "LTL_currencyPlural" : "litas lituanas", "LTL_currencySingular" : "litas lituana", "LTL_currencySymbol" : "Lt", "LTT_currencyISO" : "talonas lituano", "LTT_currencyPlural" : "talonas lituanas", "LTT_currencySingular" : "talonas lituana", "LTT_currencySymbol" : "LTT", "LUC_currencyISO" : "franco convertible luxemburgués", "LUC_currencyPlural" : "francos convertibles luxemburgueses", "LUC_currencySingular" : "franco convertible luxemburgués", "LUC_currencySymbol" : "LUC", "LUF_currencyISO" : "franco luxemburgués", "LUF_currencyPlural" : "francos luxemburgueses", "LUF_currencySingular" : "franco luxemburgués", "LUF_currencySymbol" : "LUF", "LUL_currencyISO" : "franco financiero luxemburgués", "LUL_currencyPlural" : "francos financieros luxemburgueses", "LUL_currencySingular" : "franco financiero luxemburgués", "LUL_currencySymbol" : "LUL", "LVL_currencyISO" : "lats letón", "LVL_currencyPlural" : "lats letones", "LVL_currencySingular" : "lats letón", "LVL_currencySymbol" : "Ls", "LVR_currencyISO" : "rublo letón", "LVR_currencyPlural" : "rublos letones", "LVR_currencySingular" : "rublo letón", "LVR_currencySymbol" : "LVR", "LYD_currencyISO" : "dinar libio", "LYD_currencyPlural" : "dinares libios", "LYD_currencySingular" : "dinar libio", "LYD_currencySymbol" : "LD", "MAD_currencyISO" : "dirham marroquí", "MAD_currencyPlural" : "dirhams marroquíes", "MAD_currencySingular" : "dirham marroquí", "MAD_currencySymbol" : "MAD", "MAF_currencyISO" : "franco marroquí", "MAF_currencyPlural" : "francos marroquíes", "MAF_currencySingular" : "franco marroquí", "MAF_currencySymbol" : "MAF", "MCF_currencyISO" : "franco marroquí", "MCF_currencyPlural" : "francos marroquíes", "MCF_currencySingular" : "franco marroquí", "MCF_currencySymbol" : "MAF", "MDC_currencyISO" : "franco marroquí", "MDC_currencyPlural" : "francos marroquíes", "MDC_currencySingular" : "franco marroquí", "MDC_currencySymbol" : "MAF", "MDL_currencyISO" : "leu moldavo", "MDL_currencyPlural" : "francos marroquíes", "MDL_currencySingular" : "franco marroquí", "MDL_currencySymbol" : "MDL", "MGA_currencyISO" : "ariary malgache", "MGA_currencyPlural" : "francos marroquíes", "MGA_currencySingular" : "franco marroquí", "MGA_currencySymbol" : "MGA", "MGF_currencyISO" : "franco malgache", "MGF_currencyPlural" : "francos marroquíes", "MGF_currencySingular" : "franco marroquí", "MGF_currencySymbol" : "MGF", "MKD_currencyISO" : "dinar macedonio", "MKD_currencyPlural" : "dinares macedonios", "MKD_currencySingular" : "dinar macedonio", "MKD_currencySymbol" : "MKD", "MKN_currencyISO" : "dinar macedonio", "MKN_currencyPlural" : "dinares macedonios", "MKN_currencySingular" : "dinar macedonio", "MKN_currencySymbol" : "MKD", "MLF_currencyISO" : "franco malí", "MLF_currencyPlural" : "dinares macedonios", "MLF_currencySingular" : "dinar macedonio", "MLF_currencySymbol" : "MLF", "MMK_currencyISO" : "kyat de Myanmar", "MMK_currencyPlural" : "dinares macedonios", "MMK_currencySingular" : "dinar macedonio", "MMK_currencySymbol" : "MMK", "MNT_currencyISO" : "tugrik mongol", "MNT_currencyPlural" : "dinares macedonios", "MNT_currencySingular" : "dinar macedonio", "MNT_currencySymbol" : "₮", "MOP_currencyISO" : "pataca de Macao", "MOP_currencyPlural" : "dinares macedonios", "MOP_currencySingular" : "dinar macedonio", "MOP_currencySymbol" : "MOP$", "MRO_currencyISO" : "ouguiya mauritano", "MRO_currencyPlural" : "dinares macedonios", "MRO_currencySingular" : "dinar macedonio", "MRO_currencySymbol" : "UM", "MTL_currencyISO" : "lira maltesa", "MTL_currencyPlural" : "liras maltesas", "MTL_currencySingular" : "lira maltesa", "MTL_currencySymbol" : "Lm", "MTP_currencyISO" : "libra maltesa", "MTP_currencyPlural" : "libras maltesas", "MTP_currencySingular" : "libra maltesa", "MTP_currencySymbol" : "MT£", "MUR_currencyISO" : "rupia mauriciana", "MUR_currencyPlural" : "libras maltesas", "MUR_currencySingular" : "libra maltesa", "MUR_currencySymbol" : "MURs", "MVP_currencyISO" : "rupia mauriciana", "MVP_currencyPlural" : "libras maltesas", "MVP_currencySingular" : "libra maltesa", "MVP_currencySymbol" : "MURs", "MVR_currencyISO" : "rufiyaa de Maldivas", "MVR_currencyPlural" : "libras maltesas", "MVR_currencySingular" : "libra maltesa", "MVR_currencySymbol" : "MVR", "MWK_currencyISO" : "kwacha de Malawi", "MWK_currencyPlural" : "libras maltesas", "MWK_currencySingular" : "libra maltesa", "MWK_currencySymbol" : "MWK", "MXN_currencyISO" : "peso mexicano", "MXN_currencyPlural" : "pesos mexicanos", "MXN_currencySingular" : "peso mexicano", "MXN_currencySymbol" : "MX$", "MXP_currencyISO" : "peso de plata mexicano (1861-1992)", "MXP_currencyPlural" : "pesos de plata mexicanos (MXP)", "MXP_currencySingular" : "peso de plata mexicano (MXP)", "MXP_currencySymbol" : "MXP", "MXV_currencyISO" : "unidad de inversión (UDI) mexicana", "MXV_currencyPlural" : "unidades de inversión (UDI) mexicanas", "MXV_currencySingular" : "unidad de inversión (UDI) mexicana", "MXV_currencySymbol" : "MXV", "MYR_currencyISO" : "ringgit malasio", "MYR_currencyPlural" : "unidades de inversión (UDI) mexicanas", "MYR_currencySingular" : "unidad de inversión (UDI) mexicana", "MYR_currencySymbol" : "RM", "MZE_currencyISO" : "escudo mozambiqueño", "MZE_currencyPlural" : "escudos mozambiqueños", "MZE_currencySingular" : "escudo mozambiqueño", "MZE_currencySymbol" : "MZE", "MZM_currencyISO" : "antiguo metical mozambiqueño", "MZM_currencyPlural" : "escudos mozambiqueños", "MZM_currencySingular" : "escudo mozambiqueño", "MZM_currencySymbol" : "Mt", "MZN_currencyISO" : "metical mozambiqueño", "MZN_currencyPlural" : "escudos mozambiqueños", "MZN_currencySingular" : "escudo mozambiqueño", "MZN_currencySymbol" : "MTn", "NAD_currencyISO" : "dólar de Namibia", "NAD_currencyPlural" : "escudos mozambiqueños", "NAD_currencySingular" : "escudo mozambiqueño", "NAD_currencySymbol" : "N$", "NGN_currencyISO" : "naira nigeriano", "NGN_currencyPlural" : "escudos mozambiqueños", "NGN_currencySingular" : "escudo mozambiqueño", "NGN_currencySymbol" : "₦", "NIC_currencyISO" : "córdoba nicaragüense", "NIC_currencyPlural" : "córdobas nicaragüenses", "NIC_currencySingular" : "córdoba nicaragüense", "NIC_currencySymbol" : "NIC", "NIO_currencyISO" : "córdoba oro nicaragüense", "NIO_currencyPlural" : "córdobas oro nicaragüenses", "NIO_currencySingular" : "córdoba oro nicaragüense", "NIO_currencySymbol" : "C$", "NLG_currencyISO" : "florín neerlandés", "NLG_currencyPlural" : "florines neerlandeses", "NLG_currencySingular" : "florín neerlandés", "NLG_currencySymbol" : "fl", "NOK_currencyISO" : "corona noruega", "NOK_currencyPlural" : "coronas noruegas", "NOK_currencySingular" : "corona noruega", "NOK_currencySymbol" : "Nkr", "NPR_currencyISO" : "rupia nepalesa", "NPR_currencyPlural" : "rupias nepalesas", "NPR_currencySingular" : "rupia nepalesa", "NPR_currencySymbol" : "NPRs", "NZD_currencyISO" : "dólar neozelandés", "NZD_currencyPlural" : "dólares neozelandeses", "NZD_currencySingular" : "dólar neozelandés", "NZD_currencySymbol" : "NZ$", "OMR_currencyISO" : "rial omaní", "OMR_currencyPlural" : "dólares neozelandeses", "OMR_currencySingular" : "dólar neozelandés", "OMR_currencySymbol" : "OMR", "PAB_currencyISO" : "balboa panameño", "PAB_currencyPlural" : "balboas panameños", "PAB_currencySingular" : "balboa panameño", "PAB_currencySymbol" : "B/.", "PEI_currencyISO" : "inti peruano", "PEI_currencyPlural" : "intis peruanos", "PEI_currencySingular" : "inti peruano", "PEI_currencySymbol" : "I/.", "PEN_currencyISO" : "nuevo sol peruano", "PEN_currencyPlural" : "nuevos soles peruanos", "PEN_currencySingular" : "nuevo sol peruano", "PEN_currencySymbol" : "S/.", "PES_currencyISO" : "sol peruano", "PES_currencyPlural" : "soles peruanos", "PES_currencySingular" : "sol peruano", "PES_currencySymbol" : "PES", "PGK_currencyISO" : "kina de Papúa Nueva Guinea", "PGK_currencyPlural" : "soles peruanos", "PGK_currencySingular" : "sol peruano", "PGK_currencySymbol" : "PGK", "PHP_currencyISO" : "peso filipino", "PHP_currencyPlural" : "pesos filipinos", "PHP_currencySingular" : "peso filipino", "PHP_currencySymbol" : "₱", "PKR_currencyISO" : "rupia pakistaní", "PKR_currencyPlural" : "pesos filipinos", "PKR_currencySingular" : "peso filipino", "PKR_currencySymbol" : "PKRs", "PLN_currencyISO" : "zloty polaco", "PLN_currencyPlural" : "zlotys polacos", "PLN_currencySingular" : "zloty polaco", "PLN_currencySymbol" : "zł", "PLZ_currencyISO" : "zloty polaco (1950-1995)", "PLZ_currencyPlural" : "zlotys polacos (PLZ)", "PLZ_currencySingular" : "zloty polaco (PLZ)", "PLZ_currencySymbol" : "PLZ", "PTE_currencyISO" : "escudo portugués", "PTE_currencyPlural" : "escudos portugueses", "PTE_currencySingular" : "escudo portugués", "PTE_currencySymbol" : "Esc", "PYG_currencyISO" : "guaraní paraguayo", "PYG_currencyPlural" : "guaraníes paraguayos", "PYG_currencySingular" : "guaraní paraguayo", "PYG_currencySymbol" : "₲", "QAR_currencyISO" : "riyal de Qatar", "QAR_currencyPlural" : "guaraníes paraguayos", "QAR_currencySingular" : "guaraní paraguayo", "QAR_currencySymbol" : "QR", "RHD_currencyISO" : "dólar rodesiano", "RHD_currencyPlural" : "guaraníes paraguayos", "RHD_currencySingular" : "guaraní paraguayo", "RHD_currencySymbol" : "RH$", "ROL_currencyISO" : "antiguo leu rumano", "ROL_currencyPlural" : "antiguos lei rumanos", "ROL_currencySingular" : "antiguo leu rumano", "ROL_currencySymbol" : "ROL", "RON_currencyISO" : "leu rumano", "RON_currencyPlural" : "lei rumanos", "RON_currencySingular" : "leu rumano", "RON_currencySymbol" : "RON", "RSD_currencyISO" : "dinar serbio", "RSD_currencyPlural" : "dinares serbios", "RSD_currencySingular" : "dinar serbio", "RSD_currencySymbol" : "din.", "RUB_currencyISO" : "rublo ruso", "RUB_currencyPlural" : "rublos rusos", "RUB_currencySingular" : "rublo ruso", "RUB_currencySymbol" : "RUB", "RUR_currencyISO" : "rublo ruso (1991-1998)", "RUR_currencyPlural" : "rublos rusos (RUR)", "RUR_currencySingular" : "rublo ruso (RUR)", "RUR_currencySymbol" : "RUR", "RWF_currencyISO" : "franco ruandés", "RWF_currencyPlural" : "francos ruandeses", "RWF_currencySingular" : "franco ruandés", "RWF_currencySymbol" : "RWF", "SAR_currencyISO" : "riyal saudí", "SAR_currencyPlural" : "francos ruandeses", "SAR_currencySingular" : "franco ruandés", "SAR_currencySymbol" : "SR", "SBD_currencyISO" : "dólar de las Islas Salomón", "SBD_currencyPlural" : "dólares de las Islas Salomón", "SBD_currencySingular" : "dólar de las Islas Salomón", "SBD_currencySymbol" : "SI$", "SCR_currencyISO" : "rupia de Seychelles", "SCR_currencyPlural" : "dólares de las Islas Salomón", "SCR_currencySingular" : "dólar de las Islas Salomón", "SCR_currencySymbol" : "SRe", "SDD_currencyISO" : "dinar sudanés", "SDD_currencyPlural" : "dinares sudaneses", "SDD_currencySingular" : "dinar sudanés", "SDD_currencySymbol" : "LSd", "SDG_currencyISO" : "libra sudanesa", "SDG_currencyPlural" : "libras sudanesas", "SDG_currencySingular" : "libra sudanesa", "SDG_currencySymbol" : "SDG", "SDP_currencyISO" : "libra sudanesa antigua", "SDP_currencyPlural" : "libras sudanesas antiguas", "SDP_currencySingular" : "libra sudanesa antigua", "SDP_currencySymbol" : "SDP", "SEK_currencyISO" : "corona sueca", "SEK_currencyPlural" : "coronas suecas", "SEK_currencySingular" : "corona sueca", "SEK_currencySymbol" : "Skr", "SGD_currencyISO" : "dólar singapurense", "SGD_currencyPlural" : "coronas suecas", "SGD_currencySingular" : "corona sueca", "SGD_currencySymbol" : "S$", "SHP_currencyISO" : "libra de Santa Elena", "SHP_currencyPlural" : "libras de Santa Elena", "SHP_currencySingular" : "libra de Santa Elena", "SHP_currencySymbol" : "SH£", "SIT_currencyISO" : "tólar esloveno", "SIT_currencyPlural" : "tólares eslovenos", "SIT_currencySingular" : "tólar esloveno", "SIT_currencySymbol" : "SIT", "SKK_currencyISO" : "corona eslovaca", "SKK_currencyPlural" : "coronas eslovacas", "SKK_currencySingular" : "corona eslovaca", "SKK_currencySymbol" : "Sk", "SLL_currencyISO" : "leone de Sierra Leona", "SLL_currencyPlural" : "coronas eslovacas", "SLL_currencySingular" : "corona eslovaca", "SLL_currencySymbol" : "Le", "SOS_currencyISO" : "chelín somalí", "SOS_currencyPlural" : "chelines somalíes", "SOS_currencySingular" : "chelín somalí", "SOS_currencySymbol" : "Ssh", "SRD_currencyISO" : "dólar surinamés", "SRD_currencyPlural" : "chelines somalíes", "SRD_currencySingular" : "chelín somalí", "SRD_currencySymbol" : "SR$", "SRG_currencyISO" : "florín surinamés", "SRG_currencyPlural" : "chelines somalíes", "SRG_currencySingular" : "chelín somalí", "SRG_currencySymbol" : "Sf", "SSP_currencyISO" : "florín surinamés", "SSP_currencyPlural" : "chelines somalíes", "SSP_currencySingular" : "chelín somalí", "SSP_currencySymbol" : "Sf", "STD_currencyISO" : "dobra de Santo Tomé y Príncipe", "STD_currencyPlural" : "chelines somalíes", "STD_currencySingular" : "chelín somalí", "STD_currencySymbol" : "Db", "SUR_currencyISO" : "rublo soviético", "SUR_currencyPlural" : "rublos soviéticos", "SUR_currencySingular" : "rublo soviético", "SUR_currencySymbol" : "SUR", "SVC_currencyISO" : "colón salvadoreño", "SVC_currencyPlural" : "colones salvadoreños", "SVC_currencySingular" : "colón salvadoreño", "SVC_currencySymbol" : "SV₡", "SYP_currencyISO" : "libra siria", "SYP_currencyPlural" : "libras sirias", "SYP_currencySingular" : "libra siria", "SYP_currencySymbol" : "SY£", "SZL_currencyISO" : "lilangeni suazi", "SZL_currencyPlural" : "libras sirias", "SZL_currencySingular" : "libra siria", "SZL_currencySymbol" : "SZL", "THB_currencyISO" : "baht tailandés", "THB_currencyPlural" : "libras sirias", "THB_currencySingular" : "libra siria", "THB_currencySymbol" : "฿", "TJR_currencyISO" : "rublo tayiko", "TJR_currencyPlural" : "libras sirias", "TJR_currencySingular" : "libra siria", "TJR_currencySymbol" : "TJR", "TJS_currencyISO" : "somoni tayiko", "TJS_currencyPlural" : "libras sirias", "TJS_currencySingular" : "libra siria", "TJS_currencySymbol" : "TJS", "TMM_currencyISO" : "manat turcomano", "TMM_currencyPlural" : "libras sirias", "TMM_currencySingular" : "libra siria", "TMM_currencySymbol" : "TMM", "TMT_currencyISO" : "manat turcomano", "TMT_currencyPlural" : "libras sirias", "TMT_currencySingular" : "libra siria", "TMT_currencySymbol" : "TMM", "TND_currencyISO" : "dinar tunecino", "TND_currencyPlural" : "libras sirias", "TND_currencySingular" : "libra siria", "TND_currencySymbol" : "DT", "TOP_currencyISO" : "paʻanga tongano", "TOP_currencyPlural" : "libras sirias", "TOP_currencySingular" : "libra siria", "TOP_currencySymbol" : "T$", "TPE_currencyISO" : "escudo timorense", "TPE_currencyPlural" : "libras sirias", "TPE_currencySingular" : "libra siria", "TPE_currencySymbol" : "TPE", "TRL_currencyISO" : "lira turca antigua", "TRL_currencyPlural" : "liras turcas antiguas", "TRL_currencySingular" : "lira turca antigua", "TRL_currencySymbol" : "TRL", "TRY_currencyISO" : "nueva lira turca", "TRY_currencyPlural" : "liras turcas", "TRY_currencySingular" : "lira turca", "TRY_currencySymbol" : "TL", "TTD_currencyISO" : "dólar de Trinidad y Tobago", "TTD_currencyPlural" : "liras turcas", "TTD_currencySingular" : "lira turca", "TTD_currencySymbol" : "TT$", "TWD_currencyISO" : "nuevo dólar taiwanés", "TWD_currencyPlural" : "liras turcas", "TWD_currencySingular" : "lira turca", "TWD_currencySymbol" : "NT$", "TZS_currencyISO" : "chelín tanzano", "TZS_currencyPlural" : "liras turcas", "TZS_currencySingular" : "lira turca", "TZS_currencySymbol" : "TSh", "UAH_currencyISO" : "grivna ucraniana", "UAH_currencyPlural" : "grivnias ucranianas", "UAH_currencySingular" : "grivnia ucraniana", "UAH_currencySymbol" : "₴", "UAK_currencyISO" : "karbovanet ucraniano", "UAK_currencyPlural" : "karbovanets ucranianos", "UAK_currencySingular" : "karbovanet ucraniano", "UAK_currencySymbol" : "UAK", "UGS_currencyISO" : "chelín ugandés (1966-1987)", "UGS_currencyPlural" : "karbovanets ucranianos", "UGS_currencySingular" : "karbovanet ucraniano", "UGS_currencySymbol" : "UGS", "UGX_currencyISO" : "chelín ugandés", "UGX_currencyPlural" : "chelines ugandeses", "UGX_currencySingular" : "chelín ugandés", "UGX_currencySymbol" : "USh", "USD_currencyISO" : "dólar estadounidense", "USD_currencyPlural" : "dólares estadounidenses", "USD_currencySingular" : "dólar estadounidense", "USD_currencySymbol" : "US$", "USN_currencyISO" : "dólar estadounidense (día siguiente)", "USN_currencyPlural" : "dólares estadounidenses (día siguiente)", "USN_currencySingular" : "dólar estadounidense (día siguiente)", "USN_currencySymbol" : "USN", "USS_currencyISO" : "dólar estadounidense (mismo día)", "USS_currencyPlural" : "dólares estadounidenses (mismo día)", "USS_currencySingular" : "dólar estadounidense (mismo día)", "USS_currencySymbol" : "USS", "UYI_currencyISO" : "peso uruguayo en unidades indexadas", "UYI_currencyPlural" : "pesos uruguayos en unidades indexadas", "UYI_currencySingular" : "peso uruguayo en unidades indexadas", "UYI_currencySymbol" : "UYI", "UYP_currencyISO" : "peso uruguayo (1975-1993)", "UYP_currencyPlural" : "pesos uruguayos (UYP)", "UYP_currencySingular" : "peso uruguayo (UYP)", "UYP_currencySymbol" : "UYP", "UYU_currencyISO" : "peso uruguayo", "UYU_currencyPlural" : "pesos uruguayos", "UYU_currencySingular" : "peso uruguayo", "UYU_currencySymbol" : "$U", "UZS_currencyISO" : "sum uzbeko", "UZS_currencyPlural" : "pesos uruguayos", "UZS_currencySingular" : "peso uruguayo", "UZS_currencySymbol" : "UZS", "VEB_currencyISO" : "bolívar venezolano", "VEB_currencyPlural" : "bolívares venezolanos", "VEB_currencySingular" : "bolívar venezolano", "VEB_currencySymbol" : "VEB", "VEF_currencyISO" : "bolívar fuerte venezolano", "VEF_currencyPlural" : "bolívares fuertes venezolanos", "VEF_currencySingular" : "bolívar fuerte venezolano", "VEF_currencySymbol" : "Bs.F.", "VND_currencyISO" : "dong vietnamita", "VND_currencyPlural" : "bolívares fuertes venezolanos", "VND_currencySingular" : "bolívar fuerte venezolano", "VND_currencySymbol" : "₫", "VNN_currencyISO" : "dong vietnamita", "VNN_currencyPlural" : "bolívares fuertes venezolanos", "VNN_currencySingular" : "bolívar fuerte venezolano", "VNN_currencySymbol" : "₫", "VUV_currencyISO" : "vatu vanuatuense", "VUV_currencyPlural" : "bolívares fuertes venezolanos", "VUV_currencySingular" : "bolívar fuerte venezolano", "VUV_currencySymbol" : "VT", "WST_currencyISO" : "tala samoano", "WST_currencyPlural" : "bolívares fuertes venezolanos", "WST_currencySingular" : "bolívar fuerte venezolano", "WST_currencySymbol" : "WS$", "XAF_currencyISO" : "franco CFA BEAC", "XAF_currencyPlural" : "bolívares fuertes venezolanos", "XAF_currencySingular" : "bolívar fuerte venezolano", "XAF_currencySymbol" : "FCFA", "XAG_currencyISO" : "plata", "XAG_currencyPlural" : "plata", "XAG_currencySingular" : "plata", "XAG_currencySymbol" : "XAG", "XAU_currencyISO" : "oro", "XAU_currencyPlural" : "oro", "XAU_currencySingular" : "oro", "XAU_currencySymbol" : "XAU", "XBA_currencyISO" : "unidad compuesta europea", "XBA_currencyPlural" : "unidades compuestas europeas", "XBA_currencySingular" : "unidad compuesta europea", "XBA_currencySymbol" : "XBA", "XBB_currencyISO" : "unidad monetaria europea", "XBB_currencyPlural" : "unidades monetarias europeas", "XBB_currencySingular" : "unidad monetaria europea", "XBB_currencySymbol" : "XBB", "XBC_currencyISO" : "unidad de cuenta europea (XBC)", "XBC_currencyPlural" : "unidades de cuenta europeas (XBC)", "XBC_currencySingular" : "unidad de cuenta europea (XBC)", "XBC_currencySymbol" : "XBC", "XBD_currencyISO" : "unidad de cuenta europea (XBD)", "XBD_currencyPlural" : "unidades de cuenta europeas (XBD)", "XBD_currencySingular" : "unidad de cuenta europea (XBD)", "XBD_currencySymbol" : "XBD", "XCD_currencyISO" : "dólar del Caribe Oriental", "XCD_currencyPlural" : "dólares del Caribe Oriental", "XCD_currencySingular" : "dólar del Caribe Oriental", "XCD_currencySymbol" : "EC$", "XDR_currencyISO" : "derechos especiales de giro", "XDR_currencyPlural" : "dólares del Caribe Oriental", "XDR_currencySingular" : "dólar del Caribe Oriental", "XDR_currencySymbol" : "XDR", "XEU_currencyISO" : "unidad de moneda europea", "XEU_currencyPlural" : "unidades de moneda europeas", "XEU_currencySingular" : "unidad de moneda europea", "XEU_currencySymbol" : "XEU", "XFO_currencyISO" : "franco oro francés", "XFO_currencyPlural" : "francos oro franceses", "XFO_currencySingular" : "franco oro francés", "XFO_currencySymbol" : "XFO", "XFU_currencyISO" : "franco UIC francés", "XFU_currencyPlural" : "francos UIC franceses", "XFU_currencySingular" : "franco UIC francés", "XFU_currencySymbol" : "XFU", "XOF_currencyISO" : "franco CFA BCEAO", "XOF_currencyPlural" : "francos UIC franceses", "XOF_currencySingular" : "franco UIC francés", "XOF_currencySymbol" : "CFA", "XPD_currencyISO" : "paladio", "XPD_currencyPlural" : "paladio", "XPD_currencySingular" : "paladio", "XPD_currencySymbol" : "XPD", "XPF_currencyISO" : "franco CFP", "XPF_currencyPlural" : "paladio", "XPF_currencySingular" : "paladio", "XPF_currencySymbol" : "CFPF", "XPT_currencyISO" : "platino", "XPT_currencyPlural" : "platino", "XPT_currencySingular" : "platino", "XPT_currencySymbol" : "XPT", "XRE_currencyISO" : "fondos RINET", "XRE_currencyPlural" : "platino", "XRE_currencySingular" : "platino", "XRE_currencySymbol" : "XRE", "XSU_currencyISO" : "fondos RINET", "XSU_currencyPlural" : "platino", "XSU_currencySingular" : "platino", "XSU_currencySymbol" : "XRE", "XTS_currencyISO" : "código reservado para pruebas", "XTS_currencyPlural" : "platino", "XTS_currencySingular" : "platino", "XTS_currencySymbol" : "XTS", "XUA_currencyISO" : "código reservado para pruebas", "XUA_currencyPlural" : "platino", "XUA_currencySingular" : "platino", "XUA_currencySymbol" : "XTS", "XXX_currencyISO" : "Sin divisa", "XXX_currencyPlural" : "monedas desconocidas/no válidas", "XXX_currencySingular" : "moneda desconocida/no válida", "XXX_currencySymbol" : "XXX", "YDD_currencyISO" : "dinar yemení", "YDD_currencyPlural" : "monedas desconocidas/no válidas", "YDD_currencySingular" : "moneda desconocida/no válida", "YDD_currencySymbol" : "YDD", "YER_currencyISO" : "rial yemení", "YER_currencyPlural" : "monedas desconocidas/no válidas", "YER_currencySingular" : "moneda desconocida/no válida", "YER_currencySymbol" : "YR", "YUD_currencyISO" : "dinar fuerte yugoslavo", "YUD_currencyPlural" : "monedas desconocidas/no válidas", "YUD_currencySingular" : "moneda desconocida/no válida", "YUD_currencySymbol" : "YUD", "YUM_currencyISO" : "super dinar yugoslavo", "YUM_currencyPlural" : "monedas desconocidas/no válidas", "YUM_currencySingular" : "moneda desconocida/no válida", "YUM_currencySymbol" : "YUM", "YUN_currencyISO" : "dinar convertible yugoslavo", "YUN_currencyPlural" : "dinares convertibles yugoslavos", "YUN_currencySingular" : "dinar convertible yugoslavo", "YUN_currencySymbol" : "YUN", "YUR_currencyISO" : "dinar convertible yugoslavo", "YUR_currencyPlural" : "dinares convertibles yugoslavos", "YUR_currencySingular" : "dinar convertible yugoslavo", "YUR_currencySymbol" : "YUN", "ZAL_currencyISO" : "rand sudafricano (financiero)", "ZAL_currencyPlural" : "dinares convertibles yugoslavos", "ZAL_currencySingular" : "dinar convertible yugoslavo", "ZAL_currencySymbol" : "ZAL", "ZAR_currencyISO" : "rand sudafricano", "ZAR_currencyPlural" : "dinares convertibles yugoslavos", "ZAR_currencySingular" : "dinar convertible yugoslavo", "ZAR_currencySymbol" : "R", "ZMK_currencyISO" : "kwacha zambiano", "ZMK_currencyPlural" : "dinares convertibles yugoslavos", "ZMK_currencySingular" : "dinar convertible yugoslavo", "ZMK_currencySymbol" : "ZK", "ZRN_currencyISO" : "nuevo zaire zaireño", "ZRN_currencyPlural" : "dinares convertibles yugoslavos", "ZRN_currencySingular" : "dinar convertible yugoslavo", "ZRN_currencySymbol" : "NZ", "ZRZ_currencyISO" : "zaire zaireño", "ZRZ_currencyPlural" : "dinares convertibles yugoslavos", "ZRZ_currencySingular" : "dinar convertible yugoslavo", "ZRZ_currencySymbol" : "ZRZ", "ZWD_currencyISO" : "dólar de Zimbabue", "ZWD_currencyPlural" : "dinares convertibles yugoslavos", "ZWD_currencySingular" : "dinar convertible yugoslavo", "ZWD_currencySymbol" : "Z$", "ZWL_currencyISO" : "dólar de Zimbabue", "ZWL_currencyPlural" : "dinares convertibles yugoslavos", "ZWL_currencySingular" : "dinar convertible yugoslavo", "ZWL_currencySymbol" : "Z$", "ZWR_currencyISO" : "dólar de Zimbabue", "ZWR_currencyPlural" : "dinares convertibles yugoslavos", "ZWR_currencySingular" : "dinar convertible yugoslavo", "ZWR_currencySymbol" : "Z$", "currencyFormat" : "¤#,##0.00;¤-#,##0.00", "currencyPatternPlural" : "e u", "currencyPatternSingular" : "{0} {1}", "decimalFormat" : "#,##0.###", "decimalSeparator" : ",", "defaultCurrency" : "CLP", "exponentialSymbol" : "E", "groupingSeparator" : ".", "infinitySign" : "∞", "minusSign" : "-", "nanSymbol" : "NaN", "numberZero" : "0", "perMilleSign" : "‰", "percentFormat" : "#,##0%", "percentSign" : "%", "plusSign" : "+", "scientificFormat" : "#E0" }
'use strict'; require('../common'); const assert = require('assert'); const inspect = require('util').inspect; const url = require('url'); // when source is false assert.strictEqual(url.resolveObject('', 'foo'), 'foo'); /* [from, path, expected] */ const relativeTests = [ ['/foo/bar/baz', 'quux', '/foo/bar/quux'], ['/foo/bar/baz', 'quux/asdf', '/foo/bar/quux/asdf'], ['/foo/bar/baz', 'quux/baz', '/foo/bar/quux/baz'], ['/foo/bar/baz', '../quux/baz', '/foo/quux/baz'], ['/foo/bar/baz', '/bar', '/bar'], ['/foo/bar/baz/', 'quux', '/foo/bar/baz/quux'], ['/foo/bar/baz/', 'quux/baz', '/foo/bar/baz/quux/baz'], ['/foo/bar/baz', '../../../../../../../../quux/baz', '/quux/baz'], ['/foo/bar/baz', '../../../../../../../quux/baz', '/quux/baz'], ['/foo', '.', '/'], ['/foo', '..', '/'], ['/foo/', '.', '/foo/'], ['/foo/', '..', '/'], ['/foo/bar', '.', '/foo/'], ['/foo/bar', '..', '/'], ['/foo/bar/', '.', '/foo/bar/'], ['/foo/bar/', '..', '/foo/'], ['foo/bar', '../../../baz', '../../baz'], ['foo/bar/', '../../../baz', '../baz'], ['http://example.com/b//c//d;p?q#blarg', 'https:#hash2', 'https:///#hash2'], ['http://example.com/b//c//d;p?q#blarg', 'https:/p/a/t/h?s#hash2', 'https://p/a/t/h?s#hash2'], ['http://example.com/b//c//d;p?q#blarg', 'https://u:p@h.com/p/a/t/h?s#hash2', 'https://u:p@h.com/p/a/t/h?s#hash2'], ['http://example.com/b//c//d;p?q#blarg', 'https:/a/b/c/d', 'https://a/b/c/d'], ['http://example.com/b//c//d;p?q#blarg', 'http:#hash2', 'http://example.com/b//c//d;p?q#hash2'], ['http://example.com/b//c//d;p?q#blarg', 'http:/p/a/t/h?s#hash2', 'http://example.com/p/a/t/h?s#hash2'], ['http://example.com/b//c//d;p?q#blarg', 'http://u:p@h.com/p/a/t/h?s#hash2', 'http://u:p@h.com/p/a/t/h?s#hash2'], ['http://example.com/b//c//d;p?q#blarg', 'http:/a/b/c/d', 'http://example.com/a/b/c/d'], ['/foo/bar/baz', '/../etc/passwd', '/etc/passwd'], ['http://localhost', 'file:///Users/foo', 'file:///Users/foo'], ['http://localhost', 'file://foo/Users', 'file://foo/Users'] ]; relativeTests.forEach(function(relativeTest) { const a = url.resolve(relativeTest[0], relativeTest[1]); const e = relativeTest[2]; assert.strictEqual(a, e, `resolve(${relativeTest[0]}, ${relativeTest[1]})` + ` == ${e}\n actual=${a}`); }); // // Tests below taken from Chiron // http://code.google.com/p/chironjs/source/browse/trunk/src/test/http/url.js // // Copyright (c) 2002-2008 Kris Kowal <http://cixar.com/~kris.kowal> // used with permission under MIT License // // Changes marked with @isaacs const bases = [ 'http://a/b/c/d;p?q', 'http://a/b/c/d;p?q=1/2', 'http://a/b/c/d;p=1/2?q', 'fred:///s//a/b/c', 'http:///s//a/b/c' ]; //[to, from, result] const relativeTests2 = [ // http://lists.w3.org/Archives/Public/uri/2004Feb/0114.html ['../c', 'foo:a/b', 'foo:c'], ['foo:.', 'foo:a', 'foo:'], ['/foo/../../../bar', 'zz:abc', 'zz:/bar'], ['/foo/../bar', 'zz:abc', 'zz:/bar'], // @isaacs Disagree. Not how web browsers resolve this. ['foo/../../../bar', 'zz:abc', 'zz:bar'], // ['foo/../../../bar', 'zz:abc', 'zz:../../bar'], // @isaacs Added ['foo/../bar', 'zz:abc', 'zz:bar'], ['zz:.', 'zz:abc', 'zz:'], ['/.', bases[0], 'http://a/'], ['/.foo', bases[0], 'http://a/.foo'], ['.foo', bases[0], 'http://a/b/c/.foo'], // http://gbiv.com/protocols/uri/test/rel_examples1.html // examples from RFC 2396 ['g:h', bases[0], 'g:h'], ['g', bases[0], 'http://a/b/c/g'], ['./g', bases[0], 'http://a/b/c/g'], ['g/', bases[0], 'http://a/b/c/g/'], ['/g', bases[0], 'http://a/g'], ['//g', bases[0], 'http://g/'], // changed with RFC 2396bis //('?y', bases[0], 'http://a/b/c/d;p?y'], ['?y', bases[0], 'http://a/b/c/d;p?y'], ['g?y', bases[0], 'http://a/b/c/g?y'], // changed with RFC 2396bis //('#s', bases[0], CURRENT_DOC_URI + '#s'], ['#s', bases[0], 'http://a/b/c/d;p?q#s'], ['g#s', bases[0], 'http://a/b/c/g#s'], ['g?y#s', bases[0], 'http://a/b/c/g?y#s'], [';x', bases[0], 'http://a/b/c/;x'], ['g;x', bases[0], 'http://a/b/c/g;x'], ['g;x?y#s', bases[0], 'http://a/b/c/g;x?y#s'], // changed with RFC 2396bis //('', bases[0], CURRENT_DOC_URI], ['', bases[0], 'http://a/b/c/d;p?q'], ['.', bases[0], 'http://a/b/c/'], ['./', bases[0], 'http://a/b/c/'], ['..', bases[0], 'http://a/b/'], ['../', bases[0], 'http://a/b/'], ['../g', bases[0], 'http://a/b/g'], ['../..', bases[0], 'http://a/'], ['../../', bases[0], 'http://a/'], ['../../g', bases[0], 'http://a/g'], ['../../../g', bases[0], ('http://a/../g', 'http://a/g')], ['../../../../g', bases[0], ('http://a/../../g', 'http://a/g')], // changed with RFC 2396bis //('/./g', bases[0], 'http://a/./g'], ['/./g', bases[0], 'http://a/g'], // changed with RFC 2396bis //('/../g', bases[0], 'http://a/../g'], ['/../g', bases[0], 'http://a/g'], ['g.', bases[0], 'http://a/b/c/g.'], ['.g', bases[0], 'http://a/b/c/.g'], ['g..', bases[0], 'http://a/b/c/g..'], ['..g', bases[0], 'http://a/b/c/..g'], ['./../g', bases[0], 'http://a/b/g'], ['./g/.', bases[0], 'http://a/b/c/g/'], ['g/./h', bases[0], 'http://a/b/c/g/h'], ['g/../h', bases[0], 'http://a/b/c/h'], ['g;x=1/./y', bases[0], 'http://a/b/c/g;x=1/y'], ['g;x=1/../y', bases[0], 'http://a/b/c/y'], ['g?y/./x', bases[0], 'http://a/b/c/g?y/./x'], ['g?y/../x', bases[0], 'http://a/b/c/g?y/../x'], ['g#s/./x', bases[0], 'http://a/b/c/g#s/./x'], ['g#s/../x', bases[0], 'http://a/b/c/g#s/../x'], ['http:g', bases[0], ('http:g', 'http://a/b/c/g')], ['http:', bases[0], ('http:', bases[0])], // not sure where this one originated ['/a/b/c/./../../g', bases[0], 'http://a/a/g'], // http://gbiv.com/protocols/uri/test/rel_examples2.html // slashes in base URI's query args ['g', bases[1], 'http://a/b/c/g'], ['./g', bases[1], 'http://a/b/c/g'], ['g/', bases[1], 'http://a/b/c/g/'], ['/g', bases[1], 'http://a/g'], ['//g', bases[1], 'http://g/'], // changed in RFC 2396bis //('?y', bases[1], 'http://a/b/c/?y'], ['?y', bases[1], 'http://a/b/c/d;p?y'], ['g?y', bases[1], 'http://a/b/c/g?y'], ['g?y/./x', bases[1], 'http://a/b/c/g?y/./x'], ['g?y/../x', bases[1], 'http://a/b/c/g?y/../x'], ['g#s', bases[1], 'http://a/b/c/g#s'], ['g#s/./x', bases[1], 'http://a/b/c/g#s/./x'], ['g#s/../x', bases[1], 'http://a/b/c/g#s/../x'], ['./', bases[1], 'http://a/b/c/'], ['../', bases[1], 'http://a/b/'], ['../g', bases[1], 'http://a/b/g'], ['../../', bases[1], 'http://a/'], ['../../g', bases[1], 'http://a/g'], // http://gbiv.com/protocols/uri/test/rel_examples3.html // slashes in path params // all of these changed in RFC 2396bis ['g', bases[2], 'http://a/b/c/d;p=1/g'], ['./g', bases[2], 'http://a/b/c/d;p=1/g'], ['g/', bases[2], 'http://a/b/c/d;p=1/g/'], ['g?y', bases[2], 'http://a/b/c/d;p=1/g?y'], [';x', bases[2], 'http://a/b/c/d;p=1/;x'], ['g;x', bases[2], 'http://a/b/c/d;p=1/g;x'], ['g;x=1/./y', bases[2], 'http://a/b/c/d;p=1/g;x=1/y'], ['g;x=1/../y', bases[2], 'http://a/b/c/d;p=1/y'], ['./', bases[2], 'http://a/b/c/d;p=1/'], ['../', bases[2], 'http://a/b/c/'], ['../g', bases[2], 'http://a/b/c/g'], ['../../', bases[2], 'http://a/b/'], ['../../g', bases[2], 'http://a/b/g'], // http://gbiv.com/protocols/uri/test/rel_examples4.html // double and triple slash, unknown scheme ['g:h', bases[3], 'g:h'], ['g', bases[3], 'fred:///s//a/b/g'], ['./g', bases[3], 'fred:///s//a/b/g'], ['g/', bases[3], 'fred:///s//a/b/g/'], ['/g', bases[3], 'fred:///g'], // may change to fred:///s//a/g ['//g', bases[3], 'fred://g'], // may change to fred:///s//g ['//g/x', bases[3], 'fred://g/x'], // may change to fred:///s//g/x ['///g', bases[3], 'fred:///g'], ['./', bases[3], 'fred:///s//a/b/'], ['../', bases[3], 'fred:///s//a/'], ['../g', bases[3], 'fred:///s//a/g'], ['../../', bases[3], 'fred:///s//'], ['../../g', bases[3], 'fred:///s//g'], ['../../../g', bases[3], 'fred:///s/g'], // may change to fred:///s//a/../../../g ['../../../../g', bases[3], 'fred:///g'], // http://gbiv.com/protocols/uri/test/rel_examples5.html // double and triple slash, well-known scheme ['g:h', bases[4], 'g:h'], ['g', bases[4], 'http:///s//a/b/g'], ['./g', bases[4], 'http:///s//a/b/g'], ['g/', bases[4], 'http:///s//a/b/g/'], ['/g', bases[4], 'http:///g'], // may change to http:///s//a/g ['//g', bases[4], 'http://g/'], // may change to http:///s//g ['//g/x', bases[4], 'http://g/x'], // may change to http:///s//g/x ['///g', bases[4], 'http:///g'], ['./', bases[4], 'http:///s//a/b/'], ['../', bases[4], 'http:///s//a/'], ['../g', bases[4], 'http:///s//a/g'], ['../../', bases[4], 'http:///s//'], ['../../g', bases[4], 'http:///s//g'], // may change to http:///s//a/../../g ['../../../g', bases[4], 'http:///s/g'], // may change to http:///s//a/../../../g ['../../../../g', bases[4], 'http:///g'], // from Dan Connelly's tests in http://www.w3.org/2000/10/swap/uripath.py ['bar:abc', 'foo:xyz', 'bar:abc'], ['../abc', 'http://example/x/y/z', 'http://example/x/abc'], ['http://example/x/abc', 'http://example2/x/y/z', 'http://example/x/abc'], ['../r', 'http://ex/x/y/z', 'http://ex/x/r'], ['q/r', 'http://ex/x/y', 'http://ex/x/q/r'], ['q/r#s', 'http://ex/x/y', 'http://ex/x/q/r#s'], ['q/r#s/t', 'http://ex/x/y', 'http://ex/x/q/r#s/t'], ['ftp://ex/x/q/r', 'http://ex/x/y', 'ftp://ex/x/q/r'], ['', 'http://ex/x/y', 'http://ex/x/y'], ['', 'http://ex/x/y/', 'http://ex/x/y/'], ['', 'http://ex/x/y/pdq', 'http://ex/x/y/pdq'], ['z/', 'http://ex/x/y/', 'http://ex/x/y/z/'], ['#Animal', 'file:/swap/test/animal.rdf', 'file:/swap/test/animal.rdf#Animal'], ['../abc', 'file:/e/x/y/z', 'file:/e/x/abc'], ['/example/x/abc', 'file:/example2/x/y/z', 'file:/example/x/abc'], ['../r', 'file:/ex/x/y/z', 'file:/ex/x/r'], ['/r', 'file:/ex/x/y/z', 'file:/r'], ['q/r', 'file:/ex/x/y', 'file:/ex/x/q/r'], ['q/r#s', 'file:/ex/x/y', 'file:/ex/x/q/r#s'], ['q/r#', 'file:/ex/x/y', 'file:/ex/x/q/r#'], ['q/r#s/t', 'file:/ex/x/y', 'file:/ex/x/q/r#s/t'], ['ftp://ex/x/q/r', 'file:/ex/x/y', 'ftp://ex/x/q/r'], ['', 'file:/ex/x/y', 'file:/ex/x/y'], ['', 'file:/ex/x/y/', 'file:/ex/x/y/'], ['', 'file:/ex/x/y/pdq', 'file:/ex/x/y/pdq'], ['z/', 'file:/ex/x/y/', 'file:/ex/x/y/z/'], ['file://meetings.example.com/cal#m1', 'file:/devel/WWW/2000/10/swap/test/reluri-1.n3', 'file://meetings.example.com/cal#m1'], ['file://meetings.example.com/cal#m1', 'file:/home/connolly/w3ccvs/WWW/2000/10/swap/test/reluri-1.n3', 'file://meetings.example.com/cal#m1'], ['./#blort', 'file:/some/dir/foo', 'file:/some/dir/#blort'], ['./#', 'file:/some/dir/foo', 'file:/some/dir/#'], // Ryan Lee ['./', 'http://example/x/abc.efg', 'http://example/x/'], // Graham Klyne's tests // http://www.ninebynine.org/Software/HaskellUtils/Network/UriTest.xls // 01-31 are from Connelly's cases // 32-49 ['./q:r', 'http://ex/x/y', 'http://ex/x/q:r'], ['./p=q:r', 'http://ex/x/y', 'http://ex/x/p=q:r'], ['?pp/rr', 'http://ex/x/y?pp/qq', 'http://ex/x/y?pp/rr'], ['y/z', 'http://ex/x/y?pp/qq', 'http://ex/x/y/z'], ['local/qual@domain.org#frag', 'mailto:local', 'mailto:local/qual@domain.org#frag'], ['more/qual2@domain2.org#frag', 'mailto:local/qual1@domain1.org', 'mailto:local/more/qual2@domain2.org#frag'], ['y?q', 'http://ex/x/y?q', 'http://ex/x/y?q'], ['/x/y?q', 'http://ex?p', 'http://ex/x/y?q'], ['c/d', 'foo:a/b', 'foo:a/c/d'], ['/c/d', 'foo:a/b', 'foo:/c/d'], ['', 'foo:a/b?c#d', 'foo:a/b?c'], ['b/c', 'foo:a', 'foo:b/c'], ['../b/c', 'foo:/a/y/z', 'foo:/a/b/c'], ['./b/c', 'foo:a', 'foo:b/c'], ['/./b/c', 'foo:a', 'foo:/b/c'], ['../../d', 'foo://a//b/c', 'foo://a/d'], ['.', 'foo:a', 'foo:'], ['..', 'foo:a', 'foo:'], // 50-57[cf. TimBL comments -- // http://lists.w3.org/Archives/Public/uri/2003Feb/0028.html, // http://lists.w3.org/Archives/Public/uri/2003Jan/0008.html) ['abc', 'http://example/x/y%2Fz', 'http://example/x/abc'], ['../../x%2Fabc', 'http://example/a/x/y/z', 'http://example/a/x%2Fabc'], ['../x%2Fabc', 'http://example/a/x/y%2Fz', 'http://example/a/x%2Fabc'], ['abc', 'http://example/x%2Fy/z', 'http://example/x%2Fy/abc'], ['q%3Ar', 'http://ex/x/y', 'http://ex/x/q%3Ar'], ['/x%2Fabc', 'http://example/x/y%2Fz', 'http://example/x%2Fabc'], ['/x%2Fabc', 'http://example/x/y/z', 'http://example/x%2Fabc'], ['/x%2Fabc', 'http://example/x/y%2Fz', 'http://example/x%2Fabc'], // 70-77 ['local2@domain2', 'mailto:local1@domain1?query1', 'mailto:local2@domain2'], ['local2@domain2?query2', 'mailto:local1@domain1', 'mailto:local2@domain2?query2'], ['local2@domain2?query2', 'mailto:local1@domain1?query1', 'mailto:local2@domain2?query2'], ['?query2', 'mailto:local@domain?query1', 'mailto:local@domain?query2'], ['local@domain?query2', 'mailto:?query1', 'mailto:local@domain?query2'], ['?query2', 'mailto:local@domain?query1', 'mailto:local@domain?query2'], ['http://example/a/b?c/../d', 'foo:bar', 'http://example/a/b?c/../d'], ['http://example/a/b#c/../d', 'foo:bar', 'http://example/a/b#c/../d'], // 82-88 // @isaacs Disagree. Not how browsers do it. // ['http:this', 'http://example.org/base/uri', 'http:this'], // @isaacs Added ['http:this', 'http://example.org/base/uri', 'http://example.org/base/this'], ['http:this', 'http:base', 'http:this'], ['.//g', 'f:/a', 'f://g'], ['b/c//d/e', 'f://example.org/base/a', 'f://example.org/base/b/c//d/e'], ['m2@example.ord/c2@example.org', 'mid:m@example.ord/c@example.org', 'mid:m@example.ord/m2@example.ord/c2@example.org'], ['mini1.xml', 'file:///C:/DEV/Haskell/lib/HXmlToolbox-3.01/examples/', 'file:///C:/DEV/Haskell/lib/HXmlToolbox-3.01/examples/mini1.xml'], ['../b/c', 'foo:a/y/z', 'foo:a/b/c'], //changeing auth ['http://diff:auth@www.example.com', 'http://asdf:qwer@www.example.com', 'http://diff:auth@www.example.com/'], // changing port ['https://example.com:81/', 'https://example.com:82/', 'https://example.com:81/'], // https://github.com/nodejs/node/issues/1435 ['https://another.host.com/', 'https://user:password@example.org/', 'https://another.host.com/'], ['//another.host.com/', 'https://user:password@example.org/', 'https://another.host.com/'], ['http://another.host.com/', 'https://user:password@example.org/', 'http://another.host.com/'], ['mailto:another.host.com', 'mailto:user@example.org', 'mailto:another.host.com'], ['https://example.com/foo', 'https://user:password@example.com', 'https://user:password@example.com/foo'], // No path at all ['#hash1', '#hash2', '#hash1'] ]; relativeTests2.forEach(function(relativeTest) { const a = url.resolve(relativeTest[1], relativeTest[0]); const e = url.format(relativeTest[2]); assert.strictEqual(a, e, `resolve(${relativeTest[0]}, ${relativeTest[1]})` + ` == ${e}\n actual=${a}`); }); //if format and parse are inverse operations then //resolveObject(parse(x), y) == parse(resolve(x, y)) //format: [from, path, expected] relativeTests.forEach(function(relativeTest) { let actual = url.resolveObject(url.parse(relativeTest[0]), relativeTest[1]); let expected = url.parse(relativeTest[2]); assert.deepStrictEqual(actual, expected); expected = relativeTest[2]; actual = url.format(actual); assert.strictEqual(actual, expected, `format(${actual}) == ${expected}\n` + `actual: ${actual}`); }); //format: [to, from, result] // the test: ['.//g', 'f:/a', 'f://g'] is a fundamental problem // url.parse('f:/a') does not have a host // url.resolve('f:/a', './/g') does not have a host because you have moved // down to the g directory. i.e. f: //g, however when this url is parsed // f:// will indicate that the host is g which is not the case. // it is unclear to me how to keep this information from being lost // it may be that a pathname of ////g should collapse to /g but this seems // to be a lot of work for an edge case. Right now I remove the test if (relativeTests2[181][0] === './/g' && relativeTests2[181][1] === 'f:/a' && relativeTests2[181][2] === 'f://g') { relativeTests2.splice(181, 1); } relativeTests2.forEach(function(relativeTest) { let actual = url.resolveObject(url.parse(relativeTest[1]), relativeTest[0]); let expected = url.parse(relativeTest[2]); assert.deepStrictEqual( actual, expected, `expected ${inspect(expected)} but got ${inspect(actual)}` ); expected = url.format(relativeTest[2]); actual = url.format(actual); assert.strictEqual(actual, expected, `format(${relativeTest[1]}) == ${expected}\n` + `actual: ${actual}`); });
var _curry1 = require('./internal/_curry1'); var curryN = require('./curryN'); /** * Returns a curried equivalent of the provided function. The curried * function has two unusual capabilities. First, its arguments needn't * be provided one at a time. If `f` is a ternary function and `g` is * `R.curry(f)`, the following are equivalent: * * - `g(1)(2)(3)` * - `g(1)(2, 3)` * - `g(1, 2)(3)` * - `g(1, 2, 3)` * * Secondly, the special placeholder value `R.__` may be used to specify * "gaps", allowing partial application of any combination of arguments, * regardless of their positions. If `g` is as above and `_` is `R.__`, * the following are equivalent: * * - `g(1, 2, 3)` * - `g(_, 2, 3)(1)` * - `g(_, _, 3)(1)(2)` * - `g(_, _, 3)(1, 2)` * - `g(_, 2)(1)(3)` * - `g(_, 2)(1, 3)` * - `g(_, 2)(_, 3)(1)` * * @func * @memberOf R * @category Function * @sig (* -> a) -> (* -> a) * @param {Function} fn The function to curry. * @return {Function} A new, curried function. * @see R.curryN * @example * * var addFourNumbers = function(a, b, c, d) { * return a + b + c + d; * }; * * var curriedAddFourNumbers = R.curry(addFourNumbers); * var f = curriedAddFourNumbers(1, 2); * var g = f(3); * g(4); //=> 10 */ module.exports = _curry1(function curry(fn) { return curryN(fn.length, fn); });
// @flow import React, { Component } from 'react'; import { Header, Icon, Segment } from 'semantic-ui-react'; export default class TitleBar extends Component { render() { const { icon, title, handleClose } = this.props; let { color } = this.props; if (!color) color = "blue"; let closeButton = false; if (handleClose) { closeButton = <Icon name="close" style={{ float: 'right' }} onClick={handleClose} /> } return ( <Segment color={color} clearing inverted attached data-tid="container"> {closeButton} <Header floated="left" icon={icon} content={title} /> </Segment> ); } }
/* globals jQuery, d3, document, metaStates, config, metaActions, currentComboString, loadImages, updatePreview, hideHotSpots */ "use strict"; // Create a graph, exploring all possible interaction pathways: var graph = { nodes : [], links : [] }, linkLookup = {}, visited = {}, allMetaStates = {}, allActionTypes = {}, metaStateColors = [ '#1f77b4', // d3.scale.category20, but parsed '#ff7f0e', // so that states are only '#2ca02c', // encoded with saturated colors, '#d62728', // and actions are only encoded with '#9467bd', // desaturated ones. Also rotated '#8c564b', // so that hues are less likely to be '#e377c2', // repeated between the two '#bcbd22', '#17becf'], metaActionColors = ['#c49c94', '#f7b6d2', '#dbdb8d', '#9edae5', '#aec7e8', '#ffbb78', '#98df8a', '#ff9896', '#c5b0d5']; function initialMetaActionIndices() { var indices = {}, entity, metaAction, i; for (entity in metaActions) { if (metaActions.hasOwnProperty(entity)) { indices[entity] = {}; for (metaAction in metaActions[entity]) { if (metaActions[entity].hasOwnProperty(metaAction)) { indices[entity][metaAction] = {}; for (i = 0; i < metaActions[entity][metaAction].length; i += 1) { indices[entity][metaAction][i] = 0; } } } } } return indices; } function constructGraph (config, metaStates, metaActionIndices) { var tempConfig, tempMetaStates, tempMetaActionIndices, stateTree, stateString, comboString = "", currentStateStrings = {}, currentStates = {}, actions, actionString, events, eventString, targetComboString, entity, link, metaAction, pathNum, step, edge; // Extract the current states for (stateTree in config) { if (config.hasOwnProperty(stateTree)) { stateString = config[stateTree].currentState; currentStateStrings[stateTree] = stateString; if (config[stateTree].states.hasOwnProperty(stateString) === false) { throw "Attempted to set stateTree '" + stateTree + "' to nonexistent state '" + stateString + "'"; } currentStates[stateTree] = config[stateTree].states[stateString]; comboString += stateString; } } // If we haven't been in this exact state before... if (visited.hasOwnProperty(comboString) === false) { visited[comboString] = graph.nodes.length; // ... add the graph node graph.nodes.push({ comboString : comboString, states : currentStates, stateStrings : currentStateStrings, metaStates : {} }); // ... copy our current meta states into the node for (entity in metaStates) { if (metaStates.hasOwnProperty(entity)) { graph.nodes[graph.nodes.length - 1].metaStates[entity] = metaStates[entity]; // collect all possible meta states if (allMetaStates.hasOwnProperty(entity) === false) { allMetaStates[entity] = {}; } allMetaStates[entity][metaStates[entity]] = true; } } // ... recurse for all the possible next states for (stateTree in currentStates) { if (currentStates.hasOwnProperty(stateTree)) { actions = currentStates[stateTree].actions; for (actionString in actions) { if (actions.hasOwnProperty(actionString)) { // Don't follow actions if their hotSpots aren't even visible if (actions[actionString].hotSpot.isVisible(config, metaStates) === true) { // Okay, everything in here deals with edges: link = { source : visited[comboString], target : null, metaActions : {}, actionType : actions[actionString].actionType }; // Note that we've seen this actionType allActionTypes[actions[actionString].actionType] = true; // Is this action next in any of our metaAction sequences? for (entity in metaActionIndices) { if (metaActionIndices.hasOwnProperty(entity)) { for (metaAction in metaActionIndices[entity]) { if (metaActionIndices[entity].hasOwnProperty(metaAction)) { for (pathNum in metaActionIndices[entity][metaAction]) { if (metaActionIndices[entity][metaAction].hasOwnProperty(pathNum)) { step = metaActions[entity][metaAction][pathNum][metaActionIndices[entity][metaAction][pathNum]]; if (step.stateTree === stateTree && step.state === currentStateStrings[stateTree] && step.action === actionString) { // Store info about the metaAction and some context info in the edge if (link.metaActions.hasOwnProperty(entity) === false) { link.metaActions[entity] = {}; } if (link.metaActions[entity].hasOwnProperty(metaAction) === false) { link.metaActions[entity][metaAction] = {}; } link.metaActions[entity][metaAction][pathNum] = { pathNum : pathNum, isFirst : metaActionIndices[entity][metaAction][pathNum] === 0, isLast : metaActionIndices[entity][metaAction][pathNum] >= metaActions[entity][metaAction][pathNum].length - 1 }; // Increment the step in the sequence, restart if we reach the end if (link.metaActions[entity][metaAction][pathNum].isLast === true) { metaActionIndices[entity][metaAction][pathNum] = 0; } else { metaActionIndices[entity][metaAction][pathNum] += 1; } } } } } } } } events = actions[actionString].events; for (eventString in events) { if (events.hasOwnProperty(eventString)) { // deep clone our parameters; this allows effect functions // to do anything they want to them tempConfig = jQuery.extend(true, {}, config); tempMetaStates = jQuery.extend(true, {}, metaStates); tempMetaActionIndices = jQuery.extend(true, {}, metaActionIndices); // apply the event to our clones (with a null event object) events[eventString](null, tempConfig, tempMetaStates, tempMetaActionIndices); // recurse targetComboString = constructGraph(tempConfig, tempMetaStates, tempMetaActionIndices); // we don't want self-edges, or reduntant edges that we've already created if (comboString !== targetComboString && linkLookup.hasOwnProperty(comboString + "->" + targetComboString) === false) { // clone our link, and add it to the graph edge = jQuery.extend(true, {}, link); edge.target = visited[targetComboString]; graph.links.push(edge); // add a lookup for the edge linkLookup[comboString + "->" + targetComboString] = graph.links[graph.links.length - 1]; } } } } } } } } } return comboString; } // Show the interface: function updateAll() { var images = [], actions = [], stateTree, state, action, temp; // First, remove the previous graph highlight temp = document.getElementById(currentComboString); if (temp !== null) { temp.setAttribute("class", "node"); } updatePreview(updateAll); // Highlight the relevant node in the graph temp = document.getElementById(currentComboString); if (temp !== null) { temp.setAttribute("class", "active node"); } } // Visualize the graph: // Helper functions function clickNode (d) { var stateTree; for (stateTree in d.stateStrings) { if (d.stateStrings.hasOwnProperty(stateTree)) { config[stateTree].currentState = d.stateStrings[stateTree]; } } updateAll(); } function updateGraphColors () { var colorScheme = jQuery('#graphColorScheme').val(), entity = jQuery('#graphEntities').val(), legendHeight = jQuery('#graphLegend').height() - 20, // -20 for scroll bar offset, colors, path = d3.select("#edges").selectAll("path"), node = d3.select("#nodes").selectAll("circle"), edgeLegend = [], nodeLegend = [], legendScale, state, metaAction, domain, range, i; // Set up our color scheme, and draw our legend if (colorScheme === 'actionType') { colors = d3.scale.category10(); // Prep 'No State' as grey (the others are dummy values) colors.domain(['a','b','c','d','e','f','g','No State']); edgeLegend = Object.keys(allActionTypes); legendScale = d3.scale.ordinal().domain(edgeLegend).rangePoints([0,legendHeight],1); } else { domain = ['No Meta Action','No State']; range = ['rgba(100,100,100,0.25)','#7f7f7f']; i = 0; for (state in allMetaStates[entity]) { if (allMetaStates[entity].hasOwnProperty(state)) { domain.push(state); nodeLegend.push(state); range.push(metaStateColors[i]); i += 1; if (i >= metaStateColors.length) { i = 0; } } } i = 0; for (metaAction in metaActions[entity]) { if (metaActions[entity].hasOwnProperty(metaAction)) { domain.push(metaAction); edgeLegend.push(metaAction); range.push(metaActionColors[i]); i += 1; if (i >= metaActionColors.length) { i = 0; } } } legendScale = d3.scale.ordinal().domain(edgeLegend.concat(nodeLegend)).rangePoints([0,legendHeight],1); colors = d3.scale.ordinal(10).domain(domain).range(range); } // Apply the colors path.attr("fill", function (d) { if (colorScheme === 'actionType') { return colors(d.actionType); } else { var metaAction, pathNum, foundColor = false; for (metaAction in d.metaActions[entity]) { if (d.metaActions[entity].hasOwnProperty(metaAction)) { return colors(metaAction); // TODO: encoding problem: we need to somehow encode: // 1) multiple overlapping steps for different or same (different pathNums) metaActions // 2) which step in the process this is (start, stop, intermediate) } } return colors('No Meta Action'); } }); node.attr("fill", function (d) { if (colorScheme === 'actionType' || d.metaStates.hasOwnProperty(entity) === false) { return colors('No State'); } else { return colors(d.metaStates[entity]); } }); // Redraw the legend document.getElementById('graphLegend').innerHTML = ""; var svg = d3.select("#graphLegend").append("svg") .attr("height", legendHeight) .selectAll("g"); var edges = svg.data(edgeLegend), nodes = svg.data(nodeLegend); var oneEdgeGroup = edges.enter() .append("g"); oneEdgeGroup.append("path") .attr("d" , function (d) { offset = legendScale(d); return 'M6.33301113330128,' + (10.00666937243196 + offset) + 'Q32.21052497327895,' + (14.41824348294756 + offset) + ',57.74629172573322,' + (3.83371113451292 + offset) + 'Q32.21052497327895,' + (14.41824348294756 + offset) + ',6.105179741619,' + (0.00926506646513 + offset) + 'Z'; }) .attr("fill", function (d) { return colors(d); }); oneEdgeGroup.append("text") .attr("x", 60) .attr("y", function (d) { return legendScale(d) + 12; }) .text(function (d) { return d; }) .attr("font-family", "sans-serif") .attr("font-size", "12px") .attr("fill", "black"); var oneNodeGroup = nodes.enter() .append("g"); oneNodeGroup.append("circle") .attr("cx", 10) .attr("cy", function (d) { return legendScale(d) + 8; }) .attr("r",5) .attr("fill", function (d) { return colors(d); }); oneNodeGroup.append("text") .attr("x", 25) .attr("y", function (d) { return legendScale(d) + 12; }) .text(function (d) { return d; }) .attr("font-family", "sans-serif") .attr("font-size", "12px") .attr("fill", "black"); } function centerGraph() { var graphRegion = jQuery('#graphRegion'), svg = jQuery('#graphRegion svg'); graphRegion.animate({ scrollTop : svg.height() / 2 - graphRegion.innerHeight() / 2, scrollLeft : svg.width() / 2 - graphRegion.innerWidth() / 2 }); } function initGraph() { // Set up the graph svg element var bounds = document.getElementById("configContents").getBoundingClientRect(), width, height, style, svg; if (bounds.width === 0) { return; } // I'm guessing with current styling, etc, we need 50px per node? width = graph.nodes.length * 50; height = graph.nodes.length * 50; svg = d3.select("#graphRegion") .selectAll("svg.graph") .data(["graph"]) .enter().append("svg") .attr("id", function (d) { return d; }) .attr("class", "graph") .attr("width", width) .attr("height", height); // Add the edges and nodes groups svg.append("svg:g").attr("id","edges"); svg.append("svg:g").attr("id","nodes"); // Start the layout algorithm var force = d3.layout.force() .charge(-100) .linkDistance(60) .size([width, height]) .nodes(graph.nodes) .links(graph.links) .start(); // Add the links and arrows var path = svg.select("#edges").selectAll("path") .data(force.links()); path.enter().append("svg:path") .attr("class", function (d) { var result = "link"; if (d.metaActions.length > 0) { result += " " + d.metaActions.join(" "); } return result; }); // Add the nodes var nodeRadius = 5; var node = svg.select("#nodes").selectAll("circle") .data(graph.nodes); node.enter().append("circle") .attr("id", function (d) { return d.comboString; }) .attr("r", nodeRadius) .on('dblclick', clickNode) .call(force.drag); node.attr("class", function (d) { if (d.comboString === currentComboString) { return "active node"; } else { return "node"; } }); updateGraphColors(); // Update with the algorithm force.on("tick", function () { // draw curvy, pointy arc path.attr("d", function(d) { var dx = d.target.x - d.source.x, dy = d.target.y - d.source.y, arcRadius = 10 * dx / Math.abs(dx), theta, edgePoint, front, back, arc; if (dx === 0) { if (dy >= 0) { theta = Math.PI; } else { theta = -Math.PI; } edgePoint = { x : 0, y : nodeRadius }; } else { theta = Math.atan((d.target.y - d.source.y)/(d.target.x - d.source.x)) + Math.PI / 2; edgePoint = { x : nodeRadius * Math.cos(theta), y : nodeRadius * Math.sin(theta) }; } front = { x : d.source.x + edgePoint.x, y : d.source.y + edgePoint.y }; back = { x : d.source.x - edgePoint.x, y : d.source.y - edgePoint.y }; arc = { x : (d.source.x + d.target.x) / 2 + arcRadius * Math.cos(theta), y : (d.source.y + d.target.y) / 2 + arcRadius * Math.sin(theta) }; return "M" + front.x + "," + front.y + "Q" + arc.x + "," + arc.y + "," + d.target.x + "," + d.target.y + "Q" + arc.x + "," + arc.y + "," + back.x + "," + back.y + "Z"; }); node.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; }); }); // Finally, scroll to the center of the viewport centerGraph(); } // Visualize the process matrix: function initMatrix() { // TODO: create the data by traversing the graph; // here I'm just putting it in manually for // a proof-of-concept var matrix; } function initGui() { // Handle collapsing / expanding the config panel jQuery("#collapseBar").on("click", function (event) { var panel = jQuery("#configPanel"), collapsed = panel.attr('class'); if (typeof collapsed !== typeof undefined && collapsed !== false) { panel.removeAttr('class'); jQuery("#collapseBar img").attr("src", "images/collapse.png"); } else { panel.attr("class", "collapsed"); jQuery("#collapseBar img").attr("src", "images/expand.png"); } initGraph(); initMatrix(); }); // Handle maximizing the graphContainer jQuery('#maximizeButton').on('click', function (event) { var graphContainer = jQuery('#graphContainer'); if (graphContainer.hasClass('maximized')) { graphContainer.removeClass('maximized'); jQuery('#maximizeButton').text('Fill Screen'); } else { graphContainer.addClass('maximized'); jQuery('#maximizeButton').text('Back'); } centerGraph(); }); // Populate the graph entity menu var menu = jQuery("#graphEntities"), entity; for (entity in metaActions) { if (metaActions.hasOwnProperty(entity)) { menu.append(jQuery('<option value="' + entity + '">' + entity + '</option>')); } } // Update the graph when selects are changed jQuery("#graphColorScheme").on('change', function (event) { if (event.target.value === 'actionType') { menu.prop('disabled','disabled'); } else { menu.prop('disabled', false); } updateGraphColors(); }); menu.on('change', function(event) { updateGraphColors(); }); } loadImages(); hideHotSpots(); constructGraph(jQuery.extend(true, {}, config), jQuery.extend(true, {}, metaStates), initialMetaActionIndices()); updateAll(); initGraph(); initMatrix(); initGui();
var testData = { videoSrc: "http://www.youtube.com/watch/?v=nfGV32RNkhw", expectedDuration: 151, createMedia: function( id ) { return Popcorn.HTMLYouTubeVideoElement( id ); }, // We need to test YouTube's URL params, which not all // wrappers mimic. Do it as a set of tests specific // to YouTube. playerSpecificAsyncTests: function() { asyncTest( "YouTube 01 - autoplay, loop params", 4, function() { var video = testData.createMedia( "#video" ); video.addEventListener( "loadedmetadata", function onLoadedMetadata() { video.removeEventListener( "loadedmetadata", onLoadedMetadata, false ); equal( video.autoplay, true, "autoplay is set via param" ); equal( video.loop, true, "loop is set via param" ); start(); }, false); equal( video.autoplay, false, "autoplay is initially false" ); equal( video.loop, false, "loop is initially false" ); video.src = testData.videoSrc + "&autoplay=1&loop=1"; }); }, playerSpecificSyncTests: function() { // Testing the id property inherited from MediaElementProto test( "YouTube 01 - id property accessible on wrapper object", 1, function() { var video = testData.createMedia( "#video" ); ok( video.id, "id property on wrapper object isn't null" ); }); // Testing the style property inherited from MediaElementProto test( "YouTube 02 - style property accessible on wrapper object", 1, function() { var video = testData.createMedia( "#video" ); ok( video.style, "Style property on wrapper object isn't null" ); }); test( "YouTube 03 - _canPlaySrc", 6, function() { ok( Popcorn.HTMLYouTubeVideoElement._canPlaySrc( "http://youtube.com/watch/v/6v3jsVivU6U?format=json" ), "youtube can play url in this format: http://youtube.com/watch/v/6v3jsVivU6U?format=json" ); ok( Popcorn.HTMLYouTubeVideoElement._canPlaySrc( "http://www.youtube.com/v/M3r2XDceM6A&amp;fs=1" ), "youtube can play url in this format: http://www.youtube.com/v/M3r2XDceM6A&amp;fs=1" ); ok( Popcorn.HTMLYouTubeVideoElement._canPlaySrc( "youtube.com/v/M3r2XDceM6A&fs=1" ), "youtube can play url in this format: youtube.com/v/M3r2XDceM6A&fs=1" ); ok( Popcorn.HTMLYouTubeVideoElement._canPlaySrc( "www.youtube.com/v/M3r2XDceM6A&amp;fs=1" ), "youtube can play url in this format: www.youtube.com/v/M3r2XDceM6A&amp;fs=1" ); ok( !Popcorn.HTMLYouTubeVideoElement._canPlaySrc( "http://www.youtube.com" ), "Youtube can't play http://www.youtube.com without a video id" ); ok( !Popcorn.HTMLYouTubeVideoElement._canPlaySrc( "www.youtube.com" ), "Youtube can't play www.youtube.com without a video id" ); start(); }); test( "YouTube 04 - property getters for parent style height/width", 2, function() { var video = testData.createMedia( "#video" ); equal( video.width, 360, "Returned expected parent element width" ); equal( video.height, 300, "Returned expected parent element height" ); }); asyncTest( "YouTube 05 - buffered", function() { var video = testData.createMedia( "#video" ), buffered = video.buffered; video.addEventListener( "progress", function onProgress() { var end = buffered.end( 0 ); equal( buffered.start( 0 ), 0, "video.buffered range start is always 0" ); if ( end > 0 ) { ok( true, "buffered.end( 0 ) " + end + " > 0 on progress" ); video.removeEventListener( "progress", onProgress, false ); start(); } else { ok( end >= 0, "buffered.end( 0 ): " + end + " >= 0 on progress" ); } }, false); video.src = testData.videoSrc + "&autoplay=1&loop=1"; ok( buffered && typeof buffered === "object", "video.buffered exists" ); equal( buffered.length, 1, "video.buffered.length === 1" ); equal( buffered.start( 0 ), 0, "video.buffered range start is always 0" ); equal( buffered.end( 0 ), 0, "video.buffered range end is 0" ); try { buffered.start( 1 ); ok( false, "selecting a time range > 0 should throw an error" ); } catch ( e ) { ok( e, "selecting a time range > 0 throws an error" ); } }); } }; // YouTube tends to fail when the iframes live in the qunit-fixture // div. Simulate the same effect by deleting all iframes under #video // after each test ends. var qunitStart = start; start = function() { // Give the video time to finish loading so callbacks don't throw setTimeout( function() { qunitStart(); var video = document.querySelector( "#video" ); while( video.hasChildNodes() ) { video.removeChild( video.lastChild ); } }, 500 ); };
import _extends from "@babel/runtime/helpers/esm/extends"; import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose"; import * as React from 'react'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import Collapse from '../Collapse'; import withStyles from '../styles/withStyles'; export const styles = theme => ({ /* Styles applied to the root element. */ root: { marginTop: 8, marginLeft: 12, // half icon paddingLeft: 8 + 12, // margin + half icon paddingRight: 8, borderLeft: `1px solid ${theme.palette.type === 'light' ? theme.palette.grey[400] : theme.palette.grey[600]}` }, /* Styles applied to the root element if `last={true}` (controlled by `Step`). */ last: { borderLeft: 'none' }, /* Styles applied to the Transition component. */ transition: {} }); const StepContent = /*#__PURE__*/React.forwardRef(function StepContent(props, ref) { const { // eslint-disable-next-line react/prop-types active, children, classes, className, // eslint-disable-next-line react/prop-types expanded, // eslint-disable-next-line react/prop-types last, // eslint-disable-next-line react/prop-types orientation, TransitionComponent = Collapse, transitionDuration: transitionDurationProp = 'auto', TransitionProps } = props, other = _objectWithoutPropertiesLoose(props, ["active", "alternativeLabel", "children", "classes", "className", "completed", "expanded", "last", "optional", "orientation", "TransitionComponent", "transitionDuration", "TransitionProps"]); if (process.env.NODE_ENV !== 'production') { if (orientation !== 'vertical') { console.error('Material-UI: <StepContent /> is only designed for use with the vertical stepper.'); } } let transitionDuration = transitionDurationProp; if (transitionDurationProp === 'auto' && !TransitionComponent.muiSupportAuto) { transitionDuration = undefined; } return /*#__PURE__*/React.createElement("div", _extends({ className: clsx(classes.root, className, last && classes.last), ref: ref }, other), /*#__PURE__*/React.createElement(TransitionComponent, _extends({ in: active || expanded, className: classes.transition, timeout: transitionDuration, unmountOnExit: true }, TransitionProps), children)); }); process.env.NODE_ENV !== "production" ? StepContent.propTypes = { // ----------------------------- Warning -------------------------------- // | These PropTypes are generated from the TypeScript type definitions | // | To update them edit the d.ts file and run "yarn proptypes" | // ---------------------------------------------------------------------- /** * Step content. */ children: PropTypes.node, /** * Override or extend the styles applied to the component. * See [CSS API](#css) below for more details. */ classes: PropTypes.object, /** * @ignore */ className: PropTypes.string, /** * The component used for the transition. * [Follow this guide](/components/transitions/#transitioncomponent-prop) to learn more about the requirements for this component. */ TransitionComponent: PropTypes.elementType, /** * Adjust the duration of the content expand transition. * Passed as a prop to the transition component. * * Set to 'auto' to automatically calculate transition time based on height. */ transitionDuration: PropTypes.oneOfType([PropTypes.oneOf(['auto']), PropTypes.number, PropTypes.shape({ appear: PropTypes.number, enter: PropTypes.number, exit: PropTypes.number })]), /** * Props applied to the [`Transition`](http://reactcommunity.org/react-transition-group/transition#Transition-props) element. */ TransitionProps: PropTypes.object } : void 0; export default withStyles(styles, { name: 'MuiStepContent' })(StepContent);
'use strict'; exports.__esModule = true; const Module = require('module'); const path = require('path'); // borrowed from babel-eslint function createModule(filename) { const mod = new Module(filename); mod.filename = filename; mod.paths = Module._nodeModulePaths(path.dirname(filename)); return mod; } exports.default = function moduleRequire(p) { try { // attempt to get espree relative to eslint const eslintPath = require.resolve('eslint'); const eslintModule = createModule(eslintPath); return require(Module._resolveFilename(p, eslintModule)); } catch(err) { /* ignore */ } try { // try relative to entry point return require.main.require(p); } catch(err) { /* ignore */ } // finally, try from here return require(p); };
{ "name": "g.js", "url": "https://github.com/nodebox/g.js.git" }
'use strict'; exports.__esModule = true; exports.BSNotification = undefined; var _class, _temp; var _notificationController = require('./notification-controller'); var BSNotification = exports.BSNotification = (_temp = _class = function () { function BSNotification(controller) { this.controller = controller; } BSNotification.prototype.activate = function activate(model) { this.level = model.level; this.notification = model.notification; }; return BSNotification; }(), _class.inject = [_notificationController.NotificationController], _temp);