code
stringlengths
2
1.05M
/** * Copyright (c) UNA, Inc - https://una.io * MIT License - https://opensource.org/licenses/MIT * * @defgroup Messenger Messenger * @ingroup UnaModules * @{ */ /** * Record video js file. */ function oJotVideoRecorder(oOptions) { this.bstart = oOptions.bstart || '#start-record'; this.bplay = oOptions.bplay || '#play-record'; this.bclose = oOptions.bclose || '#close-record'; this.bsend = oOptions.bsend || '#send-record'; this.video = oOptions.video || '#video'; this.title = oOptions.title || '.bx-messenger-video-recording'; this.start = oOptions.start || function(){}; this.stop = oOptions.stop || function(){}; this.send = oOptions.send || function(){}; this.close = oOptions.close || function(){}; this.oStream = null; this.oVideoBlob = null; this.oRecorder = null; this.sPopUpWrapper = '.bx-popup-wrapper'; this.sDisableButtonClass = 'bx-btn-disabled'; }; oJotVideoRecorder.prototype.InitWebCam = function() { const _this = this; try { navigator.mediaDevices.getUserMedia({ video: true, audio: true }) .then(async function (oCamera) { _this.oStream = oCamera; $(_this.video).prop('srcObject', _this.oStream); $(_this.bstart) .removeClass(_this.sDisableButtonClass) .prop('disabled', false); }); } catch(e){ alert(_t('_bx_messenger_video_record_is_not_supported', e.toString())); $(_this.bclose).click(); }; }; oJotVideoRecorder.prototype.stopWebCamAndClose = function() { if (this.oStream) this .oStream .getTracks() .forEach(function(track) { track.stop(); }); $(this.video) .parents(this.sPopUpWrapper) .dolPopupHide(); }; oJotVideoRecorder.prototype.init = function() { var _this = this; $(_this.bclose).click(function(){ if ((_this.oVideoBlob != undefined && confirm(_t('_bx_messenger_close_video_confirm'))) || !_this.oVideoBlob) { _this.stopWebCamAndClose(); _this.close(); } }); $(this.bsend).click(function() { if (_this.oVideoBlob != undefined) { _this.send(_this.oVideoBlob, function() { _this.stopWebCamAndClose(); }); } }); $(_this.video).on('loadeddata', function() { $(this) .parents(_this.sPopUpWrapper) .dolPopupCenter(); }); this.InitWebCam(); $(_this.bplay) .click( function() { var iActivePos = $(this).data('click'); switch(iActivePos) { case 1: $(this) .html('<i class="sys-icon play"></i>') .data('click', 2); $(_this.video) .trigger('pause'); break; default: $(_this.video) .trigger('play'); $(this) .removeClass('empty') .html('<i class="sys-icon pause"></i>') .data('click', 1); } }); $(_this.video) .on('ended', function(e) { $(_this.bplay) .html('<i class="sys-icon undo"></i>') .addClass('empty') .unbind() .toggle( function() { $(_this.video).trigger('play'); $(this) .removeClass('empty') .html(feather.toSvg('pause')); }, function() { $(this).html(feather.toSvg('play')); $(_this.video) .trigger('pause'); } ); }); $(_this.bstart) .click( function() { const __this = $(this); switch(__this.data('click')) { case 1: $(__this).removeClass('active'); __this .html('<i class="sys-icon circle"></i>') .data('click', 2); _this.stop(function() { var oFile = this.getBlob(); _this.stopRecording(oFile); }); break; default: $(_this.video).prop('srcObject', _this.oStream); URL.revokeObjectURL(_this.oVideoBlob); _this.start(_this.oStream); $(_this.video) .prop('muted', true) .prop('autoplay', true) .prepend('<i class="sys-icon circle"></i>'); $(_this.bplay) .html('<i class="sys-icon play"></i>') .addClass(_this.sDisableButtonClass) .prop('disabled', true) .removeClass('empty') .data('click', ''); $(_this.bsend) .addClass(_this.sDisableButtonClass) .prop('disabled', true); $(_this.title).css('display', 'flex'); __this.html('<i class="sys-icon square"></i>').data('click', 1); } }); }; oJotVideoRecorder.prototype.isMimeTypeSupported = function(mimeType){ return typeof MediaRecorder.isTypeSupported === 'function' ? MediaRecorder.isTypeSupported(mimeType) : true; }; oJotVideoRecorder.prototype.getMimeType = function(mimeType){ var mimeType = 'video/mp4\;codecs=h264'; // H264 if (this.isMimeTypeSupported(mimeType) === false) mimeType = 'video/webm'; return mimeType; }; oJotVideoRecorder.prototype.stopRecording = function(oBlob) { var _this = this; _this.oVideoBlob = oBlob || null; $(_this.title).fadeOut('slow'); $(_this.video) .height($(_this.video).height()) .width($(_this.video).width()) .prop('srcObject', null) .prop('autoplay', false) .prop('src', _this.oVideoBlob ? URL.createObjectURL(_this.oVideoBlob) : '') .prop('muted', false); $(_this.bplay) .removeClass(_this.sDisableButtonClass) .prop('disabled', false); $(_this.bsend) .removeClass(_this.sDisableButtonClass) .prop('disabled', false); };
console.log("Start Bot"); var Twit = require('twit'); var client = new Twit(require('./config')); var fs = require('fs'); var exec = require('child_process').exec; folder = require('path').dirname(require.main.filename); blender = false; // Check for the operating system if(process.platform === 'win32') { console.log('Runnning on Windows machine') } else if(process.platform === 'linux') { console.log('Running on Linux machine'); // Runs Blender in software GL mode, from // https://www.blender.org/forum/viewtopic.php?t=16526 process.env.LIBGL_ALWAYS_SOFTWARE = 1; } else { console.log('OS not supported: ' + process.platform); process.exit(); } upload(); setInterval(upload, 10000); function upload() { if(blender){ command = "blender -b -P blender_spheres.py"; cwd = 'blender_example/'; caption = "Some flying spheres"; }else{ command = "processing-java --sketch="+folder+"/processing_example --run"; cwd = 'processing_example/'; caption = "Some fancy barchart"; } pRun = exec(command, {cwd: cwd}, function(){ console.log('Image created'); var b64content = fs.readFileSync(cwd+"output.png", {encoding: 'base64'}); client.post('media/upload', { media_data: b64content }, function (err, data, response) { var mediaIdStr = data.media_id_string var altText = "Image"; var meta_params = { media_id: mediaIdStr, alt_text: { text: altText } } client.post('media/metadata/create', meta_params, function (err, data, response) { if (!err) { // now we can reference the media and post a tweet (media will attach to the tweet) client.post('statuses/update', { status: caption, media_ids: [mediaIdStr] }, function (err, data, response) { console.log("Tweeted with id : " + data.id); } ); } else { console.log(err); } }); }); }).stdout.pipe(process.stdout); }
'use strict'; /** * Module dependencies. */ var _ = require('lodash'), fs = require('fs'), path = require('path'), errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller')), mongoose = require('mongoose'), multer = require('multer'), config = require(path.resolve('./config/config')), User = mongoose.model('User'); /** * Update user details */ exports.update = function (req, res) { // Init Variables var user = req.user; // For security measurement we remove the roles from the req.body object delete req.body.roles; if (user) { // Merge existing user user = _.extend(user, req.body); user.updated = Date.now(); user.displayName = user.firstName + ' ' + user.lastName; user.save(function (err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { req.login(user, function (err) { if (err) { res.status(400).send(err); } else { res.json(user); } }); } }); } else { res.status(400).send({ message: 'User is not signed in' }); } }; /** * Send User */ exports.me = function (req, res) { res.json(req.user || null); };
import { debug, sendMessageRequest, } from '../../utils/'; import { ACTION, } from '../../constants/'; import { patchXHR } from './patch-xhr'; import { patchFetch } from './patch-fetch'; const clientLog = debug.scope('legacy'); const registrations = {}; export class LegacyClient { /** * Indicates which mode current client is running on. * * @readonly * @type {boolean} */ isLegacy = true; /** * Defines whether a client has connected to mocker server. * Resolves with `null` as there're actually no registrations * * @readonly * @type {Promise<null>} */ ready = null; /** * Points to currently activated ServiceWorker object. * Stays null when running in legacy mode. * * @readonly * @type {null} */ controller = null; _registration = null; constructor(scriptURL) { patchXHR(); patchFetch(); let promise = null; // avoid duplications if (registrations[scriptURL]) { promise = registrations[scriptURL]; } else { registrations[scriptURL] = promise = new Promise((resolve, reject) => { const script = document.createElement('script'); script.src = scriptURL; script.onload = resolve; script.onerror = reject; document.body.appendChild(script); }); } /* istanbul ignore next */ this.ready = promise .then(() => { return sendMessageRequest(window, { action: ACTION.PING, }); }) .then(() => { clientLog.info('connection established'); return this._registration; }) .catch((error) => { // `ready` should never be rejected clientLog.error('bootstrap failed', error); }); } /** * Update registration, this method has no effect in legacy mode * * @return {Promise<null>} */ async update() { return Promise.resolve(this._registration); } /** * Get current registration, resolved with `null` in legacy mode * * @return {Promise<null>} */ async getRegistration() { return Promise.resolve(this._registration); } /* istanbul ignore next */ /** * Unregister mocker, this method has no effect in legacy mode * * @return {Promise<false>} */ async unregister() { debug.scope('legacy').warn('mocker in legacy mode can\'t be unregistered'); return false; } }
(function(){ 'use strict'; var context = null; var contextReal; var width = null; var height = null; var addSnow = true; var maxSnowTheta = Math.PI*1/3; var timer; var nBranchDivisions; //var nTrees = 1; var forest = function(canvasId){ self = {}; self.init = function(){ var canvasReal = document.getElementById(canvasId), convas = document.createElement('canvas'); context = canvas.getContext("2d"); contextReal = canvas.getContext("2d"); draw(); setTimeout(function(){ canvas.classList.remove("loading"); }, 300); } function draw(){ canvas.width = window.innerWidth; canvas.height = window.innerHeight; width = canvas.width; height = canvas.height; //var ts = []; var cWidth = width < 500? width/2: 500; var nBranchDivisions = cWidth/10; // for (var i = 0; i < nTrees; i ++){ // ts[i] = tree((i+1)*width/(nTrees+1), height, -(Math.PI/2), 10, cWidth, randomSign(0.03)); // ts[i].draw(); // } var t = tree(width/2, height, -(Math.PI/2), 10, cWidth, randomSign(0.03)); t.draw(); render(); } function render(){ contextReal.drawImage(canvas, 0, 0); } return self; } var tree = function(x1I, y1I, thetaI, branchWidth0I, totalBranchLengthI,dThetaGrowMaxI){ var that = {}; var percentBranchless = 0.3, branchSizeFraction = 0.5, // dThetaGrowMax = Math.PI/36, dThetaSplitMax = Math.PI/6, oddsOfBranching = 0.3, lengthSoFar = 0, nextSectionLength; that.x1 = x1I; that.y1 = y1I; that.x2 = x1I; that.y2 = y1I; that.theta = thetaI; that.branchWidth0 = branchWidth0I; that.branchWidth = that.branchWidth0; that.totalBranchLength = totalBranchLengthI; that.dThetaGrowMax = dThetaGrowMaxI, that.draw = function(){ if (that.branchWidth < 0.7){ lengthSoFar = that.totalBranchLength; } while(lengthSoFar < that.totalBranchLength){ that.branchWidth = that.branchWidth0*(1-lengthSoFar/that.totalBranchLength); nextSectionLength = that.totalBranchLength/nBranchDivisions; lengthSoFar += nextSectionLength; that.theta += randomSign(that.dThetaGrowMax); that.x2 = that.x1 + nextSectionLength*Math.cos(that.theta); that.y2 = that.y1 + nextSectionLength*Math.sin(that.theta); context.save(); context.strokeStyle = "#000000"; context.beginPath(); context.moveTo(that.x1,that.y1); context.lineTo(that.x2,that.y2); context.lineWidth = Math.abs(that.branchWidth); context.lineCap = 'round'; context.stroke(); context.restore(); //branch out //cache variable var x3 = that.x1; var y3 = that.y1; var theta3 = that.theta+randomSign(dThetaSplitMax); var branchWidth3 = that.branchWidth; var totalBranchLength3 = that.totalBranchLength*branchSizeFraction; var dThetaGrowMax3 = Math.PI/36; if(lengthSoFar/that.totalBranchLength > percentBranchless){ if(Math.random() < oddsOfBranching){ var t3 = tree(x3, y3, theta3, branchWidth3, totalBranchLength3, dThetaGrowMax3); t3.draw(); } } // add snow addSnow(that.x1, that.y1, that.x2, that.y2, that.theta, that.branchWidth); //update cordinates that.x1 = that.x2; that.y1 = that.y2; } } function addSnow( x1, y1, x2, y2, theta, branchWidth){ //Add some snow if(addSnow){ var dx = 0, dy = 0, overlapScaling = 1.2, xs1, xs2, ys1, ys2, constrain = constrainer(0,Math.abs(branchWidth)/2); if(theta < - Math.PI/2){ if (Math.abs(Math.PI + theta) < maxSnowTheta){ var snowThickness = constrain(Math.abs(branchWidth)/2*(1-Math.abs(theta+Math.PI)/Math.PI/2)); dx = (Math.abs(branchWidth)-snowThickness)/2*Math.cos(theta+Math.PI/2)*overlapScaling; dy = (Math.abs(branchWidth)-snowThickness)/2*Math.sin(theta+Math.PI/2)*overlapScaling; xs1 = x1+dx-Math.abs(branchWidth)*Math.cos(theta)/4; ys1 = y1+dy-Math.abs(branchWidth)*Math.sin(theta)/4; xs2 = x2+dx; ys2 = y2+dy; } } if(theta > -Math.PI/2){ if(Math.abs(theta) < maxSnowTheta ){ var snowThickness = constrain(Math.abs(branchWidth)/2*(1-Math.abs(theta)/Math.PI/2)); dx = (Math.abs(branchWidth)-snowThickness)/2*Math.cos(theta-Math.PI/2)*overlapScaling; dy = (Math.abs(branchWidth)-snowThickness)/2*Math.sin(theta-Math.PI/2)*overlapScaling; xs1 = x1+dx-Math.abs(branchWidth)*Math.cos(theta)/4; ys1 = y1+dy-Math.abs(branchWidth)*Math.sin(theta)/4; xs2 = x2+dx; ys2 = y2+dy; } } context.save(); context.strokeStyle="#FFFFFF"; context.lineWidth = snowThickness; context.beginPath(); context.moveTo(xs1, ys1); context.lineTo(xs2,ys2); context.stroke(); context.restore(); } } return that; } window.forest = forest; })(); var f = forest("canvas"); f.init();
'use strict'; /* jshint ignore:start */ /** * This code was generated by * \ / _ _ _| _ _ * | (_)\/(_)(_|\/| |(/_ v1.0.0 * / / */ /* jshint ignore:end */ var _ = require('lodash'); /* jshint ignore:line */ var Holodeck = require('../../../../../../holodeck'); /* jshint ignore:line */ var Request = require( '../../../../../../../../lib/http/request'); /* jshint ignore:line */ var Response = require( '../../../../../../../../lib/http/response'); /* jshint ignore:line */ var RestException = require( '../../../../../../../../lib/base/RestException'); /* jshint ignore:line */ var Twilio = require('../../../../../../../../lib'); /* jshint ignore:line */ var client; var holodeck; describe('CredentialListMapping', function() { beforeEach(function() { holodeck = new Holodeck(); client = new Twilio('ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'AUTHTOKEN', { httpClient: holodeck }); }); it('should generate valid create request', function() { holodeck.mock(new Response(500, '{}')); var opts = { credentialListSid: 'CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' }; var promise = client.api.v2010.accounts('ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa') .sip .domains('SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa') .credentialListMappings.create(opts); promise = promise.then(function() { throw new Error('failed'); }, function(error) { expect(error.constructor).toBe(RestException.prototype.constructor); }); promise.done(); var solution = { accountSid: 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', domainSid: 'SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' }; var url = _.template('https://api.twilio.com/2010-04-01/Accounts/<%= accountSid %>/SIP/Domains/<%= domainSid %>/CredentialListMappings.json')(solution); var values = { CredentialListSid: 'CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', }; holodeck.assertHasRequest(new Request({ method: 'POST', url: url, data: values })); } ); it('should generate valid create response', function() { var body = JSON.stringify({ 'account_sid': 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'date_created': 'Wed, 11 Sep 2013 17:51:38 -0000', 'date_updated': 'Wed, 11 Sep 2013 17:51:38 -0000', 'friendly_name': 'Production Gateways IP Address - Scranton', 'sid': 'CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'subresource_uris': { 'credentials': '/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/CredentialLists/CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Credentials.json' }, 'uri': '/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/Domains/SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/CredentialLists/CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json' }); holodeck.mock(new Response(201, body)); var opts = { credentialListSid: 'CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' }; var promise = client.api.v2010.accounts('ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa') .sip .domains('SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa') .credentialListMappings.create(opts); promise = promise.then(function(response) { expect(response).toBeDefined(); }, function() { throw new Error('failed'); }); promise.done(); } ); it('should generate valid list request', function() { holodeck.mock(new Response(500, '{}')); var promise = client.api.v2010.accounts('ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa') .sip .domains('SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa') .credentialListMappings.list(); promise = promise.then(function() { throw new Error('failed'); }, function(error) { expect(error.constructor).toBe(RestException.prototype.constructor); }); promise.done(); var solution = { accountSid: 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', domainSid: 'SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' }; var url = _.template('https://api.twilio.com/2010-04-01/Accounts/<%= accountSid %>/SIP/Domains/<%= domainSid %>/CredentialListMappings.json')(solution); holodeck.assertHasRequest(new Request({ method: 'GET', url: url })); } ); it('should generate valid read_full response', function() { var body = JSON.stringify({ 'credential_list_mappings': [ { 'account_sid': 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'date_created': 'Wed, 11 Sep 2013 17:51:38 -0000', 'date_updated': 'Wed, 11 Sep 2013 17:51:38 -0000', 'friendly_name': 'Production Gateways IP Address - Scranton', 'sid': 'CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'subresource_uris': { 'credentials': '/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/CredentialLists/CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Credentials.json' }, 'uri': '/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/CredentialLists/CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json' } ], 'first_page_uri': '/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/Domains/SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/CredentialListMappings.json?PageSize=50&Page=0', 'next_page_uri': null, 'page': 0, 'page_size': 50, 'previous_page_uri': null, 'uri': '/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/Domains/SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/CredentialListMappings.json?PageSize=50&Page=0' }); holodeck.mock(new Response(200, body)); var promise = client.api.v2010.accounts('ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa') .sip .domains('SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa') .credentialListMappings.list(); promise = promise.then(function(response) { expect(response).toBeDefined(); }, function() { throw new Error('failed'); }); promise.done(); } ); it('should generate valid read_empty response', function() { var body = JSON.stringify({ 'credential_list_mappings': [], 'first_page_uri': '/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/Domains/SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/CredentialListMappings.json?PageSize=50&Page=0', 'next_page_uri': null, 'page': 0, 'page_size': 50, 'previous_page_uri': null, 'uri': '/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/Domains/SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/CredentialListMappings.json?PageSize=50&Page=0' }); holodeck.mock(new Response(200, body)); var promise = client.api.v2010.accounts('ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa') .sip .domains('SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa') .credentialListMappings.list(); promise = promise.then(function(response) { expect(response).toBeDefined(); }, function() { throw new Error('failed'); }); promise.done(); } ); it('should generate valid fetch request', function() { holodeck.mock(new Response(500, '{}')); var promise = client.api.v2010.accounts('ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa') .sip .domains('SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa') .credentialListMappings('CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa').fetch(); promise = promise.then(function() { throw new Error('failed'); }, function(error) { expect(error.constructor).toBe(RestException.prototype.constructor); }); promise.done(); var solution = { accountSid: 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', domainSid: 'SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', sid: 'CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' }; var url = _.template('https://api.twilio.com/2010-04-01/Accounts/<%= accountSid %>/SIP/Domains/<%= domainSid %>/CredentialListMappings/<%= sid %>.json')(solution); holodeck.assertHasRequest(new Request({ method: 'GET', url: url })); } ); it('should generate valid fetch response', function() { var body = JSON.stringify({ 'account_sid': 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'date_created': 'Wed, 11 Sep 2013 17:51:38 -0000', 'date_updated': 'Wed, 11 Sep 2013 17:51:38 -0000', 'friendly_name': 'Production Gateways IP Address - Scranton', 'sid': 'CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'subresource_uris': { 'credentials': '/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/CredentialLists/CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Credentials.json' }, 'uri': '/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/Domains/SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/CredentialLists/CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json' }); holodeck.mock(new Response(200, body)); var promise = client.api.v2010.accounts('ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa') .sip .domains('SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa') .credentialListMappings('CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa').fetch(); promise = promise.then(function(response) { expect(response).toBeDefined(); }, function() { throw new Error('failed'); }); promise.done(); } ); it('should generate valid remove request', function() { holodeck.mock(new Response(500, '{}')); var promise = client.api.v2010.accounts('ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa') .sip .domains('SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa') .credentialListMappings('CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa').remove(); promise = promise.then(function() { throw new Error('failed'); }, function(error) { expect(error.constructor).toBe(RestException.prototype.constructor); }); promise.done(); var solution = { accountSid: 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', domainSid: 'SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', sid: 'CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' }; var url = _.template('https://api.twilio.com/2010-04-01/Accounts/<%= accountSid %>/SIP/Domains/<%= domainSid %>/CredentialListMappings/<%= sid %>.json')(solution); holodeck.assertHasRequest(new Request({ method: 'DELETE', url: url })); } ); it('should generate valid delete response', function() { var body = JSON.stringify(null); holodeck.mock(new Response(204, body)); var promise = client.api.v2010.accounts('ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa') .sip .domains('SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa') .credentialListMappings('CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa').remove(); promise = promise.then(function(response) { expect(response).toBe(true); }, function() { throw new Error('failed'); }); promise.done(); } ); });
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global.mergeImages = factory()); }(this, (function () { 'use strict'; // Defaults var defaultOptions = { format: 'image/png', quality: 0.92, width: undefined, height: undefined, Canvas: undefined }; // Return Promise var mergeImages = function (sources, options) { if ( sources === void 0 ) sources = []; if ( options === void 0 ) options = {}; return new Promise(function (resolve) { options = Object.assign({}, defaultOptions, options); // Setup browser/Node.js specific variables var canvas = options.Canvas ? new options.Canvas() : window.document.createElement('canvas'); var Image = options.Canvas ? options.Canvas.Image : window.Image; if (options.Canvas) { options.quality *= 100; } // Load sources var images = sources.map(function (source) { return new Promise(function (resolve, reject) { // Convert sources to objects if (source.constructor.name !== 'Object') { source = { src: source }; } // Resolve source and img when loaded var img = new Image(); img.onerror = function () { return reject(new Error('Couldn\'t load image')); }; img.onload = function () { return resolve(Object.assign({}, source, { img: img })); }; img.src = source.src; }); }); // Get canvas context var ctx = canvas.getContext('2d'); // When sources have loaded resolve(Promise.all(images) .then(function (images) { // Set canvas dimensions var getSize = function (dim) { return options[dim] || Math.max.apply(Math, images.map(function (image) { return image.img[dim]; })); }; canvas.width = getSize('width'); canvas.height = getSize('height'); // Draw images to canvas images.forEach(function (image) { return ctx.drawImage(image.img, image.x || 0, image.y || 0); }); if (options.Canvas && options.format === 'image/jpeg') { // Resolve data URI for node-canvas jpeg async return new Promise(function (resolve) { canvas.toDataURL(options.format, { quality: options.quality, progressive: false }, function (err, jpeg) { if (err) { throw err; } resolve(jpeg); }); }); } // Resolve all other data URIs sync return canvas.toDataURL(options.format, options.quality); })); }); }; return mergeImages; }))); //# sourceMappingURL=index.umd.js.map
module.exports = require('./lib/qbws');
/* global hexo */ 'use strict'; hexo.extend.filter.register('theme_inject', injects => { if (injects.comment.raws.length > 1) { hexo.log.warn('It is currently not supported to launch mutli-comments systems at the same time, so stay tuned for subsequent versions of iteration.'); hexo.log.warn('Please keep one of the following.'); injects.comment.raws.forEach(element => { let commentName = element.name; // List comment system hexo.log.warn(' - ' + commentName); // Close comment system injects.postMeta.raw(commentName, '', {disableDefaultLayout: true}, {cache: true}); injects.comment.raw(commentName, '', {}, {cache: true}); injects.bodyEnd.raw(commentName, '', {}, {cache: true}); }); } }, 999);
import { defaultAction, } from '../actions'; import { DEFAULT_ACTION, } from '../constants'; describe('TrackingPage actions', () => { describe('Default Action', () => { it('has a type of DEFAULT_ACTION', () => { const expected = { type: DEFAULT_ACTION, }; expect(defaultAction()).toEqual(expected); }); }); });
'use strict'; const RuleTester = require('eslint').RuleTester; const rule = require('../../lib/rules/no-nested-tests'); const ruleTester = new RuleTester(); ruleTester.run('no-nested-tests', rule, { valid: [ 'it()', 'it(); it(); it()', 'describe("", function () { it(); })', 'describe("", function () { describe("", function () { it(); }); it(); })', { code: 'foo("", function () { it(); })', settings: { 'mocha/additionalCustomNames': [ { name: 'foo', interfaces: [ 'BDD' ] } ] } }, { code: 'foo("", function () { it(); })', settings: { mocha: { additionalCustomNames: [ { name: 'foo', type: 'suite', interfaces: [ 'BDD' ] } ] } } } ], invalid: [ { code: 'it("", function () { it() });', errors: [ { message: 'Unexpected test nested within another test.', line: 1, column: 22 } ] }, { code: 'it.only("", function () { it() });', errors: [ { message: 'Unexpected test nested within another test.', line: 1, column: 27 } ] }, { code: 'it.skip("", function () { it() });', errors: [ { message: 'Unexpected test nested within another test.', line: 1, column: 27 } ] }, { code: 'test("", function () { it() });', errors: [ { message: 'Unexpected test nested within another test.', line: 1, column: 24 } ] }, { code: 'specify("", function () { it() });', errors: [ { message: 'Unexpected test nested within another test.', line: 1, column: 27 } ] }, { code: 'it("", function () { describe() });', errors: [ { message: 'Unexpected suite nested within a test.', line: 1, column: 22 } ] }, { code: 'it("", function () { context() });', errors: [ { message: 'Unexpected suite nested within a test.', line: 1, column: 22 } ] }, { code: 'it("", function () { suite() });', errors: [ { message: 'Unexpected suite nested within a test.', line: 1, column: 22 } ] }, { code: 'it("", function () { describe.skip() });', errors: [ { message: 'Unexpected suite nested within a test.', line: 1, column: 22 } ] }, { code: 'it("", function () { describe("", function () { it(); it(); }); });', errors: [ { message: 'Unexpected suite nested within a test.', line: 1, column: 22 }, { message: 'Unexpected test nested within another test.', line: 1, column: 49 }, { message: 'Unexpected test nested within another test.', line: 1, column: 55 } ] }, { code: 'it("", function () { foo() });', settings: { 'mocha/additionalCustomNames': [ { name: 'foo', type: 'suite', interfaces: [ 'BDD' ] } ] }, errors: [ { message: 'Unexpected suite nested within a test.', line: 1, column: 22 } ] }, { code: 'it("", function () { foo() });', settings: { mocha: { additionalCustomNames: [ { name: 'foo', type: 'suite', interfaces: [ 'BDD' ] } ] } }, errors: [ { message: 'Unexpected suite nested within a test.', line: 1, column: 22 } ] }, { code: 'beforeEach(function () { it("foo", function () {}); });', errors: [ { message: 'Unexpected test nested within a test hook.', line: 1, column: 26 } ] }, { code: 'beforeEach(function () { beforeEach("foo", function () {}); });', errors: [ { message: 'Unexpected test hook nested within a test hook.', line: 1, column: 26 } ] } ] });
import { PostsList } from "../PostsList/PostsList" import { ArrowLink } from "../../shared/ArrowLink/ArrowLink" import { SharePost } from "../../posts/SharePost/SharePost" import { Footer, Container, Bio, RelatedPost, AuthorLabel, StyledProfilePicture } from "./styles" const PostFooter = ({ post }) => { return ( <Footer> <Container> <StyledProfilePicture /> <Bio> <div> <div> <AuthorLabel>Written by</AuthorLabel> <strong>Nicolas Thiry</strong> </div> <SharePost /> </div> <p> This site is my personal space where I write and share things that I enjoy working with. If you liked it and want to share some feedback, send me a message on Twitter! </p> </Bio> </Container> {post.relatedPost && ( <RelatedPost> <span>You may be interested in reading this</span> <PostsList posts={[post.relatedPost]} /> <ArrowLink href={"/posts"} as={"/posts"} label="View all writings" /> </RelatedPost> )} </Footer> ) } export { PostFooter }
var app = require('express')(), wizard = require('hmpo-form-wizard'), steps = require('./steps'), fields = require('./fields'); app.use(require('hmpo-template-mixins')(fields, { sharedTranslationKey: 'prototype' })); app.use(wizard(steps, fields, { controller: require('../../../controllers/form'), templatePath: 'prototype_oix_170821/filter-common', name: 'common' })); module.exports = app;
/** * MouseEvent * @param src * @param props * @constructor * @require System,Event,Math,Object; */ function MouseEvent( type, bubbles,cancelable ) { if( !(this instanceof MouseEvent) )return new MouseEvent(type, bubbles,cancelable); Event.call(this, type, bubbles,cancelable ); } System.MouseEvent=MouseEvent; MouseEvent.prototype=Object.create( Event.prototype ); MouseEvent.prototype.constructor=MouseEvent; MouseEvent.prototype.wheelDelta= null; MouseEvent.prototype.pageX= NaN; MouseEvent.prototype.pageY= NaN; MouseEvent.prototype.offsetX=NaN; MouseEvent.prototype.offsetY=NaN; MouseEvent.prototype.screenX= NaN; MouseEvent.prototype.screenY= NaN; MouseEvent.MOUSE_DOWN='mousedown'; MouseEvent.MOUSE_UP='mouseup'; MouseEvent.MOUSE_OVER='mouseover'; MouseEvent.MOUSE_OUT='mouseout'; MouseEvent.MOUSE_OUTSIDE='mouseoutside'; MouseEvent.MOUSE_MOVE='mousemove'; MouseEvent.MOUSE_WHEEL='mousewheel'; MouseEvent.CLICK='click'; MouseEvent.DBLCLICK='dblclick'; //鼠标事件 Event.registerEvent(function ( type , target, originalEvent ) { if( type && /^mouse|click$/i.test(type) ) { var event =new MouseEvent( type ); event.pageX= originalEvent.x || originalEvent.clientX || originalEvent.pageX; event.pageY= originalEvent.y || originalEvent.clientY || originalEvent.pageY; event.offsetX = originalEvent.offsetX; event.offsetY = originalEvent.offsetY; event.screenX= originalEvent.screenX; event.screenY= originalEvent.screenY; if( typeof event.offsetX !=='number' && target ) { event.offsetX=originalEvent.pageX-target.offsetLeft; event.offsetY=originalEvent.pageY-target.offsetTop; } if( type === MouseEvent.MOUSE_WHEEL ) { event.wheelDelta=originalEvent.wheelDelta || ( originalEvent.detail > 0 ? -originalEvent.detail : Math.abs( originalEvent.detail ) ); } return event; } }); if( System.env.platform( System.env.BROWSER_FIREFOX ) ) { Event.fix.map[ MouseEvent.MOUSE_WHEEL ] = 'DOMMouseScroll'; }
/** * Sprite.js * * HTML5游戏开发者社区 QQ群:326492427 127759656 Email:siriushtml5@gmail.com * Copyright (c) 2014 Sirius2D www.Sirius2D.com www.html5gamedev.org * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ (function() { /** * Sprite 显示容器类,只能用于嵌套MovieClip,Sprite可以互相嵌套。 * <br />演示地址:http://sirius2d.com/demos/d_4/ * @class */ ss2d.Sprite = Class ( /** @lends ss2d.Sprite.prototype */ { Extends:ss2d.Scene, m_width : 1, m_height : 1, m_scaleX : 1, m_scaleY : 1, m_skewX : 0, m_skewY : 0, m_pivotX : 0, m_pivotY : 0, m_rotation : 0, m_visible : true, m_parent : null, m_mouseEnabled : false, m_userData : null, m_center:false, m_forceCenter:false, m_quad:null, m_displayerlist:null, group:null, initialize : function() { this.init(); }, init:function() { this.m_displayerlist=[]; this.group=new ss2d.Group(); }, /** * 销毁所有元素 * dispose */ dispose : function() { this.group.dispose(); for(var i=0;i<this.m_displayerlist.length;i++) { this.removeChild(this.m_displayerlist[i]); this.m_displayerlist[i]=null; } this.m_displayerlist=null; }, /** * 添加显示对象 * add display object * @param child */ addChild:function(child) { if(child instanceof ss2d.Sprite) { this.m_displayerlist.push(child); child.group.setParentGroup(this.group); child.setParent(this); }else if(child instanceof ss2d.MovieClip) { this.m_displayerlist.push(child); this.group.addChild(child.m_quad); } }, /** * 移除显示对象 * remove display object * @param child */ removeChild:function(child) { this.m_displayerlist.splice(this.m_displayerlist.indexOf(child),1); child.group.clearParentGroup(); child.setParent(null); }, /** * 重绘 * paint */ paint : function() { for(var i=0;i < this.m_displayerlist.length;i++) { var scene = this.m_displayerlist[i]; scene.dispatchEvent(ss2d.Event.ENTER_FRAME); scene.paint(); } }, getQuadsUnderPoint : function(x, y) { var quads = null; for(var i = this.m_displayerlist.length - 1;i >= 0; i--) { quads=this.m_displayerlist[i].getQuadsUnderPoint(x,y); if(quads!=null) { return quads; } } return quads; }, /** * 获取对象的X轴位置 * get X * @returns {ss2d.Group._x|*|ss2d.Transform._x|ss2d.DisplayObject._x|number|ss2d.MovieClip._x} */ getX : function() { return this.group._x;}, /** * 设置对象的X轴位置 * set X * @param value */ setX : function(value){ this.group._x = value; this.group.isRedraw = true; }, /** * 获取对象的Y轴位置 * get Y * @returns {ss2d.Group._y|*|ss2d.Transform._y|ss2d.DisplayObject._y|number|ss2d.MovieClip._y} */ getY : function() { return this.group._y;}, /** * 设置对象Y轴位置 * set Y * @param value */ setY : function(value){ this.group._y = value; this.group.isRedraw = true; }, /** * 获取对象宽度 * get width * @returns {number|ss2d.File._width|ss2d.DisplayObject._width|ss2d.MovieClip._width|_width|*} */ getWidth : function() { return this.group.m_width;}, /** * 设置对象宽度 * set width * @param value */ setWidth : function(value){ this.group.m_width = value; this.group.isRedraw = true;}, /** * 获取对象高度 * get height * @returns {number|ss2d.File._height|ss2d.DisplayObject._height|ss2d.MovieClip._height|_height|*} */ getHeight : function() { return this.group.m_height;}, /** * 设置对象的高度 * set height * @param value */ setHeight : function(value){ this.group.m_height = value; this.group.isRedraw = true; }, /** * 获取对象的X轴比例 * get scale X * @returns {number|ss2d.Group._scaleX|ss2d.Transform._scaleX|ss2d.DisplayObject._scaleX|_scaleX|*} */ getScaleX : function() { return this.group.m_scaleX;}, /** * 设置对象的X轴比例 * set scale X * @param value */ setScaleX : function(value){ this.group.m_scaleX = value; this.group.isRedraw = true; }, /** * 获取对象的Y轴比例 * get scale Y * @returns {number|ss2d.Group._scaleY|ss2d.Transform._scaleY|ss2d.DisplayObject._scaleY|_scaleY|*} */ getScaleY : function() { return this.group.m_scaleY;}, /** * 设置对象的Y轴比例 * set scale Y * @param value */ setScaleY : function(value){ this.group.m_scaleY = value; this.group.isRedraw = true; }, /** * 获取对象的X轴倾斜值 * get skew X * @returns {number|ss2d.Group._skewX|ss2d.DisplayObject._skewX|_skewX|*} */ getSkewX : function() { return this.group.m_skewX;}, /** * 设置对象的X轴倾斜值 * set skew X * @param value */ setSkewX : function(value){ this.group.m_skewX = value; this.group.isRedraw = true; }, /** * 获取对象的Y轴倾斜值 * get skew Y * @returns {number|ss2d.Group._skewY|ss2d.DisplayObject._skewY|_skewY|*} */ getSkewY : function() { return this.group.m_skewY;}, /** * 设置对象的Y轴倾斜值 * set skew Y * @param value */ setSkewY : function(value){ this.group.m_skewY = value; this.group.isRedraw = true; }, /** * 获取对象的角度 * get angle * @returns {number|ss2d.Group._rotation|ss2d.DisplayObject._rotation|_rotation|*} */ getRotation : function() { return this.group.m_rotation;}, /** * 设置对象的角度 * set angle * @param value */ setRotation : function(value){ this.group.m_rotation = value; this.group.isRedraw = true; }, /** * 获取对象的可见性 * get visibility * @returns {boolean} */ getVisible : function() { return this.m_visible;}, /** * 设置对象的可见性 * set visibility * @param value */ setVisible : function(value){ this.m_visible = value;}, /** * 获取对象的上级 * get parent * @returns {null} */ getParent : function() { return this.m_parent;}, /** * 设置对象的上级 * set parent * @param value */ setParent : function(value){ this.m_parent = value; }, /** * 获取对象的鼠标监测状态 * get a boolean value that indicates whether the mouse event is listened * @returns {boolean} */ getMouseEnabled : function() { return this.m_mouseEnabled;}, /** * 设置对象的鼠标监测状态 * set a boolean value that indicates whether the mouse event is listened * @param value */ setMouseEnabled : function(value){ this.m_mouseEnabled = value; }, /** * 存储用户数据 * get user data * @returns {null} */ getUserData : function() { return this.m_userData;}, /** * 设置用户零时数据 * set user data * @param value */ setUserData : function(value){ this.m_userData = value; } } ); })();
var app = require('express')(); var server = require('http').Server(app); var io = require('socket.io')(server); var redis = require('redis'); server.listen(8080, function () { console.log('Tiny server is running...'); }); io.on('connection', function (socket) { console.log('New client connected...'); var client = redis.createClient(); client.subscribe('message'); client.on('message', function(channel, message) { var msg = JSON.parse(message); console.log('New message in queue ' + channel + '/' + msg.event); console.log('Data to send: ' + message); socket.emit(channel + '/' + msg.event, msg.data); }); socket.on('disconnect', function() { client.quit(); console.log('...client disconnected.'); }); });
module.exports = function(str) { //var regex = /"[a-z\s]*"/g; var regex = /"[^"]*"/g; return str.match(regex); };
'use strict'; import ReactDOM from 'react-dom'; import classNames from 'classnames'; import getScrollbarWidth from '../utils/getScrollbarWidth'; import CSSCore from '../utils/CSSCore'; module.exports = { setDimmerContainer: function () { let container = (this.props.container && ReactDOM.findDOMNode(this.props.container)) || document.body; let bodyPaddingRight = parseInt((container.style.paddingRight || 0), 10); let barWidth = getScrollbarWidth(); if (barWidth) { container.style.paddingRight = bodyPaddingRight + barWidth + 'px'; } CSSCore.addClass(container, this.setClassNamespace('dimmer-active')); }, resetDimmerContainer: function () { let container = (this.props.container && ReactDOM.findDOMNode(this.props.container)) || document.body; CSSCore.removeClass(container, this.setClassNamespace('dimmer-active')); container.style.paddingRight = ''; }, renderDimmer: function (children) { let onClick = this.handleDimmerClick || null; let classSet = {}; classSet[this.setClassNamespace('dimmer')] = true; classSet[this.setClassNamespace('active')] = true; return ( <div> <div onClick={onClick} ref="dimmer" style={{display: 'block'}} className={classNames(classSet)}></div> {children} </div> ); }, };
Array.prototype.removeDuplicates = function() { return this.filter((element, index, array) => array.indexOf(element) == index); };
/* globals $, _ */ var Plumage = require('PlumageRoot'); var Field = require('view/form/fields/Field'); var Select = require('view/form/fields/Select'); module.exports = Plumage.view.form.fields.CategorySelect = Select.extend({ className: 'category-select field', template: require('view/form/fields/templates/CategorySelect.html'), listValueAttr: 'name', listLabelAttr: 'label', modelAttr: 'filter', noSelectionText: 'All', noSelectionValue: '', events:{ 'click a': 'onItemClick' }, initialize: function() { Select.prototype.initialize.apply(this, arguments); }, setModel: function() { Select.prototype.setModel.apply(this, arguments); }, /** * Overrides */ onListModelLoad: function(model, options) { this.render(); }, update: function() { this.render(); }, onItemClick: function(e) { e.preventDefault(); var li = $(e.target).closest('li'), value = li && li.data('value'); if (!this.isValueDisabled(value)) { this.setValue(value); } }, getItemData: function(item) { return Select.prototype.getItemData.apply(this, arguments); } });
import { namespace, whitespaceChecker } from "../../utils"; import { utils } from "stylelint"; import { variableColonSpaceChecker } from "../dollar-variable-colon-space-after"; export const ruleName = namespace("dollar-variable-colon-space-before"); export const messages = utils.ruleMessages(ruleName, { expectedBefore: () => 'Expected single space before ":"', rejectedBefore: () => 'Unexpected whitespace before ":"' }); export default function(expectation, _, context) { const checker = whitespaceChecker("space", expectation, messages); return (root, result) => { const validOptions = utils.validateOptions(result, ruleName, { actual: expectation, possible: ["always", "never"] }); if (!validOptions) { return; } variableColonSpaceChecker({ root, result, locationChecker: checker.before, checkedRuleName: ruleName, position: "before", expectation, context }); }; }
const mongoose = require('mongoose'); mongoose.Promise = global.Promise; mongoose.connect(process.env.MONGODB_URL); module.exports={ mongoose }
(function() {var implementors = {}; implementors["growable"] = [{"text":"impl&lt;T:&nbsp;?<a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/marker/trait.Sized.html\" title=\"trait core::marker::Sized\">Sized</a>&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/ops/deref/trait.Deref.html\" title=\"trait core::ops::deref::Deref\">Deref</a> for <a class=\"struct\" href=\"growable/struct.Reusable.html\" title=\"struct growable::Reusable\">Reusable</a>&lt;T&gt;","synthetic":false,"types":["growable::Reusable"]}]; if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})()
import { PureComponent } from 'react' import PropTypes from 'prop-types' import autobind from 'autobind-decorator' import { GMAP_EVENTS } from './utils/const' import { setupEvents, removeEvent } from './utils/mapEventHelpers' const enableControls = (enable = true) => ({ draggable: enable, zoomControl: enable, scrollwheel: enable, disableDoubleClickZoom: enable, }) export default class FreeDrawLayer extends PureComponent { static propTypes = { map: PropTypes.object, enabled: PropTypes.bool, onDrawBegin: PropTypes.func, onDrawEnd: PropTypes.func, shapes: PropTypes.object, dataStyle: PropTypes.object, mapControls: PropTypes.object, } static defaultProps = { shapes: {}, dataStyle: {}, } componentDidMount() { this.enabled = false this.addShapes() if (this.props.enabled) this.enableDraw() } componentWillReceiveProps(nextProps) { const { enabled } = nextProps if (this.enabled !== enabled) { enabled ? this.enableDraw() : this.disableDraw() // eslint-disable-line no-unused-expressions } } componentDidUpdate(prevProps) { if (this.props.shapes !== prevProps.shapes) { this.clearAllShapes() this.addShapes() } } getPolygonCoords(poly) { return poly && poly.getPath().getArray().map(path => [path.lng(), path.lat()]) } enableMapControls() { const { map, mapControls } = this.props map.setOptions({ ...enableControls(true), ...mapControls, }) } disableMapControls() { const { map } = this.props map.setOptions(enableControls(false)) } enableDraw() { this.enabled = true this.disableMapControls() this.clearAllShapes() this.drawFreeHand() } @autobind handleMouseUp() { this.mouseDown = false const polygonCoords = this.getPolygonCoords(this.polygon) if (polygonCoords.length) this.finishDraw(polygonCoords) this.endDraw() this.drawFreeHand() } finishDraw(polygonCoords) { if (this.enabled) { const { onDrawEnd } = this.props if (onDrawEnd) onDrawEnd(polygonCoords) } } endDraw() { if (this.events) { Object.keys(this.events).forEach(name => { removeEvent(this.events[name]) }) } if (this.polyline) this.polyline.setMap(null) if (this.polygon) this.polygon.setMap(null) } disableDraw() { this.endDraw() this.enableMapControls() this.enabled = false } createPolyline() { const { map, dataStyle } = this.props return new window.google.maps.Polyline({ map, clickable: false, ...dataStyle.polyline, }) } createPolygon(polyline, attributes) { return new window.google.maps.Polygon({ map: this.props.map, path: polyline, clickable: false, ...attributes, }) } drawFreeHand() { const { map, dataStyle, onDrawBegin, } = this.props this.polyline = this.createPolyline() this.polygon = this.createPolygon(this.polyline.getPath(), dataStyle.polylineFill) if (onDrawBegin) onDrawBegin() this.events = { ...setupEvents(map, GMAP_EVENTS, { onMouseDown: this.handleMouseDown, onTouchStart: this.handleMouseDown, onMouseMove: this.handleMouseMove, onTouchMove: this.handleMouseMove, onMouseUp: this.handleMouseUp, onTouchEnd: this.handleMouseUp, }, false), } } @autobind handleMouseDown() { this.mouseDown = true } @autobind handleMouseMove(e) { if (this.mouseDown) { this.polyline.getPath().push(e.latLng) } } addShapes() { const { polyline, polygon } = this.props.dataStyle const shapes = this.formatLongLatToGmapsCoordinates() this.polygons = shapes.map(path => ( this.createPolygon(path, { ...polyline, ...polygon }) )) } clearAllShapes() { this.polygons.forEach(poly => poly.setMap(null)) this.polygons = [] } formatLongLatToGmapsCoordinates() { // Should be refactored later to // over(pipe(allArr, allArr), point => ({lat: point[1], lng: point[0]})(Object.values(shape) return Object.values(this.props.shapes).map(polygon => ( polygon.map(point => ({ lat: point[1], lng: point[0] })) )) } render() { return null } }
function demo() { multiConnection(); } function multiConnection() { var node_button = LiteGraph.createNode("widget/button"); node_button.pos = [100,400]; graph.add(node_button); var node_console = LiteGraph.createNode("basic/console"); node_console.pos = [400,400]; graph.add(node_console); node_button.connect(0, node_console ); var node_const_A = LiteGraph.createNode("basic/const"); node_const_A.pos = [200,200]; graph.add(node_const_A); node_const_A.setValue(4.5); var node_const_B = LiteGraph.createNode("basic/const"); node_const_B.pos = [200,300]; graph.add(node_const_B); node_const_B.setValue(10); var node_math = LiteGraph.createNode("math/operation"); node_math.pos = [400,200]; graph.add(node_math); var node_watch = LiteGraph.createNode("basic/watch"); node_watch.pos = [700,200]; graph.add(node_watch); var node_watch2 = LiteGraph.createNode("basic/watch"); node_watch2.pos = [700,300]; graph.add(node_watch2); node_const_A.connect(0,node_math,0 ); node_const_B.connect(0,node_math,1 ); node_math.connect(0,node_watch,0 ); node_math.connect(0,node_watch2,0 ); } function sortTest() { var rand = LiteGraph.createNode("math/rand",null, {pos: [10,100] }); graph.add(rand); var nodes = []; for(var i = 4; i >= 1; i--) { var n = LiteGraph.createNode("basic/watch",null, {pos: [i * 120,100] }); graph.add(n); nodes[i-1] = n; } rand.connect(0, nodes[0], 0); for(var i = 0; i < nodes.length - 1; i++) nodes[i].connect(0,nodes[i+1], 0); } function benchmark() { var num_nodes = 200; var nodes = []; for(var i = 0; i < num_nodes; i++) { var n = LiteGraph.createNode("basic/watch",null, {pos: [(2000 * Math.random())|0, (2000 * Math.random())|0] }); graph.add(n); nodes.push(n); } for(var i = 0; i < nodes.length; i++) nodes[ (Math.random() * nodes.length)|0 ].connect(0, nodes[ (Math.random() * nodes.length)|0 ], 0 ); } //Show value inside the debug console function TestWidgetsNode() { this.addOutput("","number"); this.properties = {}; var that = this; this.slider = this.addWidget("slider","Slider", 0.5, function(v){}, { min: 0, max: 1} ); this.number = this.addWidget("number","Number", 0.5, function(v){}, { min: 0, max: 100} ); this.combo = this.addWidget("combo","Combo", "red", function(v){}, { values:["red","green","blue"]} ); this.text = this.addWidget("text","Text", "edit me", function(v){}, {} ); this.text2 = this.addWidget("text","Text", "multiline", function(v){}, { multiline:true } ); this.toggle = this.addWidget("toggle","Toggle", true, function(v){}, { on: "enabled", off:"disabled"} ); this.button = this.addWidget("button","Button", null, function(v){}, {} ); this.toggle2 = this.addWidget("toggle","Disabled", true, function(v){}, { on: "enabled", off:"disabled"} ); this.toggle2.disabled = true; this.size = this.computeSize(); this.serialize_widgets = true; } TestWidgetsNode.title = "Widgets"; LiteGraph.registerNodeType("features/widgets", TestWidgetsNode ); //Show value inside the debug console function TestSpecialNode() { this.addInput("","number"); this.addOutput("","number"); this.properties = {}; var that = this; this.size = this.computeSize(); this.enabled = false; this.visible = false; } TestSpecialNode.title = "Custom Shapes"; TestSpecialNode.title_mode = LiteGraph.TRANSPARENT_TITLE; TestSpecialNode.slot_start_y = 20; TestSpecialNode.prototype.onDrawBackground = function(ctx) { if(this.flags.collapsed) return; ctx.fillStyle = "#555"; ctx.fillRect(0,0,this.size[0],20); if(this.enabled) { ctx.fillStyle = "#AFB"; ctx.beginPath(); ctx.moveTo(this.size[0]-20,0); ctx.lineTo(this.size[0]-25,20); ctx.lineTo(this.size[0],20); ctx.lineTo(this.size[0],0); ctx.fill(); } if(this.visible) { ctx.fillStyle = "#ABF"; ctx.beginPath(); ctx.moveTo(this.size[0]-40,0); ctx.lineTo(this.size[0]-45,20); ctx.lineTo(this.size[0]-25,20); ctx.lineTo(this.size[0]-20,0); ctx.fill(); } ctx.strokeStyle = "#333"; ctx.beginPath(); ctx.moveTo(0,20); ctx.lineTo(this.size[0]+1,20); ctx.moveTo(this.size[0]-20,0); ctx.lineTo(this.size[0]-25,20); ctx.moveTo(this.size[0]-40,0); ctx.lineTo(this.size[0]-45,20); ctx.stroke(); if( this.mouseOver ) { ctx.fillStyle = "#AAA"; ctx.fillText( "Example of helper", 0, this.size[1] + 14 ); } } TestSpecialNode.prototype.onMouseDown = function(e, pos) { if(pos[1] > 20) return; if( pos[0] > this.size[0] - 20) this.enabled = !this.enabled; else if( pos[0] > this.size[0] - 40) this.visible = !this.visible; } TestSpecialNode.prototype.onBounding = function(rect) { if(!this.flags.collapsed && this.mouseOver ) rect[3] = this.size[1] + 20; } LiteGraph.registerNodeType("features/shape", TestSpecialNode ); //Show value inside the debug console function TestSlotsNode() { this.addInput("C","number"); this.addOutput("A","number"); this.addOutput("B","number"); this.horizontal = true; this.size = [100,40]; } TestSlotsNode.title = "Flat Slots"; LiteGraph.registerNodeType("features/slots", TestSlotsNode ); //Show value inside the debug console function TestPropertyEditorsNode() { this.properties = { name: "foo", age: 10, alive: true, children: ["John","Emily","Charles"], skills: { speed: 10, dexterity: 100 } } var that = this; this.addWidget("button","Log",null,function(){ console.log(that.properties); }); } TestPropertyEditorsNode.title = "Properties"; LiteGraph.registerNodeType("features/properties_editor", TestPropertyEditorsNode );
__history = [{"date":"Fri, 12 Jul 2013 08:56:49 GMT","sloc":28,"lloc":26,"functions":4,"deliveredBugs":0.36255791263629855,"maintainability":69.84781893414903,"lintErrors":4,"difficulty":14.57142857142857}]
/** * @file 检查版本更新 * @author zqyadam(zqyadam@qq.com) */ /* eslint-disable no-console */ 'use strict'; const chalk = require('chalk'); const semver = require('semver'); const packageConfig = require('../package.json'); const shell = require('shelljs'); function exec(cmd) { return require('child_process').execSync(cmd).toString().trim(); } let versionRequirements = [ { name: 'node', currentVersion: semver.clean(process.version), versionRequirement: packageConfig.engines.node } ]; if (shell.which('npm')) { versionRequirements.push({ name: 'npm', currentVersion: exec('npm --version'), versionRequirement: packageConfig.engines.npm }); } module.exports = function () { let warnings = []; for (let i = 0, len = versionRequirements.length; i < len; i++) { let mod = versionRequirements[i]; if (!semver.satisfies(mod.currentVersion, mod.versionRequirement)) { warnings.push(mod.name + ': ' + chalk.red(mod.currentVersion) + ' should be ' + chalk.green(mod.versionRequirement) ); } } if (warnings.length) { console.log(chalk.yellow('\nTo use this template, you must update following to modules:\n')); warnings.forEach(function (warning) { console.log(' ' + warning); }); process.exit(1); } };
var Spritesheet = (function () { //Here is where you should put all your rendering code, which will be private //This canvas will be used as a buffer to store the image off-screen var buffercanvas = document.createElement("canvas"); buffercanvas.width = 1366; buffercanvas.height = 768; var buffer_w = 1366, buffer_h = 768; //The context of the screen buffer //Everything should be written here //The 'real' context will only be modified when copying the buffer to the screen var context = buffercanvas.getContext('2d'); //Here the 'real' canvas and context will be stored var canvas, realcontext; var workingFolder = ""; var paused = false; //Whether the animation is paused //The camera allows to move the view without moving the individual sprites var camera = { x: 0, y: 0 }; //Here we store the list of spritesheets var spritesheets = []; //Here we store the list of objects var objects = []; //This array is used to store the rendering order specified by the zindex of each object var objectsorder = []; //This variable stores the frames per second var fps; //This is the default rendermode, it just scales the buffer and prints it on the canvas var rendermode_default = function (contextinput, contextoutput) { contextoutput.clearRect(0, 0, contextoutput.canvas.width, contextoutput.canvas.height); contextoutput.drawImage(contextinput.canvas, 0, (contextoutput.canvas.height - contextinput.canvas.height * contextoutput.canvas.width / contextinput.canvas.width) / 2, contextoutput.canvas.width, (contextinput.canvas.height * contextoutput.canvas.width / contextinput.canvas.width)); }; //It makes sense to set rendermode_default as the default rendermode! var rendermode = rendermode_default; var debugMode = false; var debugMessagesCache = []; var debugHandler = function (x) { debugMessagesCache.push(x); }; //Holds the spritesheet: Player, enemy1... function spritesheet() { this.name = ""; this.img; this.states = []; this.layers = []; this.frames = []; } //Holds a 'state': Idle, jumping... function state() { this.name = "Name"; this.layers = []; } //Holds a layer: Body, arms... function layer() { this.frames = []; this.x; this.y; this.t = 0; } //Holds a single frame function frame(x, y, w, h, t) { this.x = x; this.y = y; this.w = w; this.h = h; this.t = t; } //This function is executed as many times per second as possible (using requestAnimationFrame) //It renders all the objects on the buffer //And then it copies it to the screen using the rendermode function renderdraw() { if (!objectsProcessed) { return; //TODO: See if this really affects perf } if (zIndexNeedsSorting) {//If the zindex is not updated, sort it sortZindex(); } //First we clear the context context.clearRect(0, 0, buffercanvas.width, buffercanvas.height); //In case it was modified before, we reset the alpha //For each object for (var i = 0; i < objectsorder.length; i++) { context.globalAlpha = 1; //We get the object in that position acoording to the zindex var object = objects[objectsorder[i].v]; //We get its spritesheet var spritesheet = object.spritesheet; var state = spritesheet.states[0]; //We get the current state if (object.state != undefined) { state = object.state; } //We loop over the layers of its current state for (var j in state.layers) { //We get the data corresponding to that layer var layer_n = state.layers[j]; var layer = spritesheet.layers[layer_n]; if (object.hiddenLayers[layer.name] == true) { continue; } //We calculate which frame should be drawn //We set k to the first frame of the layer //And we add the duration of the frames until we reach current t var tempt = 0, k = 0; var substractFlag = false; while (tempt < superModulo(object.t, layer.t)) { substractFlag = true; var thisframe = spritesheet.frames[layer.frames[k]]; //If the duration of a frame is set to 0 it stops there if (thisframe.t == 0) { substractFlag = false; break; } k++; //If we have reached exactly the end of the animation we set the first frame if (k == layer.frames.length) { break; } //We add the duration of this frame to the counter tempt += thisframe.t; } k = substractFlag ? k - 1 : k; //We finally have the frame that must be drawn var frame = spritesheet.frames[layer.frames[k]]; //If it is a full texture frame, set the appropiate x,y,w,h if (frame.fullTexture) { frame.x = frame.y = 0; var img = object.img || spritesheet.img; frame.w = img.width; frame.h = img.height; } //If the object is static we dont take into account camera movements if (object.isstatic == true) { var xposition = (+layer.x(object.t, object.vars)) + (+object.x); var yposition = (+layer.y(object.t, object.vars)) + (+object.y); } else { var xposition = (+layer.x(object.t, object.vars)) + (+object.x) - camera.x; var yposition = (+layer.y(object.t, object.vars)) + (+object.y) - camera.y; } //Maybe the image must be flipped in some axis var flipoffsetx = 0; var flipoffsety = 0; switch (state.flip) { case 1: context.save(); flipoffsetx = -2 * xposition - frame.w; context.scale(-1, 1); break; case 2: context.save(); flipoffsety = -2 * yposition - frame.h; context.scale(1, -1); break; case 3: context.save(); flipoffsetx = -2 * xposition - frame.w; flipoffsety = -2 * yposition - frame.h; context.scale(-1, -1); break; default: break; } if (frame.code == undefined) { //If it is a frame from a file we draw it on the buffer if (debugMode) { try { context.drawImage(object.img || spritesheet.img, frame.x, frame.y, frame.w, frame.h, xposition + flipoffsetx, yposition + flipoffsety, frame.w, frame.h); } catch (e) { debugHandler("Exception drawing frame " + frame.name + " of " + spritesheet.name + " : Maybe the image path is wrong or the coordinates step outside the image."); } } else { context.drawImage(object.img || spritesheet.img, frame.x, frame.y, frame.w, frame.h, xposition + flipoffsetx, yposition + flipoffsety, frame.w, frame.h); } //If we flipped before then we restore everything switch (state.flip) { case 1: case 2: case 3: context.restore(); break; default: break; } } else { //Code shouldnt flip?s switch (state.flip) { case 1: case 2: case 3: context.restore(); break; default: break; } //If it is a 'custom' frame, we execute the code if (debugMode) { try { frame.code(xposition, yposition, object.t, context, object.vars); } catch (e) { debugHandler("Exception executing frame " + frame.name + " of " + spritesheet.name + " : " + e.message); } } else { frame.code(xposition, yposition, object.t, context, object.vars); } } //If we flipped before then we restore everything switch (state.flip) { case 1: case 2: case 3: context.restore(); break; default: break; } } } //Finally we draw the buffer on the screen rendermode(context, realcontext); objectsProcessed = false; } //This function is executed as many times as the fps specify //It just increments each object timer if needed function renderprocess() { for (var i = 0; i < objects.length; i++) { if (objectsorder[i] == undefined) { break; } var object = objects[objectsorder[i].v]; if (!object) { continue; } if (object.pause != true) { object.t += 1000 / fps; var spritesheet = object.spritesheet; var state = object.state; if (object.t > state.totalduration) { if (object.callback) { object.callback(); object.callback = undefined; } } } } objectsProcessed = true; } //This function sorts the objects according to its z index function sortZindex() { var objectIndexes = []; for (var i = 0; i < objectsInScope.length; i++) { if (objects[objectsInScope[i]] != null) { objectIndexes.push(objectsInScope[i]); } } objectsorder = sortingCriteria(objectIndexes); } var sortingCriteria = function (values) { var objectsorder = []; for (var i = 0; i < values.length; i++) { var ob = objects[values[i]]; objectsorder.push({ v: values[i], z: ob.zindex, x: ob.x, y: ob.y }); } return objectsorder.sort(function (a, b) { if (a.z != b.z) { return a.z - b.z; //Draw from back to front } else if (a.y != b.y) { return a.y - b.y; //From down to up } else { return a.x - b.x;//From left to right } }); }; function updateObjectState(object) { object.spritesheet = searchWhere(spritesheets, "name", object.spritesheetName); object.state = searchWhere(object.spritesheet.states, "name", object.stateName) || object.spritesheet.states[0] } function superModulo(a, b) { if (a >= 0) { return a % b; } else { return b + a % b; } } function findwhere(array, property, value) { for (var i = 0; i < array.length; i++) { if (array[i][property] == value) { return i; } } return -1; } function getlayerduration(layer, spritesheet) { var d = 0; for (var i = 0; i < layer.frames.length; i++) { d += spritesheet.frames[layer.frames[i]].t; if (spritesheet.frames[layer.frames[i]].t == 0) { d += Infinity; //If i dont do this the modulo may reset before reaching the t=0 layer } } return d; } function searchWhere(array, key, value) { for (var i = 0; i < array.length; i++) { if (array[i][key] == value) { return array[i]; } } return null; } //Grid rendering optimization logic //Flag no indicate if the annimation has been processed since the last draw var objectsProcessed = true; //This is the quad tree used to decide which objects are in the screen var quadtree = []; var readQuadtree = function (x, y) { if (quadtree[x] && quadtree[x][y]) { return quadtree[x][y]; } else { return null; } } var addQuadtree = function (x, y, element) { if (quadtree[x]) { if (quadtree[x][y]) { } else { quadtree[x][y] = []; } } else { quadtree[x] = []; quadtree[x][y] = []; } quadtree[x][y].push(element); } var removeQuadtree = function (x, y, element) { if (quadtree[x] && quadtree[x][y]) { var index = quadtree[x][y].indexOf(element); if (index >= 0) { quadtree[x][y].splice(index, 1); } } } var quadtreeWidth, quadtreeHeight; quadtreeWidth = buffercanvas.width / 2; quadtreeHeight = buffercanvas.height / 2; var getQuadtreeCoordinate = function (x) { return Math.floor(x / quadtreeWidth); } var moveQuadtreeObject = function (element, oldx, oldy, newx, newy) { var bounds = objects[element].bounds; if (bounds == null) { moveQuadtreeObjectPosition(element, oldx, oldy, newx, newy); } else { var oldxc = getQuadtreeCoordinate(oldx); var oldyc = getQuadtreeCoordinate(oldy); var newxc = getQuadtreeCoordinate(newx); var newyc = getQuadtreeCoordinate(newy); moveQuadtreeObjectCoordinates(element, oldxc, oldyc, newxc, newyc); var startx = getQuadtreeCoordinate(newx - bounds.w); var endx = getQuadtreeCoordinate(newx + bounds.w); var starty = getQuadtreeCoordinate(newy - bounds.h); var endy = getQuadtreeCoordinate(newy + bounds.h); if (oldxc != newxc || oldyc != newyc) { for (var i = startx; i <= endx; i++) { for (var j = starty; j <= endy; j++) { moveQuadtreeObjectCoordinatesIfDifferent(element, oldxc, oldyc, newxc, newyc, oldxc + (i - newxc), oldyc + (j - newyc), i, j); } } } } } var moveQuadtreeObjectPosition = function (element, oldx, oldy, newx, newy) { var oldxc = getQuadtreeCoordinate(oldx); var oldyc = getQuadtreeCoordinate(oldy); var newxc = getQuadtreeCoordinate(newx); var newyc = getQuadtreeCoordinate(newy); if (oldxc == newxc && oldyc == newyc) { return; } removeQuadtree(oldxc, oldyc, element); addQuadtree(newxc, newyc, element); } var moveQuadtreeObjectCoordinates = function (element, oldxc, oldyc, newxc, newyc) { if (oldxc == newxc && oldyc == newyc) { return; } removeQuadtree(oldxc, oldyc, element); addQuadtree(newxc, newyc, element); } var moveQuadtreeObjectPositionIfDifferent = function (element, oldxc1, oldyc1, newxc1, newyc1, oldx, oldy, newx, newy) { var oldxc = getQuadtreeCoordinate(oldx); var oldyc = getQuadtreeCoordinate(oldy); var newxc = getQuadtreeCoordinate(newx); var newyc = getQuadtreeCoordinate(newy); if (oldxc == newxc && oldyc == newyc) { return; } if (oldxc != oldxc1 || oldyc != oldyc1) { removeQuadtree(oldxc, oldyc, element); } if (newxc != newxc1 || newyc != newyc1) { addQuadtree(newxc, newyc, element); } } var moveQuadtreeObjectCoordinatesIfDifferent = function (element, oldxc1, oldyc1, newxc1, newyc1, oldxc, oldyc, newxc, newyc) { if (oldxc != oldxc1 || oldyc != oldyc1) { removeQuadtree(oldxc, oldyc, element); } if (newxc != newxc1 || newyc != newyc1) { addQuadtree(newxc, newyc, element); } } //Objects that might be seen by the camera var objectsInScope = []; //Static objects are always shown var staticObjects = []; function updateScope(x, y) { // 1 | 2 | 3 // | | //---------------------------------------- // | | // 4 | 5 | 6 // | (camera) | //---------------------------------------- // | | // 7 | 8 | 8 var area1 = readQuadtree(getQuadtreeCoordinate(x) - 1, getQuadtreeCoordinate(y) - 1) || []; var area2 = readQuadtree(getQuadtreeCoordinate(x), getQuadtreeCoordinate(y) - 1) || []; var area3 = readQuadtree(getQuadtreeCoordinate(x) + 1, getQuadtreeCoordinate(y) - 1) || []; var area4 = readQuadtree(getQuadtreeCoordinate(x) - 1, getQuadtreeCoordinate(y)) || []; var area5 = readQuadtree(getQuadtreeCoordinate(x), getQuadtreeCoordinate(y)) || []; var area6 = readQuadtree(getQuadtreeCoordinate(x) + 1, getQuadtreeCoordinate(y)) || []; var area7 = readQuadtree(getQuadtreeCoordinate(x) - 1, getQuadtreeCoordinate(y) + 1) || []; var area8 = readQuadtree(getQuadtreeCoordinate(x), getQuadtreeCoordinate(y) + 1) || []; var area9 = readQuadtree(getQuadtreeCoordinate(x) + 1, getQuadtreeCoordinate(y) + 1) || []; objectsInScope = [].concatUnique(area1).concatUnique(area2).concatUnique(area3).concatUnique(area4).concatUnique(area5).concatUnique(area6).concatUnique(area7).concatUnique(area8).concatUnique(area9).concatUnique(staticObjects); } Object.defineProperty(Array.prototype, 'concatUnique', { value: function (b) { for (i = 0; i < b.length; i++) { if (this.indexOf(b[i]) < 0) { this.push(b[i]); } } return this; }, configurable: true }); var zIndexNeedsSorting = false; function getObjectBounds(object) { var bounds = { w: 0, h: 0 }; var spritesheet = object.spritesheet; for (var i in spritesheet.frames) { var frame = spritesheet.frames[i]; //If it is a full texture frame, set the appropiate w.h if (frame.fullTexture) { var img = object.img || spritesheet.img; frame.w = img.width; frame.h = img.height; } //Maybe the image must be flipped in some axis, we are going to make the worst assumption if (frame.code == undefined) { if (bounds.w < frame.w) { bounds.w = frame.w; } if (bounds.h < frame.h) { bounds.h = frame.h; } } } return bounds; } //And these are the public functions that the engine will use to talk to your library return { setUp: function (mycanvas, nfps) { //This function receives a reference to a canvaselement and the number of fps requested canvas = mycanvas; realcontext = canvas.getContext('2d'); //We loop renderprocess and renderdraw var msPerFrame = 1000 / nfps; var lastTime = performance.now(); requestAnimationFrame(function renderdrawrequest(timestamp) { var timeElapsed = timestamp - lastTime; var dirtyFrame = false; while (timeElapsed >= msPerFrame) { if (paused != true) { renderprocess(); } dirtyFrame = true; timeElapsed -= msPerFrame; } renderdraw(); lastTime = timestamp - timeElapsed; requestAnimationFrame(renderdrawrequest); }); fps = nfps; }, pauseAll: function () { paused = true; }, restart: function () { paused = false; }, setCamera: function (x, y, z) { if (camera.x == x && camera.y == y) { return; } camera.x = x; camera.y = y; updateScope(x + buffer_w / 2, y + buffer_h / 2); }, getCamera: function () { return { x: camera.x, y: camera.y }; }, moveCameraX: function (x) { camera.x += x; updateScope(camera.x + buffer_w / 2, camera.y + buffer_h / 2); }, moveCameraY: function (y) { camera.y += y; updateScope(camera.x + buffer_w / 2, camera.y + buffer_h / 2); }, moveCameraZ: function (z) { //In this library this has no meaning so it does nothing }, loadSpritesheetJSONObject: function (newspritesheets) { spritesheets = spritesheets.concat(newspritesheets.map(function (s) { var newspritesheet = new spritesheet(); newspritesheet.name = s.name; newspritesheet.positionBasedOptimizations = s.positionBasedOptimizations == "false" ? false : true; if (s.src != undefined) { newspritesheet.img = new Image() if (workingFolder) { newspritesheet.img.src = (workingFolder + "/" + s.src); } else { newspritesheet.img.src = s.src; } } for (var name in s.frames) { var f = s.frames[name]; var newframe = new frame(); newframe.name = name; if (f.code) { newframe.t = f.t; newframe.code = new Function("x", "y", "t", "context", "vars", f.code); } else { if (f.fullTexture) { newframe.fullTexture = true; } else { newframe.x = f.x; newframe.y = f.y; newframe.w = f.w; newframe.h = f.h; newframe.t = f.t; } } newspritesheet.frames.push(newframe); } for (var name in s.layers) { var l = s.layers[name]; var newlayer = new layer(); newlayer.name = name; newlayer.x = new Function("t", "vars", "return " + l.x); newlayer.y = new Function("t", "vars", "return " + l.y); newlayer.frames = l.frames.map(function (x) { return findwhere(newspritesheet.frames, "name", x); }); newlayer.t = getlayerduration(newlayer, newspritesheet); newspritesheet.layers.push(newlayer); } for (var name in s.states) { var st = s.states[name]; var newstate = new state(); newstate.name = name; newstate.totalduration = 0; newstate.layers = st.layers.map(function (x) { var thislayer = findwhere(newspritesheet.layers, "name", x); if (!newspritesheet.layers[thislayer]) { debugHandler("There is no layer " + x + " defined in spritesheet " + newspritesheet.name); } else { newstate.totalduration = newspritesheet.layers[thislayer].t > newstate.totalduration ? newspritesheet.layers[thislayer].t : newstate.totalduration; } return thislayer; }); switch (st.flip) { case "h": newstate.flip = 1; break; case "v": newstate.flip = 2; break; case "hv": newstate.flip = 3; break; case "vh": newstate.flip = 3; break; default: newstate.flip = 0; break; } newspritesheet.states.push(newstate); } return newspritesheet; })); }, addObject: function (spritesheet, state, x, y, z, isstatic) { var object = { vars: {}, spritesheetName: spritesheet, stateName: state, x: x, y: y, t: 0, zindex: z || 0, isstatic: isstatic || false, hiddenLayers: {} }; updateObjectState(object); object.bounds = getObjectBounds(object); objects.push(object); var index = objects.length - 1; if (object.isstatic === true || object.spritesheet.positionBasedOptimizations === false) { staticObjects.push(index); } else { moveQuadtreeObject(index, NaN, NaN, x, y); } updateScope(camera.x + buffer_w / 2, camera.y + buffer_h / 2); zIndexNeedsSorting = true; return index; }, deleteObject: function (id) { objects[id] = null; zIndexNeedsSorting = true; }, clear: function () { objects = []; objectsInScope = []; }, pause: function (id) { objects[id].pause = true; }, unpause: function (id) { objects[id].pause = false; }, setX: function (id, x) { var object = objects[id]; if (!(object.isstatic === true || object.spritesheet.positionBasedOptimizations === false)) { moveQuadtreeObject(id, object.x, object.y, x, object.y); } object.x = x; }, setY: function (id, y) { var object = objects[id]; if (!(object.isstatic === true || object.spritesheet.positionBasedOptimizations === false)) { moveQuadtreeObject(id, object.x, object.y, object.x, y); } object.y = y; }, setZ: function (id, z) { if (objects[id].zindex != z) { objects[id].zindex = z; zIndexNeedsSorting = true; } }, setParameter: function (id, key, value) { objects[id].vars[key] = value; }, setState: function (id, state) { if (objects[id].stateName != state) { objects[id].stateName = state; updateObjectState(objects[id]); var temp = objects[id].t; objects[id].t = 0; return temp; } return NaN; }, setSpritesheet: function (id, s) { objects[id].spritesheetName = s; updateObjectState(objects[id]); }, sendCommand: function (command, commandArgs) { switch (command) { case "setImage": objects[commandArgs.id].img = commandArgs.img; break; case "addObjectBatched": var object = { vars: {}, spritesheetName: commandArgs.spritesheet, stateName: commandArgs.state, x: commandArgs.x, y: commandArgs.y, t: 0, zindex: commandArgs.z || 0, isstatic: commandArgs.isstatic || false, hiddenLayers: {} }; updateObjectState(object); object.bounds = getObjectBounds(object); objects.push(object); var index = objects.length - 1; if (object.isstatic === true || object.spritesheet.positionBasedOptimizations === false) { staticObjects.push(index); } else { moveQuadtreeObject(index, NaN, NaN, x, y); } return index; case "endObjectBatch": updateScope(camera.x + buffer_w / 2, camera.y + buffer_h / 2); zIndexNeedsSorting = true; break; case "showLayer": objects[commandArgs.id].hiddenLayers[commandArgs.layer] = undefined; break; case "hideLayer": objects[commandArgs.id].hiddenLayers[commandArgs.layer] = true; break; } //This function sends a command to your library, you can use this an extension point to provide additional functionality }, setObjectTimer: function (id, t) { objects[id].t = t; }, getObjectTimer: function (id) { return objects[id].t; }, setEndedCallback: function (id, callback) { objects[id].callback = callback; }, setRenderMode: function (mode) { rendermode = mode; }, setBufferSize: function (w, h) { buffer_w = w; buffer_h = h; buffercanvas.width = w; buffercanvas.height = h; quadtreeWidth = buffercanvas.width / 2; quadtreeHeight = buffercanvas.height / 2; }, getContext: function () { return context; }, chainWith: function (renderingLibrary) { if (debugMode) { debugHandler("Spritesheet.js does not support chaining to another rendering library"); } //Chains to an instance of another rendering library, used in 'proxy' libraries (for recording, networking, perspective...) }, getSpriteBox: function (spritesheet, animationstate) { var minX, maxX, minY, maxY; var spritesheet = searchWhere(spritesheets, "name", spritesheet); var state = spritesheet.states[0]; if (animationstate != undefined) { state = searchWhere(spritesheet.states, "name", animationstate); } //We loop over the layers of its current state for (var i in state.layers) { var layer_n = state.layers[i]; var layer = spritesheet.layers[layer_n]; var t = 0; for (var j in layer.frames) { var frame = spritesheet.frames[layer.frames[j]]; var startX = layer.x(t, {}); var startY = layer.y(t, {}); if (startX < minX || minX == undefined) { minX = startX; } if (startY < minY || minY == undefined) { minY = startY; } if (frame.w > maxX || maxX == undefined) { maxX = frame.w; } if (frame.h > maxY || maxY == undefined) { maxY = frame.h; } t += frame.t; } } return { x: minX || 0, y: minY || 0, w: maxX || 100, h: maxY || 100 }; }, debug: function (handler) { debugMode = true; debugHandler = handler; debugMessagesCache.forEach(debugHandler); }, setWorkingFolder: function (folder) { workingFolder = folder; }, getWorkingFolder: function () { return workingFolder; } }; });
import { TypeOf } from 'element-ui/src/utils/funcs'; import objectAssign from 'element-ui/src/utils/merge'; import { getValueByPath } from 'element-ui/src/utils/util'; let columnIdSeed = 1; const defaults = { default: { order: '' }, selection: { width: 48, minWidth: 48, realWidth: 48, order: '', className: 'el-table-column--selection' }, expand: { width: 48, minWidth: 48, realWidth: 48, order: '' }, index: { width: 48, minWidth: 48, realWidth: 48, order: '' } }; // 设置动态选项数据 const setOptionData = function(callOption, row, column, $index, option){ if(TypeOf(callOption) === 'Function'){ let opData = callOption.call(column, row, column, $index) || {}; return objectAssign(option || {}, opData || {}); } return option || {}; }; // 获取禁用值 const getDisabledVal = function(row, column, store, $index, type) { let disableField = store.states.disableField; let isDisField = Boolean(store.table.disableField) && Boolean(store.table.disableField); let trueVal = disableField.trueVal; function getCallOp() { return column.selectable ? !column.selectable.call(null, row, $index) : false; } function getCallEdit() { return column.editable ? !column.editable.call(null, row, $index) : false; } if (isDisField) { if (row[disableField.field] === trueVal) return true; return type === 'op' ? getCallOp() : getCallEdit(); } return type === 'op' ? getCallOp() : getCallEdit(); }; const forced = { selection: { renderHeader: function(h) { return <el-checkbox nativeOn-click={ this.toggleAllSelection } value={ this.isAllSelected } />; }, renderCell: function(h, { row, column, store, $index }) { return <el-checkbox value={ store.isSelected(row) } disabled={ column.selectable ? !column.selectable.call(null, row, $index) : false } on-input={ () => { store.commit('rowSelectedChanged', row); } } />; }, sortable: false, resizable: false }, index: { renderHeader: function(h, { column }) { return column.label || '#'; }, renderCell: function(h, { $index }) { return <div>{ $index + 1 }</div>; }, sortable: false }, expand: { renderHeader: function(h, {}) { return ''; }, renderCell: function(h, { row, store }, proxy) { const expanded = store.states.expandRows.indexOf(row) > -1; return <div class={ 'el-table__expand-icon ' + (expanded ? 'el-table__expand-icon--expanded' : '') } on-click={ () => proxy.handleExpandClick(row) }> <i class='el-icon el-icon-arrow-right'></i> </div>; }, sortable: false, resizable: false, className: 'el-table__expand-column' }, manual: { renderHeader: function(h, {column}) { return column.label || ''; }, renderCell: function(h, data, self) { if (self.$scopedSlots.default) { return <div>{ self.$scopedSlots.default(data) } </div>; } return <div>{ self.$slots.default } </div>; }, sortable: false }, operate: { renderHeader: function(h, { row, column, store}) { let tableData = store.states.data; return ( <op-box isheader = { true } delete-visit = { column.deleteVisiable? !!column.deleteVisiable.call(null, tableData) : false } addVisit = { column.addVisiable? !!column.addVisiable.call(null, tableData) : false } saveVisit = { column.saveVisiable? !!column.saveVisiable.call(null, tableData) : false } deleteRow ={ column.deleteRow } addRowPre = { column.addRowPre } addNewRow ={ column.addNewRow } saveRow ={ column.saveRow } column ={ column } store ={ store }/> ); }, renderCell: function(h, { row, column, store, $index}) { let rowIndex = store.states.data.indexOf(row); let tableData = store.states.data; return ( <op-box deleteVisit = { column.deleteVisiable? !!column.deleteVisiable.call(null, tableData, row, rowIndex) : false } saveVisit = { column.saveVisiable? !!column.saveVisiable.call(null, tableData, row, rowIndex) : false } editVisit = { column.editVisiable? !!column.editVisiable.call(null, tableData, row, rowIndex) : false } deleteRow={ column.deleteRow } editRow={ column.editRow } saveRow ={ column.saveRow } row ={ row } column ={ column } store ={ store } index ={ $index } disabled={ getDisabledVal(row, column, store, $index, 'op') } /> ); }, sortable: false }, input: { // 文本框类型 renderCell: function(h, { row, column, store, $index}, that) { let option = column.inputOption || {}; return ( <el-input type= { option.type } precision={ option.precision } roundoff={ option.roundoff } histype={ option.histype } value={ row[column.property] } name= { option.name } placeholder= { option.placeholder } readonly= { option.readonly } maxlength= { option.maxlength } minlength= { option.minlength } auto-complete= { option.autoComplete } autofocus= { option.autofocus } min= { option.min } max= { option.max } form= { option.form } disabled={ getDisabledVal(row, column, store, $index) } onInput={ (val) => { store.commit('colInputChanged', row, column, val, that); }} /> ); }, sortable: false }, rate: { // 文本框百分比千分比类型 renderCell: function(h, { row, column, store, $index}, that) { let option = column.inputOption || {}; return ( <rate-number type= { option.type } value={ row[column.property] } rate={ column.useRate } name= { option.name } isEmpty={ option.isEmpty } placeholder= { option.placeholder } readonly= { option.readonly } maxlength= { option.maxlength } minlength= { option.minlength } autoComplete= { option.autoComplete } autofocus= { option.autofocus } min= { option.min } max= { option.max } form= { option.form } disabled={ getDisabledVal(row, column, store, $index) } onInput={ (val) => { store.commit('colInputChanged', row, column, val, that); }} /> ); }, sortable: false }, fnumber: { // 数字格式化 renderCell: function(h, { row, column, store, $index}, that) { let option = column.inputOption || {}; return ( <format-number type= { option.type } value={ row[column.property] } name= { option.name } isEmpty={ option.isEmpty } placeholder= { option.placeholder } readonly= { option.readonly } max= { option.max } min= { option.min } split= { option.split } splitMark= { option.splitMark } precision= { option.precision } autoComplete= { option.autoComplete } autofocus= { option.autofocus } min= { option.min } max= { option.max } form= { option.form } disabled={ getDisabledVal(row, column, store, $index) } onInput={ (val) => { store.commit('colInputChanged', row, column, val, that); }} /> ); }, sortable: false }, labelBtn: { // 标签翻译加按钮类型 renderCell: function(h, { row, column, store, $index}, that) { let option = column.labelOption || {}; return ( <button-label value={ row[column.property] } formatter={ column.formatter } dictId= { option.dictId || column.dictId } dictParams= { option.dictParams || column.dictParams } dictFilter= { option.dictFilter || column.dictFilter } tipDisabled={ option.tipDisabled} row ={ row } column ={ column } store ={ store } index ={ $index } width = { option.width } btnIcon = { option.btnIcon } btnClicked = { column.labelBtnClicked } disabled={ getDisabledVal(row, column, store, $index) } onInput={ (val) => { store.commit('colInputChanged', row, column, val, that); }} /> ); }, sortable: false }, inputBtn: { // 文本框加按钮类型 renderCell: function(h, { row, column, store, $index}, that) { let option = column.inputBtnOption || {}; return ( <button-input type= { option.type } value={ row[column.property] } formatter={ column.formatter } name= { option.name } placeholder= { option.placeholder } readonly= { option.readonly } maxlength= { option.maxlength } minlength= { option.minlength } autoComplete= { option.autoComplete } autofocus= { option.autofocus } disInput= { option.disabled } min= { option.min } max= { option.max } form= { option.form } row ={ row } column ={ column } store ={ store } index ={ $index } btnIcon = { option.btnIcon } btnClick = { column.inputBtnClick } disabled={ getDisabledVal(row, column, store, $index) } onInput={ (val) => { store.commit('colInputChanged', row, column, val, that); }} /> ); }, sortable: false }, checkbox: { // 检查类型 renderHeader: function(h, { column, store }) { if (!store.states.headerChecks.hasOwnProperty(column.property)){ store.states.headerChecks[column.property] = false; } return ( <check-all-box value={ store.states.headerChecks } headerChecked = { column.headerChecked } column ={ column } store ={ store }/> ); }, renderCell: function(h, { row, column, store, $index }) { let option = column.checkboxOption || {}; setTimeout(function(){ store.commit('checkAllboxChanged', column); }); return (column.boxStyl && column.boxStyl === 'rich') ? <rich-checkbox value={ row[column.property] } checked = { option.checked } name = { option.name } trueLabel = { option.trueLabel } falseLabel = { option.falseLabel } disabled={ getDisabledVal(row, column, store, $index) } onInput={ (val) => { store.commit('colCheckboxChanged', row, column, val); }} onChange ={ (e) => { store.commit('checkAllboxChanged', column); }}> { option.marked || row[column.property] } </rich-checkbox> :<el-checkbox value={ row[column.property] } checked = { option.checked } name = { option.name } trueLabel = { option.trueLabel } falseLabel = { option.falseLabel } disabled={ getDisabledVal(row, column, store, $index) } onInput={ (val) => { store.commit('colCheckboxChanged', row, column, val); }} onChange ={ (e) => { store.commit('checkAllboxChanged', column); }}> </el-checkbox>; }, sortable: false }, switch: { // 检查类型 renderCell: function(h, { row, column, store, $index }) { let option = column.switchOption || {}; return ( <custom-switch value={ row[column.property] } name = { option.name } width = { option.width } oIconClass = { option.onIconClass } offIconClass = { option.offIconClass } oText = { option.onText } offText = { option.offText } oColor = { option.onColor } offColor = { option.offColor } oValue = { option.onValue } offValue = { option.offValue } disabled={ getDisabledVal(row, column, store, $index) } onInput={ (val) => { store.commit('colSwitchChanged', row, column, val); } }> </custom-switch> ); }, sortable: false }, select: { //select类型 renderCell: function (h, { row, column, store, $index }, this$1) { // 动态加载Option let option = setOptionData(column.setColOption, row, column, $index, column.selectOption); return ( <el-select translated = { column.translated === 'select' } value={ row[column.property]} optionsData={ column.optionsData } name = { option.name } clearable = { option.clearable } filterable = { option.filterable } loading = { option.loading } remote = { option.remote } remoteMethod = { option.remoteMethod } filterMethod = { option.filterMethod } multiple = { option.multiple } placeholder = { option.placeholder } disabled={ getDisabledVal(row, column, store, $index) } onInput={ (val) => { store.commit('colSelectChanged', row, column, val); } }> { this$1._l(column.optionsData, (item)=> <el-option value={item.value} label={item.label} />)} </el-select> ); }, sortable: false }, date: { // 日期类型 renderCell: function(h, { row, column, store, $index }) { let option = column.dateOption || {}; let dataType = option.dataType || 'string'; return ( <el-date-picker value={ row[column.property] } type = { option.type } dataType = { dataType } format = { option.format } readonly = { option.readonly } placeholder = { option.placeholder } editable = { option.editable } clearable = { option.clearable } align = { option.align } pickerOptions = { column.pickerOptions } disabled={ getDisabledVal(row, column, store, $index) } onInput={ (val) => { store.commit('colDatePickerChanged', row, column, val); } }> </el-date-picker> ); }, sortable: false }, address: { // 地址类型 renderCell: function(h, { row, column, store, $index }) { let option = column.addressOption || {}; return ( <address-box translated = { column.translated === 'address' } value = { row[column.property] } resdata = { column.addressData } dataUrl = { option.dataUrl } placeholder = { option.placeholder } disabled={ getDisabledVal(row, column, store, $index) } onInput={ (val) => { store.commit('colAddressChanged', row, column, val); } }> </address-box> ); }, sortable: false }, combobox: { //combobox类型 renderCell: function (h, { row, column, store, $index }, this$1) { // 动态加载Option let option = setOptionData(column.setColOption, row, column, $index, column.comboboxOption); return ( <combobox value={ row[column.property]} dictId = { option.dictId || column.dictId } forceRefresh = { option.forceRefresh } dictParams = { option.dictParams || this$1.dictParams} dictRowData = { row } dictRowCascade = { option.dictRowCascade || false} dictRowCascadeMap = { option.dictRowCascadeMap } name = { option.name } clearable = { option.clearable } filterable = { option.filterable } loading = { option.loading } remote = { option.remote } remoteMethod = { option.remoteMethod } filterMethod = { option.filterMethod } multiple = { option.multiple } placeholder = { option.placeholder } disabled={ getDisabledVal(row, column, store, $index) } onInput={ (val) => { store.commit('colSelectChanged', row, column, val); } }> </combobox> ); }, sortable: false } }; const getDefaultColumn = function(type, options) { const column = {}; objectAssign(column, defaults[type || 'default']); for (let name in options) { if (options.hasOwnProperty(name)) { const value = options[name]; if (typeof value !== 'undefined') { column[name] = value; } } } if (!column.minWidth) { column.minWidth = 80; } column.realWidth = column.width || column.minWidth; return column; }; const DEFAULT_RENDER_CELL = function(h, { row, column }) { const property = column.property; const value = property && property.indexOf('.') === -1 ? row[property] : getValueByPath(row, property); if (column && column.formatter) { return column.formatter(row, column, value); } return value; }; function FnTrue(){ return true; } export default { name: 'FormTableColumn', componentName: 'FormTableColumn', props: { type: { type: String, default: 'default' }, label: String, className: String, labelClassName: String, property: String, prop: String, width: {}, minWidth: {}, renderHeader: Function, sortable: { type: [String, Boolean], default: false }, sortMethod: Function, resizable: { type: Boolean, default: true }, context: {}, columnKey: String, align: String, headerAlign: String, showTooltipWhenOverflow: Boolean, showOverflowTooltip: { // 修改为默认显示提示 type: Boolean, default: true }, fixed: [Boolean, String], formatter: Function, selectable: Function, addVisiable: { // 隐藏 添加按钮 type: Function, default(){ return FnTrue; } }, deleteVisiable: { // 隐藏 删除按钮 type: Function, default(){ return FnTrue; } } , saveVisiable: { // 隐藏 保存按钮 type: Function, default(){ return FnTrue; } } , editVisiable: { // 隐藏 动作按钮 type: Function, default(){ return FnTrue; } }, useRate:{ // 百分比组件比率类型 type: String, default(){ return 'percent'; } }, optionsStore: null, setColOption: Function, // 动态设置列组件选错值 translated: [Boolean, String], // 是否翻译,如果翻译组件将消失 switchOption: Object, // Switch类型初始化参数 deleteRow: Function, // 删除行回调 editRow: Function, //编辑行 addRowPre: Function, // 添加行前调用 addNewRow: Function, // 添加行回调 saveRow: Function, // 保存列表数据 editable: Function, // 是否可编辑 inputOption: Object, // 文本类型初始化参数 inputBtnOption: Object, labelOption: Object, inputBtnClick: Function, labelBtnClicked: Function, headerChecked: { // 表头是否显示 checkbox type: Boolean, default: false }, boxStyl: String, // checkbox 样式风格 checkboxAllToggle: Function, // checkbox 全选或反选通知 checkboxOption: Object, // 检查类型初始化参数 checkedSelection: Function, // 返回 true | false 控制是否选择本行,如未定义而则不关联该功能 selectOption: Object, // select类型初始化参数 comboboxOption: Object, // combobox类型初始化参数 dictParams:Object, // combobox类型下拉框参数 dictId:String, // combobox类型下拉框字典ID dictFilter: Boolean, // 大数据过滤 optionsData: [Object, Array], // 初始化select列表数据 dateOption: Object, // 日期控件初始化参数 pickerOptions: Object, // 日期其他参数 addressOption: Object, // 地址类型初始化参数 addressData: [Object, Array], // 初始化地址数据 reserveSelection: Boolean, filterMethod: Function, filteredValue: Array, filters: Array, filterPlacement: String, filterMultiple: { type: Boolean, default: true } }, data() { return { isSubColumn: false, columns: [] }; }, beforeCreate() { this.row = {}; this.column = {}; this.$index = 0; }, computed: { owner() { let parent = this.$parent; while (parent && !parent.tableId) { parent = parent.$parent; } return parent; } }, created() { this.customRender = this.$options.render; this.$options.render = h => h('div', this.$slots.default); this.columnId = (this.$parent.tableId || (this.$parent.columnId + '_')) + 'column_' + columnIdSeed++; let parent = this.$parent; let owner = this.owner; this.isSubColumn = owner !== parent; let type = this.type; let width = this.width; if (width !== undefined) { width = parseInt(width, 10); if (isNaN(width)) { width = null; } } let minWidth = this.minWidth; if (minWidth !== undefined) { minWidth = parseInt(minWidth, 10); if (isNaN(minWidth)) { minWidth = 80; } } let isColumnGroup = false; let column = getDefaultColumn(type, { id: this.columnId, columnKey: this.columnKey, label: this.label, className: this.className, labelClassName: this.labelClassName, property: this.prop || this.property, type, renderCell: null, renderHeader: this.renderHeader, minWidth, width, isColumnGroup, context: this.context, align: this.align ? 'is-' + this.align : null, headerAlign: this.headerAlign ? 'is-' + this.headerAlign : (this.align ? 'is-' + this.align : null), sortable: this.sortable === '' ? true : this.sortable, sortMethod: this.sortMethod, resizable: this.resizable, showOverflowTooltip: this.showOverflowTooltip || this.showTooltipWhenOverflow, formatter: this.formatter, selectable: this.selectable, translated: this.translated, useRate: this.useRate, setColOption: this.setColOption, textCNWord: '', // 默认翻译内容 addRowPre: this.addRowPre, addVisiable: this.addVisiable, // 隐藏 添加按钮 deleteVisiable: this.deleteVisiable, // 隐藏 删除按钮 saveVisiable: this.saveVisiable, // 隐藏 保存按钮 editVisiable: this.editVisiable, // 隐藏 动作按钮 switchOption: this.switchOption, // Switch类型初始化参数 deleteRow: this.deleteRow, // 删除行回调 addNewRow: this.addNewRow, // 添加行回调 saveRow: this.saveRow, // 保存列表数据 editRow: this.editRow, // 编辑行 editable: this.editable, // 是否可编辑 inputOption: this.inputOption, // 文本类型初始化参数 inputBtnOption: this.inputBtnOption, labelOption: this.labelOption, labelBtnClicked: this.labelBtnClicked, inputBtnClick: this.inputBtnClick, headerChecked: this.headerChecked, boxStyl: this.boxStyl, checkboxAllToggle: this.checkboxAllToggle, checkboxOption: this.checkboxOption, // 检查类型初始化参数 checkedSelection: this.checkedSelection, // 返回 true | false 控制是否选择本行,如未定义而则不关联该功能 selectOption: this.selectOption, // select类型初始化参数 optionsData: this.optionsData, // 初始化select列表数据 dateOption: this.dateOption, // 日期控件初始化参数 pickerOptions: this.pickerOptions, addressOption: this.addressOption, // 地址类型初始化参数 addressData: this.addressData, // 初始化地址数据 comboboxOption: this.comboboxOption, // combobox类型初始化参数 dictParams: this.dictParams, // combobox下拉框参数 dictId: this.dictId, // combobox下拉框字段ID dictFilter: this.dictFilter, // 大数据过滤 reserveSelection: this.reserveSelection, fixed: this.fixed === '' ? true : this.fixed, filterMethod: this.filterMethod, filters: this.filters, filterable: this.filters || this.filterMethod, filterMultiple: this.filterMultiple, filterOpened: false, filteredValue: this.filteredValue || [], filterPlacement: this.filterPlacement || '' }); objectAssign(column, forced[type] || {}); this.columnConfig = column; let renderCell = column.renderCell; let _self = this, hiddenExpandIcon = ''; if (type === 'expand') { // 自定义隐藏展开式编辑 if(this.owner.store.table.expandIconHidden){ column.realWidth = 1; hiddenExpandIcon = 'hidden-expand-icon'; } owner.renderExpanded = function(h, data) { return _self.$scopedSlots.default ? _self.$scopedSlots.default(data) : _self.$slots.default; }; column.renderCell = function(h, data) { return <div class={'cell ' + hiddenExpandIcon}>{ renderCell(h, data, this._renderProxy) }</div>; }; return; } column.renderCell = function(h, data) { let {row, column} = data; // 未来版本移除 if (_self.$vnode.data.inlineTemplate) { renderCell = function() { data._self = _self.context || data._self; if (Object.prototype.toString.call(data._self) === '[object Object]') { for (let prop in data._self) { if (!data.hasOwnProperty(prop)) { data[prop] = data._self[prop]; } } } // 静态内容会缓存到 _staticTrees 内,不改的话获取的静态数据就不是内部 context data._staticTrees = _self._staticTrees; data.$options.staticRenderFns = _self.$options.staticRenderFns; return _self.customRender.call(data); }; } else if (_self.$scopedSlots.default) { renderCell = () => _self.$scopedSlots.default(data); } if (!renderCell) { renderCell = DEFAULT_RENDER_CELL; } return (_self.showOverflowTooltip || _self.showTooltipWhenOverflow) && _self.type === 'default' ? <div class={ 'cell el-tooltip ' + 'row' + data.$index + data.column.property } style={'width:' + (data.column.realWidth || data.column.width) + 'px'}>{ renderCell(h, data, _self) }</div> : <form-table-item prop={data} property={ 'row' + data.$index + data.column.property } class={ 'row' + data.$index + data.column.property } value={row[column.property]}> { renderCell(h, data, _self) } </form-table-item>; }; }, destroyed() { if (!this.$parent) return; this.owner.store.commit('removeColumn', this.columnConfig); }, watch: { label(newVal) { if (this.columnConfig) { this.columnConfig.label = newVal; } }, prop(newVal) { if (this.columnConfig) { this.columnConfig.property = newVal; } }, property(newVal) { if (this.columnConfig) { this.columnConfig.property = newVal; } }, filters(newVal) { if (this.columnConfig) { this.columnConfig.filters = newVal; } }, filterMultiple(newVal) { if (this.columnConfig) { this.columnConfig.filterMultiple = newVal; } }, align(newVal) { if (this.columnConfig) { this.columnConfig.align = newVal ? 'is-' + newVal : null; if (!this.headerAlign) { this.columnConfig.headerAlign = newVal ? 'is-' + newVal : null; } } }, headerAlign(newVal) { if (this.columnConfig) { this.columnConfig.headerAlign = 'is-' + (newVal ? newVal : this.align); } }, width(newVal) { if (this.columnConfig) { this.columnConfig.width = newVal; this.owner.store.scheduleLayout(); } }, minWidth(newVal) { if (this.columnConfig) { this.columnConfig.minWidth = newVal; this.owner.store.scheduleLayout(); } }, fixed(newVal) { if (this.columnConfig) { this.columnConfig.fixed = newVal; this.owner.store.scheduleLayout(); } }, sortable(newVal) { if (this.columnConfig) { this.columnConfig.sortable = newVal; } } }, mounted() { const owner = this.owner; const parent = this.$parent; let columnIndex; if (!this.isSubColumn) { columnIndex = [].indexOf.call(parent.$refs.hiddenColumns.children, this.$el); } else { columnIndex = [].indexOf.call(parent.$el.children, this.$el); } owner.store.commit('insertColumn', this.columnConfig, columnIndex, this.isSubColumn ? parent.columnConfig : null); } };
System.config({ baseURL: "./", defaultJSExtensions: true, transpiler: "babel", babelOptions: { "optional": [ "runtime", "optimisation.modules.system" ], "compact" : false }, paths: { "test/*": "./test/*", "github:*": "jspm_packages/github/*", "npm:*": "jspm_packages/npm/*" }, sassPluginOptions: { "autoprefixer": true, "sassOptions": {} }, map: { "autoprefixer": "npm:autoprefixer@6.3.6", "babel": "npm:babel-core@5.8.25", "babel-runtime": "npm:babel-runtime@5.8.25", "bootstrap": "github:twbs/bootstrap-sass@3.3.6", "core-js": "npm:core-js@1.2.0", "fs": "github:jspm/nodelibs-fs@0.1.2", "lodash": "npm:lodash@4.8.2", "lodash.clonedeep": "npm:lodash.clonedeep@4.3.2", "path": "github:jspm/nodelibs-path@0.1.0", "postcss": "npm:postcss@5.0.19", "reqwest": "github:ded/reqwest@2.0.5", "sass.js": "npm:sass.js@0.9.6", "scss": "index.js", "url": "github:jspm/nodelibs-url@0.1.0", "github:jspm/nodelibs-assert@0.1.0": { "assert": "npm:assert@1.3.0" }, "github:jspm/nodelibs-buffer@0.1.0": { "buffer": "npm:buffer@3.6.0" }, "github:jspm/nodelibs-constants@0.1.0": { "constants-browserify": "npm:constants-browserify@0.0.1" }, "github:jspm/nodelibs-crypto@0.1.0": { "crypto-browserify": "npm:crypto-browserify@3.11.0" }, "github:jspm/nodelibs-events@0.1.1": { "events": "npm:events@1.0.2" }, "github:jspm/nodelibs-path@0.1.0": { "path-browserify": "npm:path-browserify@0.0.0" }, "github:jspm/nodelibs-process@0.1.2": { "process": "npm:process@0.11.2" }, "github:jspm/nodelibs-stream@0.1.0": { "stream-browserify": "npm:stream-browserify@1.0.0" }, "github:jspm/nodelibs-string_decoder@0.1.0": { "string_decoder": "npm:string_decoder@0.10.31" }, "github:jspm/nodelibs-url@0.1.0": { "url": "npm:url@0.10.3" }, "github:jspm/nodelibs-util@0.1.0": { "util": "npm:util@0.10.3" }, "github:jspm/nodelibs-vm@0.1.0": { "vm-browserify": "npm:vm-browserify@0.0.4" }, "npm:asn1.js@4.3.0": { "assert": "github:jspm/nodelibs-assert@0.1.0", "bn.js": "npm:bn.js@4.10.0", "buffer": "github:jspm/nodelibs-buffer@0.1.0", "inherits": "npm:inherits@2.0.1", "minimalistic-assert": "npm:minimalistic-assert@1.0.0", "systemjs-json": "github:systemjs/plugin-json@0.1.0", "vm": "github:jspm/nodelibs-vm@0.1.0" }, "npm:assert@1.3.0": { "util": "npm:util@0.10.3" }, "npm:autoprefixer@6.3.6": { "browserslist": "npm:browserslist@1.3.1", "caniuse-db": "npm:caniuse-db@1.0.30000449", "normalize-range": "npm:normalize-range@0.1.2", "num2fraction": "npm:num2fraction@1.2.2", "postcss": "npm:postcss@5.0.19", "postcss-value-parser": "npm:postcss-value-parser@3.3.0", "process": "github:jspm/nodelibs-process@0.1.2", "systemjs-json": "github:systemjs/plugin-json@0.1.0" }, "npm:babel-runtime@5.8.25": { "process": "github:jspm/nodelibs-process@0.1.2" }, "npm:bn.js@4.10.0": { "buffer": "github:jspm/nodelibs-buffer@0.1.0", "systemjs-json": "github:systemjs/plugin-json@0.1.0" }, "npm:browserify-aes@1.0.6": { "buffer": "github:jspm/nodelibs-buffer@0.1.0", "buffer-xor": "npm:buffer-xor@1.0.3", "cipher-base": "npm:cipher-base@1.0.2", "create-hash": "npm:create-hash@1.1.2", "crypto": "github:jspm/nodelibs-crypto@0.1.0", "evp_bytestokey": "npm:evp_bytestokey@1.0.0", "fs": "github:jspm/nodelibs-fs@0.1.2", "inherits": "npm:inherits@2.0.1", "systemjs-json": "github:systemjs/plugin-json@0.1.0" }, "npm:browserify-cipher@1.0.0": { "browserify-aes": "npm:browserify-aes@1.0.6", "browserify-des": "npm:browserify-des@1.0.0", "buffer": "github:jspm/nodelibs-buffer@0.1.0", "crypto": "github:jspm/nodelibs-crypto@0.1.0", "evp_bytestokey": "npm:evp_bytestokey@1.0.0" }, "npm:browserify-des@1.0.0": { "buffer": "github:jspm/nodelibs-buffer@0.1.0", "cipher-base": "npm:cipher-base@1.0.2", "crypto": "github:jspm/nodelibs-crypto@0.1.0", "des.js": "npm:des.js@1.0.0", "inherits": "npm:inherits@2.0.1", "systemjs-json": "github:systemjs/plugin-json@0.1.0" }, "npm:browserify-rsa@4.0.0": { "bn.js": "npm:bn.js@4.10.0", "buffer": "github:jspm/nodelibs-buffer@0.1.0", "constants": "github:jspm/nodelibs-constants@0.1.0", "crypto": "github:jspm/nodelibs-crypto@0.1.0", "randombytes": "npm:randombytes@2.0.2", "systemjs-json": "github:systemjs/plugin-json@0.1.0" }, "npm:browserify-sign@4.0.0": { "bn.js": "npm:bn.js@4.10.0", "browserify-rsa": "npm:browserify-rsa@4.0.0", "buffer": "github:jspm/nodelibs-buffer@0.1.0", "create-hash": "npm:create-hash@1.1.2", "create-hmac": "npm:create-hmac@1.1.4", "crypto": "github:jspm/nodelibs-crypto@0.1.0", "elliptic": "npm:elliptic@6.2.3", "inherits": "npm:inherits@2.0.1", "parse-asn1": "npm:parse-asn1@5.0.0", "stream": "github:jspm/nodelibs-stream@0.1.0" }, "npm:browserslist@1.3.1": { "caniuse-db": "npm:caniuse-db@1.0.30000449", "fs": "github:jspm/nodelibs-fs@0.1.2", "path": "github:jspm/nodelibs-path@0.1.0", "process": "github:jspm/nodelibs-process@0.1.2", "systemjs-json": "github:systemjs/plugin-json@0.1.0" }, "npm:buffer-xor@1.0.3": { "buffer": "github:jspm/nodelibs-buffer@0.1.0", "systemjs-json": "github:systemjs/plugin-json@0.1.0" }, "npm:buffer@3.6.0": { "base64-js": "npm:base64-js@0.0.8", "child_process": "github:jspm/nodelibs-child_process@0.1.0", "fs": "github:jspm/nodelibs-fs@0.1.2", "ieee754": "npm:ieee754@1.1.6", "isarray": "npm:isarray@1.0.0", "process": "github:jspm/nodelibs-process@0.1.2", "systemjs-json": "github:systemjs/plugin-json@0.1.0" }, "npm:cipher-base@1.0.2": { "buffer": "github:jspm/nodelibs-buffer@0.1.0", "inherits": "npm:inherits@2.0.1", "stream": "github:jspm/nodelibs-stream@0.1.0", "string_decoder": "github:jspm/nodelibs-string_decoder@0.1.0", "systemjs-json": "github:systemjs/plugin-json@0.1.0" }, "npm:constants-browserify@0.0.1": { "systemjs-json": "github:systemjs/plugin-json@0.1.0" }, "npm:core-js@1.2.0": { "fs": "github:jspm/nodelibs-fs@0.1.2", "process": "github:jspm/nodelibs-process@0.1.2", "systemjs-json": "github:systemjs/plugin-json@0.1.0" }, "npm:core-util-is@1.0.2": { "buffer": "github:jspm/nodelibs-buffer@0.1.0" }, "npm:create-ecdh@4.0.0": { "bn.js": "npm:bn.js@4.10.0", "buffer": "github:jspm/nodelibs-buffer@0.1.0", "crypto": "github:jspm/nodelibs-crypto@0.1.0", "elliptic": "npm:elliptic@6.2.3" }, "npm:create-hash@1.1.2": { "buffer": "github:jspm/nodelibs-buffer@0.1.0", "cipher-base": "npm:cipher-base@1.0.2", "crypto": "github:jspm/nodelibs-crypto@0.1.0", "fs": "github:jspm/nodelibs-fs@0.1.2", "inherits": "npm:inherits@2.0.1", "ripemd160": "npm:ripemd160@1.0.1", "sha.js": "npm:sha.js@2.4.4" }, "npm:create-hmac@1.1.4": { "buffer": "github:jspm/nodelibs-buffer@0.1.0", "create-hash": "npm:create-hash@1.1.2", "crypto": "github:jspm/nodelibs-crypto@0.1.0", "inherits": "npm:inherits@2.0.1", "stream": "github:jspm/nodelibs-stream@0.1.0" }, "npm:crypto-browserify@3.11.0": { "browserify-cipher": "npm:browserify-cipher@1.0.0", "browserify-sign": "npm:browserify-sign@4.0.0", "create-ecdh": "npm:create-ecdh@4.0.0", "create-hash": "npm:create-hash@1.1.2", "create-hmac": "npm:create-hmac@1.1.4", "diffie-hellman": "npm:diffie-hellman@5.0.2", "inherits": "npm:inherits@2.0.1", "pbkdf2": "npm:pbkdf2@3.0.4", "public-encrypt": "npm:public-encrypt@4.0.0", "randombytes": "npm:randombytes@2.0.2", "systemjs-json": "github:systemjs/plugin-json@0.1.0" }, "npm:des.js@1.0.0": { "buffer": "github:jspm/nodelibs-buffer@0.1.0", "inherits": "npm:inherits@2.0.1", "minimalistic-assert": "npm:minimalistic-assert@1.0.0" }, "npm:diffie-hellman@5.0.2": { "bn.js": "npm:bn.js@4.10.0", "buffer": "github:jspm/nodelibs-buffer@0.1.0", "crypto": "github:jspm/nodelibs-crypto@0.1.0", "miller-rabin": "npm:miller-rabin@4.0.0", "randombytes": "npm:randombytes@2.0.2", "systemjs-json": "github:systemjs/plugin-json@0.1.0" }, "npm:elliptic@6.2.3": { "bn.js": "npm:bn.js@4.10.0", "brorand": "npm:brorand@1.0.5", "hash.js": "npm:hash.js@1.0.3", "inherits": "npm:inherits@2.0.1", "systemjs-json": "github:systemjs/plugin-json@0.1.0" }, "npm:evp_bytestokey@1.0.0": { "buffer": "github:jspm/nodelibs-buffer@0.1.0", "create-hash": "npm:create-hash@1.1.2", "crypto": "github:jspm/nodelibs-crypto@0.1.0", "systemjs-json": "github:systemjs/plugin-json@0.1.0" }, "npm:has-flag@1.0.0": { "process": "github:jspm/nodelibs-process@0.1.2" }, "npm:hash.js@1.0.3": { "inherits": "npm:inherits@2.0.1" }, "npm:inherits@2.0.1": { "util": "github:jspm/nodelibs-util@0.1.0" }, "npm:isarray@1.0.0": { "systemjs-json": "github:systemjs/plugin-json@0.1.0" }, "npm:js-base64@2.1.9": { "buffer": "github:jspm/nodelibs-buffer@0.1.0" }, "npm:lodash._baseclone@4.5.4": { "buffer": "github:jspm/nodelibs-buffer@0.1.0" }, "npm:lodash.clonedeep@4.3.2": { "lodash._baseclone": "npm:lodash._baseclone@4.5.4" }, "npm:lodash@4.8.2": { "buffer": "github:jspm/nodelibs-buffer@0.1.0", "process": "github:jspm/nodelibs-process@0.1.2" }, "npm:miller-rabin@4.0.0": { "bn.js": "npm:bn.js@4.10.0", "brorand": "npm:brorand@1.0.5" }, "npm:parse-asn1@5.0.0": { "asn1.js": "npm:asn1.js@4.3.0", "browserify-aes": "npm:browserify-aes@1.0.6", "buffer": "github:jspm/nodelibs-buffer@0.1.0", "create-hash": "npm:create-hash@1.1.2", "evp_bytestokey": "npm:evp_bytestokey@1.0.0", "pbkdf2": "npm:pbkdf2@3.0.4", "systemjs-json": "github:systemjs/plugin-json@0.1.0" }, "npm:path-browserify@0.0.0": { "process": "github:jspm/nodelibs-process@0.1.2" }, "npm:pbkdf2@3.0.4": { "buffer": "github:jspm/nodelibs-buffer@0.1.0", "child_process": "github:jspm/nodelibs-child_process@0.1.0", "create-hmac": "npm:create-hmac@1.1.4", "crypto": "github:jspm/nodelibs-crypto@0.1.0", "path": "github:jspm/nodelibs-path@0.1.0", "process": "github:jspm/nodelibs-process@0.1.2", "systemjs-json": "github:systemjs/plugin-json@0.1.0" }, "npm:postcss@5.0.19": { "fs": "github:jspm/nodelibs-fs@0.1.2", "js-base64": "npm:js-base64@2.1.9", "path": "github:jspm/nodelibs-path@0.1.0", "process": "github:jspm/nodelibs-process@0.1.2", "source-map": "npm:source-map@0.5.3", "supports-color": "npm:supports-color@3.1.2" }, "npm:process@0.11.2": { "assert": "github:jspm/nodelibs-assert@0.1.0" }, "npm:public-encrypt@4.0.0": { "bn.js": "npm:bn.js@4.10.0", "browserify-rsa": "npm:browserify-rsa@4.0.0", "buffer": "github:jspm/nodelibs-buffer@0.1.0", "create-hash": "npm:create-hash@1.1.2", "crypto": "github:jspm/nodelibs-crypto@0.1.0", "parse-asn1": "npm:parse-asn1@5.0.0", "randombytes": "npm:randombytes@2.0.2" }, "npm:punycode@1.3.2": { "process": "github:jspm/nodelibs-process@0.1.2" }, "npm:randombytes@2.0.2": { "buffer": "github:jspm/nodelibs-buffer@0.1.0", "crypto": "github:jspm/nodelibs-crypto@0.1.0", "process": "github:jspm/nodelibs-process@0.1.2", "systemjs-json": "github:systemjs/plugin-json@0.1.0" }, "npm:readable-stream@1.1.13": { "buffer": "github:jspm/nodelibs-buffer@0.1.0", "core-util-is": "npm:core-util-is@1.0.2", "events": "github:jspm/nodelibs-events@0.1.1", "inherits": "npm:inherits@2.0.1", "isarray": "npm:isarray@0.0.1", "process": "github:jspm/nodelibs-process@0.1.2", "stream-browserify": "npm:stream-browserify@1.0.0", "string_decoder": "npm:string_decoder@0.10.31" }, "npm:ripemd160@1.0.1": { "buffer": "github:jspm/nodelibs-buffer@0.1.0", "process": "github:jspm/nodelibs-process@0.1.2" }, "npm:sass.js@0.9.6": { "buffer": "github:jspm/nodelibs-buffer@0.1.0", "crypto": "github:jspm/nodelibs-crypto@0.1.0", "fs": "github:jspm/nodelibs-fs@0.1.2", "path": "github:jspm/nodelibs-path@0.1.0", "process": "github:jspm/nodelibs-process@0.1.2" }, "npm:sha.js@2.4.4": { "buffer": "github:jspm/nodelibs-buffer@0.1.0", "fs": "github:jspm/nodelibs-fs@0.1.2", "inherits": "npm:inherits@2.0.1", "process": "github:jspm/nodelibs-process@0.1.2" }, "npm:source-map@0.5.3": { "process": "github:jspm/nodelibs-process@0.1.2" }, "npm:stream-browserify@1.0.0": { "events": "github:jspm/nodelibs-events@0.1.1", "inherits": "npm:inherits@2.0.1", "readable-stream": "npm:readable-stream@1.1.13" }, "npm:string_decoder@0.10.31": { "buffer": "github:jspm/nodelibs-buffer@0.1.0" }, "npm:supports-color@3.1.2": { "has-flag": "npm:has-flag@1.0.0", "process": "github:jspm/nodelibs-process@0.1.2" }, "npm:url@0.10.3": { "assert": "github:jspm/nodelibs-assert@0.1.0", "punycode": "npm:punycode@1.3.2", "querystring": "npm:querystring@0.2.0", "util": "github:jspm/nodelibs-util@0.1.0" }, "npm:util@0.10.3": { "inherits": "npm:inherits@2.0.1", "process": "github:jspm/nodelibs-process@0.1.2" }, "npm:vm-browserify@0.0.4": { "indexof": "npm:indexof@0.0.1" } } });
import { Component, PropTypes } from 'react'; import ReactComponent from 'components/ReactComponent'; export default class Components extends Component { static propTypes = { components: PropTypes.array.isRequired } renderComponents() { return this.props.components.map((component) => { return ( <ReactComponent component={component} key={component.name}/> ); }); } render() { return ( <div> {this.renderComponents()} </div> ); } }
'use strict'; /* jshint sub: true */ var path = require('path'); var EventEmitter = require('events').EventEmitter; var should = require('chai').should(); var crypto = require('crypto'); var bitcore = require('bitcore-lib'); var _ = bitcore.deps._; var sinon = require('sinon'); var proxyquire = require('proxyquire'); var fs = require('fs'); var sinon = require('sinon'); var index = require('../../lib'); var log = index.log; var errors = index.errors; var Transaction = bitcore.Transaction; var readFileSync = sinon.stub().returns(fs.readFileSync(path.resolve(__dirname, '../data/bitcoin.conf'))); var BitcoinService = proxyquire('../../lib/services/bitcoind', { fs: { readFileSync: readFileSync } }); var defaultBitcoinConf = fs.readFileSync(path.resolve(__dirname, '../data/default.bitcoin.conf'), 'utf8'); describe('Bitcoin Service', function() { });
var assert = require('assert'); var helpers = require('./helpers'); var args = []; describe('retries', function() { this.timeout(1000); it('are ran in correct order', function(done) { helpers.runMocha('retries/hooks.js', args, function(err, res) { var lines, expected; assert(!err); lines = res.output.split(/[\n․]+/).map(function(line) { return line.trim(); }).filter(function(line) { return line.length; }).slice(0, -1); expected = [ 'before', 'before each 0', 'TEST 0', 'after each 1', 'before each 1', 'TEST 1', 'after each 2', 'before each 2', 'TEST 2', 'after each 3', 'before each 3', 'TEST 3', 'after each 4', 'before each 4', 'TEST 4', 'after each 5', 'after' ]; expected.forEach(function(line, i) { assert.equal(lines[i], line); }); assert.equal(res.code, 1); done(); }); }); it('should exit early if test passes', function (done) { helpers.runMochaJSON('retries/early-pass.js', args, function(err, res) { assert(!err); assert.equal(res.stats.passes, 1); assert.equal(res.stats.failures, 0); assert.equal(res.tests[0].currentRetry, 1); assert.equal(res.stats.tests, 1); assert.equal(res.code, 0); done(); }); }); it('should let test override', function (done) { helpers.runMochaJSON('retries/nested.js', args, function(err, res) { assert(!err); assert.equal(res.stats.passes, 0); assert.equal(res.stats.failures, 1); assert.equal(res.stats.tests, 1); assert.equal(res.tests[0].currentRetry, 1); assert.equal(res.code, 1); done(); }); }); it('should not hang w/ async test', function (done) { helpers.runMocha('retries/async.js', args, function(err, res) { var lines, expected; assert(!err); lines = res.output.split(/[\n․]+/).map(function(line) { return line.trim(); }).filter(function(line) { return line.length; }).slice(0, -1); expected = [ 'before', 'before each 0', 'TEST 0', 'after each 1', 'before each 1', 'TEST 1', 'after each 2', 'before each 2', 'TEST 2', 'after each 3', 'after' ]; expected.forEach(function(line, i) { assert.equal(lines[i], line); }); assert.equal(res.code, 0); done(); }); }); });
// Eloquent JavaScript // Run this file in your terminal using `node my_solution.js`. Make sure it works before moving on! // Program Structure // Write your own variable and do something to it. // var Illusion = "Is it a dream?" // console.log(Illusion) /* Write a short program that asks for a user to input their favorite food. After they hit return, have the program respond with "Hey! That's my favorite too!" (You will probably need to run this in the Chrome console 
rather than node since node does not support prompt or alert). */ // prompt("What is your favorite food?", "..."); // alert("Hey! That's my favorite too!"); // Complete one of the exercises: Looping a Triangle, FizzBuzz, or Chess Board // for (var brick = "#"; brick.length <= 7; brick += "#") // console.log(brick); // Functions // Complete the `minimum` exercise. /* var min = function(num1, num2){ if (num1 < num2) return num1; else return num2 } console.log(min(0, 3)); */ // Data Structures: Objects and Arrays // Create an object called "me" that stores your name, age, 3 favorite foods, and a quirk below. var me = { name: "Mila", age: 28, foods: ["Seafood", "Avocado", "Salad"], quirk: "sporty nerd" }; console.log(me.name); console.log(me.age); console.log(me.foods); console.log(me.quirk);
vti_encoding:SR|utf8-nl vti_author:SR|OMCORP\\saten.kumar vti_modifiedby:SR|OMCORP\\saten.kumar vti_timelastmodified:TR|26 May 2006 15:17:10 -0000 vti_timecreated:TR|26 May 2006 15:17:10 -0000 vti_cacheddtm:TX|26 May 2006 15:17:10 -0000 vti_filesize:IR|1882 vti_extenderversion:SR|6.0.2.6551 vti_backlinkinfo:VX|
var React = require('react'); module.exports = React.createClass({ render : function() { return <div>No route found : 404</div> } });
/* eslint-disable no-var, no-unused-vars, no-underscore-dangle */ // Create the WebdriverIO browser object var client = {}; // Make a proxy of the global Jest expect function so we can test the global // Chai version global._expect = global.expect;
import { setData } from '@progress/kendo-angular-intl'; setData({ name: "es-CU", identity: { language: "es", territory: "CU" }, territory: "CU", numbers: { symbols: { decimal: ".", group: ",", list: ";", percentSign: "%", plusSign: "+", minusSign: "-", exponential: "E", superscriptingExponent: "×", perMille: "‰", infinity: "∞", nan: "NaN", timeSeparator: ":" }, decimal: { patterns: [ "n" ], groupSize: [ 3 ] }, scientific: { patterns: [ "nEn" ], groupSize: [] }, percent: { patterns: [ "n %" ], groupSize: [ 3 ] }, currency: { patterns: [ "$n" ], groupSize: [ 3 ], "unitPattern-count-one": "n $", "unitPattern-count-other": "n $" }, accounting: { patterns: [ "$n" ], groupSize: [ 3 ] }, currencies: { ADP: { displayName: "peseta andorrana", "displayName-count-one": "peseta andorrana", "displayName-count-other": "pesetas andorranas", symbol: "ADP" }, AED: { displayName: "dírham de los Emiratos Árabes Unidos", "displayName-count-one": "dírham de los Emiratos Árabes Unidos", "displayName-count-other": "dírhams de los Emiratos Árabes Unidos", symbol: "AED" }, AFA: { displayName: "afgani (1927–2002)", symbol: "AFA" }, AFN: { displayName: "afgani", "displayName-count-one": "afgani", "displayName-count-other": "afganis", symbol: "AFN" }, ALL: { displayName: "lek", "displayName-count-one": "lek", "displayName-count-other": "lekes", symbol: "ALL" }, AMD: { displayName: "dram armenio", "displayName-count-one": "dram", "displayName-count-other": "drams", symbol: "AMD" }, ANG: { displayName: "florín de las Antillas Neerlandesas", "displayName-count-one": "florín de las Antillas Neerlandesas", "displayName-count-other": "florines de las Antillas Neerlandesas", symbol: "ANG" }, AOA: { displayName: "kuanza", "displayName-count-one": "kuanza", "displayName-count-other": "kuanzas", symbol: "AOA", "symbol-alt-narrow": "Kz" }, AOK: { displayName: "kwanza angoleño (1977–1990)", symbol: "AOK" }, AON: { displayName: "nuevo kwanza angoleño (1990–2000)", symbol: "AON" }, AOR: { displayName: "kwanza reajustado angoleño (1995–1999)", symbol: "AOR" }, ARA: { displayName: "austral argentino", "displayName-count-one": "austral argentino", "displayName-count-other": "australes argentinos", symbol: "ARA" }, ARL: { displayName: "ARL", symbol: "ARL" }, ARM: { displayName: "ARM", symbol: "ARM" }, ARP: { displayName: "peso argentino (1983–1985)", "displayName-count-one": "peso argentino (ARP)", "displayName-count-other": "pesos argentinos (ARP)", symbol: "ARP" }, ARS: { displayName: "peso argentino", "displayName-count-one": "peso argentino", "displayName-count-other": "pesos argentinos", symbol: "ARS", "symbol-alt-narrow": "$" }, ATS: { displayName: "chelín austriaco", "displayName-count-one": "chelín austriaco", "displayName-count-other": "chelines austriacos", symbol: "ATS" }, AUD: { displayName: "dólar australiano", "displayName-count-one": "dólar australiano", "displayName-count-other": "dólares australianos", symbol: "AUD", "symbol-alt-narrow": "$" }, AWG: { displayName: "florín arubeño", "displayName-count-one": "florín arubeño", "displayName-count-other": "florines arubeños", symbol: "AWG" }, AZM: { displayName: "manat azerí (1993–2006)", symbol: "AZM" }, AZN: { displayName: "manat azerí", "displayName-count-one": "manat azerí", "displayName-count-other": "manat azeríes", symbol: "AZN" }, BAD: { displayName: "dinar bosnio", "displayName-count-one": "dinar bosnio", "displayName-count-other": "dinares bosnios", symbol: "BAD" }, BAM: { displayName: "marco convertible de Bosnia-Herzegovina", "displayName-count-one": "marco convertible de Bosnia-Herzegovina", "displayName-count-other": "marcos convertibles de Bosnia-Herzegovina", symbol: "BAM", "symbol-alt-narrow": "KM" }, BAN: { displayName: "BAN", symbol: "BAN" }, BBD: { displayName: "dólar barbadense", "displayName-count-one": "dólar barbadense", "displayName-count-other": "dólares barbadenses", symbol: "BBD", "symbol-alt-narrow": "$" }, BDT: { displayName: "taka", "displayName-count-one": "taka", "displayName-count-other": "takas", symbol: "BDT", "symbol-alt-narrow": "৳" }, BEC: { displayName: "franco belga (convertible)", "displayName-count-one": "franco belga (convertible)", "displayName-count-other": "francos belgas (convertibles)", symbol: "BEC" }, BEF: { displayName: "franco belga", "displayName-count-one": "franco belga", "displayName-count-other": "francos belgas", symbol: "BEF" }, BEL: { displayName: "franco belga (financiero)", "displayName-count-one": "franco belga (financiero)", "displayName-count-other": "francos belgas (financieros)", symbol: "BEL" }, BGL: { displayName: "lev fuerte búlgaro", "displayName-count-one": "lev fuerte búlgaro", "displayName-count-other": "leva fuertes búlgaros", symbol: "BGL" }, BGM: { displayName: "BGM", symbol: "BGM" }, BGN: { displayName: "lev búlgaro", "displayName-count-one": "lev búlgaro", "displayName-count-other": "leva búlgaros", symbol: "BGN" }, BGO: { displayName: "BGO", symbol: "BGO" }, BHD: { displayName: "dinar bahreiní", "displayName-count-one": "dinar bahreiní", "displayName-count-other": "dinares bahreiníes", symbol: "BHD" }, BIF: { displayName: "franco burundés", "displayName-count-one": "franco burundés", "displayName-count-other": "francos burundeses", symbol: "BIF" }, BMD: { displayName: "dólar de Bermudas", "displayName-count-one": "dólar de Bermudas", "displayName-count-other": "dólares de Bermudas", symbol: "BMD", "symbol-alt-narrow": "$" }, BND: { displayName: "dólar bruneano", "displayName-count-one": "dólar bruneano", "displayName-count-other": "dólares bruneanos", symbol: "BND", "symbol-alt-narrow": "$" }, BOB: { displayName: "boliviano", "displayName-count-one": "boliviano", "displayName-count-other": "bolivianos", symbol: "BOB", "symbol-alt-narrow": "Bs" }, BOL: { displayName: "BOL", symbol: "BOL" }, BOP: { displayName: "peso boliviano", "displayName-count-one": "peso boliviano", "displayName-count-other": "pesos bolivianos", symbol: "BOP" }, BOV: { displayName: "MVDOL boliviano", "displayName-count-one": "MVDOL boliviano", "displayName-count-other": "MVDOL bolivianos", symbol: "BOV" }, BRB: { displayName: "nuevo cruceiro brasileño (1967–1986)", "displayName-count-one": "nuevo cruzado brasileño (BRB)", "displayName-count-other": "nuevos cruzados brasileños (BRB)", symbol: "BRB" }, BRC: { displayName: "cruzado brasileño", "displayName-count-one": "cruzado brasileño", "displayName-count-other": "cruzados brasileños", symbol: "BRC" }, BRE: { displayName: "cruceiro brasileño (1990–1993)", "displayName-count-one": "cruceiro brasileño (BRE)", "displayName-count-other": "cruceiros brasileños (BRE)", symbol: "BRE" }, BRL: { displayName: "real brasileño", "displayName-count-one": "real brasileño", "displayName-count-other": "reales brasileños", symbol: "BRL", "symbol-alt-narrow": "R$" }, BRN: { displayName: "nuevo cruzado brasileño", "displayName-count-one": "nuevo cruzado brasileño", "displayName-count-other": "nuevos cruzados brasileños", symbol: "BRN" }, BRR: { displayName: "cruceiro brasileño", "displayName-count-one": "cruceiro brasileño", "displayName-count-other": "cruceiros brasileños", symbol: "BRR" }, BRZ: { displayName: "BRZ", symbol: "BRZ" }, BSD: { displayName: "dólar bahameño", "displayName-count-one": "dólar bahameño", "displayName-count-other": "dólares bahameños", symbol: "BSD", "symbol-alt-narrow": "$" }, BTN: { displayName: "gultrum", "displayName-count-one": "gultrum", "displayName-count-other": "gultrums", symbol: "BTN" }, BUK: { displayName: "kyat birmano", "displayName-count-one": "kyat birmano", "displayName-count-other": "kyat birmanos", symbol: "BUK" }, BWP: { displayName: "pula", "displayName-count-one": "pula", "displayName-count-other": "pulas", symbol: "BWP", "symbol-alt-narrow": "P" }, BYB: { displayName: "nuevo rublo bielorruso (1994–1999)", "displayName-count-one": "nuevo rublo bielorruso", "displayName-count-other": "nuevos rublos bielorrusos", symbol: "BYB" }, BYN: { displayName: "rublo bielorruso", "displayName-count-one": "rublo bielorruso", "displayName-count-other": "rublos bielorrusos", symbol: "BYN", "symbol-alt-narrow": "р." }, BYR: { displayName: "rublo bielorruso (2000–2016)", "displayName-count-one": "rublo bielorruso (2000–2016)", "displayName-count-other": "rublos bielorrusos (2000–2016)", symbol: "BYR" }, BZD: { displayName: "dólar beliceño", "displayName-count-one": "dólar beliceño", "displayName-count-other": "dólares beliceños", symbol: "BZD", "symbol-alt-narrow": "$" }, CAD: { displayName: "dólar canadiense", "displayName-count-one": "dólar canadiense", "displayName-count-other": "dólares canadienses", symbol: "CAD", "symbol-alt-narrow": "$" }, CDF: { displayName: "franco congoleño", "displayName-count-one": "franco congoleño", "displayName-count-other": "francos congoleños", symbol: "CDF" }, CHE: { displayName: "euro WIR", "displayName-count-one": "euro WIR", "displayName-count-other": "euros WIR", symbol: "CHE" }, CHF: { displayName: "franco suizo", "displayName-count-one": "franco suizo", "displayName-count-other": "francos suizos", symbol: "CHF" }, CHW: { displayName: "franco WIR", "displayName-count-one": "franco WIR", "displayName-count-other": "francos WIR", symbol: "CHW" }, CLE: { displayName: "CLE", symbol: "CLE" }, CLF: { displayName: "unidad de fomento chilena", "displayName-count-one": "unidad de fomento chilena", "displayName-count-other": "unidades de fomento chilenas", symbol: "CLF" }, CLP: { displayName: "peso chileno", "displayName-count-one": "peso chileno", "displayName-count-other": "pesos chilenos", symbol: "CLP", "symbol-alt-narrow": "$" }, CNY: { displayName: "yuan", "displayName-count-one": "yuan", "displayName-count-other": "yuanes", symbol: "CNY", "symbol-alt-narrow": "¥" }, COP: { displayName: "peso colombiano", "displayName-count-one": "peso colombiano", "displayName-count-other": "pesos colombianos", symbol: "COP", "symbol-alt-narrow": "$" }, COU: { displayName: "unidad de valor real colombiana", "displayName-count-one": "unidad de valor real", "displayName-count-other": "unidades de valor reales", symbol: "COU" }, CRC: { displayName: "colón costarricense", "displayName-count-one": "colón costarricense", "displayName-count-other": "colones costarricenses", symbol: "CRC", "symbol-alt-narrow": "₡" }, CSD: { displayName: "antiguo dinar serbio", "displayName-count-one": "antiguo dinar serbio", "displayName-count-other": "antiguos dinares serbios", symbol: "CSD" }, CSK: { displayName: "corona fuerte checoslovaca", "displayName-count-one": "corona fuerte checoslovaca", "displayName-count-other": "coronas fuertes checoslovacas", symbol: "CSK" }, CUC: { displayName: "peso cubano convertible", "displayName-count-one": "peso cubano convertible", "displayName-count-other": "pesos cubanos convertibles", symbol: "CUC", "symbol-alt-narrow": "$" }, CUP: { displayName: "peso cubano", "displayName-count-one": "peso cubano", "displayName-count-other": "pesos cubanos", symbol: "$", "symbol-alt-narrow": "$" }, CVE: { displayName: "escudo de Cabo Verde", "displayName-count-one": "escudo de Cabo Verde", "displayName-count-other": "escudos de Cabo Verde", symbol: "CVE" }, CYP: { displayName: "libra chipriota", "displayName-count-one": "libra chipriota", "displayName-count-other": "libras chipriotas", symbol: "CYP" }, CZK: { displayName: "corona checa", "displayName-count-one": "corona checa", "displayName-count-other": "coronas checas", symbol: "CZK", "symbol-alt-narrow": "Kč" }, DDM: { displayName: "ostmark de Alemania del Este", "displayName-count-one": "marco de la República Democrática Alemana", "displayName-count-other": "marcos de la República Democrática Alemana", symbol: "DDM" }, DEM: { displayName: "marco alemán", "displayName-count-one": "marco alemán", "displayName-count-other": "marcos alemanes", symbol: "DEM" }, DJF: { displayName: "franco yibutiano", "displayName-count-one": "franco yibutiano", "displayName-count-other": "francos yibutianos", symbol: "DJF" }, DKK: { displayName: "corona danesa", "displayName-count-one": "corona danesa", "displayName-count-other": "coronas danesas", symbol: "DKK", "symbol-alt-narrow": "kr" }, DOP: { displayName: "peso dominicano", "displayName-count-one": "peso dominicano", "displayName-count-other": "pesos dominicanos", symbol: "DOP", "symbol-alt-narrow": "$" }, DZD: { displayName: "dinar argelino", "displayName-count-one": "dinar argelino", "displayName-count-other": "dinares argelinos", symbol: "DZD" }, ECS: { displayName: "sucre ecuatoriano", "displayName-count-one": "sucre ecuatoriano", "displayName-count-other": "sucres ecuatorianos", symbol: "ECS" }, ECV: { displayName: "unidad de valor constante (UVC) ecuatoriana", "displayName-count-one": "unidad de valor constante (UVC) ecuatoriana", "displayName-count-other": "unidades de valor constante (UVC) ecuatorianas", symbol: "ECV" }, EEK: { displayName: "corona estonia", "displayName-count-one": "corona estonia", "displayName-count-other": "coronas estonias", symbol: "EEK" }, EGP: { displayName: "libra egipcia", "displayName-count-one": "libra egipcia", "displayName-count-other": "libras egipcias", symbol: "EGP", "symbol-alt-narrow": "E£" }, ERN: { displayName: "nafka", "displayName-count-one": "nakfa", "displayName-count-other": "nakfas", symbol: "ERN" }, ESA: { displayName: "peseta española (cuenta A)", "displayName-count-one": "peseta española (cuenta A)", "displayName-count-other": "pesetas españolas (cuenta A)", symbol: "ESA" }, ESB: { displayName: "peseta española (cuenta convertible)", "displayName-count-one": "peseta española (cuenta convertible)", "displayName-count-other": "pesetas españolas (cuenta convertible)", symbol: "ESB" }, ESP: { displayName: "peseta española", "displayName-count-one": "peseta española", "displayName-count-other": "pesetas españolas", symbol: "₧", "symbol-alt-narrow": "₧" }, ETB: { displayName: "bir", "displayName-count-one": "bir", "displayName-count-other": "bires", symbol: "ETB" }, EUR: { displayName: "euro", "displayName-count-one": "euro", "displayName-count-other": "euros", symbol: "EUR", "symbol-alt-narrow": "€" }, FIM: { displayName: "marco finlandés", "displayName-count-one": "marco finlandés", "displayName-count-other": "marcos finlandeses", symbol: "FIM" }, FJD: { displayName: "dólar fiyiano", "displayName-count-one": "dólar fiyiano", "displayName-count-other": "dólares fiyianos", symbol: "FJD", "symbol-alt-narrow": "$" }, FKP: { displayName: "libra malvinense", "displayName-count-one": "libra malvinense", "displayName-count-other": "libras malvinenses", symbol: "FKP", "symbol-alt-narrow": "£" }, FRF: { displayName: "franco francés", "displayName-count-one": "franco francés", "displayName-count-other": "francos franceses", symbol: "FRF" }, GBP: { displayName: "libra británica", "displayName-count-one": "libra británica", "displayName-count-other": "libras británicas", symbol: "GBP", "symbol-alt-narrow": "£" }, GEK: { displayName: "kupon larit georgiano", symbol: "GEK" }, GEL: { displayName: "lari", "displayName-count-one": "lari", "displayName-count-other": "laris", symbol: "GEL", "symbol-alt-narrow": "₾", "symbol-alt-variant": "₾" }, GHC: { displayName: "cedi ghanés (1979–2007)", symbol: "GHC" }, GHS: { displayName: "cedi", "displayName-count-one": "cedi", "displayName-count-other": "cedis", symbol: "GHS" }, GIP: { displayName: "libra gibraltareña", "displayName-count-one": "libra gibraltareña", "displayName-count-other": "libras gibraltareñas", symbol: "GIP", "symbol-alt-narrow": "£" }, GMD: { displayName: "dalasi", "displayName-count-one": "dalasi", "displayName-count-other": "dalasis", symbol: "GMD" }, GNF: { displayName: "franco guineano", "displayName-count-one": "franco guineano", "displayName-count-other": "francos guineanos", symbol: "GNF", "symbol-alt-narrow": "FG" }, GNS: { displayName: "syli guineano", symbol: "GNS" }, GQE: { displayName: "ekuele de Guinea Ecuatorial", "displayName-count-one": "ekuele de Guinea Ecuatorial", "displayName-count-other": "ekueles de Guinea Ecuatorial", symbol: "GQE" }, GRD: { displayName: "dracma griego", "displayName-count-one": "dracma griego", "displayName-count-other": "dracmas griegos", symbol: "GRD" }, GTQ: { displayName: "quetzal guatemalteco", "displayName-count-one": "quetzal guatemalteco", "displayName-count-other": "quetzales guatemaltecos", symbol: "GTQ", "symbol-alt-narrow": "Q" }, GWE: { displayName: "escudo de Guinea Portuguesa", symbol: "GWE" }, GWP: { displayName: "peso de Guinea-Bissáu", symbol: "GWP" }, GYD: { displayName: "dólar guyanés", "displayName-count-one": "dólar guyanés", "displayName-count-other": "dólares guyaneses", symbol: "GYD", "symbol-alt-narrow": "$" }, HKD: { displayName: "dólar hongkonés", "displayName-count-one": "dólar hongkonés", "displayName-count-other": "dólares hongkoneses", symbol: "HKD", "symbol-alt-narrow": "$" }, HNL: { displayName: "lempira hondureño", "displayName-count-one": "lempira hondureño", "displayName-count-other": "lempiras hondureños", symbol: "HNL", "symbol-alt-narrow": "L" }, HRD: { displayName: "dinar croata", "displayName-count-one": "dinar croata", "displayName-count-other": "dinares croatas", symbol: "HRD" }, HRK: { displayName: "kuna", "displayName-count-one": "kuna", "displayName-count-other": "kunas", symbol: "HRK", "symbol-alt-narrow": "kn" }, HTG: { displayName: "gourde haitiano", "displayName-count-one": "gourde haitiano", "displayName-count-other": "gourdes haitianos", symbol: "HTG" }, HUF: { displayName: "forinto húngaro", "displayName-count-one": "forinto húngaro", "displayName-count-other": "forintos húngaros", symbol: "HUF", "symbol-alt-narrow": "Ft" }, IDR: { displayName: "rupia indonesia", "displayName-count-one": "rupia indonesia", "displayName-count-other": "rupias indonesias", symbol: "IDR", "symbol-alt-narrow": "Rp" }, IEP: { displayName: "libra irlandesa", "displayName-count-one": "libra irlandesa", "displayName-count-other": "libras irlandesas", symbol: "IEP" }, ILP: { displayName: "libra israelí", "displayName-count-one": "libra israelí", "displayName-count-other": "libras israelíes", symbol: "ILP" }, ILS: { displayName: "nuevo séquel israelí", "displayName-count-one": "nuevo séquel israelí", "displayName-count-other": "nuevos séqueles israelíes", symbol: "ILS", "symbol-alt-narrow": "₪" }, INR: { displayName: "rupia india", "displayName-count-one": "rupia india", "displayName-count-other": "rupias indias", symbol: "INR", "symbol-alt-narrow": "₹" }, IQD: { displayName: "dinar iraquí", "displayName-count-one": "dinar iraquí", "displayName-count-other": "dinares iraquíes", symbol: "IQD" }, IRR: { displayName: "rial iraní", "displayName-count-one": "rial iraní", "displayName-count-other": "riales iraníes", symbol: "IRR" }, ISK: { displayName: "corona islandesa", "displayName-count-one": "corona islandesa", "displayName-count-other": "coronas islandesas", symbol: "ISK", "symbol-alt-narrow": "kr" }, ITL: { displayName: "lira italiana", "displayName-count-one": "lira italiana", "displayName-count-other": "liras italianas", symbol: "ITL" }, JMD: { displayName: "dólar jamaicano", "displayName-count-one": "dólar jamaicano", "displayName-count-other": "dólares jamaicanos", symbol: "JMD", "symbol-alt-narrow": "$" }, JOD: { displayName: "dinar jordano", "displayName-count-one": "dinar jordano", "displayName-count-other": "dinares jordanos", symbol: "JOD" }, JPY: { displayName: "yen", "displayName-count-one": "yen", "displayName-count-other": "yenes", symbol: "JPY", "symbol-alt-narrow": "¥" }, KES: { displayName: "chelín keniano", "displayName-count-one": "chelín keniano", "displayName-count-other": "chelines kenianos", symbol: "KES" }, KGS: { displayName: "som", "displayName-count-one": "som", "displayName-count-other": "soms", symbol: "KGS" }, KHR: { displayName: "riel", "displayName-count-one": "riel", "displayName-count-other": "rieles", symbol: "KHR", "symbol-alt-narrow": "៛" }, KMF: { displayName: "franco comorense", "displayName-count-one": "franco comorense", "displayName-count-other": "francos comorenses", symbol: "KMF", "symbol-alt-narrow": "CF" }, KPW: { displayName: "won norcoreano", "displayName-count-one": "won norcoreano", "displayName-count-other": "wons norcoreanos", symbol: "KPW", "symbol-alt-narrow": "₩" }, KRH: { displayName: "KRH", symbol: "KRH" }, KRO: { displayName: "KRO", symbol: "KRO" }, KRW: { displayName: "won surcoreano", "displayName-count-one": "won surcoreano", "displayName-count-other": "wons surcoreanos", symbol: "KRW", "symbol-alt-narrow": "₩" }, KWD: { displayName: "dinar kuwaití", "displayName-count-one": "dinar kuwaití", "displayName-count-other": "dinares kuwaitíes", symbol: "KWD" }, KYD: { displayName: "dólar de las Islas Caimán", "displayName-count-one": "dólar de las Islas Caimán", "displayName-count-other": "dólares de las Islas Caimán", symbol: "KYD", "symbol-alt-narrow": "$" }, KZT: { displayName: "tenge kazako", "displayName-count-one": "tenge kazako", "displayName-count-other": "tenges kazakos", symbol: "KZT", "symbol-alt-narrow": "₸" }, LAK: { displayName: "kip", "displayName-count-one": "kip", "displayName-count-other": "kips", symbol: "LAK", "symbol-alt-narrow": "₭" }, LBP: { displayName: "libra libanesa", "displayName-count-one": "libra libanesa", "displayName-count-other": "libras libanesas", symbol: "LBP", "symbol-alt-narrow": "L£" }, LKR: { displayName: "rupia esrilanquesa", "displayName-count-one": "rupia esrilanquesa", "displayName-count-other": "rupias esrilanquesas", symbol: "LKR", "symbol-alt-narrow": "Rs" }, LRD: { displayName: "dólar liberiano", "displayName-count-one": "dólar liberiano", "displayName-count-other": "dólares liberianos", symbol: "LRD", "symbol-alt-narrow": "$" }, LSL: { displayName: "loti lesothense", symbol: "LSL" }, LTL: { displayName: "litas lituano", "displayName-count-one": "litas lituana", "displayName-count-other": "litas lituanas", symbol: "LTL", "symbol-alt-narrow": "Lt" }, LTT: { displayName: "talonas lituano", "displayName-count-one": "talonas lituana", "displayName-count-other": "talonas lituanas", symbol: "LTT" }, LUC: { displayName: "franco convertible luxemburgués", "displayName-count-one": "franco convertible luxemburgués", "displayName-count-other": "francos convertibles luxemburgueses", symbol: "LUC" }, LUF: { displayName: "franco luxemburgués", "displayName-count-one": "franco luxemburgués", "displayName-count-other": "francos luxemburgueses", symbol: "LUF" }, LUL: { displayName: "franco financiero luxemburgués", "displayName-count-one": "franco financiero luxemburgués", "displayName-count-other": "francos financieros luxemburgueses", symbol: "LUL" }, LVL: { displayName: "lats letón", "displayName-count-one": "lats letón", "displayName-count-other": "lats letónes", symbol: "LVL", "symbol-alt-narrow": "Ls" }, LVR: { displayName: "rublo letón", "displayName-count-one": "rublo letón", "displayName-count-other": "rublos letones", symbol: "LVR" }, LYD: { displayName: "dinar libio", "displayName-count-one": "dinar libio", "displayName-count-other": "dinares libios", symbol: "LYD" }, MAD: { displayName: "dírham marroquí", "displayName-count-one": "dírham marroquí", "displayName-count-other": "dírhams marroquíes", symbol: "MAD" }, MAF: { displayName: "franco marroquí", "displayName-count-one": "franco marroquí", "displayName-count-other": "francos marroquíes", symbol: "MAF" }, MCF: { displayName: "MCF", symbol: "MCF" }, MDC: { displayName: "MDC", symbol: "MDC" }, MDL: { displayName: "leu moldavo", "displayName-count-one": "leu moldavo", "displayName-count-other": "leus moldavos", symbol: "MDL" }, MGA: { displayName: "ariari", "displayName-count-one": "ariari", "displayName-count-other": "ariaris", symbol: "MGA", "symbol-alt-narrow": "Ar" }, MGF: { displayName: "franco malgache", symbol: "MGF" }, MKD: { displayName: "dinar macedonio", "displayName-count-one": "dinar macedonio", "displayName-count-other": "dinares macedonios", symbol: "MKD" }, MKN: { displayName: "MKN", symbol: "MKN" }, MLF: { displayName: "franco malí", symbol: "MLF" }, MMK: { displayName: "kiat", "displayName-count-one": "kiat", "displayName-count-other": "kiats", symbol: "MMK", "symbol-alt-narrow": "K" }, MNT: { displayName: "tugrik", "displayName-count-one": "tugrik", "displayName-count-other": "tugriks", symbol: "MNT", "symbol-alt-narrow": "₮" }, MOP: { displayName: "pataca de Macao", "displayName-count-one": "pataca de Macao", "displayName-count-other": "patacas de Macao", symbol: "MOP" }, MRO: { displayName: "uguiya", "displayName-count-one": "uguiya", "displayName-count-other": "uguiyas", symbol: "MRO" }, MTL: { displayName: "lira maltesa", "displayName-count-one": "lira maltesa", "displayName-count-other": "liras maltesas", symbol: "MTL" }, MTP: { displayName: "libra maltesa", "displayName-count-one": "libra maltesa", "displayName-count-other": "libras maltesas", symbol: "MTP" }, MUR: { displayName: "rupia mauriciana", "displayName-count-one": "rupia mauriciana", "displayName-count-other": "rupias mauricianas", symbol: "MUR", "symbol-alt-narrow": "Rs" }, MVR: { displayName: "rufiya", "displayName-count-one": "rufiya", "displayName-count-other": "rufiyas", symbol: "MVR" }, MWK: { displayName: "kwacha malauí", "displayName-count-one": "kwacha malauí", "displayName-count-other": "kwachas malauís", symbol: "MWK" }, MXN: { displayName: "peso mexicano", "displayName-count-one": "peso mexicano", "displayName-count-other": "pesos mexicanos", symbol: "MXN", "symbol-alt-narrow": "$" }, MXP: { displayName: "peso de plata mexicano (1861–1992)", "displayName-count-one": "peso de plata mexicano (MXP)", "displayName-count-other": "pesos de plata mexicanos (MXP)", symbol: "MXP" }, MXV: { displayName: "unidad de inversión (UDI) mexicana", "displayName-count-one": "unidad de inversión (UDI) mexicana", "displayName-count-other": "unidades de inversión (UDI) mexicanas", symbol: "MXV" }, MYR: { displayName: "ringit", "displayName-count-one": "ringit", "displayName-count-other": "ringits", symbol: "MYR", "symbol-alt-narrow": "RM" }, MZE: { displayName: "escudo mozambiqueño", "displayName-count-one": "escudo mozambiqueño", "displayName-count-other": "escudos mozambiqueños", symbol: "MZE" }, MZM: { displayName: "antiguo metical mozambiqueño", symbol: "MZM" }, MZN: { displayName: "metical", "displayName-count-one": "metical", "displayName-count-other": "meticales", symbol: "MZN" }, NAD: { displayName: "dólar namibio", "displayName-count-one": "dólar namibio", "displayName-count-other": "dólares namibios", symbol: "NAD", "symbol-alt-narrow": "$" }, NGN: { displayName: "naira", "displayName-count-one": "naira", "displayName-count-other": "nairas", symbol: "NGN", "symbol-alt-narrow": "₦" }, NIC: { displayName: "córdoba nicaragüense (1988–1991)", "displayName-count-one": "córdoba nicaragüense (1988–1991)", "displayName-count-other": "córdobas nicaragüenses (1988–1991)", symbol: "NIC" }, NIO: { displayName: "córdoba nicaragüense", "displayName-count-one": "córdoba nicaragüense", "displayName-count-other": "córdobas nicaragüenses", symbol: "NIO", "symbol-alt-narrow": "C$" }, NLG: { displayName: "florín neerlandés", "displayName-count-one": "florín neerlandés", "displayName-count-other": "florines neerlandeses", symbol: "NLG" }, NOK: { displayName: "corona noruega", "displayName-count-one": "corona noruega", "displayName-count-other": "coronas noruegas", symbol: "NOK", "symbol-alt-narrow": "kr" }, NPR: { displayName: "rupia nepalí", "displayName-count-one": "rupia nepalí", "displayName-count-other": "rupias nepalíes", symbol: "NPR", "symbol-alt-narrow": "Rs" }, NZD: { displayName: "dólar neozelandés", "displayName-count-one": "dólar neozelandés", "displayName-count-other": "dólares neozelandeses", symbol: "NZD", "symbol-alt-narrow": "$" }, OMR: { displayName: "rial omaní", "displayName-count-one": "rial omaní", "displayName-count-other": "riales omaníes", symbol: "OMR" }, PAB: { displayName: "balboa panameño", "displayName-count-one": "balboa panameño", "displayName-count-other": "balboas panameños", symbol: "PAB" }, PEI: { displayName: "inti peruano", "displayName-count-one": "inti peruano", "displayName-count-other": "intis peruanos", symbol: "PEI" }, PEN: { displayName: "sol peruano", "displayName-count-one": "sol peruano", "displayName-count-other": "soles peruanos", symbol: "PEN" }, PES: { displayName: "sol peruano (1863–1965)", "displayName-count-one": "sol peruano (1863–1965)", "displayName-count-other": "soles peruanos (1863–1965)", symbol: "PES" }, PGK: { displayName: "kina", "displayName-count-one": "kina", "displayName-count-other": "kinas", symbol: "PGK" }, PHP: { displayName: "peso filipino", "displayName-count-one": "peso filipino", "displayName-count-other": "pesos filipinos", symbol: "PHP", "symbol-alt-narrow": "₱" }, PKR: { displayName: "rupia pakistaní", "displayName-count-one": "rupia pakistaní", "displayName-count-other": "rupias pakistaníes", symbol: "PKR", "symbol-alt-narrow": "Rs" }, PLN: { displayName: "esloti", "displayName-count-one": "esloti", "displayName-count-other": "eslotis", symbol: "PLN", "symbol-alt-narrow": "zł" }, PLZ: { displayName: "zloty polaco (1950–1995)", "displayName-count-one": "zloty polaco (PLZ)", "displayName-count-other": "zlotys polacos (PLZ)", symbol: "PLZ" }, PTE: { displayName: "escudo portugués", "displayName-count-one": "escudo portugués", "displayName-count-other": "escudos portugueses", symbol: "PTE" }, PYG: { displayName: "guaraní paraguayo", "displayName-count-one": "guaraní paraguayo", "displayName-count-other": "guaraníes paraguayos", symbol: "PYG", "symbol-alt-narrow": "₲" }, QAR: { displayName: "rial catarí", "displayName-count-one": "rial catarí", "displayName-count-other": "riales cataríes", symbol: "QAR" }, RHD: { displayName: "dólar rodesiano", symbol: "RHD" }, ROL: { displayName: "antiguo leu rumano", "displayName-count-one": "antiguo leu rumano", "displayName-count-other": "antiguos lei rumanos", symbol: "ROL" }, RON: { displayName: "leu rumano", "displayName-count-one": "leu rumano", "displayName-count-other": "leus rumanos", symbol: "RON", "symbol-alt-narrow": "L" }, RSD: { displayName: "dinar serbio", "displayName-count-one": "dinar serbio", "displayName-count-other": "dinares serbios", symbol: "RSD" }, RUB: { displayName: "rublo ruso", "displayName-count-one": "rublo ruso", "displayName-count-other": "rublos rusos", symbol: "RUB", "symbol-alt-narrow": "₽" }, RUR: { displayName: "rublo ruso (1991–1998)", "displayName-count-one": "rublo ruso (RUR)", "displayName-count-other": "rublos rusos (RUR)", symbol: "RUR", "symbol-alt-narrow": "р." }, RWF: { displayName: "franco ruandés", "displayName-count-one": "franco ruandés", "displayName-count-other": "francos ruandeses", symbol: "RWF", "symbol-alt-narrow": "RF" }, SAR: { displayName: "rial saudí", "displayName-count-one": "rial saudí", "displayName-count-other": "riales saudíes", symbol: "SAR" }, SBD: { displayName: "dólar salomonense", "displayName-count-one": "dólar salomonense", "displayName-count-other": "dólares salomonenses", symbol: "SBD", "symbol-alt-narrow": "$" }, SCR: { displayName: "rupia seychellense", "displayName-count-one": "rupia seychellense", "displayName-count-other": "rupias seychellenses", symbol: "SCR" }, SDD: { displayName: "dinar sudanés", "displayName-count-one": "dinar sudanés", "displayName-count-other": "dinares sudaneses", symbol: "SDD" }, SDG: { displayName: "libra sudanesa", "displayName-count-one": "libra sudanesa", "displayName-count-other": "libras sudanesas", symbol: "SDG" }, SDP: { displayName: "libra sudanesa antigua", "displayName-count-one": "libra sudanesa antigua", "displayName-count-other": "libras sudanesas antiguas", symbol: "SDP" }, SEK: { displayName: "corona sueca", "displayName-count-one": "corona sueca", "displayName-count-other": "coronas suecas", symbol: "SEK", "symbol-alt-narrow": "kr" }, SGD: { displayName: "dólar singapurense", "displayName-count-one": "dólar singapurense", "displayName-count-other": "dólares singapurenses", symbol: "SGD", "symbol-alt-narrow": "$" }, SHP: { displayName: "libra de Santa Elena", "displayName-count-one": "libra de Santa Elena", "displayName-count-other": "libras de Santa Elena", symbol: "SHP", "symbol-alt-narrow": "£" }, SIT: { displayName: "tólar esloveno", "displayName-count-one": "tólar esloveno", "displayName-count-other": "tólares eslovenos", symbol: "SIT" }, SKK: { displayName: "corona eslovaca", "displayName-count-one": "corona eslovaca", "displayName-count-other": "coronas eslovacas", symbol: "SKK" }, SLL: { displayName: "leona", "displayName-count-one": "leona", "displayName-count-other": "leonas", symbol: "SLL" }, SOS: { displayName: "chelín somalí", "displayName-count-one": "chelín somalí", "displayName-count-other": "chelines somalíes", symbol: "SOS" }, SRD: { displayName: "dólar surinamés", "displayName-count-one": "dólar surinamés", "displayName-count-other": "dólares surinameses", symbol: "SRD", "symbol-alt-narrow": "$" }, SRG: { displayName: "florín surinamés", symbol: "SRG" }, SSP: { displayName: "libra sursudanesa", "displayName-count-one": "libra sursudanesa", "displayName-count-other": "libras sursudanesas", symbol: "SSP", "symbol-alt-narrow": "£" }, STD: { displayName: "dobra", "displayName-count-one": "dobra", "displayName-count-other": "dobras", symbol: "STD", "symbol-alt-narrow": "Db" }, SUR: { displayName: "rublo soviético", "displayName-count-one": "rublo soviético", "displayName-count-other": "rublos soviéticos", symbol: "SUR" }, SVC: { displayName: "colón salvadoreño", "displayName-count-one": "colón salvadoreño", "displayName-count-other": "colones salvadoreños", symbol: "SVC" }, SYP: { displayName: "libra siria", "displayName-count-one": "libra siria", "displayName-count-other": "libras sirias", symbol: "SYP", "symbol-alt-narrow": "£" }, SZL: { displayName: "lilangeni", "displayName-count-one": "lilangeni", "displayName-count-other": "lilangenis", symbol: "SZL" }, THB: { displayName: "bat", "displayName-count-one": "bat", "displayName-count-other": "bats", symbol: "THB", "symbol-alt-narrow": "฿" }, TJR: { displayName: "rublo tayiko", symbol: "TJR" }, TJS: { displayName: "somoni tayiko", "displayName-count-one": "somoni tayiko", "displayName-count-other": "somonis tayikos", symbol: "TJS" }, TMM: { displayName: "manat turcomano (1993–2009)", "displayName-count-one": "manat turcomano (1993–2009)", "displayName-count-other": "manats turcomanos (1993–2009)", symbol: "TMM" }, TMT: { displayName: "manat turcomano", "displayName-count-one": "manat turcomano", "displayName-count-other": "manats turcomanos", symbol: "TMT" }, TND: { displayName: "dinar tunecino", "displayName-count-one": "dinar tunecino", "displayName-count-other": "dinares tunecinos", symbol: "TND" }, TOP: { displayName: "paanga", "displayName-count-one": "paanga", "displayName-count-other": "paangas", symbol: "TOP", "symbol-alt-narrow": "T$" }, TPE: { displayName: "escudo timorense", symbol: "TPE" }, TRL: { displayName: "lira turca (1922–2005)", "displayName-count-one": "lira turca (1922–2005)", "displayName-count-other": "liras turcas (1922–2005)", symbol: "TRL" }, TRY: { displayName: "lira turca", "displayName-count-one": "lira turca", "displayName-count-other": "liras turcas", symbol: "TRY", "symbol-alt-narrow": "₺", "symbol-alt-variant": "TL" }, TTD: { displayName: "dólar de Trinidad y Tobago", "displayName-count-one": "dólar de Trinidad y Tobago", "displayName-count-other": "dólares de Trinidad y Tobago", symbol: "TTD", "symbol-alt-narrow": "$" }, TWD: { displayName: "nuevo dólar taiwanés", "displayName-count-one": "nuevo dólar taiwanés", "displayName-count-other": "nuevos dólares taiwaneses", symbol: "TWD", "symbol-alt-narrow": "NT$" }, TZS: { displayName: "chelín tanzano", "displayName-count-one": "chelín tanzano", "displayName-count-other": "chelines tanzanos", symbol: "TZS" }, UAH: { displayName: "grivna", "displayName-count-one": "grivna", "displayName-count-other": "grivnas", symbol: "UAH", "symbol-alt-narrow": "₴" }, UAK: { displayName: "karbovanet ucraniano", "displayName-count-one": "karbovanet ucraniano", "displayName-count-other": "karbovanets ucranianos", symbol: "UAK" }, UGS: { displayName: "chelín ugandés (1966–1987)", symbol: "UGS" }, UGX: { displayName: "chelín ugandés", "displayName-count-one": "chelín ugandés", "displayName-count-other": "chelines ugandeses", symbol: "UGX" }, USD: { displayName: "dólar estadounidense", "displayName-count-one": "dólar estadounidense", "displayName-count-other": "dólares estadounidenses", symbol: "US$", "symbol-alt-narrow": "$" }, USN: { displayName: "dólar estadounidense (día siguiente)", "displayName-count-one": "dólar estadounidense (día siguiente)", "displayName-count-other": "dólares estadounidenses (día siguiente)", symbol: "USN" }, USS: { displayName: "dólar estadounidense (mismo día)", "displayName-count-one": "dólar estadounidense (mismo día)", "displayName-count-other": "dólares estadounidenses (mismo día)", symbol: "USS" }, UYI: { displayName: "peso uruguayo en unidades indexadas", "displayName-count-one": "peso uruguayo en unidades indexadas", "displayName-count-other": "pesos uruguayos en unidades indexadas", symbol: "UYI" }, UYP: { displayName: "peso uruguayo (1975–1993)", "displayName-count-one": "peso uruguayo (UYP)", "displayName-count-other": "pesos uruguayos (UYP)", symbol: "UYP" }, UYU: { displayName: "peso uruguayo", "displayName-count-one": "peso uruguayo", "displayName-count-other": "pesos uruguayos", symbol: "UYU", "symbol-alt-narrow": "$" }, UZS: { displayName: "sum", "displayName-count-one": "sum", "displayName-count-other": "sums", symbol: "UZS" }, VEB: { displayName: "bolívar venezolano (1871–2008)", "displayName-count-one": "bolívar venezolano (1871–2008)", "displayName-count-other": "bolívares venezolanos (1871–2008)", symbol: "VEB" }, VEF: { displayName: "bolívar venezolano", "displayName-count-one": "bolívar venezolano", "displayName-count-other": "bolívares venezolanos", symbol: "VEF", "symbol-alt-narrow": "BsF" }, VND: { displayName: "dong", "displayName-count-one": "dong", "displayName-count-other": "dongs", symbol: "VND", "symbol-alt-narrow": "₫" }, VNN: { displayName: "VNN", symbol: "VNN" }, VUV: { displayName: "vatu", "displayName-count-one": "vatu", "displayName-count-other": "vatus", symbol: "VUV" }, WST: { displayName: "tala", "displayName-count-one": "tala", "displayName-count-other": "talas", symbol: "WST" }, XAF: { displayName: "franco CFA BEAC", "displayName-count-one": "franco CFA BEAC", "displayName-count-other": "francos CFA BEAC", symbol: "XAF" }, XAG: { displayName: "plata", "displayName-count-one": "plata", "displayName-count-other": "plata", symbol: "XAG" }, XAU: { displayName: "oro", "displayName-count-one": "oro", "displayName-count-other": "oro", symbol: "XAU" }, XBA: { displayName: "unidad compuesta europea", "displayName-count-one": "unidad compuesta europea", "displayName-count-other": "unidades compuestas europeas", symbol: "XBA" }, XBB: { displayName: "unidad monetaria europea", "displayName-count-one": "unidad monetaria europea", "displayName-count-other": "unidades monetarias europeas", symbol: "XBB" }, XBC: { displayName: "unidad de cuenta europea (XBC)", "displayName-count-one": "unidad de cuenta europea (XBC)", "displayName-count-other": "unidades de cuenta europeas (XBC)", symbol: "XBC" }, XBD: { displayName: "unidad de cuenta europea (XBD)", "displayName-count-one": "unidad de cuenta europea (XBD)", "displayName-count-other": "unidades de cuenta europeas (XBD)", symbol: "XBD" }, XCD: { displayName: "dólar del Caribe Oriental", "displayName-count-one": "dólar del Caribe Oriental", "displayName-count-other": "dólares del Caribe Oriental", symbol: "XCD", "symbol-alt-narrow": "$" }, XDR: { displayName: "derechos especiales de giro", symbol: "XDR" }, XEU: { displayName: "unidad de moneda europea", "displayName-count-one": "unidad de moneda europea", "displayName-count-other": "unidades de moneda europeas", symbol: "XEU" }, XFO: { displayName: "franco oro francés", "displayName-count-one": "franco oro francés", "displayName-count-other": "francos oro franceses", symbol: "XFO" }, XFU: { displayName: "franco UIC francés", "displayName-count-one": "franco UIC francés", "displayName-count-other": "francos UIC franceses", symbol: "XFU" }, XOF: { displayName: "franco CFA BCEAO", "displayName-count-one": "franco CFA BCEAO", "displayName-count-other": "francos CFA BCEAO", symbol: "XOF" }, XPD: { displayName: "paladio", "displayName-count-one": "paladio", "displayName-count-other": "paladio", symbol: "XPD" }, XPF: { displayName: "franco CFP", "displayName-count-one": "franco CFP", "displayName-count-other": "francos CFP", symbol: "CFPF" }, XPT: { displayName: "platino", "displayName-count-one": "platino", "displayName-count-other": "platino", symbol: "XPT" }, XRE: { displayName: "fondos RINET", symbol: "XRE" }, XSU: { displayName: "XSU", symbol: "XSU" }, XTS: { displayName: "código reservado para pruebas", symbol: "XTS" }, XUA: { displayName: "XUA", symbol: "XUA" }, XXX: { displayName: "moneda desconocida", "displayName-count-one": "(unidad de moneda desconocida)", "displayName-count-other": "(moneda desconocida)", symbol: "XXX" }, YDD: { displayName: "dinar yemení", symbol: "YDD" }, YER: { displayName: "rial yemení", "displayName-count-one": "rial yemení", "displayName-count-other": "riales yemeníes", symbol: "YER" }, YUD: { displayName: "dinar fuerte yugoslavo", symbol: "YUD" }, YUM: { displayName: "super dinar yugoslavo", symbol: "YUM" }, YUN: { displayName: "dinar convertible yugoslavo", "displayName-count-one": "dinar convertible yugoslavo", "displayName-count-other": "dinares convertibles yugoslavos", symbol: "YUN" }, YUR: { displayName: "YUR", symbol: "YUR" }, ZAL: { displayName: "rand sudafricano (financiero)", symbol: "ZAL" }, ZAR: { displayName: "rand", "displayName-count-one": "rand", "displayName-count-other": "rands", symbol: "ZAR", "symbol-alt-narrow": "R" }, ZMK: { displayName: "kwacha zambiano (1968–2012)", "displayName-count-one": "kwacha zambiano (1968–2012)", "displayName-count-other": "kwachas zambianos (1968–2012)", symbol: "ZMK" }, ZMW: { displayName: "kuacha zambiano", "displayName-count-one": "kuacha zambiano", "displayName-count-other": "kuachas zambianos", symbol: "ZMW", "symbol-alt-narrow": "ZK" }, ZRN: { displayName: "nuevo zaire zaireño", symbol: "ZRN" }, ZRZ: { displayName: "zaire zaireño", symbol: "ZRZ" }, ZWD: { displayName: "dólar de Zimbabue", symbol: "ZWD" }, ZWL: { displayName: "dólar zimbabuense", symbol: "ZWL" }, ZWR: { displayName: "ZWR", symbol: "ZWR" } }, localeCurrency: "CUC" }, calendar: { patterns: { d: "d/M/y", D: "EEEE, d 'de' MMMM 'de' y", m: "d MMM", M: "d 'de' MMMM", y: "MMMM 'de' y", Y: "MMMM 'de' y", F: "EEEE, d 'de' MMMM 'de' y HH:mm:ss", g: "d/M/y HH:mm", G: "d/M/y HH:mm:ss", t: "HH:mm", T: "HH:mm:ss", s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss", u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'" }, dateTimeFormats: { full: "{1}, {0}", long: "{1}, {0}", medium: "{1} {0}", short: "{1} {0}", availableFormats: { d: "d", E: "ccc", Ed: "E d", Ehm: "E, h:mm a", EHm: "E, HH:mm", Ehms: "E, h:mm:ss a", EHms: "E, HH:mm:ss", Gy: "y G", GyMMM: "MMM y G", GyMMMd: "d 'de' MMM 'de' y G", GyMMMEd: "E, d MMM y G", GyMMMM: "MMMM 'de' y G", GyMMMMd: "d 'de' MMMM 'de' y G", GyMMMMEd: "E, d 'de' MMMM 'de' y G", h: "h a", H: "HH", hm: "h:mm a", Hm: "HH:mm", hms: "h:mm:ss a", Hms: "HH:mm:ss", hmsv: "h:mm:ss a v", Hmsv: "H:mm:ss v", hmsvvvv: "h:mm:ss a (vvvv)", Hmsvvvv: "H:mm:ss (vvvv)", hmv: "h:mm a v", Hmv: "H:mm v", M: "L", Md: "d/M", MEd: "E, d/M", MMd: "d/M", MMdd: "d/M", MMM: "LLL", MMMd: "d MMM", MMMdd: "dd-MMM", MMMEd: "E, d MMM", MMMMd: "d 'de' MMMM", MMMMEd: "E, d 'de' MMMM", "MMMMW-count-one": "'semana' W 'de' MMM", "MMMMW-count-other": "'semana' W 'de' MMM", ms: "mm:ss", y: "y", yM: "M/y", yMd: "d/M/y", yMEd: "E d/M/y", yMM: "M/y", yMMM: "MMMM 'de' y", yMMMd: "d 'de' MMMM 'de' y", yMMMEd: "E, d 'de' MMM 'de' y", yMMMM: "MMMM 'de' y", yMMMMd: "d 'de' MMMM 'de' y", yMMMMEd: "EEE, d 'de' MMMM 'de' y", yQQQ: "QQQ 'de' y", yQQQQ: "QQQQ 'de' y", "yw-count-one": "'semana' w 'de' y", "yw-count-other": "'semana' w 'de' y" } }, timeFormats: { full: "HH:mm:ss zzzz", long: "HH:mm:ss z", medium: "HH:mm:ss", short: "HH:mm" }, dateFormats: { full: "EEEE, d 'de' MMMM 'de' y", long: "d 'de' MMMM 'de' y", medium: "d MMM y", short: "d/M/yy" }, days: { format: { abbreviated: [ "dom.", "lun.", "mar.", "mié.", "jue.", "vie.", "sáb." ], narrow: [ "d", "l", "m", "m", "j", "v", "s" ], short: [ "DO", "LU", "MA", "MI", "JU", "VI", "SA" ], wide: [ "domingo", "lunes", "martes", "miércoles", "jueves", "viernes", "sábado" ] }, "stand-alone": { abbreviated: [ "dom.", "lun.", "mar.", "mié.", "jue.", "vie.", "sáb." ], narrow: [ "D", "L", "M", "M", "J", "V", "S" ], short: [ "DO", "LU", "MA", "MI", "JU", "VI", "SA" ], wide: [ "domingo", "lunes", "martes", "miércoles", "jueves", "viernes", "sábado" ] } }, months: { format: { abbreviated: [ "ene.", "feb.", "mar.", "abr.", "may.", "jun.", "jul.", "ago.", "sep.", "oct.", "nov.", "dic." ], narrow: [ "e", "f", "m", "a", "m", "j", "j", "a", "s", "o", "n", "d" ], wide: [ "enero", "febrero", "marzo", "abril", "mayo", "junio", "julio", "agosto", "septiembre", "octubre", "noviembre", "diciembre" ] }, "stand-alone": { abbreviated: [ "ene.", "feb.", "mar.", "abr.", "may.", "jun.", "jul.", "ago.", "sep.", "oct.", "nov.", "dic." ], narrow: [ "E", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D" ], wide: [ "enero", "febrero", "marzo", "abril", "mayo", "junio", "julio", "agosto", "septiembre", "octubre", "noviembre", "diciembre" ] } }, quarters: { format: { abbreviated: [ "T1", "T2", "T3", "T4" ], narrow: [ "1", "2", "3", "4" ], wide: [ "1.er trimestre", "2.º trimestre", "3.er trimestre", "4.º trimestre" ] }, "stand-alone": { abbreviated: [ "T1", "T2", "T3", "T4" ], narrow: [ "1", "2", "3", "4" ], wide: [ "1.er trimestre", "2.º trimestre", "3.er trimestre", "4.º trimestre" ] } }, dayPeriods: { format: { abbreviated: { am: "a.m.", noon: "del mediodía", pm: "p.m.", morning1: "de la madrugada", morning2: "de la mañana", evening1: "de la tarde", night1: "de la noche" }, narrow: { am: "a. m.", noon: "del mediodía", pm: "p. m.", morning1: "de la madrugada", morning2: "de la mañana", evening1: "de la tarde", night1: "de la noche" }, wide: { am: "a.m.", noon: "del mediodía", pm: "p.m.", morning1: "de la madrugada", morning2: "de la mañana", evening1: "de la tarde", night1: "de la noche" } }, "stand-alone": { abbreviated: { am: "a.m.", noon: "mediodía", pm: "p.m.", morning1: "madrugada", morning2: "mañana", evening1: "tarde", night1: "noche" }, narrow: { am: "a.m.", noon: "mediodía", pm: "p.m.", morning1: "madrugada", morning2: "mañana", evening1: "tarde", night1: "noche" }, wide: { am: "a.m.", noon: "mediodía", pm: "p.m.", morning1: "madrugada", morning2: "mañana", evening1: "tarde", night1: "noche" } } }, eras: { format: { wide: { 0: "antes de Cristo", 1: "después de Cristo", "0-alt-variant": "antes de la era común", "1-alt-variant": "era común" }, abbreviated: { 0: "a. C.", 1: "d. C.", "0-alt-variant": "a. e. c.", "1-alt-variant": "e. c." }, narrow: { 0: "a. C.", 1: "d. C.", "0-alt-variant": "a. e. c.", "1-alt-variant": "e. c." } } }, gmtFormat: "GMT{0}", gmtZeroFormat: "GMT", dateFields: { era: { wide: "era", short: "era", narrow: "era" }, year: { wide: "año", short: "a", narrow: "a" }, quarter: { wide: "trimestre", short: "trim.", narrow: "trim." }, month: { wide: "mes", short: "m", narrow: "m" }, week: { wide: "semana", short: "sem.", narrow: "sem." }, weekOfMonth: { wide: "Week Of Month", short: "Week Of Month", narrow: "Week Of Month" }, day: { wide: "día", short: "d", narrow: "d" }, dayOfYear: { wide: "Day Of Year", short: "Day Of Year", narrow: "Day Of Year" }, weekday: { wide: "día de la semana", short: "día de la semana", narrow: "día de la semana" }, weekdayOfMonth: { wide: "Weekday Of Month", short: "Weekday Of Month", narrow: "Weekday Of Month" }, dayperiod: { short: "a.m./p.m.", wide: "a.m./p.m.", narrow: "a.m./p.m." }, hour: { wide: "hora", short: "h", narrow: "h" }, minute: { wide: "minuto", short: "min", narrow: "min" }, second: { wide: "segundo", short: "s", narrow: "s" }, zone: { wide: "Zona horaria", short: "Zona horaria", narrow: "Zona horaria" } } }, firstDay: 1, likelySubtags: { es: "es-Latn-ES" } });
Template.afEachArrayItem.helpers({ innerContext: function afEachArrayItemContext(options) { var c = AutoForm.Utility.normalizeContext(options.hash, "afEachArrayItem"); var formId = c.af.formId; var name = c.atts.name; var docCount = fd.getDocCountForField(formId, name); if (docCount == null) { docCount = c.atts.initialCount; } arrayTracker.initField(formId, name, c.af.ss, docCount, c.atts.minCount, c.atts.maxCount); return arrayTracker.getField(formId, name); } });
if (typeof(MIDI) === 'undefined') var MIDI = {}; if (typeof(MIDI.Soundfont) === 'undefined') MIDI.Soundfont = {}; MIDI.Soundfont.acoustic_grand_piano = { "A0": "data:audio/ogg;base64,YQB1AGQAaQBvAA==", "Bb0": "data:audio/ogg;base64,YQB1AGQAaQBvAA==", "B0": "data:audio/ogg;base64,YQB1AGQAaQBvAA==", "C1": "data:audio/ogg;base64,YQB1AGQAaQBvAA==", "Db1": "data:audio/ogg;base64,YQB1AGQAaQBvAA==", }
var Menu, MenuItem; Menu = yamvc.View.$extend({ defaults: { tpl: new yamvc.view.Template({ config: { id: 'tpl-menu', tpl: [ '<nav class="navbar navbar-inverse navbar-embossed" role="navigation">', '<div class="navbar-header">', '<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar-collapse-01">', '<span class="sr-only">{{locale.toggleNavigation}}</span>', '</button>', '</div>', '<div class="collapse navbar-collapse" id="navbar-collapse-01">', '<ul class="nav navbar-nav navbar-left">' , '</ul>', '</div>', '</nav>' ] } }) } }); MenuItem = yamvc.View.$extend({ defaults: { tpl: new yamvc.view.Template({ config: { id: 'tpl-menu-item', tpl: [ ] } }) } }); yamvc.$onReady(function () { var menu; menu = new Menu({ config : { renderTo : '#menu', models : [ new yamvc.Model({ config : { namespace : 'locale', data : { toggleNavigation : 'Toggle navigation' } } }) ] } }); menu.render(); });
(function () { "use strict"; /** ** DEPENDENCIES ** - angular translate ** - underscore **/ angular.module("lui.translate") .directive("luidTranslations", ["$translate", "_", "$filter", "$timeout", function ($translate, _, $filter, $timeout) { function link(scope, element, attrs, ctrls) { var ngModelCtrl = ctrls[1]; var translateCtrl = ctrls[0]; /** Associations language/code */ var languagesToCodes = { en: 1033, de: 1031, es: 1034, fr: 1036, it: 1040, nl: 2067 }; /** List of all the available languages labels */ var cultures = _.keys(languagesToCodes); scope.cultures = cultures; scope.currentCulture = $translate.preferredLanguage() || "en"; var mode = !!attrs.mode ? attrs.mode : "dictionary"; if (mode === "dictionary" && ngModelCtrl.$viewValue !== undefined) { _.each(cultures, function (culture) { scope.$watch( function () { return !!ngModelCtrl.$viewValue ? ngModelCtrl.$viewValue[culture] : ngModelCtrl.$viewValue; }, function () { ngModelCtrl.$render(); } ); }); } ngModelCtrl.$render = function () { scope.internal = parse(ngModelCtrl.$viewValue); translateCtrl.updateTooltip(); }; translateCtrl.updateViewValue = function () { switch (mode) { case "dictionary": return updateDictionary(scope.internal); case "|": case "pipe": return updatePipe(scope.internal); case "lucca": return updateLucca(scope.internal); } }; translateCtrl.updateTooltip = function () { var tooltipText = ""; if(!!!scope.internal) { scope.tooltipText = undefined; return; } for(var i = 0; i < scope.cultures.length; i++) { if(!!scope.internal[scope.cultures[i]]) { tooltipText += "["+scope.cultures[i].toUpperCase()+"] : "+ scope.internal[scope.cultures[i]] + "\n"; } } scope.tooltipText = tooltipText; }; var parse = function (value) { if (value === undefined) { return undefined; } switch (mode) { case "dictionary": return parseDictionary(value); case "|": case "pipe": return parsePipe(value); case "lucca": return parseLucca(value); default: return undefined; } }; // Mode lucca var parseLucca = function (value) { return _.reduce(cultures, function (memo, culture) { var targetLabel = _.findWhere(value, { cultureCode: languagesToCodes[culture] }); memo[culture] = !!targetLabel ? targetLabel.value : undefined; // We need to keep the original id memo[culture + "_id"] = !!targetLabel ? targetLabel.id : undefined; return memo; }, {}); }; var updateLucca = function (value) { var allEmpty = true; var viewValue = []; _.each(cultures, function (culture) { if (!!value[culture] && value[culture] !== "") { viewValue.push({ id: value[culture + "_id"], cultureCode: languagesToCodes[culture], value: value[culture] }); allEmpty = false; } }); ngModelCtrl.$setViewValue(allEmpty ? undefined : viewValue); scope.$parent.$eval(attrs.ngChange); }; // Mode dictionary var parseDictionary = function (value) { return _.reduce(cultures, function (memo, culture) { memo[culture] = value[culture]; return memo; }, {}); }; var updateDictionary = function (value) { var allEmpty = true; var viewValue = {}; _.each(cultures, function (culture) { viewValue[culture] = value[culture]; allEmpty &= value[culture] === undefined || value[culture] === ""; }); ngModelCtrl.$setViewValue(allEmpty ? undefined : viewValue); scope.$parent.$eval(attrs.ngChange); // needs to be called manually cuz the object ref of the $viewValue didn't change }; // Mode pipe var parsePipe = function (value) { // value looks like this "en:some stuff|de:|nl:|fr:des bidules|it:|es:" var translations = value.split("|"); var result = {}; _.each(translations, function (t) { var key = t.substring(0, 2); var val = t.substring(3); result[key] = val; }); return _.pick(result, cultures); }; var updatePipe = function (value) { if (!_.find(cultures, function (culture) { return value[culture] !== undefined && value[culture] !== ""; })) { ngModelCtrl.$setViewValue(undefined); } else { var newVal = _.map(cultures, function (c) { if (!!value[c]) { return c + ":" + value[c]; } return c + ":"; }).join("|"); ngModelCtrl.$setViewValue(newVal); } }; } return { require: ['luidTranslations', '^ngModel'], controller: 'luidTranslationsController', scope: { mode: '@', // allowed values: "pipe" (or "|"), "dictionary", "lucca" (lucca proprietary format) size: "@", // the size of the input (short, long, x-long, fitting) isDisabled: "=ngDisabled" }, templateUrl: "lui/directives/luidTranslations.html", restrict: 'EA', link: link }; }]) .controller('luidTranslationsController', ['$scope', '$translate', '$timeout', function ($scope, $filter, $timeout) { var ctrl = this; /****************** * UPDATE * ******************/ $scope.update = function () { ctrl.updateViewValue(); ctrl.updateTooltip(); }; /****************** * FOCUS & BLUR * ******************/ $scope.focusInput = function () { $scope.focused = true; }; $scope.blurInput = function () { $scope.focused = false; }; $scope.blurOnEnter = function($event) { $event.target.blur(); $event.preventDefault(); }; }]); /**************************/ /***** TEMPLATES *****/ /**************************/ angular.module("lui").run(["$templateCache", function ($templateCache) { $templateCache.put("lui/directives/luidTranslations.html", "<div class=\"lui dropdown {{size}} field\" ng-class=\"{open:focused}\" tooltip-class=\"lui\" tooltip-placement=\"top\" uib-tooltip=\"{{tooltipText}}\">" + " <div class=\"lui input\">" + " <input type=\"text\" ng-disabled=\"isDisabled\" ng-model=\"internal[currentCulture]\" ng-focus=\"focusInput()\" ng-blur=\"blurInput()\" ng-keypress=\"$event.keyCode === 13 && blurOnEnter($event)\" ng-change=\"update()\">" + " <span class=\"unit\">{{currentCulture}}</span>" + " </div>" + " <div class=\"dropdown-menu\">" + " <div class=\"lui {{size}} field\" ng-repeat=\"culture in cultures\" ng-if=\"culture !== currentCulture\">" + " <div class=\"lui input\">" + " <input type=\"text\" ng-disabled=\"isDisabled\" ng-model=\"internal[culture]\" ng-focus=\"focusInput()\" ng-blur=\"blurInput()\" ng-keypress=\"$event.keyCode === 13 && blurOnEnter($event)\" ng-change=\"update()\">" + " <span class=\"unit addon\">{{culture}}</span>" + " </div>" + " </div>" + " </div>" + "</div>" + ""); }]); })();
import { $async, $await } from '../generate/async.macro' import multiPartition from './$multi-partition' import { $iterableCurry } from './internal/$iterable' function $partition (func, iter) { const [first, second] = multiPartition($async(item => $await(func(item)) ? 0 : 1), iter) return [first, second] } export default $iterableCurry($partition, { reduces: true })
/** * 然不是!闭包有非常强大的功能。举个栗子: 在面向对象的程序设计语言里,比如Java和C++,要在对象内部封装一个私有变量,可以用private修饰一个成员变量。 在没有class机制,只有函数的语言里,借助闭包,同样可以封装一个私有变量。我们用JavaScript创建一个计数器: * Created by hank on 2017/3/13. */ "use strict"; function create_counter(initial) { var x = initial || 0; return { inc: function () { return ++x; } } } var count = create_counter(); console.log(count.inc()); //1 console.log(count.inc()); //2 console.log(count.inc()); //3 var c2 = create_counter(10); console.log(c2.inc()); //11 console.log(c2.inc()); //12
(function($){ $('document').ready(function(){ app = $.sammy('#content', function() { // Override this function so that Sammy doesn't mess with forms this._checkFormSubmission = function(form) {return (false);}; storage = new Storage(); function unescape(str) { return String(str).replace(/&lt;/g, "<").replace(/&gt;/g, ">");} function Translate(){}; Translate.prototype.removeObject = function($this, time){ var time = time || 500; $this.animate({opacity: 0}, time, function(){ $this.remove();}); }; var translate = new Translate();//обєкт для операцій з перекладами // include the plugin this.use('Template', 'tmpl'); this.get('#/', function(context) { this.swap(''); context.render('templates/main.tmpl').appendTo(context.$element()).then(function(){ $('#shadow').appendTo('#content');//TODO: перенести в Main.tmpl app.phrasesContainer = $('#result'); //відображаємо фрази this.trigger('show-phrases', {id : 3}); }); $(document) .ajaxStart(function(){ //show preloading $('#shadow').show().center('parent'); $('#shadow img').center('parent'); }) .ajaxStop(function(){ //hide preloading $('#shadow').hide(); }); }); /** * Показує імя фільтра з кнопкою закриття */ this.bind('show-filter', function(e,data){ $('.filter').remove(); $('.word-dialog').remove(); var container = $('#aside');//TODO: винести звідси //передаємо назву фільтра та функцію, що робити по закриті фільтра this.render('templates/filter.tmpl', {data : data}).appendTo(container).then(function(content){ //console.log(content); //кнопка закриття фільтра $('.close_filter').off('click').on('click', function(){ console.time("closeFilter"); $('.word-dialog').remove(); //console.time("showAllPhrases"); app.sub.showAllPhrases(); //console.timeEnd("showAllPhrases"); $(this).parent().remove();//видаляємо фільтр console.timeEnd("closeFilter"); }); }); }); /** * Шукає слово в онлайн словнику */ this.bind('find-word-in-online-dictionary', function(e, data){ //Яндекс.Переклад $.ajax({ url : "https://translate.yandex.net/api/v1.5/tr.json/translate", data : { key : "trnsl.1.1.20131015T171502Z.d0a108edfd08efd8.b4b32462ed18e007414f408ca65a03d2a3342e85", text : data.word, lang : "uk" }, datatype : 'json', success : function(response){ var obj = $.parseJSON(response); console.log(obj); } }); }); /** * Відображає діалогове меню для слова */ this.bind('show-word-dialog', function(e, data){ $('.word-dialog').remove(); var $this = this; this.render('templates/word-dialog.tmpl', {data : data}).prependTo($('#result')).then(function(content){ var wordDialog = $('.word-dialog'); $(document).off('click').on('click', function(e){ if ($(e.target).closest(wordDialog).length) return;//якщо клік відноситься до діалогового вікна пропускаємо wordDialog.remove();//в інакшому випадку видаляємо його }); wordDialog.css({left : data.coords.left, top: data.coords.top + 20}); wordDialog .find('form').bind('submit', function(e){ e.preventDefault(); var data = $(this).serialize(); var arr = $(this).serializeArray();// => [translation, word] var word = arr[1].value; var translation = arr[0].value; $.ajax({ url : 'index/find-translation/', type : 'post', data : data, success : function(response){ try{ var obj = $.parseJSON(response); if(obj.status === "success"){ //console.log(obj.data); $('.word-dialog').empty(); $this.render('templates/translation-check-dialog.tmpl', {data : obj.data, word : word, translation : translation}).prependTo($('.word-dialog')).then(function(content){ //шукаємо слово в Онлайн Словнику та вставляємо його в наше діалогове вікно //app.trigger('find-word-in-online-dictionary', {content : $("#onlineDictionary .dictionaryBody"), word: word}); //показати переклад у власному списку var my = $('#myDictionary'); var body = my.find('.dictionaryBody'); var header = $('#translationCheckHeader'); header.data('translation', translation); header.data('word', word); //перевірка перекладу з усіма словами з словнику //якщо збігається тоді не пропонувати добавити а просто var translationDiv = $('<span></span>', {class : 'addTranslation', text : translation}); //console.log(obj.data.my.isMatched.match); //якщо немає співпадінь, тоді пропонуємо добавити слово if(obj.data.my && obj.data.my.isMatched.match === 1){ //TODO: слово співпало }else { //TODO: переробити header .on('mouseenter', function(){ my.find('.noRecords').hide();//приховуємо запис no records app.cacheHtml = body.html();//кешуємо переклади body.append(translationDiv);//добавляємо переклад до списку }) .on('mouseleave', function(){ if(app.cacheHtml){ //body.html(app.cacheHtml);//витягуємо дані з кешу //body.find('.noRecords').show(); //app.cacheHtml = null; } }) .on('click', function(){ /* записуємо слово в словник користувача * але спочатку перевіряємо в загальному словнику, * чи даний переклад міститься */ var $this = $(this); var options = {}; options.word = word; options.translation = translation; if(obj.data.common && obj.data.common.isMatched.match === 1){ //переклад уже міститься в базі, нам потрібно просто його ідентифікатор for(var i in obj.data.common){ var data = obj.data.common; if(data[i].translation === translation){ options.id_translation = data[i].id; delete options.translation; app.trigger('add-translation', options); break; } } }else { //add new word translation word app.trigger('add-translation', options); } header.off(); $('.addTranslation').remove(); }); }//else $('#commonDictionary').off('click').on('click','button', function(){ var $this = $(this); var obj = {}; obj.id_translation = $this.data('id'); obj.id_user = $this.data('id-user'); obj.word = word; obj.translation = $this.text().trim(); obj.$this = $this; app.trigger('add-translation', obj); }); //bind vs. on - різниця очевидна event тільки на елементи button, а bind на всі елементи що між ними $('#myDictionary').off('click').on('click','button', function(e){ var $this = $(this); var obj = {}; obj.id = $this.data('id'); obj.id_user = $this.data('id-user'); obj.translation = $this.text().trim(); obj.word = word; obj.$this = $this; app.trigger('remove-translation', obj); }); //Добавлення перекладу Онлайн.Словника $('#onlineDictionary').off('click').on('click','button', function(e){ var $this = $(this); var obj = {}; obj.id_user = $this.data('id-user'); obj.translation = $this.text().trim(); obj.word = word; obj.$this = $this; app.trigger('add-translation', obj); }); }); }else if(obj.status === "error"){ console.log(obj.message); } }catch(e){ console.log(e); } } }); }) .find('input[type=text]').focus();//фокусуємо поле для вводу перекладу //показати всі фрази зі словом $('#showWordPhrases').bind('click', function(){ app.trigger('show-filter', data); console.time("showSimilarPhrases"); app.sub.showSimilarPhrases(data); console.timeEnd("showSimilarPhrases"); }); $('#showTranslation') .bind('mouseenter', function(e){ e.preventDefault(); //пошук перекладу для даного слова var word = data.word.toLowerCase(); var translation = app.dictionary.getTranslation(word); if(!translation){ var info = "No translation"; }else { var info = translation.join(", "); } $(this).text(info); }) .bind('mouseleave', function(e){ $(this).text("?"); }); }); }); /** * Показує фрази зі субтитрів * @type Arguments */ this.bind('show-phrases', function(e, data){ //перевіряємо локальне сховище var subObj = storage.checkItem("subtitles", data.id); if(subObj){ //Отримали всю інформацію про субтитри: phrases, wordMap app.sub = new Subtitle(subObj); //console.log(app.sub.data.phrases); //витягуємо дані та вставляємо в DOM this.render('templates/phrases.tmpl', {data : app.sub.data.phrases}).then(function(content){ app.phrasesContainer.html(unescape(content)); app.sub.setPhrases($('.phrase'));//кешуємо фрази var phrasesProgressBar = document.getElementById('phrasesProgressBar'); app.sub.setPhrasesProgressBar(phrasesProgressBar); console.time("extendWithPhrase"); app.sub.extendPhraseObjectsWithPhraseAction(function(){ app.sub.triggerPhrasesProgressBar(); }); console.timeEnd("extendWithPhrase"); app.trigger('setup-dictionary'); //наведення на фразу $('.phrase').off('mouseenter').on('mouseenter', function(){ var id = $(this).data('phrase-id'); var phrase = app.sub.getPhrase(id); //console.log("id: " + id + " data-phrase-id: " + phrase.$phrase.getAttribute("data-phrase-id")); //console.log(phrase.toString()); }); $("#sortSwitcher").off("click").on("click", function(){ console.log("clicked"); var $this = $(this), isChecked = $this.is(":checked"); (isChecked)? app.sub.sortPhrases("priority") : app.sub.sortPhrases("index"); }); $('#sortByStatus').off("change").on("change", function(){ var selected = $(this).find("option:selected").val(); app.sub.sortByStatus(selected); }); }); }else { //запит до сервера відбуватиметься тільки, якщо даних в локальному сховищі немає $.ajax({ url : 'index/get-subtitle/', //dataType : 'json', data : {id : data.id}, type : 'post', success : function(response){ //console.log(response); var obj = $.parseJSON(response); console.log(obj); if(obj.status === "success"){ //додати субтитр якщо ідентифікатор субтитра унікальний var dictionary = obj.data.dictionary; delete obj.data.dictionary; storage.add("subtitles",obj.data); app.trigger('setup-dictionary', dictionary);//приводимо локальний словник до готовності //рекурсивно викликаємо функцію app.trigger('show-phrases', {id : data.id}); } } });//ajax end } this.trigger('phrases-loaded'); }); this.bind('setup-dictionary', function(e, dictionary){ if(!storage.checkItem("dictionary")){ if(typeof dictionary !== 'object')throw new Error('dictionary is not defined!'); storage.add("dictionary",dictionary);//TODO: чи не потребує оновлення }else { var dictionary = storage.get("dictionary")[0]; } app.dictionary = new Dictionary(dictionary); //console.log(app.dictionary); }); //пошук фраз по слову this.bind('phrases-loaded', function(){ //при нажаті на слово $('#result').off('click').on('click','.phrase span', function(){ var $this = $(this); //слово знайти у wordMap var word = $this.text().toLowerCase(); //console.log($this); //посилання на фрази, самі фрази та їх кількість var wordObj = app.sub.getWord(word); var countPhrases = wordObj.getCountOfPhrases(); var source = wordObj.getPhrasesIndexes(); //console.log(wordObj); //відображення діалогового вікна для слова app.trigger('show-word-dialog', {word : word, source : source, count : countPhrases, coords : $this.position()}); }); }); /*добавлення перекладу*/ this.bind('add-translation', function(e, data){ //console.log(data); var package = {}; if(data.$this){ package.$this = data.$this;//посилання на HTML object перекладу delete data.$this; }else { //видаляємо подібний переклад з загальному словнику, якщо власний співпав $('#commonDictionary button').each(function(){ var $this = $(this); var id = data.id || data.id_translation; if($this.data('id') === id)translate.removeObject($this); }); } $.ajax({ url : 'index/add-translation', type : 'post', data : data,// <= word, referrer, id_translation, translation success : function(response){ var obj = $.parseJSON(response); if(obj.status === "success"){ console.log(obj); package.id = obj.data.id;// <= 1. obj.data.id if(obj.data.id_user)package.id_user = obj.data.id_user;// 2. <= obj.data.id_user; if(data.translation)package.translation = data.translation; // 3. package.destination = $('#myDictionary .dictionaryBody'); // передати дані на шаблон перекладу і вставити його до власного словника //console.log(package); app.trigger('translation-replace', package); app.trigger('add-translation-to-dictionary', data); }else { console.warn(response); } } }); }); /*видалення перекладу*/ this.bind('remove-translation', function(e, data){ //console.log(data); data.destination = $('#commonDictionary .dictionaryBody'); $.ajax({ url : 'index/remove-translation', data : {id : data.id, word : data.word}, type : 'post', success : function(response){ //console.log(response); app.trigger('translation-replace', data); //app.trigger('remove-word-from-dictionary');//TODO:видалити переклад з локального словника } }); }); this.bind('translation-replace', function(e,data){ //console.log(data); var destination = data.destination; var obj = {}; if(data.id)obj.id = data.id; if(data.id_user)obj.id_user = data.id_user; //else obj.id_user = 1;//default user from session if(data.translation){ obj.translation = data.translation; }else {obj.translation = $('#translationCheckHeader').data('translation').trim();} //console.log(obj); this.render('templates/translation-item.tmpl', obj).then(function(content){ //console.log(content); //1. перемістили запозичене слово destination.append(content); //2. видалили оригінал if(data.$this) translate.removeObject(data.$this); }); }); /** * Добавлення перекладу в локальний словник */ this.bind('add-translation-to-dictionary', function(e, data){ //console.log(data); //викликати dictionary API для добавлення перекладу для вказаного слова console.time("addTranslation"); var result = app.dictionary.addTranslation(data.word, data.translation); console.timeEnd("addTranslation"); if(result){ console.info("Translation successfully added"); //if(!confirm("Continue translation?"))$('.word-dialog').remove(); app.sub.triggerPhrasesProgressBar(); } }); });//app end app.run('#/'); });//document.ready end })(jQuery);
module.exports=require('./lib/atraxi');
// Avoid `console` errors in browsers that lack a console. (function() { var method; var noop = function () {}; var methods = [ 'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error', 'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log', 'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd', 'timeline', 'timelineEnd', 'timeStamp', 'trace', 'warn' ]; var length = methods.length; var console = (window.console = window.console || {}); while (length--) { method = methods[length]; // Only stub undefined methods. if (!console[method]) { console[method] = noop; } } })(); // Place any jQuery/helper plugins in here. $(document).ready(function () { var $grid = $('.grid').packery({ // options itemSelector: '.grid-item', gutter: '.gutter-sizer', columnWidth: '.grid-sizer', percentPosition: true, }); $grid.imagesLoaded().progress(function() { $grid.packery('layout'); }); //Disable right-click $('.grid-item').on('contextmenu',function(e){ return false; }); //Disable cut, copy, paste $('.grid-item').bind('cut copy paste', function (e) { e.preventDefault(); }); var vid = document.getElementById("video"); function enableAutoplay() { vid.autoplay = true; vid.load(); } vid.addEventListener("canplay", enableAutoplay()); });
/** * Ternific Copyright (c) 2014 Miguel Castillo. * * Licensed under MIT */ define(function (require /*, exports, module*/) { 'use strict'; var HintHelper = require("HintHelper"); function TernTypes(ternProvider) { var _self = this; _self.ternProvider = ternProvider; _self._cm = null; } TernTypes.prototype.findType = function( cm ) { var _self = this; return _self.ternProvider.query(cm, "type") .then( function(data) { var findTypeType = HintHelper.typeDetails(data.type), className = findTypeType.icon; if (data.guess) { className += " Tern-completion-guess"; } var _findType = { value: data.name, type: findTypeType.name, icon: findTypeType.icon, className: className, _find: data, _type: HintHelper.findTypeType }; console.log(_findType); return _findType; }, function( error ) { return error; }); }; return TernTypes; });
var routes = require("./routes/index.js"); module.exports = function(){ routes = routes.call(this); this.get("/api/book/:bookId/checkout", routes.checkout); this.get("/api/book/:bookId/checkin", routes.checkin); this.post("/api/books/add", routes.addBook); this.get("/api/books/all", routes.getAll); this.get("/*", routes.index); }
'use strict'; const assert = require('assert'); const getFbInfo = require('../../../../src/services/user/hooks/getFbInfo.js'); describe('user getFbInfo hook', function() { it('hook can be used', function() { const mockHook = { type: 'before', app: {}, params: {}, result: {}, data: {} }; getFbInfo()(mockHook); assert.ok(mockHook.getFbInfo); }); });
/** * THIS FILE IS AUTO-GENERATED * DON'T MAKE CHANGES HERE */ import { typedDependencies } from './dependenciesTyped.generated'; import { createAbs } from '../../factoriesAny.js'; export var absDependencies = { typedDependencies: typedDependencies, createAbs: createAbs };
// NODE MODULES const mongoose = require('../services/mongoose'); // ROUTES CONFIG const APP_CONFIG = require('../app.config'); const ROUTES_CONFIG = APP_CONFIG.ROUTES_CONFIG; const routeSchema = new mongoose.Schema({ url: { type: String, required: true }, method: { type: String, default: ROUTES_CONFIG.MODEL.DEFAULT_METHOD }, middlewares: { type: String }, controller: { type: String, default: ROUTES_CONFIG.MODEL.DEFAULT_CONTROLLER } }, { versionKey: false }); routeSchema.methods.getMiddlewares = function () { const strArr = this.middlewares ? this.middlewares.split(',') : []; const midArr = []; strArr.forEach((elem) => { midArr.push(require(`..${ROUTES_CONFIG.DIRECTORY.MIDDLEWARES_DIR}/${elem}`)); }); return midArr; }; routeSchema.methods.getController = function () { return require(`..${ROUTES_CONFIG.DIRECTORY.CONTROLLERS_DIR}/${this.controller}`); }; routeSchema.pre('save', function (next) { const self = this; const routeModelName = 'Route'; const routeModel = mongoose.models[routeModelName] ? mongoose.model(routeModelName) : mongoose.model(routeModelName, routeSchema); routeModel.find({ url: self.url, method: self.method }, [], { limit: 1 }, (err, users) => { if (err) { return next(err); } if (users.length === 1) { return next(new Error({ message: `Can not save route with url: ${self.url} and method: ${self.method}`, reason: 'The route was duplicated' })); } next(); }); }); module.exports = { schema: routeSchema, model: mongoose.model('Route', routeSchema) };
import model from 'platform/models/model' import bcrypt from 'bcrypt-nodejs' import Asset from 'platform/models/asset' import Role from 'platform/models/role' import SecurityQuestion from 'platform/models/security_question' import Team from 'platform/models/team' export default model.extend({ tableName: 'users', rules: { first_name: 'required', last_name: 'required', email: ['required', 'email'] }, photo: function() { return this.belongsTo(Asset, 'photo_id') }, security_question_1: function() { return this.belongsTo(SecurityQuestion, 'security_question_1_id') }, security_question_2: function() { return this.belongsTo(SecurityQuestion, 'security_question_2_id') }, roles: function() { return this.belongsToMany(Role, 'users_roles', 'user_id', 'role_id') }, team: function() { return this.belongsTo(Team, 'team_id') }, virtuals: { activity: function() { return { type: 'user', text: this.get('full_name') } }, full_name: function() { return this.get('first_name') + ' ' + this.get('last_name') }, initials: function() { const first_name = this.get('first_name') || '' const last_name = this.get('last_name') || '' return first_name[0] + last_name[0] }, password: { get: function() {}, set: function(value) { const password_salt = bcrypt.genSaltSync(10) this.set('password_salt', password_salt) this.set('password_hash', bcrypt.hashSync(value, password_salt)) } } }, authenticate: function(password) { return this.get('password_hash') === bcrypt.hashSync(password, this.get('password_salt')) } })
'use strict'; describe('myApp.version module', function() { beforeEach(module('sandbox.version')); describe('version service', function() { it('should return current version', inject(function(version) { expect(version).toEqual('0.1'); })); }); });
'use strict'; var debug = require('diagnostics')('bigpipe:compiler') , browserify = require('browserify') , preprocess = require('smithy') , mkdirp = require('mkdirp') , crypto = require('crypto') , stream = require('stream') , async = require('async') , File = require('./file') , path = require('path') , fs = require('fs'); /** * Small extension of a Readable Stream to push content into the browserify build. * * @Constructor * @param {Mixed} str file content * @api private */ function Content(str) { stream.Readable.call(this); this.push(Array.isArray(str) ? str.join('') : str); this.push(null); } // // Inherit from Readable Stream and provide a _read stub. // require('util').inherits(Content, stream.Readable); Content.prototype._read = function noop () {}; /** * Asset compiler and management. * * @constructor * @param {String} directory The directory where we save our static files. * @param {Pipe} pipe The configured Pipe instance. * @param {Object} options Configuration. * @api private */ function Compiler(directory, pipe, options) { options = options || {}; this.pipe = pipe; // The namespace where we can download files. this.pathname = options.pathname || '/'; // Directory to save the compiled files. this.dir = directory; // List of pre-compiled or previous compiled files. this.list = []; // Contains template engines that are used to render. this.core = []; this.buffer = Object.create(null); // Precompiled asset cache this.alias = Object.create(null); // Path aliases. // // Create the provided directory, will short circuit if present. // mkdirp.sync(directory); } Compiler.prototype.__proto__ = require('eventemitter3').prototype; /** * Create the BigPipe base front-end framework that's required for the handling * of the real-time connections and the initialization of the arriving pagelets. * * @param {Function} done Completion callback. * @api private */ Compiler.prototype.bigPipe = function bigPipe(done) { var framework = this.pipe._framework , library , plugin , name , file; debug('Creating the bigpipe.js front-end library'); library = browserify(); framework.get('library').forEach(function each(file) { library.require(file.path, { expose: file.expose }); }); if (this.core.length) library.require(new Content(this.core)); for (name in this.pipe._plugins) { plugin = this.pipe._plugins[name]; if (plugin.library) { library.require(plugin.library.path, { expose: plugin.library.name }); } if (!plugin.client || !plugin.path) continue; debug('Adding the client code of the %s plugin to the client file', name); library.require(new Content(framework.get('plugin', { client: plugin.client.toString(), name: name })), { file: plugin.path, entry: true }); } library.bundle(done); }; /** * Merge in objects. * * @param {Object} target The object that receives the props * @param {Object} additional Extra object that needs to be merged in the target * @api private */ Compiler.prototype.merge = function merge(target, additional) { var result = target , compiler = this; if (Array.isArray(target)) { compiler.forEach(additional, function arrayForEach(index) { if (JSON.stringify(target).indexOf(JSON.stringify(additional[index])) === -1) { result.push(additional[index]); } }); } else if ('object' === typeof target) { compiler.forEach(additional, function objectForEach(key, value) { if (target[key] === void 0) { result[key] = value; } else { result[key] = compiler.merge(target[key], additional[key]); } }); } else { result = additional; } return result; }; /** * Iterate over a collection. When you return false, it will stop the iteration. * * @param {Mixed} collection Either an Array or Object. * @param {Function} iterator Function to be called for each item * @api private */ Compiler.prototype.forEach = function forEach(collection, iterator, context) { if (arguments.length === 1) { iterator = collection; collection = this; } var isArray = Array.isArray(collection || this) , length = collection.length , i = 0 , value; if (context) { if (isArray) { for (; i < length; i++) { value = iterator.apply(collection[i], context); if (value === false) break; } } else { for (i in collection) { value = iterator.apply(collection[i], context); if (value === false) break; } } } else { if (isArray) { for (; i < length; i++) { value = iterator.call(collection[i], i, collection[i]); if (value === false) break; } } else { for (i in collection) { value = iterator.call(collection[i], i, collection[i]); if (value === false) break; } } } return this; }; /** * Get the processed extension for a certain file. * * @param {String} filepath full path to file * @api public */ Compiler.prototype.type = function type(filepath) { var processor = this.processor(filepath); return processor ? '.' + processor.export : path.extname(filepath); }; /** * Get preprocessor. * * @param {String} filepath * @returns {Function} * @api public */ Compiler.prototype.processor = function processor(filepath) { return preprocess[path.extname(filepath).substr(1)]; }; /** * Upsert new file in compiler cache. * * @param {String} filepath full path to file * @api private */ Compiler.prototype.put = function put(filepath) { var compiler = this; compiler.process(filepath, function processed(error, code) { if (error) return compiler.emit('error', error); compiler.emit('preprocessed', filepath); compiler.register(new File(filepath, compiler.type(filepath), false, code)); }); }; /** * Read the file from disk and preprocess it depending on extension. * * @param {String} filepath full path to file * @param {Function} fn callback * @api private */ Compiler.prototype.process = function process(filepath, fn) { var processor = this.processor(filepath) , paths = [ path.dirname(filepath) ]; fs.readFile(filepath, 'utf-8', function read(error, code) { if (error || !processor) return fn(error, code); // // Only preprocess the file if required. // processor(code, { location: filepath, paths: paths }, fn); }); }; /** * Prefix selectors of CSS with [data-pagelet='name'] to contain CSS to * specific pagelets. File can have the following properties. * * @param {File} file instance of File * @param {Function} fn completion callback. * @api public */ Compiler.prototype.namespace = function prefix(file, fn) { // // Only prefix if the code is CSS content and not a page dependency. // if (!file.is('css') || file.dependency) return fn(null, file); debug('namespacing %s to pagelets %s', file.hash, file.pagelets); var processor = preprocess.css , options = {} , pagelets; // // Transform the pagelets names to data selectors. // pagelets = file.pagelets.map(function prepare(pagelet) { return '[data-pagelet="'+ pagelet +'"]'; }); options.plugins = [ processor.plugins.namespace(pagelets) ]; processor(file.code, options, function done(error, code) { if (error) return fn(error); fn(null, file.set(code, true)); }); }; /** * Register a new library with the compiler. The following traits can be * provided to register a specific file. * * @param {File} file instance of File * @api private */ Compiler.prototype.register = function register(file) { var compiler = this; // // Add file to the buffer collection. // this.buffer[file.location] = file; // // Add file references to alias. // file.aliases.forEach(function add(alias) { compiler.alias[alias] = file.location; }); this.emit('register', file); return this.save(file); }; /** * Catalog the pages. As we're not caching the file look ups, this method can be * called when a file changes so we will generate new. * * @param {Array} pages The array of pages. * @param {Function} done callback * @api private */ Compiler.prototype.catalog = function catalog(pages, done) { var framework = this.pipe._framework , temper = this.pipe._temper , core = this.core , compiler = this , list = {}; /** * Process the dependencies. * * @param {Object} assemble generated collection of file properties. * @param {String} filepath The location of a file. * @param {Function} next completion callback. * @api private */ function prefab(assemble, filepath, next) { if (/^(http:|https:)?\/\//.test(filepath)) return next(null, assemble); compiler.process(filepath, function store(error, code) { if (error) return next(error); var file = new File( filepath, compiler.type(filepath), list[filepath].dependency, code ); file = file.hash in assemble ? assemble[file.hash] : file; file.pagelets = (file.pagelets || []).concat(list[filepath].pagelets); file.alias(filepath); assemble[file.hash] = file; debug('finished pre-processing %s to hash %s', path.basename(filepath), file.hash); next(null, assemble); }); } /** * Register the files in the assembly, prefix CSS first. * * @param {Object} assemble generated collection of file properties. * @param {Function} next completion callback. * @api private */ function register(assemble, next) { async.each(Object.keys(assemble), function prefix(hash, fn) { compiler.namespace(assemble[hash], function namespaced(error, file) { if (error) return fn(error); compiler.register(file); fn(); }); }, next); } // // Check all pages for dependencies and files to add to the list. // pages.forEach(function each(Page) { var page = Page.prototype , dependencies = Array.isArray(page.dependencies) ? page.dependencies : []; /** * Add files to the process list. * * @param {String} name Pagelet name. * @param {String|Array} files Path to files. * @param {Boolean} dependency Push this file to global dependencies. * @api private */ function add(name, files, dependency) { // // Check if files is an object and return, this Pagelet has already // been cataloged and the dependencies overwritten. // if ('object' === typeof files && !Array.isArray(files)) return; files = Array.isArray(files) ? files : [ files ]; files.forEach(function loopFiles(file) { if (dependency && !~dependencies.indexOf(file)) dependencies.push(file); // // Use stored file or create a new one based on the filepath. // file = list[file] = list[file] || { dependency: false, pagelets: [] }; if (name && !~file.pagelets.indexOf(name)) file.pagelets.push(name); if (dependency) file.dependency = true; }); } /** * Register a new view. * * @param {String} path Location of the template file * @param {String} error * @api private */ function view(page, type) { var path = page[type] , data; debug('Attempting to compile the view %s', path); data = temper.fetch(path); // // The views can be rendered on the client, but some of them require // a library, this library should be cached in the core library. // if (data.library && !~core.indexOf(data.library)) { core.push(data.library); } if (!data.hash) data.hash = { client: crypto.createHash('md5').update(data.client).digest('hex') }; compiler.register(new File(path, '.js', false, framework.get('template', { name: data.hash.client, client: data.client }))); } // // Note: quick fix, now that routed pages have become pagelets // we should also resolve the Page assets. // page._children.concat(Page).forEach(function each(Pagelet) { if (Array.isArray(Pagelet)) return Pagelet.forEach(each); var pagelet = Pagelet.prototype; if (pagelet.js) add(pagelet.name, pagelet.js); if (pagelet.css) add(pagelet.name, pagelet.css); add(pagelet.name, pagelet.dependencies, true); if (pagelet.view) view(pagelet, 'view'); if (pagelet.error) view(pagelet, 'error'); }); // // Store the page level dependencies per file extension in the page. // If the file extension cannot be determined, the dependency will be tagged // as foreign, so other functions like `html` and `page` can do additional // checks to include the file. // page._dependencies = dependencies.concat(compiler.client).reduce(function reduce(memo, dependency) { var extname = path.extname(dependency) || 'foreign'; memo[extname] = memo[extname] || []; memo[extname].push(dependency); return memo; }, Object.create(null)); }); // // Process and register the CSS/JS of all the pagelets. // async.waterfall([ async.apply(async.reduce, Object.keys(list), {}, prefab), register ], function completed(err, data) { if (err) return done(err); compiler.bigPipe(function browserified(err, buffer) { if (err) return done(err); debug('Finished creating browserify build'); compiler.register(new File(compiler.client, '.js', true, buffer)); done(err, data); }); }); }; /** * Find all required dependencies for given page constructor. * * @param {Page} page The initialized page. * @returns {Object} * @api private */ Compiler.prototype.page = function find(page) { var compiler = this , assets = []; // // The page is rendered in `sync` mode, so add all the required CSS files from // the pagelet to the head of the page. // if (!('.css' in page._dependencies)) page._dependencies['.css'] = []; if ('sync' === page.mode) page._enabled.forEach(function enabled(pagelet) { Array.prototype.push.apply(page._dependencies['.css'], compiler.pagelet(pagelet).css); }); // // Push dependencies into the page. JS is pushed as extension after CSS, // still adheres to the CSS before JS pattern, although it is less important // in newer browser. See http://stackoverflow.com/questions/9271276/ for more // details. Foreign extensions are added last to allow unidentified files to // be included if possible. // preprocess.extensions.concat('.js', 'foreign').forEach(function map(type) { if (!(type in page._dependencies)) return; page._dependencies[type].forEach(function each(dependency) { dependency = compiler.html(compiler.resolve(dependency)); if (!~assets.indexOf(dependency)) assets.push(dependency); }); }); return assets; }; /** * Generate HTML. * * @param {String} file The filename that needs to be added to a DOM. * @returns {String} A correctly wrapped HTML tag. * @api private */ Compiler.prototype.html = function html(file) { var type = path.extname(file) , exp; // // Fallback to loose check of occurency of `js` or `css` string in the file. // if (!type) { exp = file.match(/css|js/i); if (exp) type = '.' + exp[0]; } switch (type) { case '.css': return '<link rel=stylesheet href="'+ file +'" />'; case '.js': return '<script src="'+ file +'"></script>'; default: return ''; } }; /** * Resolve all dependencies to their hashed versions. * * @param {String} original The original file path. * @returns {String} The hashed version. * @api private */ Compiler.prototype.resolve = function resolve(original) { return this.alias[original] || original; }; /** * A list of resources that need to be loaded for the given pagelet. * * @param {Pagelet} pagelet The initialized pagelet. * @returns {Object} * @api private */ Compiler.prototype.pagelet = function find(pagelet) { var frag = {} , css = [] , js = []; debug('Compiling data from pagelet %s/%s', pagelet.name, pagelet.id); if (pagelet.js) js = js.concat(pagelet.js.map(this.resolve.bind(this))); if (pagelet.css) css = css.concat(pagelet.css.map(this.resolve.bind(this))); if (pagelet.view) js.push(this.resolve(pagelet.view)); if (pagelet.error) js.push(this.resolve(pagelet.error)); frag.css = css; // Add the compiled css. frag.js = js; // Add the required js. return frag; }; /** * Store the compiled files to disk. This a vital part of the compiler as we're * changing the file names every single time there is a change. But these files * can still be cached on the client and it would result in 404's and or broken * functionality. * * @param {File} file The file instance. * @api private */ Compiler.prototype.save = function save(file) { var directory = path.resolve(this.dir) , pathname = this.pathname; fs.writeFileSync(path.join(directory, file.location), file.buffer); this.list = fs.readdirSync(directory).reduce(function reduce(memo, file) { if (path.extname(file)) { memo[pathname + file] = path.resolve(directory, file); } return memo; }, {}); return this; }; /** * Serve the file. * * @param {Request} req Incoming HTTP request. * @param {Response} res Outgoing HTTP response. * @returns {Boolean} The request is handled by the compiler. * @api private */ Compiler.prototype.serve = function serve(req, res) { var file = (this._compiler || this).buffer[req.uri.pathname]; if (!file) return undefined; res.setHeader('Content-Type', file.type); res.setHeader('Content-Length', file.length); res.end(file.buffer); return true; }; // // Expose the module. // module.exports = Compiler;
(function (global, factory) { if (typeof define === "function" && define.amd) { define(["exports", "prop-types", "lodash/clone", "lodash/get", "lodash/has", "react", "react-final-form-arrays", "react-bootstrap/lib/Panel", "react-bootstrap/lib/Button", "react-bootstrap/lib/Row", "react-bootstrap/lib/Col", "react-bootstrap/lib/ButtonToolbar", "react-bootstrap/lib/ControlLabel", "lodash/isFunction"], factory); } else if (typeof exports !== "undefined") { factory(exports, require("prop-types"), require("lodash/clone"), require("lodash/get"), require("lodash/has"), require("react"), require("react-final-form-arrays"), require("react-bootstrap/lib/Panel"), require("react-bootstrap/lib/Button"), require("react-bootstrap/lib/Row"), require("react-bootstrap/lib/Col"), require("react-bootstrap/lib/ButtonToolbar"), require("react-bootstrap/lib/ControlLabel"), require("lodash/isFunction")); } else { var mod = { exports: {} }; factory(mod.exports, global.propTypes, global.clone, global.get, global.has, global.react, global.reactFinalFormArrays, global.Panel, global.Button, global.Row, global.Col, global.ButtonToolbar, global.ControlLabel, global.isFunction); global.Complex = mod.exports; } })(this, function (_exports, _propTypes, _clone2, _get3, _has2, _react, _reactFinalFormArrays, _Panel, _Button, _Row, _Col, _ButtonToolbar, _ControlLabel, _isFunction2) { "use strict"; _exports.__esModule = true; _exports["default"] = void 0; _propTypes = _interopRequireDefault(_propTypes); _clone2 = _interopRequireDefault(_clone2); _get3 = _interopRequireDefault(_get3); _has2 = _interopRequireDefault(_has2); _react = _interopRequireDefault(_react); _Panel = _interopRequireDefault(_Panel); _Button = _interopRequireDefault(_Button); _Row = _interopRequireDefault(_Row); _Col = _interopRequireDefault(_Col); _ButtonToolbar = _interopRequireDefault(_ButtonToolbar); _ControlLabel = _interopRequireDefault(_ControlLabel); _isFunction2 = _interopRequireDefault(_isFunction2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } var Complex = /*#__PURE__*/ function (_React$Component) { _inheritsLoose(Complex, _React$Component); function Complex() { var _this; _this = _React$Component.call(this) || this; _this.renderComplex = _this.renderComplex.bind(_assertThisInitialized(_this)); _this.renderChildren = _this.renderChildren.bind(_assertThisInitialized(_this)); _this.state = { collapsed: null }; return _this; } var _proto = Complex.prototype; _proto.renderChildren = function renderChildren(children, name, count, remove, move, complexIndex, removeBtn, size, staticField, disabled) { var _this2 = this; var buttons = function buttons() { var returnButtons = []; if (staticField !== true) { if (complexIndex > 0 && count > 1) { returnButtons.push(_react["default"].createElement(_Button["default"], { key: 2, onClick: function onClick() { return move(complexIndex, complexIndex - 1); }, bsStyle: (0, _get3["default"])(_this2.props.field.moveBtn, 'bsStyle', 'default'), bsSize: (0, _get3["default"])(_this2.props.field.moveBtn, 'bsSize', undefined), disabled: disabled, type: "button" }, _react["default"].createElement("i", { className: "fa fa-chevron-up" }))); } if (count > 1 && complexIndex < count - 1) { returnButtons.push(_react["default"].createElement(_Button["default"], { key: 3, onClick: function onClick() { return move(complexIndex, complexIndex + 1); }, bsStyle: (0, _get3["default"])(_this2.props.field.moveBtn, 'bsStyle', 'default'), bsSize: (0, _get3["default"])(_this2.props.field.moveBtn, 'bsSize', undefined), disabled: disabled, type: "button" }, _react["default"].createElement("i", { className: "fa fa-chevron-down" }))); } returnButtons.push(_react["default"].createElement(_Button["default"], { key: 1, onClick: function onClick() { return remove(complexIndex); }, bsStyle: (0, _get3["default"])(_this2.props.field.removeBtn, 'bsStyle', 'danger'), bsSize: (0, _get3["default"])(_this2.props.field.removeBtn, 'bsSize', undefined), className: (0, _get3["default"])(_this2.props.field.removeBtn, 'className', ''), title: (0, _get3["default"])(_this2.props.field.removeBtn, 'title', ''), disabled: disabled, type: "button" }, _react["default"].createElement("i", { className: "fa fa-trash" }))); } return returnButtons; }; var _get2 = (0, _get3["default"])(this.props.field, 'panel', {}), header = _get2.header, footer = _get2.footer; var headerDiv = _react["default"].createElement("div", { className: "clearfix" }, _react["default"].createElement(_ButtonToolbar["default"], null, buttons()), header); return _react["default"].createElement(_Panel["default"], { className: "rfg-cmplx-btn-flds" }, _react["default"].createElement(_Panel["default"].Heading, null, headerDiv), _react["default"].createElement(_Panel["default"].Body, null, children.map(function (child, key) { var clone = (0, _clone2["default"])(child); clone.name = name + "." + child.name; clone.parent = "" + name; return _this2.props.addField(clone, key, size); })), footer && _react["default"].createElement(_Panel["default"].Footer, null, footer)); }; _proto.renderComplex = function renderComplex(props) { var _this3 = this; var fields = props.fields, locale = props.locale, removeBtn = props.removeBtn, addBtn = props.addBtn, size = props.size, label = props.label, children = props.children, _props$meta = props.meta, touched = _props$meta.touched, error = _props$meta.error, submitError = _props$meta.submitError; var staticField = props["static"]; var thisSize = function thisSize() { if (size !== 'medium') { return { bsSize: size }; } }; var labelSize = function labelSize() { if ((0, _has2["default"])(_this3.props.field, 'labelSize')) { return _this3.props.field.labelSize; } if (_this3.props.horizontal) { return { sm: 2 }; } }; var fieldSize = function fieldSize() { if ((0, _has2["default"])(_this3.props.field, 'fieldSize')) { return _this3.props.field.fieldSize; } if (_this3.props.horizontal) { return { sm: 10 }; } }; var toggle = function toggle() { var state = false; if (_this3.state.collapsed === null) { state = !(_this3.props.field.collapsed && _this3.props.field.collapsed === true); } else if (_this3.state.collapsed === false) { state = true; } var complexName = fields.name + "_collapsed"; _this3.setState({ 'collapsed': state }, function () {// this.props.formChange(', state); }); }; if (this.state.collapsed === true || this.state.collapsed === null && this.props.field.collapsed && this.props.field.collapsed === true) { return _react["default"].createElement(_Row["default"], { className: "rfg-cmplx rfg-cmplx-collapsed" }, _react["default"].createElement(_Col["default"], _extends({ componentClass: _ControlLabel["default"] }, labelSize()), _react["default"].createElement(_Button["default"], _extends({ type: "button", onClick: toggle, bsStyle: "link" }, thisSize()), '+ ', label))); } var disabled = false; if (this.props.field && this.props.field.disabled && (0, _isFunction2["default"])(this.props.field.disabled)) { disabled = this.props.checkDisabled(this.props.field.disabled()); } var renderAddButton = function renderAddButton() { if ((0, _get3["default"])(_this3.props.field, 'multiple', true) === true || fields.length === 0) { var bsStyle = function bsStyle() { if ((0, _get3["default"])(addBtn, 'bsStyle') && (0, _get3["default"])(addBtn, 'bsStyle') !== 'default') { return { bsStyle: (0, _get3["default"])(addBtn, 'bsStyle') }; } }; return _react["default"].createElement("div", { className: "rfg-cmplx-btn-add" }, staticField !== true && _react["default"].createElement(_Button["default"], _extends({ type: "button", onClick: function onClick() { return fields.push({}); }, disabled: disabled }, thisSize(), bsStyle(), { className: (0, _get3["default"])(_this3.props.addBtn, 'className') }), (0, _get3["default"])(addBtn, 'label', locale.complex.buttonAdd)), touched && error && _react["default"].createElement("span", null, error)); } }; return _react["default"].createElement(_Row["default"], { className: "rfg-cmplx rfg-cmplx-collapsed" }, _react["default"].createElement(_Col["default"], _extends({ componentClass: _ControlLabel["default"] }, labelSize()), _react["default"].createElement(_Button["default"], _extends({ type: "button", onClick: toggle, bsStyle: "link" }, thisSize()), '- ', label)), _react["default"].createElement(_Col["default"], fieldSize(), fields.map(function (field, key) { return _react["default"].createElement("div", { key: key, className: "rfg-cmplx-fields" }, _this3.renderChildren(children, field, fields.length, fields.remove, fields.move, key, removeBtn, size, staticField, disabled)); }), renderAddButton())); }; _proto.render = function render() { var _this$props = this.props, field = _this$props.field, size = _this$props.size; if (this.props.field && this.props.field.hidden && (0, _isFunction2["default"])(this.props.field.hidden)) { if (this.props.checkHidden(this.props.field.hidden, (0, _get3["default"])(this.props.field, 'parent')) === true) { return null; } } else if (this.props.field && this.props.field.show && (0, _isFunction2["default"])(this.props.field.show)) { if (this.props.checkShow(this.props.field.show, (0, _get3["default"])(this.props.field, 'parent')) !== true) { return null; } } return _react["default"].createElement(_reactFinalFormArrays.FieldArray, { name: field.name, label: field.label, addBtn: field.addBtn, removeBtn: field.removeBtn, children: field.children, dispatch: this.props.dispatch, size: (0, _get3["default"])(field, 'bsSize', size), component: this.renderComplex, collapsed: this.state.collapsed, "static": this.props["static"] || field["static"], locale: this.props.locale, rerenderOnEveryChange: (0, _get3["default"])(field, 'rerenderOnEveryChange', false) }); }; return Complex; }(_react["default"].Component); Complex.propTypes = { 'checkDisabled': _propTypes["default"].func, 'checkHidden': _propTypes["default"].func, 'checkShow': _propTypes["default"].func, 'size': _propTypes["default"].string, 'dispatch': _propTypes["default"].func, 'addField': _propTypes["default"].func, 'field': _propTypes["default"].object, 'formName': _propTypes["default"].string, 'static': _propTypes["default"].bool, 'locale': _propTypes["default"].object, 'horizontal': _propTypes["default"].bool.isRequired }; Complex.defaultProps = {}; var _default = Complex; _exports["default"] = _default; });
// == `math.js` == // function add(num1: number, num2: number): number { return num1 + num2; }; // This is how we export the `add()` function in CommonJS exports.add = add; function sub(num1, num2) { return num1 - num2; } var two: number = add(1, 2); var one: number = sub(2, 1);
// What if I want to re-use a result elsewhere? 'use strict'; var fs = require('fs'), async = require('async'), files = ['data/data1', 'data/data2', 'data/data3']; // files = ['data/data1', 'data/datxxa2', 'data/data3']; function useThirdFileSize(size) { console.log('the third files size is ', size); } function useFileStats(stats) { console.log('stats for files'); stats.forEach(function(stat, index) { console.log(index,':',JSON.stringify(stat)); }); } // third approach - manually control each section // maximum efficiency, error handling async.parallel([ // this deals with the third file function(callback) { fs.stat(files[2], function(error, stat) { if (stat) { useThirdFileSize(stat.size); } callback(error, [stat]); }); }, // this deals with the rest function(callback) { var firstTwoFiles = [files[0],files[1]]; async.map(firstTwoFiles, fs.stat, callback); } ], function(err, results) { // this joins the results together if (err) { console.log(err); } else { useFileStats(results[1].concat(results[0])); } });
angular.module('app').controller('loginCtrl', function($location, currentIdentity, auth, toastr) { if(currentIdentity.authenticated()) { $location.path('/home'); } this.login = function() { auth.login({ username: this.email, password: "pass" }).then(function() { $location.path('/home'); }, function(err) { toastr.error(err); }) } })
'use strict'; const Promise = require('bluebird'); const User = require('../models/User'); module.exports = function() { const create = function(userData) { return new Promise((resolve, reject) => { const user = new User(userData); user.createdAt = Date.now(); user.updatedAt = Date.now(); user.save() .then((createdUser) => { User.findById(createdUser.id) .select('-__v') .exec() .then((newUser) => { resolve(newUser.toObject()); }); }) .catch(reject); }); }; const updateByEmailOrUsername = function(emailOrUsername, updateOptions) { return new Promise((resolve, reject) => { User.findOneAndUpdate({ $or: [ { email: emailOrUsername }, { username: emailOrUsername }, ], }, updateOptions) .select('-__v -password') .exec() .then(resolve) .catch(reject); }); }; const updateManyById = function(userIds, updateOptions) { return new Promise((resolve, reject) => { User.updateMany({ _id: { $in: userIds }}, updateOptions) .then(resolve) .catch(reject); }); }; const getByEmailOrUsername = function(emailOrUsername) { return new Promise((resolve, reject) => { User.findOne({ $or: [ { email: emailOrUsername }, { username: emailOrUsername }, ], }) .select('-__v') .exec() .then((user) => { resolve(user.toObject()); }) .catch(reject); }); }; const getAllOtherUsers = function(email) { return new Promise((resolve, reject) => { User.find({ // $or: [ // { email: { $ne: emailOrUsername }}, // { username: { $ne: emailOrUsername }}, // ], email: { $ne: email }, }) .select('_id fullName email stats') .exec() .then((users) => { resolve(users); }) .catch(reject); }); }; return { create: create, updateByEmailOrUsername: updateByEmailOrUsername, updateManyById: updateManyById, getByEmailOrUsername: getByEmailOrUsername, getAllOtherUsers: getAllOtherUsers, }; };
'use strict'; module.exports = function(grunt) { // Unified Watch Object var watchFiles = { serverViews: ['app/views/**/*.*'], serverJS: ['gruntfile.js', 'server.js', 'config/**/*.js', 'app/**/*.js'], clientViews: ['public/modules/**/views/**/*.html'], clientJS: ['public/js/*.js', 'public/modules/**/*.js'], clientCSS: ['public/modules/**/*.css'], mochaTests: ['app/tests/**/*.js'] }; // Project Configuration grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), watch: { serverViews: { files: watchFiles.serverViews, options: { livereload: true } }, serverJS: { files: watchFiles.serverJS, tasks: ['jshint'], options: { livereload: true } }, clientViews: { files: watchFiles.clientViews, options: { livereload: true, } }, clientJS: { files: watchFiles.clientJS, tasks: ['jshint'], options: { livereload: true } }, clientCSS: { files: watchFiles.clientCSS, tasks: ['csslint'], options: { livereload: true } } }, jshint: { all: { src: watchFiles.clientJS.concat(watchFiles.serverJS), options: { jshintrc: true } } }, csslint: { options: { csslintrc: '.csslintrc', }, all: { src: watchFiles.clientCSS } }, uglify: { production: { options: { mangle: false }, files: { 'public/dist/application.min.js': 'public/dist/application.js' } } }, cssmin: { combine: { files: { 'public/dist/application.min.css': '<%= applicationCSSFiles %>' } } }, nodemon: { dev: { script: 'server.js', options: { nodeArgs: ['--debug'], ext: 'js,html', watch: watchFiles.serverViews.concat(watchFiles.serverJS) } } }, 'node-inspector': { custom: { options: { 'web-port': 1337, 'web-host': 'localhost', 'debug-port': 5858, 'save-live-edit': true, 'no-preload': true, 'stack-trace-limit': 50, 'hidden': [] } } }, ngAnnotate: { production: { files: { 'public/dist/application.js': '<%= applicationJavaScriptFiles %>' } } }, concurrent: { default: ['nodemon', 'watch'], debug: ['nodemon', 'watch', 'node-inspector'], options: { logConcurrentOutput: true, limit: 10 } }, env: { test: { NODE_ENV: 'test' }, secure: { NODE_ENV: 'secure' } }, mochaTest: { src: watchFiles.mochaTests, options: { reporter: 'spec', require: 'server.js' } }, karma: { unit: { configFile: 'karma.conf.js' } }, mongoimport: { options: { db : 'exammasterinteractive-dev', host : 'localhost', //optional port: '27017', //optional username : '', //optional password : '', //optional stopOnError : true, //optional collections : [ { name : 'question', type : 'json', file : 'data/db/collections/questions.json', jsonArray : true, //optional upsert : true, //optional drop : true //optional } ] } } }); // Load NPM tasks require('load-grunt-tasks')(grunt); // Making grunt default to force in order not to break the project. grunt.option('force', true); // A Task for loading the configuration object grunt.task.registerTask('loadConfig', 'Task that loads the config into a grunt option.', function() { var init = require('./config/init')(); var config = require('./config/config'); grunt.config.set('applicationJavaScriptFiles', config.assets.js); grunt.config.set('applicationCSSFiles', config.assets.css); }); // Default task(s). grunt.registerTask('default', ['lint', 'concurrent:default']); // Debug task. grunt.registerTask('debug', ['lint', 'concurrent:debug']); // Secure task(s). grunt.registerTask('secure', ['env:secure', 'lint', 'concurrent:default']); // Lint task(s). grunt.registerTask('lint', ['jshint', 'csslint']); // Build task(s). grunt.registerTask('build', ['lint', 'loadConfig', 'ngAnnotate', 'uglify', 'cssmin']); // Test task. grunt.registerTask('test', ['env:test', 'mochaTest', 'karma:unit']); // Task for converting a question text file into a JSON file grunt.registerTask( 'buildJSONFileFromChapterData', 'Converts an Exam Master Interactive question text file into a JSON format', function(file_name) { var textFileType = /\.txt/; if (file_name !== '' && file_name !== null) { grunt.log.writeln('Reading text data file ' + file_name + '...'); var text_file = grunt.file.read('data/db/' + file_name); var lines = text_file.split('\n'); var json = '{\n\t"questions": [\n'; lines.forEach(function(line, index) { if (((index + 8) % 8 === 0) && /\S+/.test(line)) { // this is the question content... json += '\t{\n'; json += '\t\t\"question\": \"' + line.replace(/[\n\r\j]/g, '') + '\",\n'; } else if ((index + 8) % 8 === 1) { // this is first response... json += '\t\t\"responses\": [\n'; json += '\t\t\t{\"response\": \"' + line.replace(/[\n\r\j]/g, '') + '\"},\n'; } else if ((index + 8) % 8 === 2) { // this is the second response... json += '\t\t\t{\"response\": \"' + line.replace(/[\n\r\j]/g, '') + '\"},\n'; } else if ((index + 8) % 8 === 3) { // this is the third response... json += '\t\t\t{\"response\": \"' + line.replace(/[\n\r\j]/g, '') + '\"},\n'; } else if ((index + 8) % 8 === 4) { // this is the fourth response... json += '\t\t\t{\"response": \"' + line.replace(/[\n\r\j]/g, '') + '\"}\n'; json += '\t\t],\n'; } else if ((index + 8) % 8 === 5) { // this is the index value of the responses indicating the actual answer... json += '\t\t\"answer\": \"' + line.replace(/[\n\r\j]/g, '') + '\",\n'; } else if ((index + 8) % 8 === 6) { // this is chapter reference... json += '\t\t\"chapter\": \"' + line.replace(/[\n\r\j]/g, '') + '\",\n'; } else if ((index + 8) % 8 === 7) { // this is the follow up information... json += '\t\t\"explanation\": \"' + line.replace(/[\n\r\j]/g, '') + '\"\n\t}'; if (index < (lines.length - 2)) { json += ',\n'; } else { json += '\n'; } } }); json += '\t]\n}'; grunt.log.writeln('Reading file ' + file_name + ' complete. Writing JSON file ' + file_name.replace('.txt', '') + '.json'); if (grunt.file.exists('data/db/chapters') === false) { grunt.file.mkdir('data/db/chapters'); } grunt.file.write('data/db/chapters/' + file_name.replace('.txt', '') + '.json', json); } } ); // Task for creating MongoDB import data file grunt.registerTask( 'importQuestionsJSONIntoMongoDB', 'Reads a JSON file containing list of questions for ExamMaster Interactive application.', function(json_path) { function addQuestionJSON(entry) { var json = '\t{\n\t\t\"content\": \"' + entry.question + '\",\n'; json += '\t\t\"responses\": [\n'; entry.responses.forEach(function(item, index) { json += '\t\t\t{\"content\": \"' + item.response + '\"}'; if (index < entry.responses.length - 1) { json += ',\n'; } else { json += '\n'; } }); json += '\t\t],\n'; json += '\t\t\"answer\": \"' + entry.answer + '\",\n'; json += '\t\t\"chapter\": ' + '\"' + entry.chapter + '\",\n'; json += '\t\t\"explanation\": ' + '\"' + entry.explanation + '\"\n\t}'; return json; } if (json_path !== '' && json_path !== null) { var questions_json = '{\n\t\"questions\": [\n'; grunt.file.recurse(json_path, function(abspath, rootdir, subdir, filename) { var json_data = grunt.file.readJSON(abspath); json_data.questions.forEach(function(item, index) { questions_json += addQuestionJSON(item); questions_json += ',\n'; }); }); questions_json += '\t]\n}'; if (grunt.file.exists('data/db/collections') === false) { grunt.file.mkdir('data/db/collections'); } grunt.file.write('data/db/collections/questions.json', questions_json); } } ); };
var win = Ti.UI.createWindow(); var AndroidID = require('ti.android.deviceid'); Ti.API.error( " ANDROID_ID is : " + AndroidID.getAndroidID()); Ti.API.error( " ANDROID_UUID is : " + AndroidID.getAndroidUUID()); win.open();
module( "fns.core module" ); test( "fns.mixin", 9, function(){ equals( typeof fns.mixin, "function", "Function existence verification" ); var test = {}; var out = fns.mixin( test, { a:1, b: "test"} ); equals( test, out ); equals( typeof test.a, 'number' ); test = { a: 5, b: 5 }; out = { b: 10, c: 10 }; fns.mixin( test, out, { c:15, d: 15} ); equals( test.a, 5 ); equals( test.b, 10 ); equals( test.c, 15 ); equals( test.d, 15 ); out = fns.mixin( test ); equals( test, out ); equals( fns.mixin(), void 0 ); }); test( "fns.toArray", 19, function(){ equals( typeof fns.toArray, "function", "Function existence verification" ); // conversion test equals( typeof fns.toArray(arguments), "object" ); //2 var arr = (function(){ return fns.toArray(arguments); })("a","b","c","d","e","f"); equals( arr[2], 'c' ); equals( Object.prototype.toString.call(arr), '[object Array]' ); equals( arr.length, 6 ); arr = fns.toArray( document.body.childNodes ); equals( arr.length, document.body.childNodes.length ); // 6 ok( typeof arr[0] !== "undefined" ); equals( arr[0], document.body.childNodes[0] ); arr = fns.toArray( {a:1, b:"test"} ); equals( arr.length, 1 ); // 9 equals( typeof arr[0], "object" ); arr = fns.toArray( 42 ); equals( arr.length, 1 ); equals( typeof arr[0], "number" ); // parameters test arr = fns.toArray( "abcdef", 2 ); equals( arr.length, 0 ); arr = fns.toArray( "abcdef", 0,2 ); equals( arr.length, 1 ); arr = (function(){ return fns.toArray(arguments, 2); })("a","b","c","d","e","f"); equals( arr.join(""), "cdef" ); arr = (function(){ return fns.toArray(arguments, 1, 3); })("a","b","c","d","e","f"); equals( arr.join(""), "bc" ); // object test arr = fns.toArray({ length: 10 }); equals( arr.length, 10 ); arr = fns.toArray({ length: 10, "5": 'a' }); equals( arr[5], 'a' ); var F = function(){}; F.prototype["4"] = "a"; var f = new F(); f.length = 10; arr = fns.toArray( f ); equals( arr[4], 'a' ); }); test( "fns.bind", 6, function(){ equals( typeof fns.bind, "function", "Function existence verification" ); var obj = { msg: "in", test: function(txt){ return txt || this.msg;} }; var fun1 = fns.bind(obj.test, obj ); var fun2 = fns.bind(obj.test, obj, "out" ); ok( fun1() === "in", "fun1 with no param" ); ok( fun1("out") === "out", "fun1 with 'out' param" ); ok( fun2() === "out", "fun2 with no param" ); ok( fun2() === "out", "fun2 with param" ); raises( function(){obj.msg.bind.call(new Object());}, TypeError, "obj.msg.bind.call(new Object()) should throw an error" ); } );
import test from 'ava' import { setMatchInProgress, getNextMinute, pauseMatch, homeGoal, awayGoal } from '../../actions/match-actions' import reducer from '../match-reducer' const componentUnderTest = 'Match Reducer' const testReduction = (assert, stateBeforeAction, action, expectedState) => { assert.deepEqual(reducer(stateBeforeAction, action), expectedState) } test( `${componentUnderTest} sets match in progress to true`, testReduction, {inProgress: false}, setMatchInProgress(true), {inProgress: true} ) test( `${componentUnderTest} sets match in progress to false`, testReduction, {inProgress: true}, setMatchInProgress(false), {inProgress: false} ) test( `${componentUnderTest} handles getNextMinute when not paused`, testReduction, {minute: 0, paused: false}, getNextMinute(), {minute: 1, paused: false} ) test( `${componentUnderTest} handles getNextMinute when paused`, testReduction, {minute: 10, paused: true}, getNextMinute(), {minute: 11, paused: false} ) test( `${componentUnderTest} pauses match`, testReduction, {paused: false}, pauseMatch(), {paused: true} ) test( `${componentUnderTest} scores a home goal. Shearer!!!`, testReduction, {homeGoals: 0}, homeGoal(), {homeGoals: 1} ) test( `${componentUnderTest} scores an away goal. Boooo!!!`, testReduction, {awayGoals: 0}, awayGoal(), {awayGoals: 1} )
Template.eraseButton.events({ 'click': function () { Meteor.call('removeAllData'); } });
(function () { 'use strict'; angular .module('widgets.imagezoomer', []) .directive('imagezoomer', function () { return { restrict: 'AE', link: function (scope, element, attrs) { //Will watch for changes on the attribute attrs.$observe('zoomImage', function () { linkElevateZoom(); }); scope.$on('$routeChangeSuccess', function() { var target = this.children('div.zoomContainer').remove(); }); scope.$on('update-image', function(e,imageName) { linkElevateZoom(); }); function linkElevateZoom() { //Check if its not empty\ if (!attrs.zoomImage) { return; } //alert(attrs.zoomImage); element.attr('data-zoom-image', attrs.zoomImage); $(element).elevateZoom( { scrollZoom : false, borderSize : 1, borderColour : "rgb(136,136,136)", tintColour : "#e7e7e7", zoomWindowWidth : 580, zoomWindowHeight : 580, zoomWindowPosition : 1, zoomWindowOffetx : 10, zoomWindowOffety : -50, zoomWindowFadeIn : 500, zoomWindowFadeOut : 500, lensFadeIn : 500, lensFadeOut : 500, }); } linkElevateZoom(); } }; }) .directive('widgets.zoomContainer', function() { return { restrict: 'A', link: function(scope, element, attrs) { scope.$on('$routeChangeSuccess', function() { var target = element.children('div.zoomContainer').remove(); }); } }; }); }());
function gallery() { var $tour = $("#tour"); var $frame = $("#frame"); $tour.on("click", function () { $frame.css("pointer-events", "auto"); }); $tour.on("mouseleave", function () { $frame.css("pointer-events", "none"); }); }
export const objectUngroup = {"viewBox":"0 0 2304 1792","children":[{"name":"path","attribs":{"d":"M2304 768h-128v640h128v384h-384v-128h-896v128h-384v-384h128v-128h-384v128h-384v-384h128v-640h-128v-384h384v128h896v-128h384v384h-128v128h384v-128h384v384zM2048 512v128h128v-128h-128zM1408 128v128h128v-128h-128zM128 128v128h128v-128h-128zM256 1280v-128h-128v128h128zM1536 1152h-128v128h128v-128zM384 1152h896v-128h128v-640h-128v-128h-896v128h-128v640h128v128zM896 1664v-128h-128v128h128zM2176 1664v-128h-128v128h128zM2048 1408v-640h-128v-128h-384v384h128v384h-384v-128h-384v128h128v128h896v-128h128z"}}]};
chrome.runtime.onMessage.addListener( function(request, sender, sendResponse) { 'use strict'; if (request.action && sender.id) { switch (request.action) { case 'getSelection': sendResponse(window.getSelection().toString()); } } });
/** * Created by yangguo on 2016/4/21 0021. */ var express = require('express'); var app = express(); app.set('port', (process.env.PORT || 3000)); app.get('/', function (req, res) { res.send('Hello World!'); }); app.get('/test', function (req, res) { var str = req.query.params; console.log(str); res.send(str); }); var server = app.listen(app.get('port'), function () { console.log('Server started: http://localhost:' + app.get('port') + '/'); });
/* * Update the scaling WITH configuration */ const request = require('request'); const password = 'YOUR_COMMANDER_PASSWORD'; const opts = { method: 'PATCH', url: 'http://localhost:8889/api/config', json: { instance: { scaling: { max: 300, }, }, }, headers: { 'Authorization': new Buffer(password).toString('base64'), }, }; request(opts, (err, res, body) => { if (err) return console.log('Error: ', err); console.log('Status: %d\n\n', res.statusCode); console.log(body); });
const fs = require('fs') const include = require('./utils').include const includeMimeType = require('./file').includeMimeType const findInFile = require('./file').findInFile /** * All elements that always ignored */ const ALWAYS_IGNORED = ['.git', 'node_modules', '.DS_Store'] /** * Check of an element is a directory. * @param {string} element The element to check. * @return {boolean} The result. */ function isADirectory (element) { return fs.statSync(element).isDirectory() } function findInDirectory (needle, directory, options) { const content = fs.readdirSync(directory) const deep = options.deep const ignore = options.ignore const fullPathRequired = options.fullPathRequired return content.reduce(function (prev, element) { const path = directory + '/' + element const ignored = fullPathRequired ? include(path, ignore) : include(element, ignore) const alwaysIgnored = include(element, ALWAYS_IGNORED) const mimeTypeIgnored = includeMimeType(element) if (ignored || alwaysIgnored || mimeTypeIgnored) return prev if (isADirectory(path)) { if (deep) return Array.from(prev).concat(findInDirectory(needle, path, options)) return prev } const lines = findInFile(needle, path) if (Object.keys(lines).length) { const result = {file: path, lines: lines} return Array.from(prev).concat(result) } return prev }, []) } module.exports = { findInDirectory: findInDirectory, isADirectory: isADirectory }
// Load modules var EventEmitter = require('events').EventEmitter; var Fs = require('fs'); var Os = require('os'); var Path = require('path'); var Stream = require('stream'); var Code = require('code'); var Lab = require('lab'); var lab = exports.lab = Lab.script(); var Hoek = require('hoek'); var GoodFile = require('..'); // Declare internals var internals = { tempDir: Os.tmpDir() }; internals.removeLog = function (path) { if (Fs.existsSync(path)) { Fs.unlinkSync(path); } }; internals.getLog = function (path, callback) { Fs.readFile(path, { encoding: 'utf8' }, function (error, data) { if (error) { return callback(error); } var results = JSON.parse('[' + data.replace(/\n/g, ',').slice(0, -1) + ']'); callback(null, results); }); }; internals.readStream = function (done) { var result = new Stream.Readable({ objectMode: true }); result._read = Hoek.ignore; if (typeof done === 'function') { result.once('end', done); } return result; }; // Lab shortcuts var describe = lab.describe; var it = lab.it; var expect = Code.expect; describe('GoodFile', function () { it('allows creation without using new', function (done) { var reporter = GoodFile({ log: '*' }, Hoek.uniqueFilename(internals.tempDir)); expect(reporter._streams).to.exist(); done(); }); it('allows creation using new', function (done) { var reporter = new GoodFile({ log: '*' }, Hoek.uniqueFilename(internals.tempDir)); expect(reporter._streams).to.exist(); done(); }); it('validates the options argument', function (done) { expect(function () { var reporter = new GoodFile({ log: '*' }); }).to.throw(Error, /value must be a (string|number)/); done(); }); it('will clear the timeout on the "stop" event', function (done) { var reporter = new GoodFile({ request: '*' }, { path: internals.tempDir, rotate: 'daily' }); var ee = new EventEmitter(); var read = internals.readStream(); reporter.init(read, ee, function (error) { expect(error).to.not.exist(); expect(reporter._state.timeout).to.exist(); read.push({ event: 'request', id: 1, timestamp: Date.now() }); read.push(null); ee.emit('stop'); reporter._streams.write.on('finish', function () { expect(reporter._streams.write.bytesWritten).to.equal(53); expect(reporter._streams.write._writableState.ended).to.be.true(); expect(reporter._state.timeout._idleTimeout).to.equal(-1); internals.removeLog(reporter._streams.write.path); done(); }); }); }); it('logs an error if one occurs on the write stream and tears down the pipeline', function (done) { var file = Hoek.uniqueFilename(internals.tempDir); var reporter = new GoodFile({ request: '*' }, file); var ee = new EventEmitter(); var logError = console.error; var read = internals.readStream(); console.error = function (value) { console.error = logError; expect(value.message).to.equal('mock error'); internals.removeLog(reporter._streams.write.path); done(); }; reporter.init(read, ee, function (error) { expect(error).to.not.exist(); reporter._streams.write.emit('error', new Error('mock error')); }); }); it('properly sanitizes `format`, `prefix` and `extension`', function (done) { var sep = Path.sep; var reporter = new GoodFile({ log: '*' }, { path: internals.tempDir, format: 'Y' + sep + 'M' + sep, extension: 'foo' + sep + 'bar' }); expect(reporter._settings.format).to.equal('Y-M-'); expect(reporter._settings.extension).to.equal('.foo-bar'); done(); }); it('writes to the current file and does not create a new one', function (done) { var file = Hoek.uniqueFilename(internals.tempDir); var reporter = new GoodFile({ request: '*' }, file); var ee = new EventEmitter(); var read = internals.readStream(); reporter.init(read, ee, function (error) { expect(error).to.not.exist(); expect(reporter._streams.write.path).to.equal(file); reporter._streams.write.on('finish', function () { expect(error).to.not.exist(); expect(reporter._streams.write.bytesWritten).to.equal(1260); internals.removeLog(reporter._streams.write.path); done(); }); for (var i = 0; i < 20; ++i) { read.push({ event: 'request', statusCode: 200, id: i, tag: 'my test ' + i }); } read.push(null); }); }); it('handles circular references in objects', function (done) { var file = Hoek.uniqueFilename(internals.tempDir); var reporter = new GoodFile({ request: '*' }, file); var ee = new EventEmitter(); var read = internals.readStream(); reporter.init(read, ee, function (error) { expect(error).to.not.exist(); var data = { id: 1, event: 'request', timestamp: Date.now() }; data._data = data; reporter._streams.write.on('finish', function () { internals.getLog(reporter._streams.write.path, function (error, results) { expect(error).to.not.exist(); expect(results.length).to.equal(1); expect(results[0]._data).to.equal('[Circular ~]'); internals.removeLog(reporter._streams.write.path); done(); }); }); read.push(data); read.push(null); }); }); it('can handle a large number of events', function (done) { var file = Hoek.uniqueFilename(internals.tempDir); var reporter = new GoodFile({ request: '*' }, file); var ee = new EventEmitter(); var read = internals.readStream(); reporter.init(read, ee, function (error) { expect(error).to.not.exist(); expect(reporter._streams.write.path).to.equal(file); reporter._streams.write.on('finish', function () { expect(reporter._streams.write.bytesWritten).to.equal(907873); internals.removeLog(reporter._streams.write.path); done(); }); for (var i = 0; i <= 10000; i++) { read.push({ event: 'request', id: i, timestamp: Date.now(), value: 'value for iteration ' + i }); } read.push(null); }); }); it('will log events even after a delay', function (done) { var file = Hoek.uniqueFilename(internals.tempDir); var reporter = new GoodFile({ request: '*' }, file); var ee = new EventEmitter(); var read = internals.readStream(); reporter.init(read, ee, function (error) { expect(error).to.not.exist(); expect(reporter._streams.write.path).to.equal(file); reporter._streams.write.on('finish', function () { expect(reporter._streams.write.bytesWritten).to.equal(17134); internals.removeLog(reporter._streams.write.path); done(); }); for (var i = 0; i <= 100; i++) { read.push({ event: 'request', id: i, timestamp: Date.now(), value: 'value for iteration ' + i }); } setTimeout(function () { for (var i = 0; i <= 100; i++) { read.push({ event: 'request', id: i, timestamp: Date.now(), value: 'inner iteration ' + i }); } read.push(null); }, 500); }); }); it('rotates logs on the specified internal', function (done) { var reporter = new GoodFile({ request: '*' }, { path: internals.tempDir, rotate: 'daily', format: 'YY#DDDD#MM', extension: '' }); var ee = new EventEmitter(); var min = Math.min; var read = internals.readStream(); var files = []; var pathOne = Path.join(internals.tempDir, 'rotate1'); var pathTwo = Path.join(internals.tempDir, 'rotate2'); Math.min = function () { Math.min = min; return 100; }; var getFile = reporter.getFile; reporter.getFile = function () { var result = getFile.call(this); files.push(result); return result; }; reporter.init(read, ee, function (error) { expect(error).to.not.exist(); for (var i = 0; i < 10; ++i) { read.push({ event: 'request', statusCode: 200, id: i, tag: 'my test 1 - ' + i }); } setTimeout(function () { reporter._streams.write.on('finish', function () { internals.getLog(files[0], function (err, fileOne) { expect(err).to.not.exist(); internals.getLog(files[1], function (err, fileTwo) { expect(err).to.not.exist(); var one = fileOne[0]; var two = fileTwo[0]; expect(fileOne).to.have.length(10); expect(fileTwo).to.have.length(10); expect(one).to.deep.equal({ event: 'request', statusCode: 200, id: 0, tag: 'my test 1 - 0' }); expect(two).to.deep.equal({ event: 'request', statusCode: 200, id: 0, tag: 'my test 2 - 0' }); for (var i = 0, il = files.length; i < il; ++i) { expect(/good-file-\d+#\d+#\d+-[\w,\d]+$/g.test(files[i])).to.be.true(); internals.removeLog(files[i]); } done(); }); }); }); for (var i = 0; i < 10; ++i) { read.push({ event: 'request', statusCode: 200, id: i, tag: 'my test 2 - ' + i }); } read.push(null); }, 200); }); }); describe('init()', function () { it('properly sets up the path and file information if the file name is specified', function (done) { var file = Hoek.uniqueFilename(internals.tempDir); var reporter = new GoodFile({ log: '*' }, file); var ee = new EventEmitter(); var stream = internals.readStream(); reporter.init(stream, ee, function (error) { expect(error).to.not.exist(); expect(reporter._streams.write.path).to.equal(file); internals.removeLog(reporter._streams.write.path); done(); }); }); it('properly creates a random file if the directory option is specified', function (done) { var reporter = new GoodFile({ log: '*' }, { path: internals.tempDir }); var ee = new EventEmitter(); var stream = internals.readStream(); reporter.init(stream, ee, function (error) { expect(error).to.not.exist(); expect(/good-file-\d+-.+.log/g.test(reporter._streams.write.path)).to.be.true(); internals.removeLog(reporter._streams.write.path); done(); }); }); it('uses the options passed via directory', function (done) { var reporter = new GoodFile({ log: '*' }, { path: internals.tempDir, extension: 'fun', prefix: 'ops-log', format: 'YY$DDDD' }); var ee = new EventEmitter(); var stream = internals.readStream(); reporter.init(stream, ee, function (error) { expect(error).to.not.exist(); expect(/\/ops-log-\d{2}\$\d{3}-.+.fun/g.test(reporter._streams.write.path)).to.be.true(); internals.removeLog(reporter._streams.write.path); done(); }); }); }); });
import { connect } from "react-redux"; import StatsTab from "../components/stats_tab"; import { fetchIdentificationCategories, fetchPopularObservations, fetchQualityGradeCounts } from "../ducks/project"; import { setConfig } from "../../../shared/ducks/config"; function mapStateToProps( state ) { return { config: state.config, project: state.project }; } function mapDispatchToProps( dispatch ) { return { fetchIdentificationCategories: ( ) => dispatch( fetchIdentificationCategories( ) ), fetchPopularObservations: ( ) => dispatch( fetchPopularObservations( ) ), fetchQualityGradeCounts: ( ) => dispatch( fetchQualityGradeCounts( ) ), setConfig: attributes => dispatch( setConfig( attributes ) ) }; } const StatsTabContainer = connect( mapStateToProps, mapDispatchToProps )( StatsTab ); export default StatsTabContainer;
XO('Event',function($){ this.on= function(fullName,handler){ if(arguments.length<=2){ XO.$body.on(fullName,handler); return; } $(arguments[0]).on(arguments[1],arguments[2]); }; this.trigger = function(fullName,args){ if(arguments.length<=2){ XO.$body.trigger(fullName,args); return; } $(arguments[0]).trigger(arguments[1],arguments[2]); }; this.init = function(){ //SYSTEM EVENTS XO.EVENT['Sys'] ={ viewChange: 'onorientationchange' in window ? 'orientationchange' : 'resize', fingerDown: XO.support.touch ? 'touchstart' : 'mousedown', fingerMove: XO.support.touch ? 'touchmove' : 'mousemove', fingerUp: XO.support.touch ? 'touchend' : 'mouseup' }; }; });
/** * manage window size save read and set */ const lastStateManager = require('./last-state') // const log = require('./log') const { isDev, minWindowWidth, minWindowHeight } = require('../utils/constants') exports.getScreenCurrent = () => { const rect = global.win ? global.win.getBounds() : { x: 0, width: minWindowWidth } const { screen } = require('electron') const all = screen .getAllDisplays() if (all.length === 1) { return all[0] } for (const d of all) { const right = rect.x + rect.width if (right > d.bounds.x && right <= d.bounds.x + d.workArea.width) { return d } } return screen.getPrimaryDisplay() } exports.getScreenSize = () => { const screen = exports.getScreenCurrent() return { ...screen.workAreaSize, x: screen.workArea.x, y: screen.workArea.y } } exports.maximize = () => { global.oldRectangle = global.win.getBounds() // global.win.setPosition(0, 0) const p = exports.getScreenCurrent() const { width, height, x, y } = p.workArea global.win.setPosition(x, y) global.win.setSize(width, height) } exports.unmaximize = () => { const { oldRectangle = { width: minWindowWidth, height: minWindowHeight, x: 0, y: 0 } } = global global.win.setPosition(oldRectangle.x, oldRectangle.y) global.win.setSize(oldRectangle.width, oldRectangle.height) } exports.getWindowSize = async () => { const windowSizeLastState = await lastStateManager.get('windowSize') const { width: maxWidth, height: maxHeight } = exports.getScreenSize() if (!windowSizeLastState || isDev) { return { width: maxWidth, height: maxHeight } } const { width, height, screenHeight, screenWidth } = windowSizeLastState const fw = width / screenWidth const fh = height / screenHeight let w = maxWidth * fw let h = maxHeight * fh const minW = minWindowWidth const minH = minWindowHeight if (w < minW) { w = minW } if (h < minH) { h = minH } return { width: w, height: h } }
var view; require([ "esri/Map", "esri/layers/FeatureLayer", "esri/views/MapView", "esri/PopupTemplate", "dojo/domReady!" ], function(Map, FeatureLayer, MapView, PopupTemplate) { var defaultSym = { type: "simple-fill", // autocasts as new SimpleFillSymbol outline: { // autocasts as new SimpleLineSymbol color: "#a3acd1", width: 0.5 } }; /****************************************************************** * * LayerRenderer example * ******************************************************************/ var renderer = { type: "simple", // autocasts as new SimpleRenderer symbol: defaultSym, label: "Private school enrollment ratio", visualVariables: [ { type: "color", field: "PrivateEnr", stops: [ { value: 0.044, color: "#edf8fb", label: "< 0.044" }, { value: 0.059, color: "#b3cde3" }, { value: 0.0748, color: "#8c96c6", label: "0.0748" }, { value: 0.0899, color: "#8856a7" }, { value: 0.105, color: "#994c99", label: "> 0.105" } ] } ] }; /*********************************** * Create renderer for centroids ************************************/ var centroidRenderer = { type: "simple", // autocasts as new SimpleRenderer symbol: { type: "picture-marker", // autocasts as new SimpleMarkerSymbol url: "http://static.arcgis.com/images/Symbols/Basic/BlueSphere.png", width: "26", height: "26" } }; /****************************************************************** * * Create feature layers * ******************************************************************/ var privateSchoolsPoint = new FeatureLayer({ // Private Schools centroids url: "https://services.arcgis.com/V6ZHFr6zdgNZuVG0/arcgis/rest/services/Centroids/FeatureServer/0", renderer: centroidRenderer }); /****************************************************************** * * Popup example * ******************************************************************/ // Step 1: Create the template var popupTemplate = new PopupTemplate({ title: "Private School enrollment", content: [ { // Specify the type of popup element - fields type: "fields", fieldInfos: [ { fieldName: "state_name", visible: true, label: "State name: " }, { fieldName: "PrivateMaj", visible: true, label: "Majority grade level for private schools: " }, { fieldName: "PrivateSch", visible: true, label: "Private school ratio to total number of schools: ", format: { places: 2, digitSeparator: true } }, { fieldName: "TotalPriva", visible: true, label: "Total number of private schools: " }, { fieldName: "Enrollment", visible: true, label: "Total number students enrolled in private schools: " }, { fieldName: "PrivateEnr", visible: true, label: "Total number of private school students enrolled in ratio to total student school enrollment: ", format: { places: 2, digitSeparator: true } } ] }, { type: "media", mediaInfos: [ { title: "Ratio private and public school enrollment", type: "pie-chart", caption: "Private school enrollment in comparison to public school", value: { theme: "Julie", fields: ["PrivateEnr", "PublicEnro"], tooltipField: "PrivateEnr" } }, { title: "Total number of private schools", type: "bar-chart", caption: "Total number of Private Schools in comparison to public. (Does not pertain to student enrollment.)", value: { theme: "Julie", fields: ["PrivateSch", "PublicScho"], tooltipField: "PrivateSch" } } ] } ] }); var privateSchoolsPoly = new FeatureLayer({ url: "https://services.arcgis.com/V6ZHFr6zdgNZuVG0/arcgis/rest/services/PrivateSchoolEnrollmentNoRendering/FeatureServer/0", outFields: ["*"], opacity: 0.8, renderer: renderer, popupTemplate: popupTemplate }); // Set map's basemap var map = new Map({ basemap: "gray-vector", layers: [privateSchoolsPoly, privateSchoolsPoint] }); view = new MapView({ container: "viewDiv", map: map, zoom: 3, center: [-99.14725260912257, 36.48617178360141], popup: { dockEnabled: true, dockOptions: { buttonEnabled: false, breakpoint: false } } }); });
'use strict'; let moment = require('moment'); let SensorUtils = require('../Command/Sensor/Utils'); const DEFAULT_CONDITION = { sensor: null, attribute: null, operator: null, value: null, }; /** * Condition * * Condition object */ class Condition { /** * Constructor * * @param {Object} condition Condition */ constructor(condition) { this.condition = Object.assign({}, DEFAULT_CONDITION); } /** * Get sensor * * @return {mixed} Sensor */ get sensor() { return this.condition.sensor; } /** * Set sensor * * @param {Sensor} sensor Sensor */ set sensor(sensor) { SensorUtils.validateSensor(sensor); this.condition.sensor = sensor; } /** * Get attribute * * @return {string} Attribute */ get attribute() { return this.condition.attribute; } /** * Set attribute * * @param {string} attribute Attribute */ set attribute(attribute) { this.condition.attribute = String(attribute); } /** * Get operator * * @return {string} Operator */ get operator() { return this.condition.operator; } /** * Set operator * * @param {string} operator Operator */ set operator(operator) { this.condition.operator = String(operator); } /** * Get value * * @return {mixed} Value */ get value() { return this.condition.value; } /** * Set value * * @param {mixed} value Value */ set value(value) { this.condition.value = value; } /** * When (field changes) * * @param {string} attribute State attribute * * @return {Condition} This object */ when(attribute) { let stateMap = this.sensor.state.stateMap; this.attribute = (attribute in stateMap) ? stateMap[attribute] : String(attribute); return this; } /** * Greater than value * * @param {string} value Value */ greaterThan(value) { this.operator = 'gt'; this.value = String(value); } /** * Less than value * * @param {string} value Value */ lessThan(value) { this.operator = 'lt'; this.value = String(value); } /** * Equals value * * @param {string} value Value */ equals(value) { this.operator = 'eq'; this.value = String(value); } /** * Changes (value changes) */ changes() { this.operator = 'dx'; this.value = undefined; } /** * Delayed changes */ delayedChanges() { this.operator = 'ddx'; this.value = undefined; } /** * Stable for (time) * * @param {int} time Time */ stableFor(time) { this.operator = 'stable'; this.value = time; } /** * Unstable for (time) * * @param {int} time Time */ unstableFor(time) { this.operator = 'not stable'; this.value = time; } /** * In (time) * * @param {string} startTime Time * @param {string} endTime Time */ in(startTime, endTime) { let startHour = moment(startTime).format('[T]HH:mm:ss'); let endHour = moment(endTime).format('[T]HH:mm:ss'); this.operator = 'in'; this.value = `${startHour}/${endHour}`; } /** * Not in (time) * * @param {string} startTime Time * @param {string} endTime Time */ notIn(startTime, endTime) { let startHour = moment(startTime).format('[T]HH:mm:ss'); let endHour = moment(endTime).format('[T]HH:mm:ss'); this.operator = 'not in'; this.value = `${startHour}/${endHour}`; } } module.exports = Condition;
/** * Created by patiernom on 09/03/2015. */ module.exports = { options: { banner: '/*!\n' + ' * <%= pkg.name %> v<%= pkg.version %>\n' + ' * Copyright 2014-<%= grunt.template.today("yyyy") %> <%= pkg.author %>\n' + ' * Licensed under <%= pkg.license.type %> (<%= pkg.license.url %>)\n' + ' */\n', report: 'min', sourceMap: true, preserveComments: 'some' }, sample: { src: 'dist/js/<%= pkg.name %>.bootstrap.js', dest: 'dist/js/<%= pkg.name %>.bootstrap.min.js' } };
'use strict'; var Twitter = require('twitter'); var express = require('express'); var http = require('http'); var generate = require('./lib/generate'); var app = express(); var port = process.env.PORT || 3000; var tweetInterval = process.env.TWEET_INTERVAL || 1800000; var tweet = new Twitter({ consumer_key: process.env.TWITTER_CONSUMER_KEY, consumer_secret: process.env.TWITTER_CONSUMER_SECRET, access_token_key: process.env.TWITTER_ACCESS_TOKEN_KEY, access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET }); function makeTweet() { var content = generate(); tweet.post('statuses/update', {status: content}, function(error, tweet, res) { if (error) { console.error(error); throw error; } console.log('Posted tweet: \"' + content + '\"'); }); } app.get('/', function(req, res) { res.send('Congratulations, you sent a GET request!'); console.log('Received a GET request and sent a response'); }); app.listen(port, function() { console.log('App now listening on port', port); }); function keepAlive() { try { http.get('http://food-truck-bot.herokuapp.com/'); console.log('GET request sent; kept alive.'); } catch(e) { console.log(e); } } makeTweet(); setInterval(makeTweet, tweetInterval); setInterval(keepAlive, 600000);
// All material copyright ESRI, All Rights Reserved, unless otherwise specified. // See https://js.arcgis.com/4.8/esri/copyright.txt for details. //>>built define(["require","exports","dojo/Deferred"],function(g,d,f){function e(a,b){if(Array.isArray(b)){var c=new f;a(b,function(){for(var b=[],a=0;a<arguments.length;a++)b[a]=arguments[a];c.resolve(b)});return c.promise}return e(a,[b]).then(function(a){return a[0]})}Object.defineProperty(d,"__esModule",{value:!0});d.when=e;d.getAbsMid=function(a,b,c){return b.toAbsMid?b.toAbsMid(a):c.id.replace(/\/[^\/]*$/gi,"/")+a}});
const { src, dest, series, parallel } = require('gulp'); const del = require('del') const rev = require('gulp-rev') const clean_css = require('gulp-clean-css') const terser = require('gulp-terser') const image = require('gulp-image') const uploadQcloud = require('gulp-qcloud-cos-upload') const revCollector = require('gulp-rev-collector') const qcloud = require('./qcloud.json') function clean(cb) { return del(['./dist'], cb) } function build_js() { return src('app/static/js/*.js') .pipe(terser()) .pipe(rev()) .pipe(dest('dist')) .pipe(rev.manifest({ path: 'dist/rev-manifest.json', base: 'dist', merge: true })) .pipe(dest('dist')) } function build_css() { return src('app/static/css/*.css') .pipe(clean_css()) .pipe(rev()) .pipe(dest('dist')) .pipe(rev.manifest({ path: 'dist/rev-manifest.json', base: 'dist', merge: true })) .pipe(dest('dist')) } function build_image() { return src('app/static/image/*.*') .pipe(image()) .pipe(rev()) .pipe(dest('dist')) .pipe(rev.manifest({ path: 'dist/rev-manifest.json', base: 'dist', merge: true })) .pipe(dest('dist')) } function upload() { return src('*.*', {cwd: 'dist'}) .pipe(uploadQcloud({ AppId: qcloud.AppId, SecretId: qcloud.SecretId, SecretKey: qcloud.SecretKey, Bucket: qcloud.Bucket, Region: qcloud.Region, prefix: qcloud.prefix })) } function rev_collect() { return src(['dist/rev-manifest.json', 'app/template/*.html']) .pipe(revCollector({ 'replaceReved': true, 'dirReplacements': { '/css/': 'https://jackeriss-1252826939.file.myqcloud.com/' + qcloud.prefix + '/', '/js/': 'https://jackeriss-1252826939.file.myqcloud.com/' + qcloud.prefix + '/', '/image/': 'https://jackeriss-1252826939.file.myqcloud.com/' + qcloud.prefix + '/' } })) .pipe(dest('app/template/dist')) } exports.default = series(clean, parallel(build_js, build_css, build_image), upload, rev_collect)
const fs = require('fs'); const path = require('path'); const configFile = JSON.parse(fs.readFileSync('./config.json')); // Solves cyclic dependency issue const texFilename = path.parse(configFile.resume_filename).name + '.tex'; const config = { configFile: configFile, distDirname: configFile.dist_dir, srcDirname: configFile.src_dir, srcPath: path.resolve(configFile.src_dir), resumeFilename: configFile.resume_filename, resumePath: path.resolve(configFile.src_dir, configFile.resume_filename), texFilename: texFilename, texPath: path.resolve(configFile.src_dir, texFilename), archiveFilename: configFile.archive_filename, archivePath: path.resolve(configFile.dist_dir, configFile.archive_filename) }; module.exports = config;
(function(pangu) { 'use strict'; var ignore_tags = /^(code|pre|textarea)$/i; var space_sensitive_tags = /^(a|del|pre|s|strike|u)$/i; var space_like_tags = /^(br|hr|i|img|pangu)$/i; var block_tags = /^(div|h1|h2|h3|h4|h5|h6|p)$/i; /* 1. 硬幹 contentEditable 元素的 child nodes 還是會被 spacing 的問題 因為 contentEditable 的值可能是 'true', 'false', 'inherit' 如果沒有顯式地指定 contentEditable 的值 一般都會是 'inherit' 而不是 'false' 2. 不要對特定 tag 裡的文字加空格 例如 pre TODO: 太暴力了,應該有更好的解法 */ function can_ignore_node(node) { var parent_node = node.parentNode; while (parent_node.nodeName.search(/^(html|head|body|#document)$/i) === -1) { if ((parent_node.getAttribute('contenteditable') === 'true') || (parent_node.getAttribute('g_editable') === 'true')) { return true; } else if (parent_node.nodeName.search(ignore_tags) >= 0) { return true; } else { parent_node = parent_node.parentNode; } } return false; } /* nodeType: http://www.w3schools.com/dom/dom_nodetype.asp 1: ELEMENT_NODE 3: TEXT_NODE 8: COMMENT_NODE */ function is_first_text_child(parent_node, target_node) { var child_nodes = parent_node.childNodes; // 只判斷第一個含有 text 的 node for (var i = 0; i < child_nodes.length; i++) { var child_node = child_nodes[i]; if (child_node.nodeType !== 8 && child_node.textContent) { return child_node === target_node; } } // 沒有顯式地 return 就是 undefined,放在 if 裡面會被當成 false // return false; } function is_last_text_child(parent_node, target_node) { var child_nodes = parent_node.childNodes; // 只判斷倒數第一個含有 text 的 node for (var i = child_nodes.length - 1; i > -1; i--) { var child_node = child_nodes[i]; if (child_node.nodeType !== 8 && child_node.textContent) { return child_node === target_node; } } // return false; } function insert_space(text) { var old_text = text; var new_text; /* Regular Expressions https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions Symbols ` ~ ! @ # $ % ^ & * ( ) _ - + = [ ] { } \ | ; : ' " < > , . / ? 3000-303F 中日韓符號和標點 3040-309F 日文平假名 (V) 30A0-30FF 日文片假名 (V) 3100-312F 注音字母 (V) 31C0-31EF 中日韓筆畫 31F0-31FF 日文片假名語音擴展 3200-32FF 帶圈中日韓字母和月份 (V) 3400-4DBF 中日韓統一表意文字擴展 A (V) 4E00-9FFF 中日韓統一表意文字 (V) AC00-D7AF 諺文音節 (韓文) F900-FAFF 中日韓兼容表意文字 (V) http://unicode-table.com/cn/ */ // 前面"字"後面 >> 前面 "字" 後面 text = text.replace(/([\u3040-\u312f\u3200-\u32ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff])(["'])/ig, '$1 $2'); text = text.replace(/(["'])([\u3040-\u312f\u3200-\u32ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff])/ig, '$1 $2'); // 避免出現 '前面 " 字" 後面' 之類的不對稱的情況 text = text.replace(/(["']+)(\s*)(.+?)(\s*)(["']+)/ig, '$1$3$5'); // # 符號需要特別處理 text = text.replace(/([\u3040-\u312f\u3200-\u32ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff])(#(\S+))/ig, '$1 $2'); text = text.replace(/((\S+)#)([\u3040-\u312f\u3200-\u32ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff])/ig, '$1 $3'); // 前面<字>後面 --> 前面 <字> 後面 old_text = text; new_text = old_text.replace(/([\u3040-\u312f\u3200-\u32ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff])([<\[\{\(]+(.*?)[>\]\}\)]+)([\u3040-\u312f\u3200-\u32ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff])/ig, '$1 $2 $4'); text = new_text; if (old_text === new_text) { // 前面<後面 --> 前面 < 後面 text = text.replace(/([\u3040-\u312f\u3200-\u32ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff])([<>\[\]\{\}\(\)])/ig, '$1 $2'); text = text.replace(/([<>\[\]\{\}\(\)])([\u3040-\u312f\u3200-\u32ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff])/ig, '$1 $2'); } // 避免出現 "前面 [ 字] 後面" 之類的不對稱的情況 text = text.replace(/([<\[\{\(]+)(\s*)(.+?)(\s*)([>\]\}\)]+)/ig, '$1$3$5'); // 中文在前 text = text.replace(/([\u3040-\u312f\u3200-\u32ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff])([a-z0-9`@&%=\$\^\*\-\+\|\/\\])/ig, '$1 $2'); // 中文在後 text = text.replace(/([a-z0-9`~!%&=;\|\,\.\:\?\$\^\*\-\+\/\\])([\u3040-\u312f\u3200-\u32ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff])/ig, '$1 $2'); return text; } function spacing(xpath_query) { // 是否加了空格 var had_spacing = false; /* 因為 xpath_query 用的是 text(),所以這些 nodes 是 text 而不是 DOM element https://developer.mozilla.org/en-US/docs/DOM/document.evaluate http://www.w3cschool.cn/dom_xpathresult.html snapshotLength 要配合 XPathResult.ORDERED_NODE_SNAPSHOT_TYPE 使用 */ var text_nodes = document.evaluate(xpath_query, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); var nodes_length = text_nodes.snapshotLength; var next_text_node; // 從最下面、最裡面的節點開始 for (var i = nodes_length - 1; i > -1; --i) { var current_text_node = text_nodes.snapshotItem(i); // console.log('current_text_node: %O, nextSibling: %O', current_text_node.data, current_text_node.nextSibling); // console.log('next_text_node: %O', next_text_node); if (can_ignore_node(current_text_node)) { next_text_node = current_text_node; continue; } // http://www.w3school.com.cn/xmldom/dom_text.asp var new_data = insert_space(current_text_node.data); if (current_text_node.data !== new_data) { had_spacing = true; current_text_node.data = new_data; } // 處理嵌套的 <tag> 中的文字 if (next_text_node) { /* TODO: 現在只是簡單地判斷相鄰的下一個 node 是不是 <br> 萬一遇上嵌套的標籤就不行了 */ if (current_text_node.nextSibling) { if (current_text_node.nextSibling.nodeName.search(space_like_tags) >= 0) { next_text_node = current_text_node; continue; } } // current_text_node 的最後一個字 + next_text_node 的第一個字 var text = current_text_node.data.toString().substr(-1) + next_text_node.data.toString().substr(0, 1); var new_text = insert_space(text); if (text !== new_text) { had_spacing = true; /* 基本上 next_node 就是 next_text_node 的 parent node current_node 就是 current_text_node 的 parent node */ /* 往上找 next_text_node 的 parent node 直到遇到 space_sensitive_tags 而且 next_text_node 必須是第一個 text child 才能把空格加在 next_text_node 的前面 */ var next_node = next_text_node; while (next_node.parentNode && next_node.nodeName.search(space_sensitive_tags) === -1 && is_first_text_child(next_node.parentNode, next_node)) { next_node = next_node.parentNode; } // console.log('next_node: %O', next_node); var current_node = current_text_node; while (current_node.parentNode && current_node.nodeName.search(space_sensitive_tags) === -1 && is_last_text_child(current_node.parentNode, current_node)) { current_node = current_node.parentNode; } // console.log('current_node: %O, nextSibling: %O', current_node, current_node.nextSibling); if (current_node.nextSibling) { if (current_node.nextSibling.nodeName.search(space_like_tags) >= 0) { next_text_node = current_text_node; continue; } } if (current_node.nodeName.search(block_tags) === -1) { if (next_node.nodeName.search(space_sensitive_tags) === -1) { if ((next_node.nodeName.search(ignore_tags) === -1) && (next_node.nodeName.search(block_tags) === -1)) { if (next_text_node.previousSibling) { if (next_text_node.previousSibling.nodeName.search(space_like_tags) === -1) { // console.log('spacing 1-1: %O', next_text_node.data); next_text_node.data = ' ' + next_text_node.data; } } else { // console.log('spacing 1-2: %O', next_text_node.data); next_text_node.data = ' ' + next_text_node.data; } } } else if (current_node.nodeName.search(space_sensitive_tags) === -1) { // console.log('spacing 2: %O', current_text_node.data); current_text_node.data = current_text_node.data + ' '; } else { var pangu_space = document.createElement('pangu'); pangu_space.innerHTML = ' '; // 避免一直被加空格 if (next_node.previousSibling) { if (next_node.previousSibling.nodeName.search(space_like_tags) === -1) { // console.log('spacing 3-1: %O', next_node.parentNode); next_node.parentNode.insertBefore(pangu_space, next_node); } } else { // console.log('spacing 3-2: %O', next_node.parentNode); next_node.parentNode.insertBefore(pangu_space, next_node); } // TODO: 這個做法真的有點蠢,但是不管還是先硬上 // 主要是想要避免在元素(通常都是 <li>)的開頭加空格 if (!pangu_space.previousElementSibling) { if (pangu_space.parentNode) { pangu_space.parentNode.removeChild(pangu_space); } } } } } } next_text_node = current_text_node; } return had_spacing; } pangu.text_spacing = function(text) { return insert_space(text); }; pangu.page_spacing = function() { // var p = 'page_spacing'; // console.profile(p); // console.time(p); // var start = new Date().getTime(); /* // >> 任意位置的節點 . >> 當前節點 .. >> 父節點 [] >> 條件 text() >> 節點的文字內容,例如 hello 之於 <tag>hello</tag> [@contenteditable] 帶有 contenteditable 屬性的節點 normalize-space(.) 當前節點的頭尾的空白字元都會被移除,大於兩個以上的空白字元會被置換成單一空白 https://developer.mozilla.org/en-US/docs/XPath/Functions/normalize-space name(..) 父節點的名稱 https://developer.mozilla.org/en-US/docs/XPath/Functions/name translate(string, "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz") 將 string 轉換成小寫,因為 XML 是 case-sensitive 的 https://developer.mozilla.org/en-US/docs/XPath/Functions/translate 1. 處理 <title> 2. 處理 <body> 底下的節點 3. 略過 contentEditable 的節點 4. 略過特定節點,例如 <script> 和 <style> 注意,以下的 query 只會取出各節點的 text 內容! */ var title_query = '/html/head/title/text()'; spacing(title_query); // var body_query = '/html/body//*[not(@contenteditable)]/text()[normalize-space(.)]'; var body_query = '/html/body//*/text()[normalize-space(.)]'; ['script', 'style', 'textarea'].forEach(function(tag) { /* 理論上這幾個 tag 裡面不會包含其他 tag 所以可以直接用 .. 取父節點 ex: [translate(name(..), "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz") != "script"] */ body_query += '[translate(name(..),"ABCDEFGHIJKLMNOPQRSTUVWXYZ","abcdefghijklmnopqrstuvwxyz")!="' + tag + '"]'; }); var had_spacing = spacing(body_query); // console.profileEnd(p); // console.timeEnd(p); // var end = new Date().getTime(); // console.log(end - start); return had_spacing; }; pangu.element_spacing = function(selector_string) { var xpath_query; if (selector_string.indexOf('#') === 0) { var target_id = selector_string.substr(1, selector_string.length - 1); // ex: id("id_name")//text() xpath_query = 'id("' + target_id + '")//text()'; } else if (selector_string.indexOf('.') === 0) { var target_class = selector_string.slice(1); // ex: //*[contains(@class, "target_class")]//*/text() xpath_query = '//*[contains(@class, "' + target_class + '")]//*/text()'; } else { var target_tag = selector_string; // ex: //tag_name/text() xpath_query = '//' + target_tag + '//text()'; } var had_spacing = spacing(xpath_query); return had_spacing; }; }(window.pangu = window.pangu || {}));
'use strict'; import React from 'react'; import Header from '../../header'; module.exports = React.createClass({ displayName: 'app/pages/home/index.js', getDefaultProps() { return { title: 'home', body: 'welcome home' }; }, render() { return ( <div className="container"> <div className="row"> <div className="twelve columns"> <Header/> </div> </div> <div className="row"> <div className="twelve columns"> <main role="main"> <h1>{this.props.title}</h1> <h3>{this.props.body}</h3> <img className="u-max-full-width" src={require('../../images/top1.jpg')} alt=""/> </main> </div> </div> </div> ) } });
window.cytubeEnhanced.addModule('videoResize', function (app, settings) { 'use strict'; var that = this; var defaultSettings = { turnedOn: true }; settings = $.extend({}, defaultSettings, settings); function setWight() { var self = this; self.ARROW = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAADZJREFUeNpiYBgFVAfzoZhoeSYsihJwGDIfKkeUK/6jGYJNjGhDSNaMbghZmokN1FFADQAQYACgYhHrEaVEsQAAAABJRU5ErkJggg=='; self.COLCOUNT = 12; self.PREFIX = 'set-width-'; self.AUTHOR = 'dfdfg'; self.positions = []; self.mode = 'show'; self.checkPosition = function() { var chatwrap = document.getElementById('chatwrap'), videowrap = document.getElementById('videowrap'); if(chatwrap.nextSibling == videowrap){ self.positions = [chatwrap, videowrap]; } else { self.positions = [videowrap, chatwrap]; } var pos1 = $(chatwrap).position().top, pos2 = $(videowrap).position().top; return pos1 == pos2; }; self.addHtml = function() { var htmlArr = []; htmlArr.push('<div id="' + self.PREFIX + 'wrap" style="top: -17px; position: relative; height: 0px;line-height: 0px;">'); for (var i = 1; i < self.COLCOUNT; i++) { htmlArr.push('<div style="left: ' + (100 * i / self.COLCOUNT) + '%; position: relative;height: 0px;">'); htmlArr.push('<img id="' + self.PREFIX + 'arrow-' + i + '" class="' + self.PREFIX + 'arrow" src="' + self.ARROW + '" style="cursor: pointer; margin-left: -8px; background-color:rgba(255,255,255,0.1); border-radius: 8px;">'); htmlArr.push('</div>'); } htmlArr.push('</div>'); $("#main").prepend(htmlArr.join("\n")); }; self.hide = function(num) { num = num || -1; if(num == -1){ var clsName = self.positions[0].getAttribute('class'); num = clsName.substr(clsName.lastIndexOf('-') + 1); } for (var i = 1; i < self.COLCOUNT; i++) { if(i != num){ $('#' + self.PREFIX + 'arrow-' + i).parent().hide(); } } self.mode = 'hide'; }; self.show = function(num) { $('.' + self.PREFIX + 'arrow').parent().show(); self.mode = 'show'; }; self.setHandlers = function() { $('.' + self.PREFIX + 'arrow').click(function(eventObject) { if(self.mode == 'show'){ var id = eventObject.currentTarget.id, num = id.substr(id.lastIndexOf('-') + 1), num2 = self.COLCOUNT - num; var next = $('#' + self.PREFIX + 'wrap').next(); app.storage.set('chatWidthInColumns', num); next.attr('class', 'col-lg-'+num+' col-md-'+num); next = next.next(); next.attr('class', 'col-lg-'+num2+' col-md-'+num2); self.hide(num); window.handleWindowResize(); return; } // else self.show(); }); }; self.loadPosition = function () { var columnNumber = app.storage.get('chatWidthInColumns'); if (columnNumber) { $('#' + q.PREFIX + 'arrow-' + columnNumber).trigger('click').load(function () { $(this).trigger('click'); }); } }; self.create = function() { $('#' + self.PREFIX + 'wrap').remove(); if (!self.checkPosition()) { return; } self.addHtml(); self.setHandlers(); self.hide(); self.loadPosition(); }; } if (settings.turnedOn) { app.storage.setDefault('chatWidthInColumns', 5); var q = new setWight(); q.create(); } });
import { Resource } from 'resource-loader'; import path from 'path'; import * as core from '../core'; const BATCH_SIZE = 1000; export default function () { return function spritesheetParser(resource, next) { let resourcePath; const imageResourceName = `${resource.name}_image`; // skip if no data, its not json, it isn't spritesheet data, or the image resource already exists if (!resource.data || !resource.isJson || !resource.data.frames || this.resources[imageResourceName]) { next(); return; } const loadOptions = { crossOrigin: resource.crossOrigin, loadType: Resource.LOAD_TYPE.IMAGE, metadata: resource.metadata.imageMetadata, }; // Prepend url path unless the resource image is a data url if (resource.isDataUrl) { resourcePath = resource.data.meta.image; } else { resourcePath = `${path.dirname(resource.url.replace(this.baseUrl, ''))}/${resource.data.meta.image}`; } // load the image for this sheet this.add(imageResourceName, resourcePath, loadOptions, function onImageLoad(res) { resource.textures = {}; const frames = resource.data.frames; const frameKeys = Object.keys(frames); const baseTexture = res.texture.baseTexture; const scale = resource.data.meta.scale; // Use a defaultValue of `null` to check if a url-based resolution is set let resolution = core.utils.getResolutionOfUrl(resource.url, null); // No resolution found via URL if (resolution === null) { // Use the scale value or default to 1 resolution = scale !== undefined ? scale : 1; } // For non-1 resolutions, update baseTexture if (resolution !== 1) { baseTexture.resolution = resolution; baseTexture.update(); } let batchIndex = 0; function processFrames(initialFrameIndex, maxFrames) { let frameIndex = initialFrameIndex; while (frameIndex - initialFrameIndex < maxFrames && frameIndex < frameKeys.length) { const i = frameKeys[frameIndex]; const rect = frames[i].frame; if (rect) { let frame = null; let trim = null; const orig = new core.Rectangle( 0, 0, frames[i].sourceSize.w / resolution, frames[i].sourceSize.h / resolution ); if (frames[i].rotated) { frame = new core.Rectangle( rect.x / resolution, rect.y / resolution, rect.h / resolution, rect.w / resolution ); } else { frame = new core.Rectangle( rect.x / resolution, rect.y / resolution, rect.w / resolution, rect.h / resolution ); } // Check to see if the sprite is trimmed if (frames[i].trimmed) { trim = new core.Rectangle( frames[i].spriteSourceSize.x / resolution, frames[i].spriteSourceSize.y / resolution, rect.w / resolution, rect.h / resolution ); } resource.textures[i] = new core.Texture( baseTexture, frame, orig, trim, frames[i].rotated ? 2 : 0 ); // lets also add the frame to pixi's global cache for fromFrame and fromImage functions core.utils.TextureCache[i] = resource.textures[i]; } frameIndex++; } } function shouldProcessNextBatch() { return batchIndex * BATCH_SIZE < frameKeys.length; } function processNextBatch(done) { processFrames(batchIndex * BATCH_SIZE, BATCH_SIZE); batchIndex++; setTimeout(done, 0); } function iteration() { processNextBatch(() => { if (shouldProcessNextBatch()) { iteration(); } else { next(); } }); } if (frameKeys.length <= BATCH_SIZE) { processFrames(0, BATCH_SIZE); next(); } else { iteration(); } }); }; }
var lpstream = require('length-prefixed-stream') var duplexify = require('duplexify') var ids = require('numeric-id-map') var crypto = require('crypto') var events = require('events') var bitfield = require('bitfield') var util = require('util') var messages = require('./messages') var MAX_BITFIELD = 4 * 1024 * 1024 var MAX_MESSAGE = 5 * 1024 * 1024 var ENCODINGS = [ messages.Join, messages.Leave, messages.Have, messages.Pause, messages.Unpause, messages.Request, messages.Response, messages.Cancel ] module.exports = Protocol function Channel (stream, link) { events.EventEmitter.call(this) this.stream = stream this.left = false this.link = link this.local = 0 this.remote = 0 this.remoteJoined = false this.remotePausing = true this.remoteBitfield = bitfield(1, {grow: MAX_BITFIELD}) this.amPausing = true this.amRequesting = bitfield(1, {grow: Infinity}) this.inflight = 0 } util.inherits(Channel, events.EventEmitter) Channel.prototype.leave = function (err) { if (this.left) return if (err) this.emit('warn', err) this.stream._push(1, {channel: this.local}) this.onleave() } Channel.prototype.bitfield = function (bitfield) { this.stream._push(2, { channel: this.local, bitfield: toBuffer(bitfield) }) } Channel.prototype.have = function (blocks, bitfield) { if (typeof blocks === 'number') blocks = [blocks] this.stream._push(2, { channel: this.local, blocks: blocks, bitfield: toBuffer(bitfield) }) } Channel.prototype.pause = function () { this.amPausing = true this.stream._push(3, {channel: this.local}) } Channel.prototype.unpause = function () { this.amPausing = false this.stream._push(4, {channel: this.local}) } Channel.prototype.request = function (block) { this.amRequesting.set(block, true) this.inflight++ this.stream.inflight++ this.stream._push(5, {channel: this.local, block: block}) } Channel.prototype.response = function (block, data, proof) { this.stream._push(6, { channel: this.local, block: block, data: data, proof: proof }) } Channel.prototype.cancel = function (block) { this._clear(block) this.stream._push(7, { channel: this.local, block: block }) } Channel.prototype.onleave = function () { if (this.left) return this.left = true if (this.remoteJoined) this.stream._remove(this) this.emit('leave') } Channel.prototype.onjoin = function (channel) { this.remote = channel this.remoteJoined = true if (this.left) this.stream._remove(this) } Channel.prototype.onhave = function (message) { if (message.bitfield) { this.remoteBitfield = bitfield(message.bitfield, {grow: MAX_BITFIELD}) } if (message.blocks) { for (var i = 0; i < message.blocks.length; i++) { var block = message.blocks[i] this.remoteBitfield.set(block) } } this.emit('have') this.emit('update') } Channel.prototype.onpause = function () { this.remotePausing = true this.emit('pause') this.emit('update') } Channel.prototype.onunpause = function () { this.remotePausing = false this.emit('unpause') this.emit('update') } Channel.prototype.onrequest = function (message) { this.emit('request', message.block) } Channel.prototype.onresponse = function (message) { var block = message.block this._clear(block) this.emit('response', block, message.data, message.proof) } Channel.prototype.oncancel = function (message) { this.emit('cancel', message.block) } Channel.prototype._clear = function (block) { if (this.amRequesting.get(block)) { this.inflight-- this.stream.inflight-- this.amRequesting.set(block, false) } } function Protocol (opts) { if (!(this instanceof Protocol)) return new Protocol(opts) if (!opts) opts = {} duplexify.call(this) var self = this this.inflight = 0 this.id = opts.id || crypto.randomBytes(32) this.remoteId = null this._parser = lpstream.decode({limit: MAX_MESSAGE}) this._generator = lpstream.encode() this._parser.on('data', parse) this._handshook = false this._channels = {} this._remote = [] this._local = ids() var handshake = { protocol: 'hypercore', id: this.id } this._generator.write(messages.Handshake.encode(handshake)) this.setReadable(this._generator) this.setWritable(this._parser) function parse (data) { self._parse(data) } } util.inherits(Protocol, duplexify) Protocol.prototype._onhandshake = function (handshake) { if (handshake.protocol !== 'hyperdrive' && handshake.protocol !== 'hypercore') { return this.destroy(new Error('Protocol must be hypercore')) } this.remoteId = handshake.id this.emit('handshake') } Protocol.prototype._parse = function (data) { if (this.destroyed) return if (!this._handshook) { try { var handshake = messages.Handshake.decode(data) } catch (err) { return this.destroy(err) } this._handshook = true this._onhandshake(handshake) return } var type = data[0] if (type >= ENCODINGS.length) return // unknown message try { var message = ENCODINGS[type].decode(data, 1) } catch (err) { return this.destroy(err) } switch (type) { case 0: return this._onjoin(message) case 1: return this._onleave(message) case 2: return this._onhave(message) case 3: return this._onpause(message) case 4: return this._onunpause(message) case 5: return this._onrequest(message) case 6: return this._onresponse(message) } } Protocol.prototype._onjoin = function (message) { if (message.channel > this._remote.length) { return this.destroy(new Error('Remote sent invalid channel id')) } if (this._remote.length > message.channel && this._remote[message.channel]) { return this.destroy(new Error('Remote reused channel id')) } var ch = this.join(message.id) if (this._remote.length === message.channel) this._remote.push(null) this._remote[message.channel] = ch ch.onjoin(message.channel) } Protocol.prototype._onleave = function (message) { var ch = this._get(message.channel) if (ch) ch.onleave() } Protocol.prototype._onhave = function (message) { var ch = this._get(message.channel) if (ch) ch.onhave(message) } Protocol.prototype._onpause = function (message) { var ch = this._get(message.channel) if (ch && !ch.remotePausing) ch.onpause() } Protocol.prototype._onunpause = function (message) { var ch = this._get(message.channel) if (ch && ch.remotePausing) ch.onunpause() } Protocol.prototype._onrequest = function (message) { var ch = this._get(message.channel) if (ch) ch.onrequest(message) } Protocol.prototype._onresponse = function (message) { var ch = this._get(message.channel) if (ch) ch.onresponse(message) } Protocol.prototype._get = function (id) { if (id >= this._remote.length) { this.destroy(new Error('Remote sent invalid channel id')) return null } return this._remote[id] } Protocol.prototype._remove = function (channel) { this._local.remove(channel.local) this._remote[channel.remote] = null delete this._channels[channel.link.toString('hex')] } Protocol.prototype._push = function (type, message) { var enc = ENCODINGS[type] var buf = new Buffer(enc.encodingLength(message) + 1) buf[0] = type enc.encode(message, buf, 1) this._generator.write(buf) } Protocol.prototype.join = function (id) { var name = id.toString('hex') var ch = this._channels[name] if (ch) return this._local.get(ch - 1) ch = new Channel(this, id) ch.local = this._local.add(ch) this._channels[name] = ch.local + 1 this._push(0, {channel: ch.local, id: id}) this.emit('channel', ch) return ch } Protocol.prototype.leave = function (id) { var name = id.toString('hex') if (!this._channels[name]) return false this.join(id).leave() } function toBuffer (bitfield) { if (!bitfield) return null if (Buffer.isBuffer(bitfield)) return bitfield return bitfield.buffer }
import { LIGHT_TYPE } from '../../const.js'; import { Light } from './Light.js'; import { DirectionalLightShadow } from './DirectionalLightShadow.js'; /** * A light that gets emitted in a specific direction. * This light will behave as though it is infinitely far away and the rays produced from it are all parallel. * The common use case for this is to simulate daylight; the sun is far enough away that its position can be considered to be infinite, and all light rays coming from it are parallel. * This light can cast shadows - see the {@link zen3d.DirectionalLightShadow} page for details. * @constructor * @memberof zen3d * @extends zen3d.Light * @param {number} [color=0xffffff] * @param {number} [intensity=1] */ function DirectionalLight(color, intensity) { Light.call(this, color, intensity); this.lightType = LIGHT_TYPE.DIRECT; /** * A {@link zen3d.DirectionalLightShadow} used to calculate shadows for this light. * @type {zen3d.DirectionalLightShadow} * @default zen3d.DirectionalLightShadow() */ this.shadow = new DirectionalLightShadow(); } DirectionalLight.prototype = Object.assign(Object.create(Light.prototype), /** @lends zen3d.DirectionalLight.prototype */{ constructor: DirectionalLight, copy: function(source) { Light.prototype.copy.call(this, source); this.shadow.copy(source.shadow); return this; } }); export { DirectionalLight };
import React from 'react' import {shallow} from 'enzyme' import App from './App' test('should render Header correctly', () => { const wrapper = shallow(<App />) expect(wrapper).toMatchSnapshot() })
import _ from 'lodash'; export default class IncludesResolver { /** * @param {Model} model */ static of(model) { return new IncludesResolver(model); } /** * @param {Model} model */ constructor(model) { this.grm = model.orm; this.model = model; } /** * @param {array|object|boolean} userIncludes * @param {boolean} includeDefaults */ resolve(userIncludes, includeDefaults = true) { if (_.isPlainObject(userIncludes)) { const relationsIncludes = _(userIncludes) .pick((cfg, fieldName) => (cfg === true || _.isPlainObject(cfg)) && this.model.relations[fieldName]) .mapValues((cfg, fieldName) => { const relationModel = this.grm.registry.get(this.model.relations[fieldName].model); return IncludesResolver.of(relationModel).resolve(cfg, includeDefaults); }).value(); const newIncludes = { ..._.omit(userIncludes, '$defaults'), ...relationsIncludes, }; if ((!userIncludes.hasOwnProperty('$defaults') && includeDefaults) || userIncludes.$defaults) { return this._mergeIncludes(this.model.defaultIncludes, newIncludes); } else { return newIncludes; } } else if (userIncludes === true) { return this.model.defaultIncludes; } else if (_.isArray(userIncludes)) { const objectUserIncludes = userIncludes.reduce((acc, field) => { const fieldObject = field.split('.').reduceRight((acc2, token) => ({ [token]: acc2 }), true); return _.merge(acc, fieldObject); }, {}); return this.resolve(objectUserIncludes, includeDefaults); } else { return {}; } } mergeDependencies(includes) { return this._addMissingIds(this._mergeVirtualFieldsDependencies(includes)); } /** * @param {Model} model * @param {object} includes * @return {object} */ _mergeVirtualFieldsDependencies(includes) { return _(this.model.virtualFields) .filter((cfg, field) => includes[field]) .map('dependsOn') .reduce((target, source) => { return this._mergeIncludes(target, this._fullResolve(source)); }, includes); } _addMissingIds(includes) { return { ...includes, id: true, ..._(this.model.relations) .pick((cfg, field) => includes[field]) .mapValues((cfg, field) => IncludesResolver.of(cfg.model)._addMissingIds(includes[field])) .value(), }; } _fullResolve(includes) { return this._mergeVirtualFieldsDependencies(this.resolve(includes, false)); } _mergeIncludes(target, source) { return _.pick({ ...target, ..._.mapValues(source, (value, key) => { if (_.isObject(target[key]) && _.isObject(source[key])) { return this._mergeIncludes(target[key], source[key]); } else { return source[key]; } }), }, _.identity); } }
window.City = Backbone.Model.extend({ urlRoot: 'rest/api/accounts', defaults: { "id": null, "username": "", "email": "", "roles": "", "about": "", "group": "", "country": "", "city": "", "password": "" } }); window.AccountList = Backbone.Collection.extend({ model: Account, url: 'rest/api/accounts' });
'use strict'; var React = require('react'); var IconBase = require(__dirname + 'components/IconBase/IconBase'); var AndroidArrowDropleftCircle = React.createClass({ displayName: 'AndroidArrowDropleftCircle', render: function render() { return React.createElement( IconBase, null, React.createElement( 'g', null, React.createElement('path', { d: 'M464,256c0-114.875-93.125-208-208-208S48,141.125,48,256s93.125,208,208,208S464,370.875,464,256z M192,256l96-96v192 L192,256z' }) ) ); } });
'use strict'; var estraverse = require('estraverse'); var defaults = { pre: require('./labels/pre'), post: require('./labels/post'), main: require('./labels/main'), invariant: require('./labels/invariant') }; /** * Process an AST and return the modified structure. * * @param {Object} ast The AST to process. * @param {Object} options The options for the processor. * @return {Object} The processed AST. */ exports.process = function (ast, options) { invariant: ast && typeof ast === 'object'; main: options = options || {}; options.libIdentifier = options.libIdentifier || 'OBLIGATIONS'; options.resultIdentifier = options.resultIdentifier || '__result'; options.completedIdentifier = options.completedIdentifier || '__completed'; options.supported = options.supported || defaults; options.global = options.global || false; options.require = options.require || 'obligations'; return processProgram(ast, options); post: __result && typeof __result === 'object'; }; /** * Process a program. * * @param {Object} ast The program to process. * @param {Object} options The options for the processor. * @return {Object} The processed AST. */ function processProgram (ast, options) { pre: ast && typeof ast === 'object'; ast.type === 'Program'; options && typeof options === 'object'; main: var total = processFunctions(ast, options)[1]; if (total && !options.global) { if (ast.body[0].type === 'ExpressionStatement' && ast.body[0].expression.value === 'use strict') { ast.body.splice(1, 0, createRequireStatement(options)); } else { ast.body.unshift(createRequireStatement(options)); } } // regular expression are being hammered in some cases, this fixes that. // but it's a bandage. The root cause is not clear, it seems to be an issue with esprima. estraverse.traverse(ast, { leave: function (node) { var matches; if (node.type === 'Literal' && (matches = /^\/(.*)\/([gimy]*)$/.exec(node.raw))) { node.value = new RegExp(matches[1], matches[2] || ''); } } }) return ast; post: ast && ast.type === 'Program'; } /** * Create a require statement to be inserted at the top of the program. * * @param {Object} options [description] * @return {Object} [description] */ function createRequireStatement (options) { pre: options && typeof options === 'object'; main: return { type: 'VariableDeclaration', kind: 'var', declarations: [ { type: 'VariableDeclarator', id: { type: 'Identifier', name: options.libIdentifier }, init: { type: 'CallExpression', callee: { type: 'Identifier', name: 'require' }, arguments: [ { type: 'Literal', value: options.require, raw: JSON.stringify(options.require) } ] } } ] }; } /** * Processes `FunctionDeclaration` and `FunctionExpression` instances. * These are the only structures which may contain contracts. * * @param {Object} ast The AST to process. * @param {Object} options The options for the processor. * @return {Array} The processed AST and the number of functions that contain contracts. */ function processFunctions (ast, options) { pre: ast && typeof ast === 'object'; main: var total = 0; estraverse.replace(ast, { enter: function (node) { var result; if (node.type === 'FunctionDeclaration' || node.type === 'FunctionExpression') { result = collectLabels(node, options); if (result[1].length) { total++; return cleanup(result[0]); } else { return result[0]; } } } }); return [ast, total]; post: Array.isArray(__result); __result[0] && typeof __result[0] === 'object'; } /** * Collects all the `LabeledStatement` instances in the tree which * have labels that match our supported contract types. * * Nodes that follow a label are then added to a new temporary `BlockStatement` * which forms the body of the label. * * * @param {Object} ast The AST to process. * @param {Object} options The options for the processor. * @return {Array} The processed AST and an array containing any collected, supported labels. */ function collectLabels (ast, options) { pre: ast && typeof ast === 'object'; ast.type === 'FunctionDeclaration' || ast.type === 'FunctionExpression'; options && typeof options === 'object'; main: var state = { ast: ast, inLabel: false, parent: null, labels: [] }; estraverse.replace(ast, { enter: enterCollect.bind(null, options, state), leave: leaveCollect.bind(null, options, state) }); return [ast, state.labels]; post: Array.isArray(__result); } /** * Invoked when `estraverse` enters a node during the collection phase. * * @param {Object} options The options for the processor. * @param {Object} state The current state of the processor. * @param {Object} node The node being processed. * @param {Object} parent The parent node. * @return {Object} The node, or a special value indicating that this node should be skipped. */ function enterCollect (options, state, node, parent) { pre: options && typeof options === 'object'; state && typeof state === 'object'; main: if (node !== state.ast && (node.type === 'FunctionExpression' || node.type === 'FunctionDeclaration')) { return estraverse.VisitorOption.Skip; } else if (node.type !== 'LabeledStatement' && state.inLabel && parent === state.parent) { return estraverse.VisitorOption.Skip; } else { return node; } post: __result && typeof __result === 'object'; } /** * Invoked when `estraverse` leaves a node during the collection phase. * * @param {Object} options The options for the processor. * @param {Object} state The current state of the processor. * @param {Object} node The node being processed. * @param {Object} parent The parent node. * @return {Object} The node, processed. */ function leaveCollect (options, state, node, parent) { pre: options && typeof options === 'object'; state && typeof state === 'object'; main: if (node.type === 'LabeledStatement' && options.supported[node.label.name]) { state.inLabel = node; if (!node.body || node.body.type !== 'BlockStatement') { node.body = { type: 'BlockStatement', body: node.body ? [node.body] : [] }; } state.parent = parent; state.labels.push(node); } else if (state.labels.length && node === state.ast) { node = processFunctionBody(node, options); } else if (state.inLabel && parent === state.parent) { state.inLabel.body.body.push(node); return { type: 'EmptyStatement', deleteMe: true }; } return node; post: __result && typeof __result === 'object'; } /** * Process a function body, after labels have been collected. * * @param {Object} ast The `FunctionDeclaration` or `FunctionExpression` to process. * @param {Object} options The options for the processor. * @return {Object} The processed node. */ function processFunctionBody (ast, options) { pre: ast && typeof ast === 'object'; ast.type === 'FunctionDeclaration' || ast.type === 'FunctionExpression'; main: return estraverse.replace(ast, { enter: function (node) { if (node.type === 'BlockStatement') { return processBlockStatement(node, ast, options); } } }); post: __result && typeof __result === 'object'; } /** * Process a block statement in a function body, after labels have been collected. * * @param {Object} ast The `BlockStatement` to process. * @param {Object} parent The `FunctionExpression` or `FunctionDeclaration` that contains the block. * @param {Object} options The options for the processor. * @return {Object} The processed node. */ function processBlockStatement (ast, parent, options) { pre: ast && typeof ast === 'object'; ast.type === 'BlockStatement'; parent && typeof parent === 'object'; parent.type === 'FunctionDeclaration' || parent.type === 'FunctionExpression'; options && typeof options === 'object'; typeof options.supported === 'object'; main: var labels = {}; return estraverse.replace(ast, { enter: function (node, parent) { if (node !== ast && (parent !== ast || node.type !== 'LabeledStatement' || !options.supported[node.label.name])) { this.skip(); } else if (node.type === 'LabeledStatement') { labels[node.label.name] = node; } }, leave: function (node) { if (node === ast) { return processLabels(ast, parent, labels, options); } } }); post: __result && typeof __result === 'object'; __result.type === ast.type; } /** * Process a list of labels that are contained within the given `BlockStatement`. * * @param {Object} ast The `BlockStatement` that contains the labels. * @param {Object} parent The `FunctionExpression` or `FunctionDeclaration` that contains the label. * @param {Object} labels The labels to process. * @param {Object} options The options for the processor. * @return {Object} The processed AST. */ function processLabels (ast, parent, labels, options) { pre: ast && typeof ast === 'object'; ast.type === 'BlockStatement'; labels && typeof labels === 'object'; parent && typeof parent === 'object'; parent.type === 'FunctionDeclaration' || parent.type === 'FunctionExpression'; options && typeof options === 'object'; typeof options.supported === 'object'; main: var keys = Object.keys(labels), total = keys.length, key, index, label, i; for (i = 0; i < total; i++) { key = keys[i]; label = labels[key]; index = ast.body.indexOf(label); if (~index) { ast.body.splice.apply(ast.body, [index, 1].concat(processLabel(label, labels, parent, options))); } } return ast; post: __result && typeof __result === 'object'; } /** * Process a magic label. * * @param {Object} ast The `LabeledStatement` to process. * @param {Object} labels The map of label names to labels. * @param {Object} parent The `FunctionExpression` or `FunctionDeclaration` that contains the label. * @param {Object} options The options for the processor. * @return {Object[]} The nodes that should be injected in place of the `LabeledStatement`. */ function processLabel (ast, labels, parent, options) { pre: ast.type === 'LabeledStatement'; ast.body.type === 'BlockStatement'; parent && typeof parent === 'object'; parent.type === 'FunctionDeclaration' || parent.type === 'FunctionExpression'; options && typeof options === 'object'; typeof options.supported === 'object'; main: if (typeof options.supported[ast.label.name] === 'function') { return options.supported[ast.label.name](ast, options, labels, parent); } else { return ast.body.body; } post: Array.isArray(__result); } /** * Remove deletable nodes from the given AST. * * @param {Object|Object[]} ast The node, or list of nodes to cleanup. * @return {Object|Object[]} The cleaned up node(s). */ function cleanup (ast) { if (!ast || typeof ast !== 'object') { return ast; } else if (Array.isArray(ast)) { return ast .filter(function (child) { return !(child && child.deleteMe); }) .map(cleanup); } var filtered = {}, keys = Object.keys(ast), total = keys.length, key, value, i; for (i = 0; i < total; i++) { key = keys[i]; value = ast[key]; if (value && typeof value === 'object') { value = cleanup(value); } filtered[key] = value; } return filtered; }
const config = require('../config') const utils = require('./utils') const path = require('path') const webpack = require('webpack') const webpackConfig = process.env.BROWSER !== 'ie8' ? require('./webpack.dev.conf') : require('./webpack.dev.ie8.conf') const express = require('express') const opn = require('opn') const debug = require('debug')('app:server') const bodyParser = require('body-parser') debug('设置server启动配置') const port = process.env.PORT || config.dev.port const autoOpenBrowser = !!config.dev.autoOpenBrowser const app = express() app.use(bodyParser.urlencoded({ extended: false })) debug('编译webpack配置') let compiler = webpack(webpackConfig) debug('webpack编译完成') debug('将编译流通过webpack-dev-middleware') let devMiddleware = require('webpack-dev-middleware')(compiler, { publicPath: webpackConfig.output.publicPath, quiet: false, noInfo: false, lazy: false, stats: { chunks: false, chunkModules: false, colors: true } }) debug('将编译流通过webpack-hot-middleware') let hotMiddleware = require('webpack-hot-middleware')(compiler, { log: () => {} }) debug('添加html修改自动刷新钩子') compiler.plugin('compilation', (compilation) => { compilation.plugin('html-webpack-plugin-after-emit', (data, cb) => { hotMiddleware.publish({ action: 'reload' }) cb() }) }) debug('设置静态文件托管目录') let staticPath = path.posix.join(config.dev.assetsPublicPath, config.dev.assetsSubDirectory) app.use(staticPath, express.static('public')) debug('设置代理信息') require('./dev-proxy')(app) debug('添加history-fallback中间件') app.use(require('connect-history-api-fallback')()) debug('添加webpack-dev-middleware中间件') app.use(devMiddleware) if (process.env.BROWSER !== 'ie8') { debug('添加webpack-hot-middleware中间件') app.use(hotMiddleware) } let uri = 'http://localhost:' + port debug('> Starting dev server...') debug('设置webpack-dev-middleware中间件编译后的回调') devMiddleware.waitUntilValid(() => { debug('> Listening at ' + uri + '\n') if (autoOpenBrowser && process.env.NODE_ENV !== 'testing') { opn(uri) } }) debug(`server开始监听端口${port}`) let server = app.listen(port)
version https://git-lfs.github.com/spec/v1 oid sha256:a4970e0ff5d9717322b4b1ff097e4972c08256d6ce3e440379cc11df773c460a size 138
/* global describe, it */ /* eslint-disable no-unused-expressions */ describe('The Coordinate class', () => { const { expect } = window.chai; const { Coordinate } = window.OdoHelpers; it('can initialize', () => { let c = new Coordinate(); expect(c.x).to.equal(0); expect(c.y).to.equal(0); c = new Coordinate(null, 5); expect(c.x).to.equal(null); expect(c.y).to.equal(5); c = new Coordinate(undefined, null); expect(c.x).to.equal(0); expect(c.y).to.equal(null); c = new Coordinate(4, 3); expect(c.x).to.equal(4); expect(c.y).to.equal(3); c = new Coordinate(4); expect(c.x).to.equal(4); expect(c.y).to.equal(0); }); it('can be compared', () => { const a = new Coordinate(1, 1); const b = new Coordinate(1, 1); const c = new Coordinate(2, 2); expect(Coordinate.equals(a, b)).to.be.true; expect(Coordinate.equals(b, a)).to.be.true; expect(Coordinate.equals(a, c)).to.be.false; expect(Coordinate.equals(b, c)).to.be.false; expect(Coordinate.equals('foo', 'foo')).to.be.true; expect(Coordinate.equals(null, a)).to.be.false; expect(Coordinate.equals(undefined, a)).to.be.false; }); it('can get the distance between two points', () => { const a = new Coordinate(0, 0); const b = new Coordinate(3, 4); expect(Coordinate.distance(a, b)).to.equal(5); }); it('can calculate the difference between two points', () => { const a = new Coordinate(0, 0); const b = new Coordinate(3, 4); const ret = Coordinate.difference(a, b); expect(Coordinate.equals(ret, new Coordinate(-3, -4))).to.be.true; }); it('can calculate the sum between two points', () => { const a = new Coordinate(1, 1); const b = new Coordinate(3, 4); const ret = Coordinate.sum(a, b); expect(Coordinate.equals(ret, new Coordinate(4, 5))).to.be.true; }); it('can calculate the product between two points', () => { const a = new Coordinate(0, 0); const b = new Coordinate(3, 4); const ret = Coordinate.product(a, b); expect(Coordinate.equals(ret, new Coordinate(0, 0))).to.be.true; }); it('can calculate the quotient between two points', () => { const a = new Coordinate(100, 0); const b = new Coordinate(10, 20); const ret = Coordinate.quotient(a, b); expect(Coordinate.equals(ret, new Coordinate(10, 0))).to.be.true; }); it('can scale a cooridinate without changing the original', () => { const a = new Coordinate(4, 4); let ret = Coordinate.scale(a, 2); expect(Coordinate.equals(ret, new Coordinate(8, 8))).to.be.true; expect(Coordinate.equals(a, new Coordinate(4, 4))).to.be.true; ret = Coordinate.scale(a, 2, 4); expect(Coordinate.equals(ret, new Coordinate(8, 16))).to.be.true; expect(Coordinate.equals(a, new Coordinate(4, 4))).to.be.true; }); it('can clone itself', () => { const a = new Coordinate(4, 4); const clone = a.clone(); expect(Coordinate.equals(clone, a)).to.be.true; clone.x = 10; clone.y = -2; expect(a.x).to.equal(4); expect(a.y).to.equal(4); }); it('can scale itself', () => { const a = new Coordinate(4, 4); a.scale(0.5); expect(a.x).to.equal(2); expect(a.y).to.equal(2); a.scale(2, 4); expect(a.x).to.equal(4); expect(a.y).to.equal(8); }); it('can translate itself', () => { const a = new Coordinate(4, 4); a.translate(10, 5); expect(a.x).to.equal(14); expect(a.y).to.equal(9); a.translate(new Coordinate(-10, -5)); expect(a.x).to.equal(4); expect(a.y).to.equal(4); }); });
var Tokenizer = require('./../tokenizer'), englishTokenizer = new Tokenizer(), TfIdf = require('./../tfidf'); describe('The Tf-Idf calculator', function() { it('should add documents', function() { var tfidfCalculator = new TfIdf(englishTokenizer); tfidfCalculator.addDocument('The quick brown brown fox', 'A'); expect(tfidfCalculator.documents.length).toEqual(1); var document = tfidfCalculator.documents[0]; expect(document.group).toEqual('A'); expect(document.tfs.size).toEqual(4); expect(tfidfCalculator.documentFrequencies.size).toEqual(4); }); it('should calculate idfs', function() { var tfidfCalculator = new TfIdf(englishTokenizer); tfidfCalculator.addDocument('this is a sample', 'A'); tfidfCalculator.addDocument('this is another example', 'A'); tfidfCalculator.calculateTfIdfs(); var tfidfs = tfidfCalculator.getTfIdfsForGroup('A'); expect(tfidfs.length).toEqual(2); expect(tfidfs[0].get('THIS')).toEqual(0); expect(tfidfs[0].get('IS')).toEqual(0); expect(tfidfs[0].get('A')).toBeCloseTo(Math.log(2), 2); }); it('should calculate the tfidf for a document that isn\'t in the set', function() { var tfidfCalculator = new TfIdf(englishTokenizer); tfidfCalculator.addDocument('this is a sample', 'A'); tfidfCalculator.addDocument('this is another example', 'A'); tfidfCalculator.calculateTfIdfs(); var tfidfs = tfidfCalculator.getPotentialTfIdfs('this is a third sample'); expect(tfidfs.get('THIS')).toEqual(0); expect(tfidfs.get('IS')).toEqual(0); expect(tfidfs.get('A')).toBeCloseTo(Math.log(2), 2); expect(tfidfs.get('THIRD')).toEqual(0); expect(tfidfs.get('SAMPLE')).toBeCloseTo(Math.log(2), 2); }); it('should save and reload its state', function() { var tfidfCalculator = new TfIdf(englishTokenizer); tfidfCalculator.addDocument('this is a sample', 'A'); tfidfCalculator.addDocument('this is another example', 'A'); tfidfCalculator.calculateTfIdfs(); var json = JSON.stringify(tfidfCalculator); tfidfCalculator = TfIdf.load(JSON.parse(json)); var tfidfs = tfidfCalculator.getTfIdfsForGroup('A'); expect(tfidfs.length).toEqual(2); expect(tfidfs[0].get('THIS')).toEqual(0); expect(tfidfs[0].get('IS')).toEqual(0); expect(tfidfs[0].get('A')).toBeCloseTo(Math.log(2), 2); }); });
'use strict'; import plugins from 'gulp-load-plugins'; import yargs from 'yargs'; import browser from 'browser-sync'; // import nodemon from 'gulp-nodemon'; import gulp from 'gulp'; import yaml from 'js-yaml'; import rimraf from 'rimraf'; import fs from 'fs'; import webpackStream from 'webpack-stream'; import webpack2 from 'webpack'; import named from 'vinyl-named'; import ext from 'gulp-ext-replace'; import octophant from 'octophant'; // use this for console commands const exec = require('child_process').exec; // Load all Gulp plugins into one variable const $ = plugins(); // Check for --production flag const PRODUCTION = !!(yargs.argv.production); // var argv = require('yargs').argv; // var isProduction = !!(argv.production); // Load settings from settings.yml const { COMPATIBILITY, PORT, UNCSS_OPTIONS, PATHS } = loadConfig(); function loadConfig() { let ymlFile = fs.readFileSync('config.yml', 'utf8'); return yaml.load(ymlFile); } // Build the "dist" folder by running all of the below tasks gulp.task('build', gulp.series( // clean, gulp.parallel( sass, // javascript, // images, // copy ), blocks )); // Delete the "dist" folder // This happens every time a build starts function clean(done) { rimraf(PATHS.dist, done); } // Copy files out of the src/partials/building-blocks folder function blocks(cb) { return gulp.src('src/partials/building-blocks/*') .pipe(ext('.handlebars')) .pipe(gulp.dest('views/partials/blocks')); cb(); } // Copy files out of the assets folder // This task skips over the "img", "js", and "scss" folders, which are parsed separately function copy() { return gulp.src(PATHS.assets) .pipe(gulp.dest(PATHS.dist + '/assets')); } // Load updated HTML templates and partials into Panini function resetPages(done) { panini.refresh(); done(); } // Generate a style guide from the Markdown content and HTML template in styleguide/ // function styleGuide(done) { // sherpa('src/styleguide/index.md', { }, done); // } // Compile Sass into CSS // In production, the CSS is compressed // gulp.task('sass', sass, watch) gulp.task('sass', gulp.series(sass, watch) ); function sass() { return gulp.src('src/assets/scss/app.scss') .pipe($.sourcemaps.init()) .pipe($.sass({ includePaths: PATHS.sass }) .on('error', $.sass.logError)) .pipe($.autoprefixer({ browsers: COMPATIBILITY })) // .pipe( // $.pleeease({ // sass: true, // autoprefixer: COMPATIBILITY, // // includePaths: PATHS.sass, // sourcemaps: PATHS.sourcemaps, // mqpacker: true, // // rem: false, // pseudoElements: false, // Converts ::before to :before // opacity: true, // Filter for IE 8 // minifier: isProduction ? true : false, // }) // ) // Comment in the pipe below to run UnCSS in production //.pipe($.if(PRODUCTION, $.uncss(UNCSS_OPTIONS))) .pipe($.if(PRODUCTION, $.cleanCss({ compatibility: 'ie9' }))) .pipe($.if(!PRODUCTION, $.sourcemaps.write())) .pipe(gulp.dest(PATHS.dist + '/assets/css')) .pipe(browser.reload({ stream: true })); } let webpackConfig = { rules: [ { test: /.js$/, use: [ { loader: 'babel-loader' } ] } ] } // Combine JavaScript into one file // In production, the file is minified function javascript() { return gulp.src(PATHS.entries) .pipe(named()) .pipe($.sourcemaps.init()) .pipe(webpackStream({module: webpackConfig}, webpack2)) .pipe($.if(PRODUCTION, $.uglify() .on('error', e => { console.log(e); }) )) .pipe($.if(!PRODUCTION, $.sourcemaps.write())) .pipe(gulp.dest(PATHS.dist + '/assets/js')); } // Copy images to the "dist" folder // In production, the images are compressed function images() { return gulp.src('src/assets/img/**/*') .pipe($.if(PRODUCTION, $.imagemin({ progressive: true }))) .pipe(gulp.dest(PATHS.dist + '/assets/img')); } gulp.task('theme', scssTheme) // Collects variables from SCSS files and ameks a settings file. // Aka makes your (s)css maintainable function scssTheme(cb) { var options = { title: 'Building-Blocks Settings', output: './src/assets/scss/_block-settings.scss', groups: { 'app-dashboard-layout': 'The Dashboard', 'dashboard-table': 'Dashboard Table', 'contact-panel': 'Contact Panel', 'login-box': 'Login', '_multilevel-offcanvas-menu':'Offcanvas-Menu', 'topbar-responsive': 'Topbar', 'marketing-site-three-up': 'Marketing', 'todo-list-card': 'Todo List', 'status-update-input-box':'Status Input', }, sort: [ 'Dashboard', 'Offcanvas-Menu', 'Topbar', 'Login & Sign up', 'Contact Panel', 'Status Input', 'Todo List', 'Marketing', ], ///// // imports (Array): A series of strings which represent Sass libraries to import. // These libraries are added as @import statements before the first section. ///// // imports: ['util/util'], // _foundationShim: true } //parser(files [, options, cb]) octophant('./src/assets/scss/components/building-blocks/', options, cb); } // Start a server with BrowserSync to preview the site in // function nodemon() { // nodemon({ // script: 'server.js', // ext: 'js html', // env: { 'NODE_ENV': 'development' } // }) // } function server(done) { browser.init({ server: PATHS.dist, port: PORT }); done(); } // Reload the browser with BrowserSync function reload(done) { browser.reload(); done(); } // Watch for changes to static assets, pages, Sass, and JavaScript function watch() { gulp.watch(PATHS.assets, copy); gulp.watch('src/assets/scss/**/*.scss').on('all', sass); gulp.watch('src/assets/js/**/*.js').on('all', gulp.series(javascript, browser.reload)); gulp.watch('src/assets/img/**/*').on('all', gulp.series(images, browser.reload)); // watch for when new building blocks are installed and move them over to the server gulp.watch('src/partials/building-blocks/**').on('all', gulp.series(blocks, browser.reload)); } // Build the site, run the server, and watch for file changes gulp.task('default', gulp.series('build', // server, watch) );
/* Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang( 'templates', 'ko', { button: '템플릿', emptyListMsg: '(템플릿이 없습니다)', insertOption: '현재 내용 바꾸기', options: '템플릿 옵션', selectPromptMsg: '에디터에서 사용할 템플릿을 선택하십시오', title: '내용 템플릿' } );