code
stringlengths
2
1.05M
repo_name
stringlengths
5
114
path
stringlengths
4
991
language
stringclasses
1 value
license
stringclasses
15 values
size
int32
2
1.05M
'use strict' exports.Utils = require('./utils') exports.Schemas = require('./schemas') exports.Validator = require('./validator')
CaliStyle/trailpack-treefrog
lib/index.js
JavaScript
mit
131
// @flow import type { Action } from "../actions/types"; import type { UserState } from "../types"; const initialState: UserState = { fetching: false, fetched: false, users: [], error: null }; export default function users(state: UserState = initialState, action: Action) { switch (action.type) { case "FETCH_USERS_PENDING": return { ...state, fetching: true }; case "FETCH_USERS_FULFILLED": return { ...state, fetching: false, fetched: true, users: action.payload.data, error: null }; case "FETCH_USERS_REJECTED": return { ...state, fetching: false, error: action.payload }; default: return state; } }
celinaberg/BitFit
client/src/reducers/users.js
JavaScript
mit
756
var ps, acorn; function start(){ ps = new PointStream(); ps.setup(document.getElementById('canvas')); ps.pointSize(5); ps.onKeyDown = function(){ ps.println(window.key); }; ps.onRender = function(){ ps.translate(0, 0, -25); ps.clear(); ps.render(acorn); }; acorn = ps.load("../../clouds/acorn.asc"); }
asalga/XB-PointStream
tests/leakedKey/acorn.js
JavaScript
mit
335
$identify("org/mathdox/formulaeditor/OrbeonForms.js"); $require("org/mathdox/formulaeditor/FormulaEditor.js"); var ORBEON; $main(function(){ if (ORBEON && ORBEON.xforms && ORBEON.xforms.Document) { /** * Extend the save function of the formula editor to use the orbeon update * mechanism, see also: * http://www.orbeon.com/ops/doc/reference-xforms-2#xforms-javascript */ org.mathdox.formulaeditor.FormulaEditor = $extend(org.mathdox.formulaeditor.FormulaEditor, { save : function() { // call the parent function arguments.callee.parent.save.apply(this, arguments); // let orbeon know about the change of textarea content var textarea = this.textarea; if (textarea.id) { ORBEON.xforms.Document.setValue(textarea.id, textarea.value); } } }); /** * Override Orbeon's xformsHandleResponse method so that it initializes any * canvases that might have been added by the xforms engine. */ /* prevent an error if the xformsHandleResponse doesn't exist */ var xformsHandleResponse; var oldXformsHandleResponse; var newXformsHandleResponse; var ancientOrbeon; if (xformsHandleResponse) { oldXformsHandleResponse = xformsHandleResponse; } else if (ORBEON.xforms.Server && ORBEON.xforms.Server.handleResponse) { oldXformsHandleResponse = ORBEON.xforms.Server.handleResponse; } else if (ORBEON.xforms.Server && ORBEON.xforms.Server.handleResponseDom) { oldXformsHandleResponse = ORBEON.xforms.Server.handleResponseDom; } else if (ORBEON.xforms.server && ORBEON.xforms.server.AjaxServer && ORBEON.xforms.server.AjaxServer.handleResponseDom) { // orbeon 3.9 oldXformsHandleResponse = ORBEON.xforms.server.AjaxServer.handleResponseDom; } else { if (org.mathdox.formulaeditor.options.ancientOrbeon !== undefined && org.mathdox.formulaeditor.options.ancientOrbeon == true) { ancientOrbeon = true; } else { ancientOrbeon = false; alert("ERROR: detected orbeon, but could not add response handler"); } } newXformsHandleResponse = function(request) { // call the overridden method if (ancientOrbeon != true ) { oldXformsHandleResponse.apply(this, arguments); } // go through all canvases in the document var canvases = document.getElementsByTagName("canvas"); for (var i=0; i<canvases.length; i++) { // initialize a FormulaEditor for each canvas var canvas = canvases[i]; if (canvas.nextSibling) { if (canvas.nextSibling.tagName.toLowerCase() == "textarea") { var FormulaEditor = org.mathdox.formulaeditor.FormulaEditor; var editor = new FormulaEditor(canvas.nextSibling, canvas); // (re-)load the contents of the textarea into the editor editor.load(); } } } }; if (xformsHandleResponse) { xformsHandleResponse = newXformsHandleResponse; } else if (ORBEON.xforms.Server && ORBEON.xforms.Server.handleResponse) { ORBEON.xforms.Server.handleResponse = newXformsHandleResponse; } else if (ORBEON.xforms.Server && ORBEON.xforms.Server.handleResponseDom) { ORBEON.xforms.Server.handleResponseDom = newXformsHandleResponse; } else if (ORBEON.xforms.server && ORBEON.xforms.server.AjaxServer && ORBEON.xforms.server.AjaxServer.handleResponseDom) { ORBEON.xforms.server.AjaxServer.handleResponseDom = newXformsHandleResponse; } } });
UTMQ/utmq-core
app/scripts/editor/org/mathdox/formulaeditor/OrbeonForms.js
JavaScript
mit
3,608
function isEmpty(value) { return angular.isUndefined(value) || value === '' || value === null || value !== value; } angular.module('Aggie') .directive('ngMin', function () { return { restrict: 'A', require: 'ngModel', link: function (scope, elem, attr, ctrl) { scope.$watch(attr.ngMin, function () { ctrl.$setViewValue(ctrl.$viewValue); }); var minValidator = function (value) { var min = scope.$eval(attr.ngMin) || 0; if (!isEmpty(value) && value < min) { ctrl.$setValidity('ngMin', false); return undefined; } else { ctrl.$setValidity('ngMin', true); return value; } }; ctrl.$parsers.push(minValidator); ctrl.$formatters.push(minValidator); } }; }) .directive('ngMax', function () { return { restrict: 'A', require: 'ngModel', link: function (scope, elem, attr, ctrl) { scope.$watch(attr.ngMax, function () { ctrl.$setViewValue(ctrl.$viewValue); }); var maxValidator = function (value) { var max = scope.$eval(attr.ngMax) || Infinity; if (!isEmpty(value) && value > max) { ctrl.$setValidity('ngMax', false); return undefined; } else { ctrl.$setValidity('ngMax', true); return value; } }; ctrl.$parsers.push(maxValidator); ctrl.$formatters.push(maxValidator); } }; });
VIP-eDemocracy/aggie
public/angular/js/directives/ng-minmax.js
JavaScript
mit
1,450
require( "../setup" ); var packageResource = require( "../../resource/package/resource.js" ); describe( "Package Resource", function() { var server = { checkForNew: _.noop }; describe( "when getting new package callback", function() { describe( "with matching package", function() { var config, serverMock, result; before( function() { config = { package: { project: "imatch" } }; serverMock = sinon.mock( server ); serverMock.expects( "checkForNew" ).once(); var envelope = { data: { project: "imatch" } }; var handler = packageResource( {}, config, server ); result = handler.actions.new.handle( envelope ); } ); it( "should call checkForNew", function() { serverMock.verify(); } ); it( "should result in a status 200", function() { result.should.eql( { status: 200 } ); } ); } ); describe( "with mis-matched package", function() { var config, serverMock, result; before( function() { config = { package: { project: "lol-aint-no-such" } }; serverMock = sinon.mock( server ); serverMock.expects( "checkForNew" ).never(); var envelope = { data: { project: "imatch" } }; var handler = packageResource( {}, config, server ); result = handler.actions.new.handle( envelope ); } ); it( "should not call checkForNew", function() { serverMock.verify(); } ); it( "should result in a status 200", function() { result.should.eql( { status: 200 } ); } ); } ); } ); } );
LeanKit-Labs/nonstop-host
spec/behavior/packageResource.spec.js
JavaScript
mit
1,522
/** * Module dependencies. */ var express = require('express'); var routes = require('./routes'); var user = require('./routes/user'); var http = require('http'); var path = require('path'); var app = express(); // all environments app.set('port', process.env.PORT || 3000); app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); app.use(express.favicon()); app.use(express.logger('dev')); app.use(express.json()); app.use(express.urlencoded()); app.use(express.methodOverride()); app.use(app.router); app.use(express.static(path.join(__dirname, 'public'))); // development only if ('development' == app.get('env')) { app.use(express.errorHandler()); } app.get('/', routes.index); app.get('/users', user.list); var server = http.createServer(app); var chatServer = require('./chat_server'); chatServer(server); server.listen(app.get('port'), function () { console.log('Express server listening on port ' + app.get('port')); });
nicolasmccurdy/ochat
app.js
JavaScript
mit
969
var resetCollection = function(collection) { collection.find().fetch().forEach(function(obj) { collection.remove({_id: obj._id}); }); }; describe('CapabilityManager', function() { var capabilityManager; beforeAll(function() { capabilityManager = new CapabilityManager(); }); it('should set initial capabilities', function() { var allCaps = capabilityManager.allCapabilities; expect(allCaps.length).toEqual(3); }); });
vikramthyagarajan/meteor-access-control
tests/server/capability-unit.js
JavaScript
mit
436
import _size from './_size'; export default class MapObject { constructor() { this._data = new Map(); } get size() { return _size(); } }
augesd/wgm
src/lib/classes/map-object/constructor.js
JavaScript
mit
149
const express = require('express'); const app = express(); app.use(express.static('./src/')) app.listen(8000, () => { console.log('The server is running on the http://localhost:8000/......'); });
maybeShuo/css-learning
index.js
JavaScript
mit
202
/** @jsx html */ import { html } from '../../../snabbdom-jsx'; import Type from 'union-type'; import { bind, pipe, isBoolean, targetValue, targetChecked } from './helpers'; import { KEY_ENTER } from './constants'; // model : {id: Number, title: String, done: Boolean, editing: Boolean, editingValue: String } const Action = Type({ SetTitle : [String], Toggle : [isBoolean], StartEdit : [], CommitEdit : [String], CancelEdit : [] }); function onInput(handler, e) { if(e.keyCode === KEY_ENTER) handler(Action.CommitEdit(e.target.value)) } const view = ({model, handler, onRemove}) => <li key={model.id} class-completed={!!model.done && !model.editing} class-editing={model.editing}> <div selector=".view"> <input selector=".toggle" type="checkbox" checked={!!model.done} on-click={ pipe(targetChecked, Action.Toggle, handler) } /> <label on-dblclick={ bind(handler, Action.StartEdit()) }>{model.title}</label> <button selector=".destroy" on-click={onRemove} /> </div> <input selector=".edit" value={model.title} on-blur={ bind(handler, Action.CancelEdit()) } on-keydown={ bind(onInput, handler) } /> </li> function init(id, title) { return { id, title, done: false, editing: false, editingValue: '' }; } function update(task, action) { return Action.case({ Toggle : done => ({...task, done}), StartEdit : () => ({...task, editing: true, editingValue: task.title}), CommitEdit : title => ({...task, title, editing: false, editingValue: ''}), CancelEdit : title => ({...task, editing: false, editingValue: ''}) }, action); } export default { view, init, update, Action }
dschalk/fun-with-monads
monads/node_modules/snabbdom-jsx/examples/todomvc/js/task.js
JavaScript
mit
1,890
import Route from '@ember/routing/route'; export default Route.extend({ redirect() { this._super(...arguments); this.transitionTo('examples.single-date-picker'); } });
shak/ember-cli-kalendae
tests/dummy/app/routes/application.js
JavaScript
mit
182
'use strict'; var fs = require('fs'); var demand = require('must'); var sinon = require('sinon'); var WebHDFS = require('../lib/webhdfs'); var WebHDFSProxy = require('webhdfs-proxy'); var WebHDFSProxyMemoryStorage = require('webhdfs-proxy-memory'); describe('WebHDFS', function () { var path = '/files/' + Math.random(); var hdfs = WebHDFS.createClient({ user: process.env.USER, port: 45000 }); this.timeout(10000); before(function (done) { var opts = { path: '/webhdfs/v1', http: { port: 45000 } }; WebHDFSProxy.createServer(opts, WebHDFSProxyMemoryStorage, done); }); it('should make a directory', function (done) { hdfs.mkdir(path, function (err) { demand(err).be.null(); done(); }); }); it('should create and write data to a file', function (done) { hdfs.writeFile(path + '/file-1', 'random data', function (err) { demand(err).be.null(); done(); }); }); it('should append content to an existing file', function (done) { hdfs.appendFile(path + '/file-1', 'more random data', function (err) { demand(err).be.null(); done(); }); }); it('should create and stream data to a file', function (done) { var localFileStream = fs.createReadStream(__filename); var remoteFileStream = hdfs.createWriteStream(path + '/file-2'); var spy = sinon.spy(); localFileStream.pipe(remoteFileStream); remoteFileStream.on('error', spy); remoteFileStream.on('finish', function () { demand(spy.called).be.falsy(); done(); }); }); it('should append stream content to an existing file', function (done) { var localFileStream = fs.createReadStream(__filename); var remoteFileStream = hdfs.createWriteStream(path + '/file-2', true); var spy = sinon.spy(); localFileStream.pipe(remoteFileStream); remoteFileStream.on('error', spy); remoteFileStream.on('finish', function () { demand(spy.called).be.falsy(); done(); }); }); it('should open and read a file stream', function (done) { var remoteFileStream = hdfs.createReadStream(path + '/file-1'); var spy = sinon.spy(); var data = []; remoteFileStream.on('error', spy); remoteFileStream.on('data', function onData (chunk) { data.push(chunk); }); remoteFileStream.on('finish', function () { demand(spy.called).be.falsy(); demand(Buffer.concat(data).toString()).be.equal('random datamore random data'); done(); }); }); it('should open and read a file', function (done) { hdfs.readFile(path + '/file-1', function (err, data) { demand(err).be.null(); demand(data.toString()).be.equal('random datamore random data'); done(); }); }); it('should list directory status', function (done) { hdfs.readdir(path, function (err, files) { demand(err).be.null(); demand(files).have.length(2); demand(files[0].pathSuffix).to.eql('file-1'); demand(files[1].pathSuffix).to.eql('file-2'); demand(files[0].type).to.eql('FILE'); demand(files[1].type).to.eql('FILE'); done(); }); }); it('should change file permissions', function (done) { hdfs.chmod(path, '0777', function (err) { demand(err).be.null(); done(); }); }); it('should change file owner', function (done) { hdfs.chown(path, process.env.USER, 'supergroup', function (err) { demand(err).be.null(); done(); }); }); it('should rename file', function (done) { hdfs.rename(path+ '/file-2', path + '/bigfile', function (err) { demand(err).be.null(); done(); }); }); it('should check file existence', function (done) { hdfs.exists(path + '/bigfile', function (exists) { demand(exists).be.true(); done(); }); }); it('should stat file', function (done) { hdfs.stat(path + '/bigfile', function (err, stats) { demand(err).be.null(); demand(stats).be.object(); demand(stats.type).to.eql('FILE'); demand(stats.owner).to.eql(process.env.USER); done(); }); }); it('should create symbolic link', function (done) { hdfs.symlink(path+ '/bigfile', path + '/biggerfile', function (err) { // Pass if server doesn't support symlinks if (err && err.message.indexOf('Symlinks not supported') !== -1) { done(); } else { demand(err).be.null(); done(); } }); }); it('should delete file', function (done) { hdfs.rmdir(path+ '/file-1', function (err) { demand(err).be.null(); done(); }); }); it('should delete directory recursively', function (done) { hdfs.rmdir(path, true, function (err) { demand(err).be.null(); done(); }); }); it('should support optional opts', function (done) { var myOpts = { "user.name": "testuser" } hdfs.writeFile(path + '/file-1', 'random data', myOpts, function (err) { demand(err).be.null(); done(); }); }); }); describe('WebHDFS with requestParams', function() { var path = '/files/' + Math.random(); var hdfs = WebHDFS.createClient({ user: process.env.USER, port: 45001 }, { headers: { 'X-My-Custom-Header': 'Kerberos' } }); this.timeout(10000); before(function (done) { var opts = { path: '/webhdfs/v1', http: { port: 45001 } }; WebHDFSProxy.createServer(opts, WebHDFSProxyMemoryStorage, done); }); it('should override request() options', function (done) { var localFileStream = fs.createReadStream(__filename); var remoteFileStream = hdfs.createWriteStream(path + '/file-2'); var spy = sinon.spy(); localFileStream.pipe(remoteFileStream); remoteFileStream.on('error', spy); remoteFileStream.on('response', function(response) { var customHeader = response.req.getHeader('X-My-Custom-Header'); demand(customHeader).equal('Kerberos'); demand(spy.called).be.falsy(); done(); }) }); it('should pass requestParams to _sendRequest', function (done) { var req = hdfs.readdir('/'); req.on('response', function(response) { var customHeader = response.req.getHeader('X-My-Custom-Header'); demand(customHeader).equal('Kerberos'); done(); }); }); it('should not override explicit opts with _sendRequest', function (done) { var mostSpecificParams = { headers: { 'X-My-Custom-Header': 'Bear' } } var endpoint = hdfs._getOperationEndpoint('liststatus', '/file-2'); hdfs._sendRequest('GET', endpoint, mostSpecificParams, function(err, response, body) { var customHeader = response.req.getHeader('X-My-Custom-Header'); demand(customHeader).equal('Bear'); done(err) }); }); });
PavelVanecek/webhdfs
test/webhdfs.js
JavaScript
mit
6,845
/* */ (function(process) { var serial = require('../serial'); module.exports = ReadableSerial; function ReadableSerial(list, iterator, callback) { if (!(this instanceof ReadableSerial)) { return new ReadableSerial(list, iterator, callback); } ReadableSerial.super_.call(this, {objectMode: true}); this._start(serial, list, iterator, callback); } })(require('process'));
elingan/riotjs-app-starter
src/jspm_packages/npm/asynckit@0.4.0/lib/readable_serial.js
JavaScript
mit
401
/** * Created by li_xiaoliang on 2015/3/29. */ define(['marked','highlight'],function(marked,highlight){ return{ parsemarkdown:function(md){ var pattern=/~.*?~/g; var matches=pattern.exec(md); while(matches!=null){ var match=matches[0]; console.log(match); var bematch=match.replace(match.charAt(0),"<div>").replace(match.substr(-1),"</div>") md=md.replace(match,bematch); matches=pattern.exec(md); } marked.setOptions({ highlight: function (code) { return highlight.highlightAuto(code).value; } }); return marked(md) } } })
LelesBox/blog
public/js/service/parsemarkdownService.js
JavaScript
mit
766
define(['exports', 'aurelia-templating'], function (exports, _aureliaTemplating) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.VirtualRepeatNext = undefined; var _dec, _class; var VirtualRepeatNext = exports.VirtualRepeatNext = (_dec = (0, _aureliaTemplating.customAttribute)('virtual-repeat-next'), _dec(_class = function () { function VirtualRepeatNext() { } VirtualRepeatNext.prototype.attached = function attached() {}; VirtualRepeatNext.prototype.bind = function bind(bindingContext, overrideContext) { this.scope = { bindingContext: bindingContext, overrideContext: overrideContext }; }; return VirtualRepeatNext; }()) || _class); });
AStoker/ui-virtualization
dist/amd/virtual-repeat-next.js
JavaScript
mit
746
import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; export default createSvgIcon( /*#__PURE__*/_jsx("path", { d: "M8 10H5V7H3v3H0v2h3v3h2v-3h3v-2zm10 1c1.66 0 2.99-1.34 2.99-3S19.66 5 18 5c-.32 0-.63.05-.91.14.57.81.9 1.79.9 2.86s-.34 2.04-.9 2.86c.28.09.59.14.91.14zm-5 0c1.66 0 2.99-1.34 2.99-3S14.66 5 13 5s-3 1.34-3 3 1.34 3 3 3zm6.62 2.16c.83.73 1.38 1.66 1.38 2.84v2h3v-2c0-1.54-2.37-2.49-4.38-2.84zM13 13c-2 0-6 1-6 3v2h12v-2c0-2-4-3-6-3z" }), 'GroupAddSharp');
mbrookes/material-ui
packages/material-ui-icons/lib/esm/GroupAddSharp.js
JavaScript
mit
518
var extend = require('extend'); var plivo = require('plivo'); var crypto = require('crypto') var phone = require('phone'); var TelcomPlivoClient = module.exports = function(opts){ if (!(this instanceof TelcomPlivoClient)) return new TelcomPlivoClient(options); this.options = {}; extend(this.options,opts); this._client = plivo.RestAPI({ authId: this.options.sid, authToken: this.options.token }); }; TelcomPlivoClient.prototype.validateRequest = function(req,callback){ if(req.header('X-Plivo-Signature') === undefined) return callback('missing requrired header.') var params = req.body; if(req.method === 'GET'){ params = req.query; } var toSign = req._telcomRequestUrlNoQuery; var expectedSignature = create_signature(toSign, params,this.options.token); if(req.header('X-Plivo-Signature') === expectedSignature) callback(); else callback('signature does not match'); } TelcomPlivoClient.prototype.sms = function(obj,callback){ var plivoMesg = { src : phone(obj.from), dst : phone(obj.to), text : obj.body }; /* { api_id: 'xxxxxxxxx-1f9d-11e3-b44b-22000ac53995', message: 'message(s) queued', message_uuid: [ 'xxxxxxxx-1f9d-11e3-b1d3-123141013a24' ] } */ this._client.send_message(plivoMesg, function(err, ret) { if(err === 202){ err = undefined; } if(!ret) ret = {}; callback(err,ret.message_uuid[0],ret.message,ret); }); }; /* { To: '15559633214', Type: 'sms', MessageUUID: 'xxxxxxx-2465-11e3-985d-0025907b94de', From: '15557894561', Text: 'Vg\n' } { to : '', from : '', body : '', messageId : '', } */ TelcomPlivoClient.prototype._convertSmsRequest = function(params){ return { to : phone(params['To']), from : phone(params['From']), body : params['Text'], messageId : params['MessageUUID'], _clientRequest : params }; } // For verifying the plivo server signature // By Jon Keating - https://github.com/mathrawka/plivo-node function create_signature(url, params,token) { var toSign = url; Object.keys(params).sort().forEach(function(key) { toSign += key + params[key]; }); var signature = crypto .createHmac('sha1',token) .update(toSign) .digest('base64'); return signature; };
AdamMagaluk/telcom
lib/providers/plivo.js
JavaScript
mit
2,286
import GameEvent from './GameEvent'; import Creature from '../entities/creatures/Creature'; import Ability from '../abilities/Ability'; import Tile from '../tiles/Tile'; export default class AbilityEvent extends GameEvent { /** * @class AbilityEvent * @description Fired whenever a creature attacks */ constructor(dungeon, creature, ability, tile) { super(dungeon); if(!(creature instanceof Creature)) { throw new Error('Second parameter must be a Creature'); } else if(!(ability instanceof Ability)) { throw new Error('Third parameter must be an Ability'); } else if((tile instanceof Tile) !== ability.isTargetted()) { throw new Error('Fourth parameter must be a Tile iff ability is targetted'); } this._creature = creature; this._ability = ability; this._tile = tile; } getCreature() { return this._creature; } getAbility() { return this._ability; } getTile() { return this._tile; } getText(dungeon) { var creature = this.getCreature(); var ability = this.getAbility(); var tile = dungeon.getTile(creature); return `${creature} used ${ability}` + (tile ? ` on ${tile}` : ''); } }
acbabis/roguelike
src/client/js/app/events/AbilityEvent.js
JavaScript
mit
1,309
//------------------------------- // ADMINISTER CODES FUNCTIONALITY //------------------------------- MFILE.administerCodes = function () { MFILE.administerCodes.handleDisplay(); MFILE.administerCodes.handleKeyboard(); } MFILE.administerCodes.handleDisplay = function () { $('#result').empty(); $('#codebox').html(MFILE.html.code_box); if (MFILE.activeCode.cstr.length === 0) { //$('#code').val('<EMPTY>'); $('#code').val(''); } else { $('#code').val(MFILE.activeCode.cstr); } $("#code").focus(function(event) { $("#topmesg").html("ESC=Back, Ins=Insert, F3=Lookup, F5=Delete, ENTER=Accept"); $("#mainarea").html(MFILE.html.change_code); }); $("#code").blur(function(event) { $('#topmesg').empty(); }); } MFILE.administerCodes.handleKeyboard = function () { // Handle function keys in Code field $("#code").keydown(function (event) { MFILE.administerCodes.processKey(event); }); $('#code').focus(); } MFILE.administerCodes.processKey = function (event) { console.log("KEYDOWN. WHICH "+event.which+", KEYCODE "+event.keyCode); // Function key handler if (event.which === 9) { // tab, shift-tab event.preventDefault(); console.log("IGNORING TAB"); return true; } else if (event.which === 27) { // ESC event.preventDefault(); MFILE.activeCode.cstr = ""; $('#code').val(''); $('#code').blur(); $('#codebox').empty(); $('#result').empty(); MFILE.state = 'MAIN_MENU'; MFILE.actOnState(); } else if (event.which === 13) { // ENTER event.preventDefault(); $('#result').empty(); MFILE.fetchCode("ACCEPT"); } else if (event.which === 45) { // Ins event.preventDefault(); MFILE.activeCode.cstr = $('#code').val(); console.log("Asking server to insert code '"+MFILE.activeCode.cstr+"'"); MFILE.insertCode(); $('#result').html(MFILE.activeCode.result); } else if (event.which === 114) { // F3 event.preventDefault(); MFILE.activeCode.cstr = $('#code').val(); console.log("Consulting server concerning the code '"+MFILE.activeCode.cstr+"'"); MFILE.searchCode(); } else if (event.which == 116) { // F5 event.preventDefault(); MFILE.activeCode.cstr = $('#code').val(); console.log("Asking server to delete code '"+MFILE.activeCode.cstr+"'"); MFILE.fetchCode('DELETE'); $('#result').html(MFILE.activeCode.result); } } //--------------- // AJAX FUNCTIONS //--------------- MFILE.insertCode = function() { console.log("About to insert code string "+MFILE.activeCode["cstr"]); $.ajax({ url: "insertcode", type: "POST", dataType: "json", data: MFILE.activeCode, success: function(result) { console.log("Query result is: '"+result.queryResult+"'"); $("#id").empty(); if (result.queryResult === "success") { console.log("SUCCESS") console.log(result); $("#code").val(result.mfilecodeCode); $("#result").empty(); $("#result").append("New code "+result.mfilecodeCode+" (ID "+result.mfilecodeId+") added to database.") } else { console.log("FAILURE") console.log(result); $("#code").empty(); $("#result").empty(); $("#result").append("FAILED: '"+result.queryResult+"'") } }, error: function(xhr, status, error) { $("#result").html("AJAX ERROR: "+xhr.status); } }); } MFILE.fetchCode = function (action) { // we fetch it in order to delete it console.log("Attempting to fetch code "+MFILE.activeCode["cstr"]); $.ajax({ url: "fetchcode", type: "POST", dataType: "json", data: MFILE.activeCode, success: function(result) { console.log("AJAX POST success, result is: '"+result.queryResult+"'"); if (result.queryResult === "success") { MFILE.activeCode.cstr = result.mfilecodeCode; $("#code").val(MFILE.activeCode.cstr); if (action === "DELETE") { MFILE.deleteCodeConf(); } else { MFILE.state = 'MAIN_MENU'; MFILE.actOnState(); } } else { $('#result').html("FAILED: '"+result.queryResult+"'"); return false; } }, error: function(xhr, status, error) { $("#result").html("AJAX ERROR: "+xhr.status); } }); } MFILE.deleteCodeConf = function () { // for now, called only from fetchCode console.log("Asking for confirmation to delete "+MFILE.activeCode["cstr"]); $("#mainarea").html(MFILE.html.code_delete_conf1); $("#mainarea").append(MFILE.activeCode.cstr+"<BR>"); $("#mainarea").append(MFILE.html.code_delete_conf2); $("#yesno").focus(); console.log("Attempting to fetch code "+MFILE.activeCode["cstr"]); $("#yesno").keydown(function(event) { event.preventDefault(); logKeyPress(event); if (event.which === 89) { MFILE.deleteCode(); } MFILE.actOnState(); }); } MFILE.searchCode = function () { console.log("Attempting to search code "+MFILE.activeCode["cstr"]); $.ajax({ url: "searchcode", type: "POST", dataType: "json", data: MFILE.activeCode, success: function(result) { console.log("AJAX POST success, result is: '"+result.result+"'"); if (result.result === "success") { if (result.values.length === 0) { $("#result").html("FAILED: 'Nothing matches'"); } else if (result.values.length === 1) { $("#result").html("SUCCESS: Code found"); MFILE.activeCode.cstr = result.values[0]; $("#code").val(MFILE.activeCode.cstr); } else { $("#mainarea").html(MFILE.html.code_search_results1); $.each(result.values, function (key, value) { $("#mainarea").append(value+" "); }); $("#mainarea").append(MFILE.html.press_any_key); $("#continue").focus(); $("#continue").keydown(function(event) { event.preventDefault(); MFILE.actOnState(); }); $("#result").html("Search found multiple matching codes. Please narrow it down."); } } else { console.log("FAILURE: "+result); $("#code").empty(); $("#result").html("FAILED: '"+result.result+"'"); } }, error: function(xhr, status, error) { $("#result").html("AJAX ERROR: "+xhr.status); } }); } MFILE.deleteCode = function() { console.log("Attempting to delete code "+MFILE.activeCode["cstr"]); $.ajax({ url: "deletecode", type: "POST", dataType: "json", data: MFILE.activeCode, success: function(result) { console.log("Query result is: '"+result.queryResult+"'"); $("#id").empty(); if (result.queryResult === "success") { console.log("SUCCESS"); console.log(result); $("#code").empty(); $("#result").empty(); $("#result").append("Code deleted"); } else { console.log("FAILURE") console.log(result); $("#result").empty(); $("#result").append("FAILED: '"+result.queryResult+"'") } }, error: function(xhr, status, error) { $("#result").html("AJAX ERROR: "+xhr.status); } }); }
smithfarm/mfile-erlang
priv/static/06code.js
JavaScript
mit
7,539
/** * @fileOverview * @name aqicn.js * @author ctgnauh <huangtc@outlook.com> * @license MIT */ var request = require('request'); var cheerio = require('cheerio'); var info = require('./info.json'); /** * 从 aqicn.org 上获取空气信息 * @module aqicn */ module.exports = { // 一些多余的信息 info: info, /** * fetchWebPage 的 callback * @callback module:aqicn~fetchWebPageCallback * @param {object} error - 请求错误 * @param {object} result - 页面文本 */ /** * 抓取移动版 aqicn.org 页面。 * aqicn.org 桌面版在300kb以上,而移动版则不足70kb。所以使用移动版,链接后面加 /m/ 。 * @param {string} city - 城市或地区代码,详见[全部地区](http://aqicn.org/city/all/) * @param {module:aqicn~fetchWebPageCallback} callback */ fetchWebPage: function (city, callback) { 'use strict'; var options = { url: 'http://aqicn.org/city/' + city + '/m/', headers: { 'User-Agent': 'wget' } }; request.get(options, function (err, res, body) { if (err) { callback(err, ''); } else { callback(null, body); } }); }, /** * 分析 html 文件并返回指定的 AQI 值 * @param {string} body - 页面文本 * @param {string} name - 污染物代码:pm25、pm10、o3、no2、so2、co * @returns {number} AQI 值 */ selectAQIText: function (body, name) { 'use strict'; var self = this; var $ = cheerio.load(body); var json; var value; try { json = JSON.parse($('#table script').text().slice(12, -2)); // "genAqiTable({...})" value = self.info.species.indexOf(name); } catch (err) { return NaN; } return json.d[value].iaqi; }, /** * 分析 html 文件并返回更新时间 * @param {string} body - 页面文本 * @returns {string} ISO格式的时间 */ selectUpdateTime: function (body) { 'use strict'; var $ = cheerio.load(body); var json; try { json = JSON.parse($('#table script').text().slice(12, -2)); // "genAqiTable({...})" } catch (err) { return new Date(0).toISOString(); } return json.t; }, /** * 污染等级及相关信息 * @param {number} level - AQI 级别 * @param {string} lang - 语言:cn、en、jp、es、kr、ru、hk、fr、pl(但当前只有 cn 和 en) * @returns {object} 由AQI级别、污染等级、对健康影响情况、建议采取的措施组成的对象 */ selectInfoText: function (level, lang) { 'use strict'; var self = this; if (level > 6 || level < 0) { level = 0; } return { value: level, name: self.info.level[level].name[lang], implication: self.info.level[level].implication[lang], statement: self.info.level[level].statement[lang] }; }, /** * 计算 AQI,这里选取 aqicn.org 采用的算法,选取 AQI 中数值最大的一个 * @param {array} aqis - 包含全部 AQI 数值的数组 * @returns {number} 最大 AQI */ calculateAQI: function (aqis) { 'use strict'; return Math.max.apply(null, aqis); }, /** * 计算空气污染等级,分级标准详见[关于空气质量与空气污染指数](http://aqicn.org/?city=&size=xlarge&aboutaqi) * @param {number} aqi - 最大 AQI * @returns {number} AQI 级别 */ calculateLevel: function (aqi) { 'use strict'; var level = 0; if (aqi >= 0 && aqi <= 50) { level = 1; } else if (aqi >= 51 && aqi <= 100) { level = 2; } else if (aqi >= 101 && aqi <= 150) { level = 3; } else if (aqi >= 151 && aqi <= 200) { level = 4; } else if (aqi >= 201 && aqi <= 300) { level = 5; } else if (aqi > 300) { level = 6; } return level; }, /** * getAQIs 的 callback * @callback module:aqicn~getAQIsCallback * @param {object} error - 请求错误 * @param {object} result - 包含全部污染物信息的对象 */ /** * 获取指定城市的全部 AQI 数值 * @param {string} city - 城市或地区代码,详见[全部地区](http://aqicn.org/city/all/) * @param {string} lang - 语言:cn、en、jp、es、kr、ru、hk、fr、pl(但当前只有 cn 和 en) * @param {module:aqicn~getAQIsCallback} callback */ getAQIs: function (city, lang, callback) { 'use strict'; var self = this; self.fetchWebPage(city, function (err, body) { if (err) { callback(err); } var result = {}; var aqis = []; // 城市代码 result.city = city; // 数据提供时间 result.time = self.selectUpdateTime(body); // 全部 AQI 值 self.info.species.forEach(function (name) { var aqi = self.selectAQIText(body, name); aqis.push(aqi); result[name] = aqi; }); // 主要 AQI 值 result.aqi = self.calculateAQI(aqis); // AQI 等级及其它 var level = self.calculateLevel(result.aqi); var levelInfo = self.selectInfoText(level, lang); result.level = levelInfo; callback(null, result); }); }, /** * getAQIByName 的 callback * @callback module:aqicn~getAQIByNameCallback * @param {object} error - 请求错误 * @param {object} result - 城市或地区代码与指定的 AQI */ /** * 获取指定城市的指定污染物数值 * @param {string} city - 城市或地区代码 * @param {string} name - 污染物代码:pm25、pm10、o3、no2、so2、co * @param {module:aqicn~getAQIByNameCallback} callback */ getAQIByName: function (city, name, callback) { 'use strict'; var self = this; self.getAQIs(city, 'cn', function (err, res) { if (err) { callback(err); } callback(null, { city: city, value: res[name], time: res.time }); }); } };
ctgnauh/aqicn
src/aqicn.js
JavaScript
mit
5,915
var loadState = { preload: function() { /* Load all game assets Place your load bar, some messages. In this case of loading, only text is placed... */ var loadingLabel = game.add.text(80, 150, 'loading...', {font: '30px Courier', fill: '#fff'}); //Load your images, spritesheets, bitmaps... game.load.image('kayle', 'assets/img/kayle.png'); game.load.image('tree', 'assets/img/tree.png'); game.load.image('rock', 'assets/img/rock.png'); game.load.image('undefined', 'assets/img/undefined.png'); game.load.image('grass', 'assets/img/grass.png'); game.load.image('player', 'assets/img/player.png'); game.load.image('btn-play','assets/img/btn-play.png'); game.load.image('btn-load','assets/img/btn-play.png'); //Load your sounds, efx, music... //Example: game.load.audio('rockas', 'assets/snd/rockas.wav'); //Load your data, JSON, Querys... //Example: game.load.json('version', 'http://phaser.io/version.json'); }, create: function() { game.stage.setBackgroundColor('#DEDEDE'); game.scale.fullScreenScaleMode = Phaser.ScaleManager.EXACT_FIT; game.state.start('menu'); } };
Edznux/kayle
js/load.js
JavaScript
mit
1,271
'use strict'; var proxy = require('proxyquire'); var stubs = { googlemaps: jasmine.createSpyObj('googlemaps', ['staticMap']), request: jasmine.createSpy('request'), '@noCallThru': true }; describe('google-static-map', function() { var uut; describe('without auto-setting a key', function() { beforeEach(function() { uut = proxy('./index', stubs ); }); it('should not work without a api key', function() { expect( uut ).toThrow(new Error('You must provide a google api console key')); }); it('should provide a method to set a global api key', function() { expect( uut.set ).toBeDefined(); uut = uut.set('some-key'); expect( uut ).not.toThrow( jasmine.any( Error )); }); }); describe('with auto-setting a key', function() { beforeEach(function() { uut = proxy('./index', stubs ).set('some-key'); }); it('should get/set config options', function() { var map = uut(); var set; ['zoom', 'resolution', 'mapType', 'markers', 'style'].forEach(function( key ) { set = key + ' ' + key; expect( map.config[key] ).toEqual( map[key]() ); var chain = map[key]( set ); expect( map.config[key] ).toEqual( set ); expect( chain ).toEqual( map ); }); }); it('should relay staticMap call to googlemaps module', function() { var map = uut(); var testAddress = 'Some Address, Some Country'; var staticMapReturn = 'http://some.where'; var requestReturn = 'request-return-value'; stubs.googlemaps.staticMap.andReturn( staticMapReturn ); stubs.request.andReturn( requestReturn ); var stream = map.address( testAddress ).staticMap().done(); expect( stream ).toEqual('request-return-value'); expect( stubs.googlemaps.staticMap ).toHaveBeenCalledWith( testAddress, map.config.zoom, map.config.resolution, false, false, map.config.mapType, map.config.markers, map.config.style, map.config.paths ); expect( stubs.request ).toHaveBeenCalledWith( staticMapReturn ); }); }); });
ds82/google-static-map
test.spec.js
JavaScript
mit
2,179
/** * Unit tests for FoxHound * * @license MIT * * @author Steven Velozo <steven@velozo.com> */ var Chai = require('chai'); var Expect = Chai.expect; var Assert = Chai.assert; var libFable = require('fable').new({}); var libFoxHound = require('../source/FoxHound.js'); suite ( 'FoxHound', function() { setup ( function() { } ); suite ( 'Object Sanity', function() { test ( 'initialize should build a happy little object', function() { var testFoxHound = libFoxHound.new(libFable); Expect(testFoxHound) .to.be.an('object', 'FoxHound should initialize as an object directly from the require statement.'); Expect(testFoxHound).to.have.a.property('uuid') .that.is.a('string'); Expect(testFoxHound).to.have.a.property('logLevel'); } ); test ( 'basic class parameters', function() { var testFoxHound = libFoxHound.new(libFable); Expect(testFoxHound).to.have.a.property('parameters') .that.is.a('object'); Expect(testFoxHound.parameters).to.have.a.property('scope') .that.is.a('boolean'); // Scope is boolean false by default. Expect(testFoxHound.parameters).to.have.a.property('dataElements') .that.is.a('boolean'); // Scope is boolean false by default. Expect(testFoxHound.parameters).to.have.a.property('filter') .that.is.a('boolean'); // Scope is boolean false by default. Expect(testFoxHound.parameters).to.have.a.property('begin') .that.is.a('boolean'); // Scope is boolean false by default. Expect(testFoxHound.parameters).to.have.a.property('cap') .that.is.a('boolean'); // Scope is boolean false by default. Expect(testFoxHound.parameters).to.have.a.property('sort') .that.is.a('boolean'); // Scope is boolean false by default. } ); } ); suite ( 'Basic Query Generation', function() { test ( 'generate a simple query of all data in a set', function() { // The default dialect is English. This one-liner is all-in. Expect(libFoxHound.new(libFable).setLogLevel().setScope('Widget').buildReadQuery().query.body) .to.equal('Please give me all your Widget records. Thanks.'); } ); test ( 'change the dialect', function() { var tmpQuery = libFoxHound.new(libFable).setLogLevel(5); // Give a scope for the data to come from tmpQuery.setScope('Widget'); // Expect there to not be a dialect yet Expect(tmpQuery).to.have.a.property('dialect') .that.is.a('boolean'); // Build the query tmpQuery.buildReadQuery(); // Expect implicit dialect of English to be instantiated Expect(tmpQuery.dialect.name) .to.equal('English'); // Now submit a bad dialect tmpQuery.setDialect(); // Expect implicit dialect of English to be instantiated Expect(tmpQuery.dialect.name) .to.equal('English'); // This is the query generated by the English dialect Expect(tmpQuery.query.body) .to.equal('Please give me all your Widget records. Thanks.'); // Now change to MySQL tmpQuery.setDialect('MySQL'); Expect(tmpQuery.dialect.name) .to.equal('MySQL'); // Build the query tmpQuery.buildReadQuery(); // This is the query generated by the English dialect Expect(tmpQuery.query.body) .to.equal('SELECT `Widget`.* FROM `Widget`;'); } ); } ); suite ( 'State Management', function() { test ( 'change the scope by function', function() { var tmpQuery = libFoxHound.new(libFable); Expect(tmpQuery.parameters.scope) .to.equal(false); tmpQuery.setScope('Widget'); Expect(tmpQuery.parameters.scope) .to.equal('Widget'); } ); test ( 'merge parameters', function() { var tmpQuery = libFoxHound.new(libFable); Expect(tmpQuery.parameters.scope) .to.equal(false); tmpQuery.mergeParameters({scope:'Fridget'}); Expect(tmpQuery.parameters.scope) .to.equal('Fridget'); } ); test ( 'clone the object', function() { // Create a query var tmpQuery = libFoxHound.new(libFable); Expect(tmpQuery.parameters.scope).to.equal(false); // Clone it var tmpQueryCloneOne = tmpQuery.clone(); Expect(tmpQueryCloneOne.parameters.scope).to.equal(false); // Set the first queries scope tmpQuery.setScope('Widget'); Expect(tmpQuery.parameters.scope).to.equal('Widget'); Expect(tmpQueryCloneOne.parameters.scope).to.equal(false); // Now clone again var tmpQueryCloneTwo = tmpQuery.clone(); Expect(tmpQueryCloneTwo.parameters.scope).to.equal('Widget'); // Set some state on the second clone, make sure it doesn't pollute other objects tmpQueryCloneTwo.setScope('Sprocket'); Expect(tmpQuery.parameters.scope).to.equal('Widget'); Expect(tmpQueryCloneOne.parameters.scope).to.equal(false); Expect(tmpQueryCloneTwo.parameters.scope).to.equal('Sprocket'); } ); test ( 'fail to change the scope by function', function() { var tmpQuery = libFoxHound.new(libFable); Expect(tmpQuery.parameters.scope) .to.equal(false); // Numbers are not valid scopes tmpQuery.setScope(100); Expect(tmpQuery.parameters.scope) .to.equal(false); } ); test ( 'change the cap by function', function() { var tmpQuery = libFoxHound.new(libFable); Expect(tmpQuery.parameters.cap) .to.equal(false); tmpQuery.setCap(50); Expect(tmpQuery.parameters.cap) .to.equal(50); } ); test ( 'fail to change the cap by function', function() { var tmpQuery = libFoxHound.new(libFable); Expect(tmpQuery.parameters.cap) .to.equal(false); tmpQuery.setCap('Disaster'); Expect(tmpQuery.parameters.cap) .to.equal(false); } ); test ( 'change the user ID', function() { var tmpQuery = libFoxHound.new(libFable); Expect(tmpQuery.parameters.userID) .to.equal(0); tmpQuery.setIDUser(1); Expect(tmpQuery.parameters.userID) .to.equal(1); Expect(tmpQuery.parameters.query.IDUser) .to.equal(1); } ); test ( 'fail to change the user ID', function() { var tmpQuery = libFoxHound.new(libFable); Expect(tmpQuery.parameters.userID) .to.equal(0); tmpQuery.setLogLevel(3); tmpQuery.setIDUser('Disaster'); Expect(tmpQuery.parameters.userID) .to.equal(0); } ); test ( 'change the begin by function', function() { var tmpQuery = libFoxHound.new(libFable); Expect(tmpQuery.parameters.begin) .to.equal(false); tmpQuery.setBegin(2); Expect(tmpQuery.parameters.begin) .to.equal(2); } ); test ( 'fail to change the begin by function', function() { var tmpQuery = libFoxHound.new(libFable); Expect(tmpQuery.parameters.begin) .to.equal(false); tmpQuery.setBegin('Looming'); Expect(tmpQuery.parameters.begin) .to.equal(false); } ); test ( 'Manually set the parameters object', function() { var tmpQuery = libFoxHound.new(libFable); tmpQuery.parameters = {Frogs:'YES'}; Expect(tmpQuery.parameters.Frogs) .to.equal('YES'); } ); test ( 'Manually set the query object', function() { var tmpQuery = libFoxHound.new(libFable); tmpQuery.query = {body:'GET TO ALL DE CHOPPA RECORDS'}; Expect(tmpQuery.query.body) .to.contain('CHOPPA'); } ); test ( 'Manually set the result object', function() { var tmpQuery = libFoxHound.new(libFable); tmpQuery.result = {executed:true, value:[{Name:'Wendy'},{Name:'Griffin'}]}; Expect(tmpQuery.result.executed) .to.equal(true); } ); test ( 'Set a bad dialect', function() { var tmpQuery = libFoxHound.new(libFable).setDialect('Esperanto'); Expect(tmpQuery.dialect.name) .to.equal('English'); } ); test ( 'Try to pass bad filters', function() { var tmpQuery = libFoxHound.new(libFable); tmpQuery.addFilter(); tmpQuery.addFilter('Name'); Expect(tmpQuery.parameters.filter) .to.equal(false); } ); test ( 'Pass many filters', function() { var tmpQuery = libFoxHound.new(libFable); tmpQuery.addFilter('Name', 'Smith'); tmpQuery.addFilter('City', 'Seattle'); Expect(tmpQuery.parameters.filter.length) .to.equal(2); tmpQuery.addFilter('Age', 25, '>', 'AND', 'AgeParameter'); Expect(tmpQuery.parameters.filter.length) .to.equal(3); } ); test ( 'Pass bad records', function() { var tmpQuery = libFoxHound.new(libFable); tmpQuery.addRecord(); Expect(tmpQuery.query.records) .to.equal(false); } ); test ( 'Pass multiple records', function() { var tmpQuery = libFoxHound.new(libFable); tmpQuery.addRecord({ID:10}); tmpQuery.addRecord({ID:100}); tmpQuery.addRecord({ID:1000}); Expect(tmpQuery.query.records.length) .to.equal(3); } ); } ); } );
stevenvelozo/foxhound
test/FoxHound_tests.js
JavaScript
mit
9,683
const path = require( 'path' ); const pkg = require( './package.json' ); const webpack = require( 'laxar-infrastructure' ).webpack( { context: __dirname, resolve: { extensions: [ '.js', '.jsx', '.ts', '.tsx' ] }, module: { rules: [ { test: /\.tsx?$/, exclude: /node_modules\/.*\/spec\//, loader: 'ts-loader' }, { test: /\.jsx?$/, exclude: path.resolve( __dirname, 'node_modules' ), loader: 'babel-loader' }, { test: /\.spec.js$/, exclude: path.resolve( __dirname, 'node_modules' ), loader: 'laxar-mocks/spec-loader' } ] } } ); module.exports = [ webpack.library(), webpack.browserSpec( [ `./spec/${pkg.name}.spec.js` ] ) ];
LaxarJS/generator-laxarjs2
generators/widget/templates/angular2.webpack.config.js
JavaScript
mit
828
import React, { Component } from "react"; import { AppHeader, AppFooter } from "../App"; import config from "../../../config"; import { fromJS } from "immutable"; import Spinner from "react-spinner"; import { PlaylistNavBar } from "../../components/PlaylistNavBar"; export class LoadingMoment extends Component { constructor(props) { super(props); this.state = { story: null, momentId: 0, storyMomentList: [] }; } async componentDidMount() { let path = this.props.location.pathname; let storyId = path.split("/")[3]; let momentId = path.split("/")[5]; let storyMomentList = []; const response = await fetch(`${config.apiEntry}/api/stories/${storyId}`); let storyObj = await response.json(); let momentList = fromJS(storyObj.momentList); momentList.forEach((m) => storyMomentList.push(m)); this.setState({ story: storyObj, momentId: momentId, storyMomentList: storyMomentList, }); this.props.history.push(`/stories/story/${storyId}/moment/${momentId}`); } render() { return ( <div className="app-container"> <AppHeader /> <PlaylistNavBar currentStory={this.state.story} currentMomentId={this.state.momentId} moments={this.state.storyMomentList} history={this.props.history} /> <div className="text-center lead"> <p>Loading moment...</p> <Spinner /> </div> <AppFooter /> </div> ); } }
UTD-CRSS/app.exploreapollo.org
src/containers/LoadingMoment/index.js
JavaScript
mit
1,496
/* */ var htmlparser = require('htmlparser2'); var _ = require('lodash'); var quoteRegexp = require('regexp-quote'); module.exports = sanitizeHtml; // Ignore the _recursing flag; it's there for recursive // invocation as a guard against this exploit: // https://github.com/fb55/htmlparser2/issues/105 function sanitizeHtml(html, options, _recursing) { var result = ''; function Frame(tag, attribs) { var that = this; this.tag = tag; this.attribs = attribs || {}; this.tagPosition = result.length; this.text = ''; // Node inner text this.updateParentNodeText = function() { if (stack.length) { var parentFrame = stack[stack.length - 1]; parentFrame.text += that.text; } }; } if (!options) { options = sanitizeHtml.defaults; } else { _.defaults(options, sanitizeHtml.defaults); } // Tags that contain something other than HTML. If we are not allowing // these tags, we should drop their content too. For other tags you would // drop the tag but keep its content. var nonTextTagsMap = { script: true, style: true }; var allowedTagsMap; if(options.allowedTags) { allowedTagsMap = {}; _.each(options.allowedTags, function(tag) { allowedTagsMap[tag] = true; }); } var selfClosingMap = {}; _.each(options.selfClosing, function(tag) { selfClosingMap[tag] = true; }); var allowedAttributesMap; var allowedAttributesGlobMap; if(options.allowedAttributes) { allowedAttributesMap = {}; allowedAttributesGlobMap = {}; _.each(options.allowedAttributes, function(attributes, tag) { allowedAttributesMap[tag] = {}; var globRegex = []; _.each(attributes, function(name) { if(name.indexOf('*') >= 0) { globRegex.push(quoteRegexp(name).replace(/\\\*/g, '.*')); } else { allowedAttributesMap[tag][name] = true; } }); allowedAttributesGlobMap[tag] = new RegExp('^(' + globRegex.join('|') + ')$'); }); } var allowedClassesMap = {}; _.each(options.allowedClasses, function(classes, tag) { // Implicitly allows the class attribute if(allowedAttributesMap) { if (!allowedAttributesMap[tag]) { allowedAttributesMap[tag] = {}; } allowedAttributesMap[tag]['class'] = true; } allowedClassesMap[tag] = {}; _.each(classes, function(name) { allowedClassesMap[tag][name] = true; }); }); var transformTagsMap = {}; _.each(options.transformTags, function(transform, tag){ if (typeof transform === 'function') { transformTagsMap[tag] = transform; } else if (typeof transform === "string") { transformTagsMap[tag] = sanitizeHtml.simpleTransform(transform); } }); var depth = 0; var stack = []; var skipMap = {}; var transformMap = {}; var skipText = false; var parser = new htmlparser.Parser({ onopentag: function(name, attribs) { var frame = new Frame(name, attribs); stack.push(frame); var skip = false; if (_.has(transformTagsMap, name)) { var transformedTag = transformTagsMap[name](name, attribs); frame.attribs = attribs = transformedTag.attribs; if (name !== transformedTag.tagName) { frame.name = name = transformedTag.tagName; transformMap[depth] = transformedTag.tagName; } } if (allowedTagsMap && !_.has(allowedTagsMap, name)) { skip = true; if (_.has(nonTextTagsMap, name)) { skipText = true; } skipMap[depth] = true; } depth++; if (skip) { // We want the contents but not this tag return; } result += '<' + name; if (!allowedAttributesMap || _.has(allowedAttributesMap, name)) { _.each(attribs, function(value, a) { if (!allowedAttributesMap || _.has(allowedAttributesMap[name], a) || (_.has(allowedAttributesGlobMap, name) && allowedAttributesGlobMap[name].test(a))) { if ((a === 'href') || (a === 'src')) { if (naughtyHref(value)) { delete frame.attribs[a]; return; } } if (a === 'class') { value = filterClasses(value, allowedClassesMap[name]); if (!value.length) { delete frame.attribs[a]; return; } } result += ' ' + a; if (value.length) { result += '="' + escapeHtml(value) + '"'; } } else { delete frame.attribs[a]; } }); } if (_.has(selfClosingMap, name)) { result += " />"; } else { result += ">"; } }, ontext: function(text) { if (skipText) { return; } var tag = stack[stack.length-1] && stack[stack.length-1].tag; if (_.has(nonTextTagsMap, tag)) { result += text; } else { var escaped = escapeHtml(text); if (options.textFilter) { result += options.textFilter(escaped); } else { result += escaped; } } if (stack.length) { var frame = stack[stack.length - 1]; frame.text += text; } }, onclosetag: function(name) { var frame = stack.pop(); if (!frame) { // Do not crash on bad markup return; } skipText = false; depth--; if (skipMap[depth]) { delete skipMap[depth]; frame.updateParentNodeText(); return; } if (transformMap[depth]) { name = transformMap[depth]; delete transformMap[depth]; } if (options.exclusiveFilter && options.exclusiveFilter(frame)) { result = result.substr(0, frame.tagPosition); return; } frame.updateParentNodeText(); if (_.has(selfClosingMap, name)) { // Already output /> return; } result += "</" + name + ">"; } }, { decodeEntities: true }); parser.write(html); parser.end(); return result; function escapeHtml(s) { if (typeof(s) !== 'string') { s = s + ''; } return s.replace(/\&/g, '&amp;').replace(/</g, '&lt;').replace(/\>/g, '&gt;').replace(/\"/g, '&quot;'); } function naughtyHref(href) { // Browsers ignore character codes of 32 (space) and below in a surprising // number of situations. Start reading here: // https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet#Embedded_tab href = href.replace(/[\x00-\x20]+/g, ''); // Clobber any comments in URLs, which the browser might // interpret inside an XML data island, allowing // a javascript: URL to be snuck through href = href.replace(/<\!\-\-.*?\-\-\>/g, ''); // Case insensitive so we don't get faked out by JAVASCRIPT #1 var matches = href.match(/^([a-zA-Z]+)\:/); if (!matches) { // No scheme = no way to inject js (right?) return false; } var scheme = matches[1].toLowerCase(); return (!_.contains(options.allowedSchemes, scheme)); } function filterClasses(classes, allowed) { if (!allowed) { // The class attribute is allowed without filtering on this tag return classes; } classes = classes.split(/\s+/); return _.filter(classes, function(c) { return _.has(allowed, c); }).join(' '); } } // Defaults are accessible to you so that you can use them as a starting point // programmatically if you wish sanitizeHtml.defaults = { allowedTags: [ 'h3', 'h4', 'h5', 'h6', 'blockquote', 'p', 'a', 'ul', 'ol', 'nl', 'li', 'b', 'i', 'strong', 'em', 'strike', 'code', 'hr', 'br', 'div', 'table', 'thead', 'caption', 'tbody', 'tr', 'th', 'td', 'pre' ], allowedAttributes: { a: [ 'href', 'name', 'target' ], // We don't currently allow img itself by default, but this // would make sense if we did img: [ 'src' ] }, // Lots of these won't come up by default because we don't allow them selfClosing: [ 'img', 'br', 'hr', 'area', 'base', 'basefont', 'input', 'link', 'meta' ], // URL schemes we permit allowedSchemes: [ 'http', 'https', 'ftp', 'mailto' ] }; sanitizeHtml.simpleTransform = function(newTagName, newAttribs, merge) { merge = (merge === undefined) ? true : merge; newAttribs = newAttribs || {}; return function(tagName, attribs) { var attrib; if (merge) { for (attrib in newAttribs) { attribs[attrib] = newAttribs[attrib]; } } else { attribs = newAttribs; } return { tagName: newTagName, attribs: attribs }; }; };
npelletm/np-jdanyow-skeleton-navigation
jspm_packages/npm/sanitize-html@1.6.1/index.js
JavaScript
mit
8,674
var path = require('path'); var winston = require('winston'); var config = require('./config.js'); var util = require('./util.js'); module.exports = initLogger(); function initLogger() { var targetDir = path.join(config('workingdir'), 'log'); util.createDirectoryIfNeeded(targetDir); var winstonConfig = { transports: [ new (winston.transports.Console)({ level: 'debug' }), new (winston.transports.File)({ filename: path.join(targetDir, 'tsync.log') }) ] }; return new (winston.Logger)(winstonConfig); }
brbrt/tsync
log.js
JavaScript
mit
629
const router = require('express').Router(); const db1 = require('../db'); // GET - Get All Students Info (Admin) // response: // [] students: // account_id: uuid // user_id: uuid // first_name: string // last_name: string // hometown: string // college: string // major: string // gender: string // birthdate: date // email: string // date_created: timestamp // image_path: string // bio: string router.get('/student/all', (req, res) => { db1.any(` SELECT account_id, user_id, first_name, last_name, hometown, college, major, gender, bio, birthdate, email, date_created, image_path FROM students natural join account natural join images`) .then(function(data) { // Send All Students Information console.log('Success: Admin Get All Students Information'); res.json({students: data}) }) .catch(function(error) { console.log(error); return res.status(400).send('Error: Problem executing Query'); }); }); // GET - Get All Associations Info (Admin) // response: // [] associations: // account_id: uuid // association_id: uuid // association_name: string // initials: string // email: string // page_link: string // image_path: string // bio: string // date_created: timestamp // room: string // building: string // city: string router.get('/association/all', (req, res) => { db1.any(` SELECT account_id, association_id, association_name, initials, page_link, image_path, email, bio, room, building, city, date_created FROM associations natural join account natural join location natural join images`) .then(function(data) { // Send All Associations Information console.log('Success: Admin Get All Associations Information'); res.json({associations: data}); }) .catch(function(error) { console.log(error); return res.status(400).send('Error: Problem executing Query'); }); }); // GET - Get All Events Info (Admin) // response: // [] events // event_id: id // event_name: string // is_live: bool (yes/no) // registration_link: string // start_date: date // end_date: date // start_time: time // end_time: time // room: string // building: string // city: string // image_path: string // time_stamp: timestamp router.get('/event/all', (req, res) => { db1.any(` SELECT event_id, event_name, is_live, registration_link, start_date, end_date, start_time, end_time, room, building, city, image_path, time_stamp FROM events natural join images natural join location`) .then(function(data) { // Send All Events Information console.log('Success: Admin Get All Events Information'); res.json({events: data}); }) .catch(function(error) { console.log(error); return res.status(400).send('Error: Problem executing Query'); }); }); module.exports = router;
mario2904/ICOM5016-Project
api/admin.js
JavaScript
mit
3,056
import one from './index-loader-syntax.css'; import two from 'button.modules.css!=!./index-loader-syntax-sass.css'; // Hash should be different import three from './button.module.scss!=!./base64-loader?LmZvbyB7IGNvbG9yOiByZWQ7IH0=!./simple.js?foo=bar'; import four from './other.module.scss!=!./base64-loader?LmZvbyB7IGNvbG9yOiByZWQ7IH0=!./simple.js?foo=baz'; __export__ = [...one, ...two, ...three, ...four]; export default [...one, ...two, ...three, ...four];
webpack-contrib/css-loader
test/fixtures/index-loader-syntax.js
JavaScript
mit
463
var mysql = require('mysql'); function discountMember(router,connection){ var self=this; self.handleRoutes(router,connection); } //KALO...UDH SEKALI DIDISKON>>>BERARTI GABOLEH LAGI LAGI DISKON YAA TODO: discountMember.prototype.handleRoutes = function(router,connection){ router.post('/discountMember',function(req,res){ var sessionCode = req.body.sessionCode; var no_bon = req.body.no_bon; var membershipCode = req.body.membershipCode; if(sessionCode == null || sessionCode == undefined || sessionCode == ''){ res.json({"message":"err.. no params s_c rec"}); }else{ if(no_bon == null || no_bon == undefined || no_bon == ''){ res.json({"message":"err.. no params n_b rec"}); }else{ if(membershipCode == null || membershipCode == undefined || membershipCode == ''){ res.json({"message":"err.. no params m_c rec"}); }else{ var query = "select role.id_role as id_role from `session` join `user` on session.id_user=user.id_user join role on role.id_role=user.id_role where session.session_code='"+sessionCode+"'"; connection.query(query,function(err,rows){ if(err){ res.json({"message":"err.. error on session","query":query}); }else{ if(rows.length == 1){ if(rows[0].id_role == 2 || rows[0].id_role == 1){ var q012 = "select discount,no_bon from `order` where no_bon='"+no_bon+"'"; connection.query(q012,function(err,rows){ if(err){ res.json({"message":"err.. on selecting disc st1"}); }else{ if(rows.length>0){ if(rows[0].discount == null || rows[0].discount == undefined || rows[0].discount == ''){ //ambil jumlah discount dulu di membership code var q2 = "select discount from `membership` where membership_code='"+membershipCode+"'"; connection.query(q2,function(err,rows){ if(err){ res.json({"message":"err.. error selecting discount"}); }else{ if(rows.length>0){ var discount = rows[0].discount; //pending var q3 = "select jumlah_bayar from `order` where no_bon = '"+no_bon+"'"; connection.query(q3,function(err,rows){ if(err){ res.json({"message":"err.. error on selecting jumlah Bayar"}); }else{ if(rows.length>0){ var jumlahBayar = rows[0].jumlah_bayar; var afterDisc = jumlahBayar-(jumlahBayar*discount/100); var q4 = "update `order` set discount="+discount+",harga_bayar_fix="+afterDisc+",jumlah_bayar="+afterDisc+" where no_bon='"+no_bon+"'"; connection.query(q4,function(err,rows){ if(err){ res.json({"message":"err.. error on updating"}); }else{ res.json({"message":"err.. success adding discount","priceAfterDiscount":afterDisc,"discount":discount}); } }); }else{ res.json({"message":"Err.. no rows absbas","q3":q3}); } } }); }else{ res.json({"message":"err.. no rows","q2":q2}); } } }); }else{ res.json({"message":"err.. have already discounted"}); } }else{ res.json({"message":"err.. no rows on order with given n_b"}); } } }); }else{ res.json({"message":"err.. you have no authorize to do this action"}); } }else{ res.json({"message":"err... rows length not equal to 1"}); } } }); } } } }); } module.exports = discountMember;
mczal/widji-server
model/cashier/discountMember.js
JavaScript
mit
4,751
import React from 'react'; import Home from './Home.js'; import Login from './Login.js'; import PointInTime from './PointInTime.js'; import Vispdat from './VISPDAT.js'; import Refuse from './Refuse.js'; import { Actions, Scene } from 'react-native-router-flux'; /** * Order of rendering is based on index of Child scene. * We set hideNavBar to true to prevent that ugly default * header. We can enable and style when we need to. */ export default Actions.create( <Scene key="root"> <Scene key="login" component={Login} hideNavBar={true} /> <Scene key="home" component={Home} hideNavBar={true} /> <Scene key="pointInTime" component={PointInTime} hideNavBar={true} /> <Scene key="vispdat" component={Vispdat} hideNavBar={true} /> <Scene key="refuse" component={Refuse} hideNavBar={true} /> </Scene> );
kawikadkekahuna/react-native-form
src/routes/index.js
JavaScript
mit
834
/*global Showdown*/ describe('$showdown', function () { 'use strict'; beforeEach(module('pl.itcrowd.services')); it('should be possible to inject initialized $showdown converter', inject(function ($showdown) { expect($showdown).not.toBeUndefined(); })); it('should be instance of $showdown.converter', inject(function ($showdown) { expect($showdown instanceof Showdown.converter).toBeTruthy(); })); });
it-crowd/angular-js-itc-utils
test/unit/services/showdown.test.js
JavaScript
mit
454
define(function () { var exports = {}; /** * Hashes string with a guarantee that if you need to hash a new string * that contains already hashed string at it's start, you can pass only * added part of that string along with the hash of already computed part * and will get correctly hash as if you passed full string. * * @param {string} str * @param {number=} hash * @return {number} */ exports.hash = function (str, hash) { hash = hash || 5381; // alghorithm by Dan Bernstein var i = -1, length = str.length; while(++i < length) { hash = ((hash << 5) + hash) ^ str.charCodeAt(i); } return hash; }; var entityDecoder = document.createElement('div'); /** * Correctly decodes all hex, decimal and named entities * @param {string} text * @return {string} */ exports.decodeHtmlEntities = function(text){ return text.replace(/&(?:#(x)?(\d+)|(\w+));/g, function(match, hexFlag, decOrHex, name) { if(decOrHex) { return String.fromCharCode(parseInt(decOrHex, hexFlag ? 16 : 10)); } switch(name) { case 'lt': return '<'; case 'gt': return '>'; case 'amp': return '&'; case 'quote': return '"'; default: entityDecoder.innerHTML = '&' + name + ';'; return entityDecoder.textContent; } }); }; /** * Calculates shallow difference between two object * @param {Object} one * @param {Object} other * @return {Object} */ exports.shallowObjectDiff = function(one, other) { // since we will be calling setAttribute there is no need to // differentiate between changes and additions var set = {}, removed = [], haveChanges = false, keys = Object.keys(one), length, key, i; // first go through all keys of `one` for(i = 0, length = keys.length; i < length; ++i) { key = keys[i]; if(other[key] != null) { if(one[key] !== other[key]) { set[key] = other[key]; haveChanges = true; } } else { removed.push(key); haveChanges = true; } } // then add all missing from the `other` into `one` keys = Object.keys(other); for(i = 0, length = keys.length; i < length; ++i) { key = keys[i]; if(one[key] == null) { set[key] = other[key]; haveChanges = true; } } return haveChanges ? { set: set, removed: removed } : false; }; return exports; });
grassator/live-html
js/src/utils.js
JavaScript
mit
2,563
version https://git-lfs.github.com/spec/v1 oid sha256:558005fd55405d3069b06849812a921274543d712676f42ad4a8c122034c02e4 size 819
yogeshsaroya/new-cdnjs
ajax/libs/mathjax/2.4.0/localization/eo/TeX.js
JavaScript
mit
128
let allExpenses exports.up = (knex, Promise) => { return knex('expenses').select('*') .then(expenses => { allExpenses = expenses return knex.schema.createTable('expense_items', (table) => { table.increments('id').primary().notNullable() table.integer('expense_id').notNullable().references('id').inTable('expenses') table.integer('position').notNullable() table.decimal('preTaxAmount').notNullable() table.decimal('taxrate').notNullable() table.text('description') table.index('expense_id') }) }) .then(() => { // this is necessary BEFORE creating the expense items because knex // drops the expenses table and then recreates it (foreign key problem). console.log('Dropping "preTaxAmount" and "taxrate" columns in expenses') return knex.schema.table('expenses', table => { table.dropColumn('preTaxAmount') table.dropColumn('taxrate') }) }) .then(() => { console.log('Migrating ' + allExpenses.length + ' expenses to items') return Promise.all( allExpenses.map(expense => createExpenseItem(knex, expense)) ) }) } exports.down = (knex, Promise) => { return knex.schema.dropTableIfExists('expense_items') } function createExpenseItem(knex, expense) { return knex('expense_items') .insert({ expense_id: expense.id, position: 0, preTaxAmount: expense.preTaxAmount, taxrate: expense.taxrate, description: '' }) }
haimich/billy
sql/migrations/20170323200721_expense_items.js
JavaScript
mit
1,527
var express = require('express'); var app = express(); var path = require('path'); var session = require('express-session'); var bodyParser = require('body-parser') var fs = require('fs'); app.use(express.static(path.join(__dirname, 'public'))); app.use(bodyParser.urlencoded({extended: true})); app.use(bodyParser.json()); app.use(session({ secret: 'angular_tutorial', resave: true, saveUninitialized: true, })); var Db = require('mongodb').Db; var Connection = require('mongodb').Connection; var Server = require('mongodb').Server; var ObjectID = require('mongodb').ObjectID; var db = new Db('tutor', new Server("localhost", 27017, {safe: true}, {auto_reconnect: true}, {})); db.open(function(){ console.log("mongo db is opened!"); db.collection('notes', function(error, notes) { db.notes = notes; }); db.collection('sections', function(error, sections) { db.sections = sections; }); }); app.get("/notes", function(req,res) { db.notes.find(req.query).toArray(function(err, items) { res.send(items); }); }); app.post("/notes", function(req,res) { db.notes.insert(req.body); res.end(); }); app.get("/sections", function(req,res) { db.sections.find(req.query).toArray(function(err, items) { res.send(items); }); }); app.get("/checkUser", function(req,res) { if (req.query.user.length>2) { res.send(true); } else { res.send(false); } }); app.post("/sections/replace", function(req,resp) { // do not clear the list if (req.body.length==0) { resp.end(); } // this should be used only for reordering db.sections.remove({}, function(err, res) { if (err) console.log(err); db.sections.insert(req.body, function(err, res) { if (err) console.log("err after insert",err); resp.end(); }); }); }); app.listen(3000);
RomanLysak/angularJsLabsLuxoft
courceLabsReady/task10/server.js
JavaScript
mit
1,778
var Screen = require('./basescreen'); var Game = require('../game'); var helpScreen = new Screen('Help'); // Define our winning screen helpScreen.render = function (display) { var text = 'jsrogue help'; var border = '-------------'; var y = 0; display.drawText(Game.getScreenWidth() / 2 - text.length / 2, y++, text); display.drawText(Game.getScreenWidth() / 2 - text.length / 2, y++, border); display.drawText(0, y++, 'The villagers have been complaining of a terrible stench coming from the cave.'); display.drawText(0, y++, 'Find the source of this smell and get rid of it!'); y += 3; display.drawText(0, y++, '[h or Left Arrow] to move left'); display.drawText(0, y++, '[l or Right Arrow] to move right'); display.drawText(0, y++, '[j or Down Arrow] to move down'); display.drawText(0, y++, '[k or Up Arrow] to move up'); display.drawText(0, y++, '[,] to pick up items'); //display.drawText(0, y++, '[d] to drop items'); //display.drawText(0, y++, '[e] to eat items'); //display.drawText(0, y++, '[w] to wield items'); //display.drawText(0, y++, '[W] to wield items'); //display.drawText(0, y++, '[x] to examine items'); display.drawText(0, y++, '[i] to view and manipulate your inventory'); display.drawText(0, y++, '[;] to look around you'); display.drawText(0, y++, '[?] to show this help screen'); y += 3; text = '--- press any key to continue ---'; display.drawText(Game.getScreenWidth() / 2 - text.length / 2, y++, text); }; helpScreen.handleInput = function (inputType, inputData) { // Switch back to the play screen. this.getParentScreen().setSubScreen(undefined); }; module.exports = helpScreen;
shaddockh/js_roguelike_tutorial
client/assets/screens/helpscreen.js
JavaScript
mit
1,665
requirejs(['helper/util'], function(util){ });
mcramos/financaspessoais
scripts/helper/util.js
JavaScript
mit
47
// Copyright (c) 2012 Ecma International. All rights reserved. // Ecma International makes this code available under the terms and conditions set // forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the // "Use Terms"). Any redistribution of this code must retain the above // copyright and this notice and otherwise comply with the Use Terms. /*--- es5id: 7.6.1-4-7 description: > Allow reserved words as property names by set function within an object, verified with hasOwnProperty: while, debugger, function includes: [runTestCase.js] ---*/ function testcase() { var test0 = 0, test1 = 1, test2 = 2; var tokenCodes = { set while(value){ test0 = value; }, get while(){ return test0 }, set debugger(value){ test1 = value; }, get debugger(){ return test1; }, set function(value){ test2 = value; }, get function(){ return test2; } }; var arr = [ 'while' , 'debugger', 'function' ]; for(var p in tokenCodes) { for(var p1 in arr) { if(arr[p1] === p) { if(!tokenCodes.hasOwnProperty(arr[p1])) { return false; }; } } } return true; } runTestCase(testcase);
PiotrDabkowski/Js2Py
tests/test_cases/language/reserved-words/7.6.1-4-7.js
JavaScript
mit
1,584
var View = require('ampersand-view'); var templates = require('../templates'); module.exports = View.extend({ template: templates.includes.scholarship, bindings: { 'model.field': '[role=field]', 'model.slots': '[role=slots]', 'model.holder': '[role=holder]', 'model.type': '[role=type]', 'model.link': { type: 'attribute', role: 'link', name: 'href' }, 'model.scholarshipIdUpperCase': '[role=link]', 'model.releaseDateFormated': '[role=release-date]', 'model.closeDateFormated': '[role=close-date]' } });
diasdavid/bolsas.istecni.co
clientApp/views/scholarship.js
JavaScript
mit
626
var toInteger = require('./toInteger'); /** Used as the `TypeError` message for "Functions" methods. */ var FUNC_ERROR_TEXT = 'Expected a function'; /** * The opposite of `_.before`; this method creates a function that invokes * `func` once it's called `n` or more times. * * @static * @memberOf _ * @category Function * @param {number} n The number of calls before `func` is invoked. * @param {Function} func The function to restrict. * @returns {Function} Returns the new restricted function. * @specs * * var saves = ['profile', 'settings']; * * var done = _.after(saves.length, function() { * console.log('done saving!'); * }); * * _.forEach(saves, function(type) { * asyncSave({ 'type': type, 'complete': done }); * }); * // => logs 'done saving!' after the two async saves have completed */ function after(n, func) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } n = toInteger(n); return function() { if (--n < 1) { return func.apply(this, arguments); } }; } module.exports = after;
mdchristopher/Protractor
node_modules/lodash/after.js
JavaScript
mit
1,073
$.widget( "alexandra.panelSlider", { options: { currentView: null, // The panel currently in focus panels:[] // All panels added to the navigation system }, //The constructor of the panelSLide widget _create: function() { var tempThis=this; this.element.addClass("panelSlider"); this.options.currentView=this.options.panels[0]; $.each(this.options.panels, function(i, val){ $("#"+val).hide(); tempThis._checkLinks(val); }); $("#"+this.options.currentView).show(); }, _checkLinks: function(val){ var tempThis=this; $("#"+val+" a").click(function (event) { event.preventDefault(); event.stopPropagation(); var url = $(this).attr('href'); var urlRegex = '/^(https?://)?([da-z.-]+).([a-z.]{2,6})([/w .-]*)*/?$/'; var res = url.match(urlRegex); if(res==null){ var newView=$.inArray(url,tempThis.options.panels); if(newView>-1){ var curView=$.inArray(tempThis.options.currentView,tempThis.options.panels); console.log("new: "+newView+", current: "+curView); if(newView>curView) tempThis.slide(url,false); else if(newView<curView) tempThis.slide(url,true); return; } } window.location = url; }); }, //It's possible to add a panel in runtime addPanel: function(panel) { this.options.panels.push(panel); $("#"+panel).hide(); this._checkLinks(panel); }, //A panel can be removed runtime removePanel: function(panel){ for(var i=0;i<this.options.panels.length;i++){ if(this.options.panels[i]==panel){ if(panel==this.options.currentView){ $("#"+panel).hide(); this.options.currentView= i-1<0 ? this.options.panels[1] : this.options.panels[i-1]; $("#"+this.options.currentView).show(); } this.options.panels.splice(i, 1); break; } } }, //The function that actually does all the sliding //If the goingBack variable is true the sliding will happen from left to right, and vice versa slide: function(panelToShow, goingBack){ /* Making sure that only registered objects can act as panels. Might be a little to rough to make such a hard return statement. */ if($.inArray(panelToShow,this.options.panels)<0) return "Not a registered panel"; var tempThis=this; var tempCurrentView=this.options.currentView; /* Temporary absolute positioned div for doing sliding of dfferent panels on same line. This is the wrapper for the panel to slide off the screen */ var currentPanel=$("<div/>",{ css:{ "position":"absolute", "top":0, "left":0, "width":"100%" } }); //Needed for keeping padding and margin while transition happens var innerWrapper=$("<div/>"); this.element.append(currentPanel); currentPanel.append(innerWrapper); innerWrapper.append($("#"+this.options.currentView)); innerWrapper.hide("slide",{direction: goingBack ? "right" : "left"}, function(){ $("#"+tempCurrentView).hide(); tempThis.element.append($("#"+tempCurrentView)); currentPanel.remove(); }); /* Temporary absolute positioned div for doing sliding of dfferent panels on same line. This is the wrapper for the panel to slide onto the screen */ var newPanel=$("<div/>",{ css:{ "position":"absolute", "top":0, "left":0, "width":"100%" } }); //Needed for keeping padding and margin while transition happens var innerWrapper2=$("<div/>"); innerWrapper2.hide(); this.element.append(newPanel); newPanel.append(innerWrapper2); innerWrapper2.append($("#"+panelToShow)); $("#"+panelToShow).show(); innerWrapper2.show("slide",{direction: goingBack ? "left" : "right"},function(){ tempThis.element.append($("#"+panelToShow)); newPanel.remove(); }); this.options.currentView=panelToShow; } });
alexandrainst/jQuery_panelSlider
panelSlider.js
JavaScript
mit
4,880
(function() { 'use strict'; function movieDetail(movieDetailService) { return { restrict: 'EA', replace: true, templateUrl: './src/app/movieDetail/template.html', scope: {}, controllerAs: 'vm', bindToController: true, /*jshint unused:false*/ controller: function($log, $stateParams) { var vm = this; movieDetailService.getMovie().then(function(response){ vm.movie = response.data; vm.movie.vote = (vm.movie.vote_average*10); vm.movie.genres_name = []; vm.movie.production_companies_name = []; vm.movie.production_countries_name = []; for (var i = 0; i <= vm.movie.genres.length-1; i++) { vm.movie.genres_name.push(vm.movie.genres[i].name); vm.movie.genres_name.sort(); } for (var i = 0; i <= vm.movie.production_companies.length-1; i++) { vm.movie.production_companies_name.push(vm.movie.production_companies[i].name); vm.movie.production_companies_name.sort(); } for (var i = 0; i <= vm.movie.production_countries.length-1; i++) { vm.movie.production_countries_name.push(vm.movie.production_countries[i].name); vm.movie.production_countries_name.sort(); } }); }, link: function(scope, elm, attrs) { } }; } angular.module('movieDetailDirective', ['services.movieDetail']) .directive('movieDetail', movieDetail); })();
gonzalesm/AngularProject
client/src/app/movieDetail/directive.js
JavaScript
mit
1,513
/* See license.txt for terms of usage */ require.def("domplate/toolTip", [ "domplate/domplate", "core/lib", "core/trace" ], function(Domplate, Lib, Trace) { with (Domplate) { // ************************************************************************************************ // Globals var mouseEvents = "mousemove mouseover mousedown click mouseout"; var currentToolTip = null; // ************************************************************************************************ // Tooltip function ToolTip() { this.element = null; } ToolTip.prototype = domplate( { tag: DIV({"class": "toolTip"}, DIV() ), show: function(target, options) { if (currentToolTip) currentToolTip.hide(); this.target = target; this.addListeners(); // Render the tooltip. var body = Lib.getBody(document); this.element = this.tag.append({options: options}, body, this); // Compute coordinates and show. var box = Lib.getElementBox(this.target); this.element.style.top = box.top + box.height + "px"; this.element.style.left = box.left + box.width + "px"; this.element.style.display = "block"; currentToolTip = this; return this.element; }, hide: function() { if (!this.element) return; this.removeListeners(); // Remove UI this.element.parentNode.removeChild(this.element); currentToolTip = this.element = null; }, addListeners: function() { this.onMouseEvent = Lib.bind(this.onMouseEvent, this); // Register listeners for all mouse events. $(document).bind(mouseEvents, this.onMouseEvent, true); }, removeListeners: function() { // Remove listeners for mouse events. $(document).unbind(mouseEvents, this.onMouseEvent, this, true); }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // // Listeners onMouseEvent: function(event) { var e = Lib.fixEvent(event); // If the mouse is hovering within the tooltip pass the event further to it. var ancestor = Lib.getAncestorByClass(e.target, "toolTip"); if (ancestor) return; var x = event.clientX, y = event.clientY; var box = Lib.getElementBox(this.element); if (event.type != "click" && event.type != "mousedown") box = Lib.inflateRect(box, 10, 10); // If the mouse is hovering within near neighbourhood, ignore it. if (Lib.pointInRect(box, x, y)) { Lib.cancelEvent(e); return; } // If the mouse is hovering over the target, ignore it too. if (Lib.isAncestor(e.target, this.target)) { Lib.cancelEvent(e); return; } // The mouse is hovering far away, let's destroy the the tooltip. this.hide(); Lib.cancelEvent(e); } }); // ************************************************************************************************ return ToolTip; // **********************************************************************************************// }});
modjs/mod-pageload-reporter
harviewer/scripts/domplate/toolTip.js
JavaScript
mit
3,280
import robot from 'robotjs' import sleep from 'sleep' import orifice from './fc8_orifice_map.json' var fs = require('fs') /*//set speed robot.setKeyboardDelay(150) robot.setMouseDelay(100)*/ let type = [ "Orifice", "Venturi", "Nozzle", "Fixed Geometry", "V-Cone", "Segmental Meters", "Linear Meters" ] exports.startFC8 = function(){ robot.keyTap('command') robot.typeString('FC8') sleep.msleep(500) robot.keyTap('enter') sleep.msleep(500) } exports.selectType = function(request){ robot.keyTap('tab') let i = 0 for(i=0; i<type.indexOf(request); i++){ robot.keyTap('down') } robot.keyTap('tab') robot.keyTap('enter') } exports.autoCompileGas = function(){ let i = 0 for(i=0; i<9; i++){ robot.keyTap('tab') } robot.keyTap('enter') for(i=0; i<7; i++){ robot.keyTap('tab') } robot.keyTap('enter') robot.keyTap('enter') robot.keyTap('tab') robot.keyTap('tab') robot.keyTap('enter') robot.keyTap('enter') } exports.calculation = function(object) { //select dp flow size let i = 0 if(object.method == "dp"){ robot.keyTap('enter') for(i=0; i<10; i++){ robot.keyTap('delete') } robot.typeString(object.base.dp.percMaxFlow) robot.keyTap('tab') for(i=0; i<10; i++){ robot.keyTap('delete') } robot.typeString(object.base.dp.maxFlow) robot.keyTap('tab') for(i=0; i<10; i++){ robot.keyTap('delete') } robot.typeString(object.base.dp.normalFlow) robot.keyTap('tab') for(i=0; i<10; i++){ robot.keyTap('delete') } robot.typeString(object.base.pipeDiameter) robot.keyTap('tab') for(i=0; i<10; i++){ robot.keyTap('delete') } robot.typeString(object.base.borePrimaryElement) robot.keyTap('tab') robot.keyTap('enter') } else if (object.method == "flow"){ robot.keyTap('tab') robot.keyTap('enter') robot.keyTap('tab') robot.keyTap('tab') for(i=0; i<10; i++){ robot.keyTap('delete') } robot.typeString(object.base.flow.differentialPressure) robot.keyTap('tab') for(i=0; i<10; i++){ robot.keyTap('delete') } robot.typeString(object.base.pipeDiameter) robot.keyTap('tab') for(i=0; i<10; i++){ robot.keyTap('delete') } robot.typeString(object.base.borePrimaryElement) robot.keyTap('tab') robot.keyTap('tab') robot.keyTap('enter') } else if (object.method == "size"){ robot.keyTap('tab') robot.keyTap('tab') robot.keyTap('enter') robot.keyTap('tab') robot.keyTap('tab') /*for(i=0; i<10; i++){ robot.keyTap('delete') } robot.typeString(object.base.size.percMaxFlow)*/ robot.keyTap('tab') for(i=0; i<10; i++){ robot.keyTap('delete') } robot.typeString(object.base.size.maxFlow) robot.keyTap('tab') for(i=0; i<10; i++){ robot.keyTap('delete') } robot.typeString(object.base.size.normalFlow) robot.keyTap('tab') for(i=0; i<10; i++){ robot.keyTap('delete') } robot.typeString(object.base.size.differential) robot.keyTap('tab') for(i=0; i<10; i++){ robot.keyTap('delete') } robot.typeString(object.base.pipeDiameter) robot.keyTap('tab') robot.keyTap('tab') robot.keyTap('enter') } if(object.checkVentDrainHole!="off"){ /* robot.keyTap('tab') robot.keyTap('tab') let ind = orifice.FlangeTaps.VentDrainHole.indexOf(object.ventDrainHole) let indStd = orifice.FlangeTaps.VentDrainHole.indexOf('No Vent/Drain Hole') if(ind<indStd){ for (i=0; i<indStd-ind; i++){ robot.keyTap('up') } } else { for (i=0; i<ind-indStd; i++){ robot.keyTap('down') } }*/ if(object.ventDrainHole=="FC8"){ robot.keyTap('enter') } else if (object.ventDrainHole=="userdefined"){ robot.keyTap('tab') robot.keyTap('tab') for(i=0;i<17;i++){ robot.keyTap('down') } robot.typeString(object.userDefinedDiameters) robot.keyTap('tab') robot.keyTap('enter') robot.keyTap('tab') robot.keyTap('enter') } for(i=0; i<2; i++){ robot.keyTap('tab', 'shift') } } } exports.printPDF = function(fileName, customer, tag){ let i=0 robot.keyTap('enter') for(i=0; i<7; i++){ robot.keyTap('tab') } for(i=0; i<10; i++){ robot.keyTap('delete') } robot.typeString(customer) robot.keyTap('tab') robot.keyTap('tab') robot.typeString(tag) for(i=0; i<15; i++){ robot.keyTap('tab') } robot.keyTap('enter') sleep.msleep(500) robot.typeString(fileName) robot.keyTap('enter') sleep.msleep(500) } exports.existFile = function (fileName, errors) { fs.exists('../Documents/'+fileName, function(exists) { if(!exists){ errors.push(fileName) console.log(fileName, "ha presentato un errore") console.log(errors) } }); }
volcano-group/desktop-automata
fc8_helpers.js
JavaScript
mit
5,602
/** * Simple re-export of frost-detail-tabs-more-tabs in the app namespace */ export {default} from 'ember-frost-tabs/components/frost-detail-tabs-more-tabs'
ciena-frost/ember-frost-tabs
app/components/frost-detail-tabs-more-tabs.js
JavaScript
mit
160
'use strict'; /** * Module dependencies */ var citiesPolicy = require('../policies/cities.server.policy'), cities = require('../controllers/cities.server.controller'); module.exports = function (app) { // City collection routes app.route('/api/cities').all(citiesPolicy.isAllowed) .get(cities.list) .post(cities.create); // Single city routes app.route('/api/cities/:cityId').all(citiesPolicy.isAllowed) .get(cities.read) .put(cities.update) .delete(cities.delete); // Finish by binding the city middleware app.param('cityId', cities.cityByID); };
ravikumargh/Infy
modules/cities/server/routes/cities.server.routes.js
JavaScript
mit
588
(function( factory ) { if ( typeof define === "function" && define.amd ) { define( ["jquery", "../jquery.validate"], factory ); } else if (typeof exports === "object") { factory(require("jquery")); } else { factory( jQuery ); } }(function( $ ) { /* * Translated default messages for the jQuery validation plugin. * Locale: ET (Estonian; eesti, eesti keel) */ $.extend($.validator.messages, { required: "See väli peab olema täidetud.", maxlength: $.validator.format("Palun sisestage vähem kui {0} tähemärki."), minlength: $.validator.format("Palun sisestage vähemalt {0} tähemärki."), rangelength: $.validator.format("Palun sisestage väärtus vahemikus {0} kuni {1} tähemärki."), email: "Palun sisestage korrektne e-maili aadress.", url: "Palun sisestage korrektne URL.", date: "Palun sisestage korrektne kuupäev.", dateISO: "Palun sisestage korrektne kuupäev (YYYY-MM-DD).", number: "Palun sisestage korrektne number.", digits: "Palun sisestage ainult numbreid.", equalTo: "Palun sisestage sama väärtus uuesti.", range: $.validator.format("Palun sisestage väärtus vahemikus {0} kuni {1}."), max: $.validator.format("Palun sisestage väärtus, mis on väiksem või võrdne arvuga {0}."), min: $.validator.format("Palun sisestage väärtus, mis on suurem või võrdne arvuga {0}."), creditcard: "Palun sisestage korrektne krediitkaardi number." }); }));
Badalik/jquery-validation
dist/localization/messages_et.js
JavaScript
mit
1,398
import { TASK_STATUS_ACTIVE, TASK_STATUS_COMPLETED } from 'modules/task/constants'; export class RouterService { constructor($state, $stateParams) { this.state = $state; this.params = $stateParams; } isActiveTasks() { return this.state.is('app.tasks', {filter: TASK_STATUS_ACTIVE}); } isCompletedTasks() { return this.state.is('app.tasks', {filter: TASK_STATUS_COMPLETED}); } isTasks() { return this.state.is('app.tasks', {filter: ''}); } toActiveTasks() { return this.state.go('app.tasks', {filter: TASK_STATUS_ACTIVE}); } toCompletedTasks() { return this.state.go('app.tasks', {filter: TASK_STATUS_COMPLETED}); } toTasks() { return this.state.go('app.tasks'); } }
r-park/todo-angular-rx
src/modules/router/router-service.js
JavaScript
mit
738
module.exports = { description: 'deconflict entry points with the same name in different directories', command: 'rollup --input main.js --input sub/main.js --format esm --dir _actual --experimentalCodeSplitting' };
corneliusweig/rollup
test/cli/samples/deconflict-entry-point-in-subdir/_config.js
JavaScript
mit
219
/** * xDo app client * * Auther: vs4vijay@gmail.com */ var app = angular.module('app', ['ngResource']); app.controller('AppCtrl', ['$scope', function($scope) { // Parent controller for all the Ctrls $scope.appModel = {} }]); // Can define config block here or use ngRoute
vs4vijay/xdo
xdo-rails/public/spa/app/app.js
JavaScript
mit
281
/** * @module creatine.transitions **/ (function() { "use strict"; /** * A transition effect to scroll the new scene. * * ## Usage example * * var game = new tine.Game(null, { * create: function() { * var transition = new tine.transitions.Scroll(tine.TOP, null, 1000); * game.replace(new MyScene(), transition); * } * }); * * @class Scroll * @constructor * @param {Constant} [direction=creatine.LEFT] The direction. * @param {Function} [ease=createjs.Ease.linear] An easing function from * `createjs.Ease` (provided by TweenJS). * @param {Number} [time=400] The transition time in milliseconds. **/ var Scroll = function(direction, ease, time) { /** * Direction of the effect. * @property direction * @type {Constant} **/ this.direction = direction || creatine.LEFT; /** * An Easing function from createjs.Ease. * @property ease * @type {Function} **/ this.ease = ease || createjs.Ease.linear; /** * The transition time in milliseconds. * @property time * @type {Number} **/ this.time = time || 400; } var p = Scroll.prototype; /** * Initialize the transition (called by the director). * @method start * @param {Director} director The Director instance. * @param {Scene} outScene The active scene. * @param {Scene} inScene The incoming scene. * @param {Function} callback The callback function called when the * transition is done. * @protected **/ p.start = function(director, outScene, inScene, callback) { this.director = director; this.outScene = outScene; this.inScene = inScene; this.callback = callback; var w = director.stage.canvas.width; var h = director.stage.canvas.height; var dir = this.direction; this.targetX = 0; this.targetY = 0; inScene.x = 0; inScene.y = 0; switch (this.direction) { case creatine.LEFT: inScene.x = w; this.targetX = -w; break; case creatine.RIGHT: inScene.x = -w; this.targetX = w; break; case creatine.TOP: inScene.y = h; this.targetY = -h; break; case creatine.BOTTOM: inScene.y = -h; this.targetY = h; break; } var self = this; createjs.Tween.get(inScene, {override:true}) .to({x:0, y:0}, this.time, this.ease) .call(function() { self.complete(); }) createjs.Tween.get(outScene, {override:true}) .to({x:this.targetX, y:this.targetY}, this.time, this.ease) } /** * Finalize the transition (called by the director). * @method complete * @protected **/ p.complete = function() { createjs.Tween.removeTweens(this.inScene); createjs.Tween.removeTweens(this.outScene); this.inScene.x = 0; this.inScene.x = 0; this.outScene.x = 0; this.outScene.y = 0; this.callback(); } creatine.transitions.Scroll = Scroll; }());
renatopp/creatine
src/scenes/transitions/Scroll.js
JavaScript
mit
3,100
function Test() { a = 1; console.log(a); try { console.log(b); } catch (e) { console.log("null"); } } console.log("Test1"); Test(); a = 2; b = 3; console.log("Test2"); Test(); Test.a = 4; Test.b = 4; console.log("Test3"); Test(); console.log("Test4"); console.log(Test.a); console.log(Test.b);
colinw7/CJavaScript
data/function2.js
JavaScript
mit
322
// All code points in the `Sc` category as per Unicode v6.3.0: [ 0x24, 0xA2, 0xA3, 0xA4, 0xA5, 0x58F, 0x60B, 0x9F2, 0x9F3, 0x9FB, 0xAF1, 0xBF9, 0xE3F, 0x17DB, 0x20A0, 0x20A1, 0x20A2, 0x20A3, 0x20A4, 0x20A5, 0x20A6, 0x20A7, 0x20A8, 0x20A9, 0x20AA, 0x20AB, 0x20AC, 0x20AD, 0x20AE, 0x20AF, 0x20B0, 0x20B1, 0x20B2, 0x20B3, 0x20B4, 0x20B5, 0x20B6, 0x20B7, 0x20B8, 0x20B9, 0x20BA, 0xA838, 0xFDFC, 0xFE69, 0xFF04, 0xFFE0, 0xFFE1, 0xFFE5, 0xFFE6 ];
mathiasbynens/unicode-data
6.3.0/categories/Sc-code-points.js
JavaScript
mit
489
var should = require('should'), supertest = require('supertest'), testUtils = require('../../../utils/index'), localUtils = require('./utils'), config = require('../../../../server/config/index'), ghost = testUtils.startGhost, request; describe('Slug API', function () { var accesstoken = '', ghostServer; before(function () { return ghost() .then(function (_ghostServer) { ghostServer = _ghostServer; request = supertest.agent(config.get('url')); }) .then(function () { return localUtils.doAuth(request); }) .then(function (token) { accesstoken = token; }); }); it('should be able to get a post slug', function (done) { request.get(localUtils.API.getApiQuery('slugs/post/a post title/')) .set('Authorization', 'Bearer ' + accesstoken) .expect('Content-Type', /json/) .expect('Cache-Control', testUtils.cacheRules.private) .expect(200) .end(function (err, res) { if (err) { return done(err); } should.not.exist(res.headers['x-cache-invalidate']); var jsonResponse = res.body; should.exist(jsonResponse); should.exist(jsonResponse.slugs); jsonResponse.slugs.should.have.length(1); localUtils.API.checkResponse(jsonResponse.slugs[0], 'slug'); jsonResponse.slugs[0].slug.should.equal('a-post-title'); done(); }); }); it('should be able to get a tag slug', function (done) { request.get(localUtils.API.getApiQuery('slugs/post/atag/')) .set('Authorization', 'Bearer ' + accesstoken) .expect('Content-Type', /json/) .expect('Cache-Control', testUtils.cacheRules.private) .expect(200) .end(function (err, res) { if (err) { return done(err); } should.not.exist(res.headers['x-cache-invalidate']); var jsonResponse = res.body; should.exist(jsonResponse); should.exist(jsonResponse.slugs); jsonResponse.slugs.should.have.length(1); localUtils.API.checkResponse(jsonResponse.slugs[0], 'slug'); jsonResponse.slugs[0].slug.should.equal('atag'); done(); }); }); it('should be able to get a user slug', function (done) { request.get(localUtils.API.getApiQuery('slugs/user/user name/')) .set('Authorization', 'Bearer ' + accesstoken) .expect('Content-Type', /json/) .expect('Cache-Control', testUtils.cacheRules.private) .expect(200) .end(function (err, res) { if (err) { return done(err); } should.not.exist(res.headers['x-cache-invalidate']); var jsonResponse = res.body; should.exist(jsonResponse); should.exist(jsonResponse.slugs); jsonResponse.slugs.should.have.length(1); localUtils.API.checkResponse(jsonResponse.slugs[0], 'slug'); jsonResponse.slugs[0].slug.should.equal('user-name'); done(); }); }); it('should be able to get an app slug', function (done) { request.get(localUtils.API.getApiQuery('slugs/app/cool app/')) .set('Authorization', 'Bearer ' + accesstoken) .expect('Content-Type', /json/) .expect('Cache-Control', testUtils.cacheRules.private) .expect(200) .end(function (err, res) { if (err) { return done(err); } should.not.exist(res.headers['x-cache-invalidate']); var jsonResponse = res.body; should.exist(jsonResponse); should.exist(jsonResponse.slugs); jsonResponse.slugs.should.have.length(1); localUtils.API.checkResponse(jsonResponse.slugs[0], 'slug'); jsonResponse.slugs[0].slug.should.equal('cool-app'); done(); }); }); it('should not be able to get a slug for an unknown type', function (done) { request.get(localUtils.API.getApiQuery('slugs/unknown/who knows/')) .set('Authorization', 'Bearer ' + accesstoken) .set('Accept', 'application/json') .expect('Content-Type', /json/) .expect('Cache-Control', testUtils.cacheRules.private) .expect(400) .end(function (err, res) { if (err) { return done(err); } var jsonResponse = res.body; should.exist(jsonResponse.errors); done(); }); }); });
Gargol/Ghost
core/test/regression/api/v0.1/slugs_spec.js
JavaScript
mit
5,073
function Grid(size) { this.size = size; this.startTiles = 2; this.cells = []; this.build(); this.playerTurn = true; } // pre-allocate these objects (for speed) Grid.prototype.indexes = []; for (var x=0; x<4; x++) { Grid.prototype.indexes.push([]); for (var y=0; y<4; y++) { Grid.prototype.indexes[x].push( {x:x, y:y} ); } } // Build a grid of the specified size Grid.prototype.build = function () { for (var x = 0; x < this.size; x++) { var row = this.cells[x] = []; for (var y = 0; y < this.size; y++) { row.push(null); } } }; // Find the first available random position Grid.prototype.randomAvailableCell = function () { var cells = this.availableCells(); if (cells.length) { return cells[Math.floor(Math.random() * cells.length)]; } }; Grid.prototype.availableCells = function () { var cells = []; var self = this; this.eachCell(function (x, y, tile) { if (!tile) { //cells.push(self.indexes[x][y]); cells.push( {x:x, y:y} ); } }); return cells; }; // Call callback for every cell Grid.prototype.eachCell = function (callback) { for (var x = 0; x < this.size; x++) { for (var y = 0; y < this.size; y++) { callback(x, y, this.cells[x][y]); } } }; // Check if there are any cells available Grid.prototype.cellsAvailable = function () { return !!this.availableCells().length; }; // Check if the specified cell is taken Grid.prototype.cellAvailable = function (cell) { return !this.cellOccupied(cell); }; Grid.prototype.cellOccupied = function (cell) { return !!this.cellContent(cell); }; Grid.prototype.cellContent = function (cell) { if (this.withinBounds(cell)) { return this.cells[cell.x][cell.y]; } else { return null; } }; // Inserts a tile at its position Grid.prototype.insertTile = function (tile) { this.cells[tile.x][tile.y] = tile; }; Grid.prototype.removeTile = function (tile) { this.cells[tile.x][tile.y] = null; }; Grid.prototype.withinBounds = function (position) { return position.x >= 0 && position.x < this.size && position.y >= 0 && position.y < this.size; }; Grid.prototype.clone = function() { newGrid = new Grid(this.size); newGrid.playerTurn = this.playerTurn; for (var x = 0; x < this.size; x++) { for (var y = 0; y < this.size; y++) { if (this.cells[x][y]) { newGrid.insertTile(this.cells[x][y].clone()); } } } return newGrid; }; // Set up the initial tiles to start the game with Grid.prototype.addStartTiles = function () { for (var i=0; i<this.startTiles; i++) { this.addRandomTile(); } }; // Adds a tile in a random position Grid.prototype.addRandomTile = function () { if (this.cellsAvailable()) { var value = Math.random() < 0.9 ? 2 : 4; //var value = Math.random() < 0.9 ? 256 : 512; var tile = new Tile(this.randomAvailableCell(), value); this.insertTile(tile); } }; // Save all tile positions and remove merger info Grid.prototype.prepareTiles = function () { this.eachCell(function (x, y, tile) { if (tile) { tile.mergedFrom = null; tile.savePosition(); } }); }; // Move a tile and its representation Grid.prototype.moveTile = function (tile, cell) { this.cells[tile.x][tile.y] = null; this.cells[cell.x][cell.y] = tile; tile.updatePosition(cell); }; Grid.prototype.vectors = { 0: { x: 0, y: -1 }, // up 1: { x: 1, y: 0 }, // right 2: { x: 0, y: 1 }, // down 3: { x: -1, y: 0 } // left } // Get the vector representing the chosen direction Grid.prototype.getVector = function (direction) { // Vectors representing tile movement return this.vectors[direction]; }; // Move tiles on the grid in the specified direction // returns true if move was successful Grid.prototype.move = function (direction) { // 0: up, 1: right, 2:down, 3: left var self = this; var cell, tile; var vector = this.getVector(direction); var traversals = this.buildTraversals(vector); var moved = false; var score = 0; var won = false; // Save the current tile positions and remove merger information this.prepareTiles(); // Traverse the grid in the right direction and move tiles traversals.x.forEach(function (x) { traversals.y.forEach(function (y) { cell = self.indexes[x][y]; tile = self.cellContent(cell); if (tile) { //if (debug) { //console.log('tile @', x, y); //} var positions = self.findFarthestPosition(cell, vector); var next = self.cellContent(positions.next); // Only one merger per row traversal? if (next && next.value === tile.value && !next.mergedFrom) { var merged = new Tile(positions.next, tile.value * 2); merged.mergedFrom = [tile, next]; self.insertTile(merged); self.removeTile(tile); // Converge the two tiles' positions tile.updatePosition(positions.next); // Update the score score += merged.value; // The mighty 2048 tile if (merged.value === 2048) { won = true; } } else { //if (debug) { //console.log(cell); //console.log(tile); //} self.moveTile(tile, positions.farthest); } if (!self.positionsEqual(cell, tile)) { self.playerTurn = false; //console.log('setting player turn to ', self.playerTurn); moved = true; // The tile moved from its original cell! } } }); }); //console.log('returning, playerturn is', self.playerTurn); //if (!moved) { //console.log('cell', cell); //console.log('tile', tile); //console.log('direction', direction); //console.log(this.toString()); //} return {moved: moved, score: score, won: won}; }; Grid.prototype.computerMove = function() { this.addRandomTile(); this.playerTurn = true; } // Build a list of positions to traverse in the right order Grid.prototype.buildTraversals = function (vector) { var traversals = { x: [], y: [] }; for (var pos = 0; pos < this.size; pos++) { traversals.x.push(pos); traversals.y.push(pos); } // Always traverse from the farthest cell in the chosen direction if (vector.x === 1) traversals.x = traversals.x.reverse(); if (vector.y === 1) traversals.y = traversals.y.reverse(); return traversals; }; Grid.prototype.findFarthestPosition = function (cell, vector) { var previous; // Progress towards the vector direction until an obstacle is found do { previous = cell; cell = { x: previous.x + vector.x, y: previous.y + vector.y }; } while (this.withinBounds(cell) && this.cellAvailable(cell)); return { farthest: previous, next: cell // Used to check if a merge is required }; }; Grid.prototype.movesAvailable = function () { return this.cellsAvailable() || this.tileMatchesAvailable(); }; // Check for available matches between tiles (more expensive check) // returns the number of matches Grid.prototype.tileMatchesAvailable = function () { var self = this; //var matches = 0; var tile; for (var x = 0; x < this.size; x++) { for (var y = 0; y < this.size; y++) { tile = this.cellContent({ x: x, y: y }); if (tile) { for (var direction = 0; direction < 4; direction++) { var vector = self.getVector(direction); var cell = { x: x + vector.x, y: y + vector.y }; var other = self.cellContent(cell); if (other && other.value === tile.value) { return true; //matches++; // These two tiles can be merged } } } } } //console.log(matches); return false; //matches; }; Grid.prototype.positionsEqual = function (first, second) { return first.x === second.x && first.y === second.y; }; Grid.prototype.toString = function() { string = ''; for (var i=0; i<4; i++) { for (var j=0; j<4; j++) { if (this.cells[j][i]) { string += this.cells[j][i].value + ' '; } else { string += '_ '; } } string += '\n'; } return string; } // counts the number of isolated groups. Grid.prototype.islands = function() { var self = this; var mark = function(x, y, value) { if (x >= 0 && x <= 3 && y >= 0 && y <= 3 && self.cells[x][y] && self.cells[x][y].value == value && !self.cells[x][y].marked ) { self.cells[x][y].marked = true; for (direction in [0,1,2,3]) { var vector = self.getVector(direction); mark(x + vector.x, y + vector.y, value); } } } var islands = 0; for (var x=0; x<4; x++) { for (var y=0; y<4; y++) { if (this.cells[x][y]) { this.cells[x][y].marked = false } } } for (var x=0; x<4; x++) { for (var y=0; y<4; y++) { if (this.cells[x][y] && !this.cells[x][y].marked) { islands++; mark(x, y , this.cells[x][y].value); } } } return islands; } /// measures how smooth the grid is (as if the values of the pieces // were interpreted as elevations). Sums of the pairwise difference // between neighboring tiles (in log space, so it represents the // number of merges that need to happen before they can merge). // Note that the pieces can be distant Grid.prototype.smoothness = function() { var smoothness = 0; for (var x=0; x<4; x++) { for (var y=0; y<4; y++) { if ( this.cellOccupied( this.indexes[x][y] )) { var value = Math.log(this.cellContent( this.indexes[x][y] ).value) / Math.log(2); for (var direction=1; direction<=2; direction++) { var vector = this.getVector(direction); var targetCell = this.findFarthestPosition(this.indexes[x][y], vector).next; if (this.cellOccupied(targetCell)) { var target = this.cellContent(targetCell); var targetValue = Math.log(target.value) / Math.log(2); smoothness -= Math.abs(value - targetValue); } } } } } return smoothness; } Grid.prototype.monotonicity = function() { var self = this; var marked = []; var queued = []; var highestValue = 0; var highestCell = {x:0, y:0}; for (var x=0; x<4; x++) { marked.push([]); queued.push([]); for (var y=0; y<4; y++) { marked[x].push(false); queued[x].push(false); if (this.cells[x][y] && this.cells[x][y].value > highestValue) { highestValue = this.cells[x][y].value; highestCell.x = x; highestCell.y = y; } } } increases = 0; cellQueue = [highestCell]; queued[highestCell.x][highestCell.y] = true; markList = [highestCell]; markAfter = 1; // only mark after all queued moves are done, as if searching in parallel var markAndScore = function(cell) { markList.push(cell); var value; if (self.cellOccupied(cell)) { value = Math.log(self.cellContent(cell).value) / Math.log(2); } else { value = 0; } for (direction in [0,1,2,3]) { var vector = self.getVector(direction); var target = { x: cell.x + vector.x, y: cell.y+vector.y } if (self.withinBounds(target) && !marked[target.x][target.y]) { if ( self.cellOccupied(target) ) { targetValue = Math.log(self.cellContent(target).value ) / Math.log(2); if ( targetValue > value ) { //console.log(cell, value, target, targetValue); increases += targetValue - value; } } if (!queued[target.x][target.y]) { cellQueue.push(target); queued[target.x][target.y] = true; } } } if (markAfter == 0) { while (markList.length > 0) { var cel = markList.pop(); marked[cel.x][cel.y] = true; } markAfter = cellQueue.length; } } while (cellQueue.length > 0) { markAfter--; markAndScore(cellQueue.shift()) } return -increases; } // measures how monotonic the grid is. This means the values of the tiles are strictly increasing // or decreasing in both the left/right and up/down directions Grid.prototype.monotonicity2 = function() { // scores for all four directions var totals = [0, 0, 0, 0]; // up/down direction for (var x=0; x<4; x++) { var current = 0; var next = current+1; while ( next<4 ) { while ( next<4 && !this.cellOccupied( this.indexes[x][next] )) { next++; } if (next>=4) { next--; } var currentValue = this.cellOccupied({x:x, y:current}) ? Math.log(this.cellContent( this.indexes[x][current] ).value) / Math.log(2) : 0; var nextValue = this.cellOccupied({x:x, y:next}) ? Math.log(this.cellContent( this.indexes[x][next] ).value) / Math.log(2) : 0; if (currentValue > nextValue) { totals[0] += nextValue - currentValue; } else if (nextValue > currentValue) { totals[1] += currentValue - nextValue; } current = next; next++; } } // left/right direction for (var y=0; y<4; y++) { var current = 0; var next = current+1; while ( next<4 ) { while ( next<4 && !this.cellOccupied( this.indexes[next][y] )) { next++; } if (next>=4) { next--; } var currentValue = this.cellOccupied({x:current, y:y}) ? Math.log(this.cellContent( this.indexes[current][y] ).value) / Math.log(2) : 0; var nextValue = this.cellOccupied({x:next, y:y}) ? Math.log(this.cellContent( this.indexes[next][y] ).value) / Math.log(2) : 0; if (currentValue > nextValue) { totals[2] += nextValue - currentValue; } else if (nextValue > currentValue) { totals[3] += currentValue - nextValue; } current = next; next++; } } return Math.max(totals[0], totals[1]) + Math.max(totals[2], totals[3]); } Grid.prototype.maxValue = function() { var max = 0; for (var x=0; x<4; x++) { for (var y=0; y<4; y++) { if (this.cellOccupied(this.indexes[x][y])) { var value = this.cellContent(this.indexes[x][y]).value; if (value > max) { max = value; } } } } return Math.log(max) / Math.log(2); } // WIP. trying to favor top-heavy distributions (force consolidation of higher value tiles) /* Grid.prototype.valueSum = function() { var valueCount = []; for (var i=0; i<11; i++) { valueCount.push(0); } for (var x=0; x<4; x++) { for (var y=0; y<4; y++) { if (this.cellOccupied(this.indexes[x][y])) { valueCount[Math.log(this.cellContent(this.indexes[x][y]).value) / Math.log(2)]++; } } } var sum = 0; for (var i=1; i<11; i++) { sum += valueCount[i] * Math.pow(2, i) + i; } return sum; } */ // check for win Grid.prototype.isWin = function() { var self = this; for (var x=0; x<4; x++) { for (var y=0; y<4; y++) { if (self.cellOccupied(this.indexes[x][y])) { if (self.cellContent(this.indexes[x][y]).value == 2048) { return true; } } } } return false; } //Grid.prototype.zobristTable = {} //for //Grid.prototype.hash = function() { //}
Kelly27/my2048
js/grid.js
JavaScript
mit
15,249
/* * Favorites * Favorites landing page */ import React, { Component } from 'react' import NavBar from '../NavBar.react' export default class Favorites extends Component { render() { return ( <div> <div className="p2 overflow-scroll mt4 mb4"> <div className="center mb3"> <button className="btn bg-purple-3 white regular py1 px3">Import from Spotify</button> </div> <div className="h6 caps white">Your favorites</div> <div className="border-bottom border-muted py2 mrn2 relative"> <div className="white h4 mb1">Let's Dance</div> <div className="white muted h6 semibold">David Bowie</div> <span className="white absolute right-0 h2 mr3" style={{top: '23px'}}> <span className="inline-block h6 bg-teal rounded mr2 relative" style={{padding: '3px 12px', top: '-3px'}}>5 events</span> › </span> </div> <div className="border-bottom border-muted py2 mrn2 relative"> <div className="white h4 mb1">Lazarus</div> <div className="white muted h6 semibold">David Bowie</div> <span className="white absolute right-0 h2 mr3" style={{top: '23px'}}> <span className="inline-block h6 bg-teal rounded mr2 relative" style={{padding: '3px 12px', top: '-3px'}}>5 events</span> › </span> </div> <div className="border-bottom border-muted py2 mrn2 relative"> <div className="white h4 mb1">Let's Dance</div> <div className="white muted h6 semibold">David Bowie</div> <span className="white absolute right-0 h2 mr3" style={{top: '23px'}}> <span className="inline-block h6 bg-teal rounded mr2 relative" style={{padding: '3px 12px', top: '-3px'}}>5 events</span> › </span> </div> <div className="border-bottom border-muted py2 mrn2 relative"> <div className="white h4 mb1">Lazarus</div> <div className="white muted h6 semibold">David Bowie</div> <span className="white absolute right-0 h2 mr3" style={{top: '23px'}}> <span className="inline-block h6 bg-teal rounded mr2 relative" style={{padding: '3px 12px', top: '-3px'}}>5 events</span> › </span> </div> <div className="border-bottom border-muted py2 mrn2 relative"> <div className="white h4 mb1">Let's Dance</div> <div className="white muted h6 semibold">David Bowie</div> <span className="white absolute right-0 h2 mr3" style={{top: '23px'}}> <span className="inline-block h6 bg-teal rounded mr2 relative" style={{padding: '3px 12px', top: '-3px'}}>5 events</span> › </span> </div> <div className="border-bottom border-muted py2 mrn2 relative"> <div className="white h4 mb1">Lazarus</div> <div className="white muted h6 semibold">David Bowie</div> <span className="white absolute right-0 h2 mr3" style={{top: '23px'}}> <span className="inline-block h6 bg-teal rounded mr2 relative" style={{padding: '3px 12px', top: '-3px'}}>5 events</span> › </span> </div> <div className="border-bottom border-muted py2 mrn2 relative"> <div className="white h4 mb1">Let's Dance</div> <div className="white muted h6 semibold">David Bowie</div> <span className="white absolute right-0 h2 mr3" style={{top: '23px'}}> <span className="inline-block h6 bg-teal rounded mr2 relative" style={{padding: '3px 12px', top: '-3px'}}>5 events</span> › </span> </div> <div className="border-bottom border-muted py2 mrn2 relative"> <div className="white h4 mb1">Lazarus</div> <div className="white muted h6 semibold">David Bowie</div> <span className="white absolute right-0 h2 mr3" style={{top: '23px'}}> <span className="inline-block h6 bg-teal rounded mr2 relative" style={{padding: '3px 12px', top: '-3px'}}>5 events</span> › </span> </div> </div> <NavBar activeTab="favorites"/> </div> ) } }
chexee/karaoke-night
js/components/pages/Favorites.react.js
JavaScript
mit
4,396
function generateList(people, template){ var i, result = '', len = people.length; result += '<ul>'; for(i = 0; i < len; i += 1){ result += '<li>'; result += template; result = result.replace('-{name}-', people[i]['name']); result = result.replace('-{age}-', people[i]['age']); result += '</li>'; } result += '</ul>'; return result; } var people = [ { name: 'Pehso', age: 20}, { name: 'Gosho', age: 30}, { name: 'Stamat', age: 25} ]; var template = document.getElementById('list-item').innerHTML; document.getElementById('list-item').innerHTML = generateList(people, template);
ni4ka7a/TelerikAcademyHomeworks
JavaScript-Fundamentals/09.Strings/12.GenerateList/script.js
JavaScript
mit
681
const admin = require('firebase-admin'); const DATABASE_URL = process.env.DATABASE_URL || 'https://dailyjack-8a930.firebaseio.com'; // const DATABASE_URL = 'https://dailyjack-d2fa0.firebaseio.com'; const jackDB = (config = {}) => { const app = admin.initializeApp({ credential: admin.credential.cert({ projectId: config.projectId, clientEmail: config.clientEmail, privateKey: config.privateKey, }), databaseURL: DATABASE_URL, }); const db = admin.database(); const jacksRef = db.ref('jacks'); const totalJacksRef = db.ref('totalJacks'); const usersRef = db.ref('users'); const insert = jack => ( jacksRef .child(jack.id) .set({ id: jack.id, title: jack.title, contents: jack.contents || [], author: jack.author || null, createdTime: Date.now(), isLimited: Boolean(jack.isLimited), isSpecial: Boolean(jack.isSpecial), }) .then(() => ( totalJacksRef.transaction(total => (total || 0) + 1) )) ); const filter = (jacks = [], filterOptions = {}) => jacks.filter( jack => (!filterOptions.shouldExcludeLimited || !jack.isLimited) && (!filterOptions.shouldExcludeSpecial || !jack.isSpecial) ); const all = (filterOptions = {}) => ( jacksRef.once('value') .then(snapshot => snapshot.val()) .then(jacks => (jacks || []).filter(Boolean)) .then(jacks => filter(jacks, filterOptions)) ); const get = id => ( jacksRef.child(id) .once('value') .then(snapshot => snapshot.val()) ); const random = (filterOptions = {}) => ( all(filterOptions) .then(jacks => jacks[Math.floor(Math.random() * jacks.length)]) ); const upvote = (id, user) => ( jacksRef.child(id) .child('ratedUsers') .child(user) .set(true) ); const downvote = (id, user) => ( jacksRef.child(id) .child('ratedUsers') .remove(user) ); const togglevote = (id, user) => ( jacksRef.child(id) .child('ratedUsers') .child(user) .transaction(rate => (rate ? null : true)) ); const getRate = id => ( jacksRef.child(id) .child('ratedUsers') .once('value') .then(snapshot => snapshot.val()) .then(rate => Object.keys(rate || {}) .filter(Boolean) .length ) ); const setUser = user => ( usersRef.child(user.name) .set(user) ); const updateUser = user => ( usersRef.child(user.name) .update(user) ); const getUser = userName => ( usersRef.child(userName) .once('value') .then(snapshot => snapshot.val()) ); const exit = () => { db.goOffline(); app.delete(); }; return { all, get, random, insert, exit, upvote, downvote, togglevote, getRate, setUser, updateUser, getUser, }; }; module.exports = { default: jackDB, };
kevin940726/dailyjack
packages/dailyjack-core/index.js
JavaScript
mit
2,926
//TODO : socket.ioコネクション処理を1.0推奨の非同期方式にする describe('serverクラスのテスト', function() { var SERVER_PORT = process.env.PORT || 3000; var SERVER_URL = 'http://localhost:'+SERVER_PORT; var assert = require('chai').assert; var io = require('socket.io-client'); var server = require('../../../server/server.js'); var http = require('http'); var dbMock = require('./../testData/dbMock.js')(); var app; var testServer; var option = { 'forceNew' : true }; beforeEach(function() { app = http.createServer().listen(SERVER_PORT); testServer = server({ httpServer : app, dao : dbMock }); }); afterEach(function() { app.close(); }); describe('退室系テスト',function(){ it('入室後に退室する',function(done){ var client = io(SERVER_URL, option); client.on('connect',doAuth); function doAuth() { client.emit('auth',{ userId : 'test001@gmail.com' }); client.once('successAuth',enterRoom); } function enterRoom() { client.emit('enterRoom',{ roomId : 0 }); client.on('succesEnterRoom',leaveRoom); } function leaveRoom() { client.emit('leaveRoom'); client.on('successLeaveRoom',done); } }); }); });
kaidouji85/gbraver
test/server/otherApi/serverLeavRoomTest.js
JavaScript
mit
1,559
// eslint-disable-next-line import/prefer-default-export export const serializePlaylist = model => ({ _id: model.id, name: model.name, author: model.author, createdAt: model.createdAt, description: model.description, shared: model.shared, nsfw: model.nsfw, size: model.media.length, });
u-wave/api-v1
src/utils/serialize.js
JavaScript
mit
303
class NotFoundError extends Error { constructor(message) { super(); if (Error.hasOwnProperty('captureStackTrace')) { Error.captureStackTrace(this, this.constructor); } else { Object.defineProperty(this, 'stack', { value : (new Error()).stack }); } Object.defineProperty(this, 'message', { value : message }); } get name() { return this.constructor.name; } } export default { NotFoundError }
CalebMorris/false-bookshelf
src/errors.js
JavaScript
mit
441
"use strict"; /* global describe it before */ const { assert } = require("chai"); const Database = require("./lib/database"); const testcases = (env) => { describe("Basic operations", () => { before(async () => { await Database.start(); }); it("should list zero objects", async () => { const list = await env.client.list("thing"); assert.isArray(list); assert.equal(list.length, 0); }); it("should create one object", async () => { const thing = await env.client.create("thing", { _id: "1", thingy: "Hello" }); assert.equal(thing.type, "scom.thing"); assert.equal(thing.thingy, "Hello"); }); it("should list one object", async () => { const list = await env.client.list("thing"); assert.isArray(list); assert.equal(list.length, 1); }); it("should update one object", async () => { const thing = await env.client.update("thing", "1", { thingy: "World" }); assert.equal(thing.type, "scom.thing"); assert.equal(thing.thingy, "World"); }); it("should delete one object", async () => { const thing = await env.client.remove("thing", "1"); assert.equal(thing.type, "scom.thing"); assert.equal(thing.thingy, "World"); }); it("should list zero objects", async () => { const list = await env.client.list("thing"); assert.isArray(list); assert.equal(list.length, 0); }); }); describe("Action operations", () => { before(async () => { await Database.start(); }); it("should create an object and tag it", async () => { await env.client.create("thing", { _id: "1", thingy: "Hello" }); const thing2 = await env.client.tag("thing", "1", { tag: [ "tag1", "tag2" ] }); assert.equal(thing2.type, "scom.thing"); assert.equal(thing2.thingy, "Hello"); assert.deepEqual(thing2.tags, [ "tag1", "tag2" ]); }); it("should get error with invalid action", async () => { try { await env.client.stuff("thing", "1", { 1: 0 }); assert(false, "Should have thrown"); } catch (error) { assert.equal(error.status, 400); } }); }); describe("Getter operations", () => { before(async () => { await Database.start(); }); it("should create an object and get something on it", async () => { await env.client.create("thing", { _id: "1", thingy: "Hello" }); const value = await env.client.thingy("thing", "1"); assert.equal(value, "Hello"); }); it("should get error with invalid getter", async () => { try { await env.client.stuff("thing", "1"); assert(false, "Should have thrown"); } catch (error) { assert.equal(error.status, 400); } }); }); }; module.exports = testcases;
Combitech/codefarm
src/lib/servicecom/test/testcases.js
JavaScript
mit
3,396
var fs = require('fs') var parseTorrent = require('parse-torrent') var test = require('tape') var WebTorrent = require('../') var DHT = require('bittorrent-dht/client') var parallel = require('run-parallel') var bufferEqual = require('buffer-equal') var leaves = fs.readFileSync(__dirname + '/torrents/leaves.torrent') var leavesTorrent = parseTorrent(leaves) var leavesBook = fs.readFileSync(__dirname + '/content/Leaves of Grass by Walt Whitman.epub') var leavesMagnetURI = 'magnet:?xt=urn:btih:d2474e86c95b19b8bcfdb92bc12c9d44667cfa36&dn=Leaves+of+Grass+by+Walt+Whitman.epub&tr=http%3A%2F%2Ftracker.thepiratebay.org%2Fannounce&tr=udp%3A%2F%2Ftracker.openbittorrent.com%3A80&tr=udp%3A%2F%2Ftracker.ccc.de%3A80&tr=udp%3A%2F%2Ftracker.publicbt.com%3A80&tr=udp%3A%2F%2Ffr33domtracker.h33t.com%3A3310%2Fannounce&tr=http%3A%2F%2Ftracker.bittorrent.am%2Fannounce' test('client.add (magnet uri, torrent file, info hash, and parsed torrent)', function (t) { // magnet uri (utf8 string) var client1 = new WebTorrent({ dht: false, tracker: false }) var torrent1 = client1.add('magnet:?xt=urn:btih:' + leavesTorrent.infoHash) t.equal(torrent1.infoHash, leavesTorrent.infoHash) t.equal(torrent1.magnetURI, 'magnet:?xt=urn:btih:' + leavesTorrent.infoHash) client1.destroy() // torrent file (buffer) var client2 = new WebTorrent({ dht: false, tracker: false }) var torrent2 = client2.add(leaves) t.equal(torrent2.infoHash, leavesTorrent.infoHash) t.equal(torrent2.magnetURI, leavesMagnetURI) client2.destroy() // info hash (hex string) var client3 = new WebTorrent({ dht: false, tracker: false }) var torrent3 = client3.add(leavesTorrent.infoHash) t.equal(torrent3.infoHash, leavesTorrent.infoHash) t.equal(torrent3.magnetURI, 'magnet:?xt=urn:btih:' + leavesTorrent.infoHash) client3.destroy() // info hash (buffer) var client4 = new WebTorrent({ dht: false, tracker: false }) var torrent4 = client4.add(new Buffer(leavesTorrent.infoHash, 'hex')) t.equal(torrent4.infoHash, leavesTorrent.infoHash) t.equal(torrent4.magnetURI, 'magnet:?xt=urn:btih:' + leavesTorrent.infoHash) client4.destroy() // parsed torrent (from parse-torrent) var client5 = new WebTorrent({ dht: false, tracker: false }) var torrent5 = client5.add(leavesTorrent) t.equal(torrent5.infoHash, leavesTorrent.infoHash) t.equal(torrent5.magnetURI, leavesMagnetURI) client5.destroy() t.end() }) test('client.seed (Buffer, Blob)', function (t) { t.plan(typeof Blob !== 'undefined' ? 4 : 2) var opts = { name: 'Leaves of Grass by Walt Whitman.epub', announce: [ 'http://tracker.thepiratebay.org/announce', 'udp://tracker.openbittorrent.com:80', 'udp://tracker.ccc.de:80', 'udp://tracker.publicbt.com:80', 'udp://fr33domtracker.h33t.com:3310/announce', 'http://tracker.bittorrent.am/announce' ] } // torrent file (Buffer) var client1 = new WebTorrent({ dht: false, tracker: false }) client1.seed(leavesBook, opts, function (torrent1) { t.equal(torrent1.infoHash, leavesTorrent.infoHash) t.equal(torrent1.magnetURI, leavesMagnetURI) client1.destroy() }) // Blob if (typeof Blob !== 'undefined') { var client2 = new WebTorrent({ dht: false, tracker: false }) client2.seed(new Blob([ leavesBook ]), opts, function (torrent2) { t.equal(torrent2.infoHash, leavesTorrent.infoHash) t.equal(torrent2.magnetURI, leavesMagnetURI) client2.destroy() }) } else { console.log('Skipping Blob test because missing `Blob` constructor') } }) test('after client.destroy(), throw on client.add() or client.seed()', function (t) { t.plan(3) var client = new WebTorrent({ dht: false, tracker: false }) client.destroy(function () { t.pass('client destroyed') }) t.throws(function () { client.add('magnet:?xt=urn:btih:' + leavesTorrent.infoHash) }) t.throws(function () { client.seed(new Buffer('sup')) }) }) test('after client.destroy(), no "torrent" or "ready" events emitted', function (t) { t.plan(1) var client = new WebTorrent({ dht: false, tracker: false }) client.add(leaves, function () { t.fail('unexpected "torrent" event (from add)') }) client.seed(leavesBook, function () { t.fail('unexpected "torrent" event (from seed)') }) client.on('ready', function () { t.fail('unexpected "ready" event') }) client.destroy(function () { t.pass('client destroyed') }) }) test('download via DHT', function (t) { t.plan(2) var data = new Buffer('blah blah') var dhts = [] // need 3 because nodes don't advertise themselves as peers for (var i = 0; i < 3; i++) { dhts.push(new DHT({ bootstrap: false })) } parallel(dhts.map(function (dht) { return function (cb) { dht.listen(function (port) { cb(null, port) }) } }), function () { for (var i = 0; i < dhts.length; i++) { for (var j = 0; j < dhts.length; j++) { if (i !== j) dhts[i].addNode('127.0.0.1:' + getDHTPort(dhts[j]), dhts[j].nodeId) } } var client1 = new WebTorrent({ dht: dhts[0], tracker: false }) var client2 = new WebTorrent({ dht: dhts[1], tracker: false }) client1.seed(data, { name: 'blah' }, function (torrent1) { client2.download(torrent1.infoHash, function (torrent2) { t.equal(torrent2.infoHash, torrent1.infoHash) torrent2.on('done', function () { t.ok(bufferEqual(getFileData(torrent2), data)) dhts.forEach(function (d) { d.destroy() }) client1.destroy() client2.destroy() }) }) }) }) }) test('don\'t kill passed in DHT on destroy', function (t) { t.plan(1) var dht = new DHT({ bootstrap: false }) var destroy = dht.destroy var okToDie dht.destroy = function () { t.equal(okToDie, true) dht.destroy = destroy.bind(dht) dht.destroy() } var client = new WebTorrent({ dht: dht, tracker: false }) client.destroy(function () { okToDie = true dht.destroy() }) }) function getFileData (torrent) { var pieces = torrent.files[0].pieces return Buffer.concat(pieces.map( function (piece) { return piece.buffer } )) } function getDHTPort (dht) { return dht.address().port }
tradle/webtorrent
test/basic.js
JavaScript
mit
6,281
export const state = () => ({ visits:[] }) export const mutations = { ADD_VISIT (state,path) { state.visits.push({ path, date:new Date().toJSON() }) } }
choukin/learnjavascript
vue/nuxt/helloworld/store/index.js
JavaScript
mit
166
Menubar.Add = function ( editor ) { var meshCount = 0; var lightCount = 0; // event handlers function onObject3DOptionClick () { var mesh = new THREE.Object3D(); mesh.name = 'Object3D ' + ( ++ meshCount ); editor.addObject( mesh ); editor.select( mesh ); } //Plane function onPlaneOptionClick () { var width = 200; var height = 200; var widthSegments = 1; var heightSegments = 1; var geometry = new THREE.PlaneGeometry( width, height, widthSegments, heightSegments ); var material = new THREE.MeshPhongMaterial(); var mesh = new THREE.Mesh( geometry, material ); mesh.name = 'Plane ' + ( ++ meshCount ); editor.addObject( mesh ); editor.select( mesh ); }; //Triangle function onTriangleOptionClick (){ var geometry = new THREE.Geometry(); var v1 = new THREE.Vector3(-100,0,0); var v2 = new THREE.Vector3(100,0,0); var v3 = new THREE.Vector3(0,100,0); geometry.vertices.push(v1); geometry.vertices.push(v2); geometry.vertices.push(v3); geometry.faces.push(new THREE.Face3(0,2,1)); var material = new THREE.MeshBasicMaterial({color:0xff0000}); var mesh = new THREE.Mesh(geometry, material); mesh.name = 'Triangle ' + (++ meshCount); editor.addObject( mesh ); editor.select(mesh); }; //Box function onBoxOptionClick () { var width = 100; var height = 100; var depth = 100; var widthSegments = 1; var heightSegments = 1; var depthSegments = 1; var geometry = new THREE.BoxGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ); var mesh = new THREE.Mesh( geometry, new THREE.MeshPhongMaterial() ); mesh.name = 'Box ' + ( ++ meshCount ); editor.addObject( mesh ); editor.select( mesh ); } //Circle function onCircleOptionClick () { var radius = 20; var segments = 32; var geometry = new THREE.CircleGeometry( radius, segments ); var mesh = new THREE.Mesh( geometry, new THREE.MeshPhongMaterial() ); mesh.name = 'Circle ' + ( ++ meshCount ); editor.addObject( mesh ); editor.select( mesh ); } //Cylinder function onCylinderOptionClick () { var radiusTop = 20; var radiusBottom = 20; var height = 100; var radiusSegments = 32; var heightSegments = 1; var openEnded = false; var geometry = new THREE.CylinderGeometry( radiusTop, radiusBottom, height, radiusSegments, heightSegments, openEnded ); var mesh = new THREE.Mesh( geometry, new THREE.MeshPhongMaterial() ); mesh.name = 'Cylinder ' + ( ++ meshCount ); editor.addObject( mesh ); editor.select( mesh ); } //Sphere function onSphereOptionClick () { var radius = 75; var widthSegments = 32; var heightSegments = 16; var geometry = new THREE.SphereGeometry( radius, widthSegments, heightSegments ); var mesh = new THREE.Mesh( geometry, new THREE.MeshPhongMaterial() ); mesh.name = 'Sphere ' + ( ++ meshCount ); editor.addObject( mesh ); editor.select( mesh ); } //Icosahedron function onIcosahedronOptionClick () { var radius = 75; var detail = 2; var geometry = new THREE.IcosahedronGeometry ( radius, detail ); var mesh = new THREE.Mesh( geometry, new THREE.MeshPhongMaterial() ); mesh.name = 'Icosahedron ' + ( ++ meshCount ); editor.addObject( mesh ); editor.select( mesh ); } //Torus function onTorusOptionClick () { var radius = 100; var tube = 40; var radialSegments = 8; var tubularSegments = 6; var arc = Math.PI * 2; var geometry = new THREE.TorusGeometry( radius, tube, radialSegments, tubularSegments, arc ); var mesh = new THREE.Mesh( geometry, new THREE.MeshPhongMaterial() ); mesh.name = 'Torus ' + ( ++ meshCount ); editor.addObject( mesh ); editor.select( mesh ); } //Torus Knot function onTorusKnotOptionClick () { var radius = 100; var tube = 40; var radialSegments = 64; var tubularSegments = 8; var p = 2; var q = 3; var heightScale = 1; var geometry = new THREE.TorusKnotGeometry( radius, tube, radialSegments, tubularSegments, p, q, heightScale ); var mesh = new THREE.Mesh( geometry, new THREE.MeshPhongMaterial() ); mesh.name = 'TorusKnot ' + ( ++ meshCount ); editor.addObject( mesh ); editor.select( mesh ); } //Sprite function onSpriteOptionClick () { var sprite = new THREE.Sprite( new THREE.SpriteMaterial() ); sprite.name = 'Sprite ' + ( ++ meshCount ); editor.addObject( sprite ); editor.select( sprite ); } function onPointLightOptionClick () { var color = 0xffffff; var intensity = 1; var distance = 0; var light = new THREE.PointLight( color, intensity, distance ); light.name = 'PointLight ' + ( ++ lightCount ); editor.addObject( light ); editor.select( light ); } function onSpotLightOptionClick () { var color = 0xffffff; var intensity = 1; var distance = 0; var angle = Math.PI * 0.1; var exponent = 10; var light = new THREE.SpotLight( color, intensity, distance, angle, exponent ); //.distance // light will attenuate linearly from maximum intensity at light position down to zero at distance. // .angle // Maximum extent of the spotlight, in radians, from its direction. Should be no more than Math.PI/2. // Default — Math.PI/3. // .exponent // Rapidity of the falloff of light from its target direction. // Default — 10.0. light.name = 'SpotLight ' + ( ++ lightCount ); light.target.name = 'SpotLight ' + ( lightCount ) + ' Target'; light.position.set( 0, 1, 0 ).multiplyScalar( 200 ); editor.addObject( light ); editor.select( light ); } function onDirectionalLightOptionClick () { var color = 0xffffff; var intensity = 1; var light = new THREE.DirectionalLight( color, intensity ); light.name = 'DirectionalLight ' + ( ++ lightCount ); light.target.name = 'DirectionalLight ' + ( lightCount ) + ' Target'; light.position.set( 1, 1, 1 ).multiplyScalar( 200 ); editor.addObject( light ); editor.select( light ); } function onHemisphereLightOptionClick () { var skyColor = 0x00aaff; var groundColor = 0xffaa00; var intensity = 1; var light = new THREE.HemisphereLight( skyColor, groundColor, intensity ); light.name = 'HemisphereLight ' + ( ++ lightCount ); light.position.set( 1, 1, 1 ).multiplyScalar( 200 ); editor.addObject( light ); editor.select( light ); } function onAmbientLightOptionClick() { var color = 0x222222; var light = new THREE.AmbientLight( color ); light.name = 'AmbientLight ' + ( ++ lightCount ); editor.addObject( light ); editor.select( light ); } // configure menu contents var createOption = UI.MenubarHelper.createOption; var createDivider = UI.MenubarHelper.createDivider; var menuConfig = [ //createOption( 'Object3D', onObject3DOptionClick ), //createDivider(), createOption( 'Plane', onPlaneOptionClick ), createOption('Triangle',onTriangleOptionClick), createOption( 'Box', onBoxOptionClick ), createOption( 'Circle', onCircleOptionClick ), createOption( 'Cylinder', onCylinderOptionClick ), createOption( 'Sphere', onSphereOptionClick ), //createOption( 'Icosahedron', onIcosahedronOptionClick ), //createOption( 'Torus', onTorusOptionClick ), //createOption( 'Torus Knot', onTorusKnotOptionClick ), createDivider(), //createOption( 'Sprite', onSpriteOptionClick ), createDivider(), createOption( 'Point light', onPointLightOptionClick ), createOption( 'Spot light', onSpotLightOptionClick ), createOption( 'Directional light', onDirectionalLightOptionClick ), createOption( 'Hemisphere light', onHemisphereLightOptionClick ), createOption( 'Ambient light', onAmbientLightOptionClick ) ]; var optionsPanel = UI.MenubarHelper.createOptionsPanel( menuConfig ); return UI.MenubarHelper.createMenuContainer( 'Add', optionsPanel ); }
akshaynagpal/3d_graphics_editor
js/Menubar.Add.js
JavaScript
mit
7,787
import React, { PropTypes } from 'react'; const ProductList = (props) => { const pl = props.productList; const products = Object.keys(pl); return (<ul> {products.map(key => <li key={key}><a href={`#/product/${key}`} >{pl[key].name}</a></li>)} </ul>); }; ProductList.propTypes = { productList: PropTypes.object.isRequired }; export default ProductList;
sunitJindal/react-tutorial
redux-with-react/app/components/ProductList/presentational/ProductList.js
JavaScript
mit
368
//Variables var chrome_points = 0; //Functions function test_chromepoints() { chrome_points = chrome_points + 1; } //HTML Updates window.setInterval(function(){ document.getElementById("chrome_points").innerHTML = chrome_points; }, 1000);
draco13th/HD-Tracker
js.js
JavaScript
mit
245
ace.define("ace/snippets/sqlserver", ["require", "exports", "module"], function(require, exports, module) { "use strict"; exports.snippetText = "# ISNULL\n\ snippet isnull\n\ ISNULL(${1:check_expression}, ${2:replacement_value})\n\ # FORMAT\n\ snippet format\n\ FORMAT(${1:value}, ${2:format})\n\ # CAST\n\ snippet cast\n\ CAST(${1:expression} AS ${2:data_type})\n\ # CONVERT\n\ snippet convert\n\ CONVERT(${1:data_type}, ${2:expression})\n\ # DATEPART\n\ snippet datepart\n\ DATEPART(${1:datepart}, ${2:date})\n\ # DATEDIFF\n\ snippet datediff\n\ DATEDIFF(${1:datepart}, ${2:startdate}, ${3:enddate})\n\ # DATEADD\n\ snippet dateadd\n\ DATEADD(${1:datepart}, ${2:number}, ${3:date})\n\ # DATEFROMPARTS \n\ snippet datefromparts\n\ DATEFROMPARTS(${1:year}, ${2:month}, ${3:day})\n\ # OBJECT_DEFINITION\n\ snippet objectdef\n\ SELECT OBJECT_DEFINITION(OBJECT_ID('${1:sys.server_permissions /*object name*/}'))\n\ # STUFF XML\n\ snippet stuffxml\n\ STUFF((SELECT ', ' + ${1:ColumnName}\n\ FROM ${2:TableName}\n\ WHERE ${3:WhereClause}\n\ FOR XML PATH('')), 1, 1, '') AS ${4:Alias}\n\ ${5:/*https://msdn.microsoft.com/en-us/library/ms188043.aspx*/}\n\ # Create Procedure\n\ snippet createproc\n\ -- =============================================\n\ -- Author: ${1:Author}\n\ -- Create date: ${2:Date}\n\ -- Description: ${3:Description}\n\ -- =============================================\n\ CREATE PROCEDURE ${4:Procedure_Name}\n\ ${5:/*Add the parameters for the stored procedure here*/}\n\ AS\n\ BEGIN\n\ -- SET NOCOUNT ON added to prevent extra result sets from interfering with SELECT statements.\n\ SET NOCOUNT ON;\n\ \n\ ${6:/*Add the T-SQL statements to compute the return value here*/}\n\ \n\ END\n\ GO\n\ # Create Scalar Function\n\ snippet createfn\n\ -- =============================================\n\ -- Author: ${1:Author}\n\ -- Create date: ${2:Date}\n\ -- Description: ${3:Description}\n\ -- =============================================\n\ CREATE FUNCTION ${4:Scalar_Function_Name}\n\ -- Add the parameters for the function here\n\ RETURNS ${5:Function_Data_Type}\n\ AS\n\ BEGIN\n\ DECLARE @Result ${5:Function_Data_Type}\n\ \n\ ${6:/*Add the T-SQL statements to compute the return value here*/}\n\ \n\ END\n\ GO"; exports.scope = "sqlserver"; }); (function() { ace.require(["ace/snippets/sqlserver"], function(m) { if (typeof module == "object" && typeof exports == "object" && module) { module.exports = m; } }); })();
TeamSPoon/logicmoo_workspace
packs_web/swish/web/node_modules/ace/build/src-noconflict/snippets/sqlserver.js
JavaScript
mit
2,522
module.exports = { 'handles belongsTo (blog, site)': { mysql: { result: { id: 2, name: 'bookshelfjs.org' } }, postgresql: { result: { id: 2, name: 'bookshelfjs.org' } }, sqlite3: { result: { id: 2, name: 'bookshelfjs.org' } } }, 'handles hasMany (posts)': { mysql: { result: [{ id: 1, owner_id: 1, blog_id: 1, name: 'This is a new Title!', content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.' },{ id: 3, owner_id: 2, blog_id: 1, name: 'This is a new Title 3!', content: 'Lorem ipsum Reprehenderit esse esse consectetur aliquip magna.' }] }, postgresql: { result: [{ id: 1, owner_id: 1, blog_id: 1, name: 'This is a new Title!', content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.' },{ id: 3, owner_id: 2, blog_id: 1, name: 'This is a new Title 3!', content: 'Lorem ipsum Reprehenderit esse esse consectetur aliquip magna.' }] }, sqlite3: { result: [{ id: 1, owner_id: 1, blog_id: 1, name: 'This is a new Title!', content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.' },{ id: 3, owner_id: 2, blog_id: 1, name: 'This is a new Title 3!', content: 'Lorem ipsum Reprehenderit esse esse consectetur aliquip magna.' }] } }, 'handles hasOne (meta)': { mysql: { result: { id: 1, site_id: 1, description: 'This is a description for the Knexjs Site' } }, postgresql: { result: { id: 1, site_id: 1, description: 'This is a description for the Knexjs Site' } }, sqlite3: { result: { id: 1, site_id: 1, description: 'This is a description for the Knexjs Site' } } }, 'handles belongsToMany (posts)': { mysql: { result: [{ id: 1, owner_id: 1, blog_id: 1, name: 'This is a new Title!', content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.', _pivot_author_id: 1, _pivot_post_id: 1 }] }, postgresql: { result: [{ id: 1, owner_id: 1, blog_id: 1, name: 'This is a new Title!', content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.', _pivot_author_id: 1, _pivot_post_id: 1 }] }, sqlite3: { result: [{ id: 1, owner_id: 1, blog_id: 1, name: 'This is a new Title!', content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.', _pivot_author_id: 1, _pivot_post_id: 1 }] } }, 'eager loads "hasOne" relationships correctly (site -> meta)': { mysql: { result: { id: 1, name: 'knexjs.org', meta: { id: 1, site_id: 1, description: 'This is a description for the Knexjs Site' } } }, postgresql: { result: { id: 1, name: 'knexjs.org', meta: { id: 1, site_id: 1, description: 'This is a description for the Knexjs Site' } } }, sqlite3: { result: { id: 1, name: 'knexjs.org', meta: { id: 1, site_id: 1, description: 'This is a description for the Knexjs Site' } } } }, 'eager loads "hasMany" relationships correctly (site -> authors, blogs)': { mysql: { result: { id: 1, name: 'knexjs.org', authors: [{ id: 1, site_id: 1, first_name: 'Tim', last_name: 'Griesser' },{ id: 2, site_id: 1, first_name: 'Bazooka', last_name: 'Joe' }], blogs: [{ id: 1, site_id: 1, name: 'Main Site Blog' },{ id: 2, site_id: 1, name: 'Alternate Site Blog' }] } }, postgresql: { result: { id: 1, name: 'knexjs.org', blogs: [{ id: 1, site_id: 1, name: 'Main Site Blog' },{ id: 2, site_id: 1, name: 'Alternate Site Blog' }], authors: [{ id: 1, site_id: 1, first_name: 'Tim', last_name: 'Griesser' },{ id: 2, site_id: 1, first_name: 'Bazooka', last_name: 'Joe' }] } }, sqlite3: { result: { id: 1, name: 'knexjs.org', authors: [{ id: 1, site_id: 1, first_name: 'Tim', last_name: 'Griesser' },{ id: 2, site_id: 1, first_name: 'Bazooka', last_name: 'Joe' }], blogs: [{ id: 1, site_id: 1, name: 'Main Site Blog' },{ id: 2, site_id: 1, name: 'Alternate Site Blog' }] } } }, 'eager loads "belongsTo" relationships correctly (blog -> site)': { mysql: { result: { id: 3, site_id: 2, name: 'Main Site Blog', site: { id: 2, name: 'bookshelfjs.org' } } }, postgresql: { result: { id: 3, site_id: 2, name: 'Main Site Blog', site: { id: 2, name: 'bookshelfjs.org' } } }, sqlite3: { result: { id: 3, site_id: 2, name: 'Main Site Blog', site: { id: 2, name: 'bookshelfjs.org' } } } }, 'eager loads "belongsToMany" models correctly (post -> tags)': { mysql: { result: { id: 1, owner_id: 1, blog_id: 1, name: 'This is a new Title!', content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.', tags: [{ id: 1, name: 'cool', _pivot_post_id: 1, _pivot_tag_id: 1 },{ id: 2, name: 'boring', _pivot_post_id: 1, _pivot_tag_id: 2 },{ id: 3, name: 'exciting', _pivot_post_id: 1, _pivot_tag_id: 3 }] } }, postgresql: { result: { id: 1, owner_id: 1, blog_id: 1, name: 'This is a new Title!', content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.', tags: [{ id: 1, name: 'cool', _pivot_post_id: 1, _pivot_tag_id: 1 },{ id: 2, name: 'boring', _pivot_post_id: 1, _pivot_tag_id: 2 },{ id: 3, name: 'exciting', _pivot_post_id: 1, _pivot_tag_id: 3 }] } }, sqlite3: { result: { id: 1, owner_id: 1, blog_id: 1, name: 'This is a new Title!', content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.', tags: [{ id: 1, name: 'cool', _pivot_post_id: 1, _pivot_tag_id: 1 },{ id: 2, name: 'boring', _pivot_post_id: 1, _pivot_tag_id: 2 },{ id: 3, name: 'exciting', _pivot_post_id: 1, _pivot_tag_id: 3 }] } } }, 'Attaches an empty related model or collection if the `EagerRelation` comes back blank': { mysql: { result: { id: 3, name: 'backbonejs.org', meta: { }, blogs: [], authors: [] } }, postgresql: { result: { id: 3, name: 'backbonejs.org', meta: { }, authors: [], blogs: [] } }, sqlite3: { result: { id: 3, name: 'backbonejs.org', meta: { }, blogs: [], authors: [] } } }, 'eager loads "hasOne" models correctly (sites -> meta)': { mysql: { result: [{ id: 1, name: 'knexjs.org', meta: { id: 1, site_id: 1, description: 'This is a description for the Knexjs Site' } },{ id: 2, name: 'bookshelfjs.org', meta: { id: 2, site_id: 2, description: 'This is a description for the Bookshelfjs Site' } },{ id: 3, name: 'backbonejs.org', meta: { } }] }, postgresql: { result: [{ id: 1, name: 'knexjs.org', meta: { id: 1, site_id: 1, description: 'This is a description for the Knexjs Site' } },{ id: 2, name: 'bookshelfjs.org', meta: { id: 2, site_id: 2, description: 'This is a description for the Bookshelfjs Site' } },{ id: 3, name: 'backbonejs.org', meta: { } }] }, sqlite3: { result: [{ id: 1, name: 'knexjs.org', meta: { id: 1, site_id: 1, description: 'This is a description for the Knexjs Site' } },{ id: 2, name: 'bookshelfjs.org', meta: { id: 2, site_id: 2, description: 'This is a description for the Bookshelfjs Site' } },{ id: 3, name: 'backbonejs.org', meta: { } }] } }, 'eager loads "belongsTo" models correctly (blogs -> site)': { mysql: { result: [{ id: 1, site_id: 1, name: 'Main Site Blog', site: { id: 1, name: 'knexjs.org' } },{ id: 2, site_id: 1, name: 'Alternate Site Blog', site: { id: 1, name: 'knexjs.org' } },{ id: 3, site_id: 2, name: 'Main Site Blog', site: { id: 2, name: 'bookshelfjs.org' } },{ id: 4, site_id: 2, name: 'Alternate Site Blog', site: { id: 2, name: 'bookshelfjs.org' } }] }, postgresql: { result: [{ id: 1, site_id: 1, name: 'Main Site Blog', site: { id: 1, name: 'knexjs.org' } },{ id: 2, site_id: 1, name: 'Alternate Site Blog', site: { id: 1, name: 'knexjs.org' } },{ id: 3, site_id: 2, name: 'Main Site Blog', site: { id: 2, name: 'bookshelfjs.org' } },{ id: 4, site_id: 2, name: 'Alternate Site Blog', site: { id: 2, name: 'bookshelfjs.org' } }] }, sqlite3: { result: [{ id: 1, site_id: 1, name: 'Main Site Blog', site: { id: 1, name: 'knexjs.org' } },{ id: 2, site_id: 1, name: 'Alternate Site Blog', site: { id: 1, name: 'knexjs.org' } },{ id: 3, site_id: 2, name: 'Main Site Blog', site: { id: 2, name: 'bookshelfjs.org' } },{ id: 4, site_id: 2, name: 'Alternate Site Blog', site: { id: 2, name: 'bookshelfjs.org' } }] } }, 'eager loads "hasMany" models correctly (site -> blogs)': { mysql: { result: { id: 1, name: 'knexjs.org', blogs: [{ id: 1, site_id: 1, name: 'Main Site Blog' },{ id: 2, site_id: 1, name: 'Alternate Site Blog' }] } }, postgresql: { result: { id: 1, name: 'knexjs.org', blogs: [{ id: 1, site_id: 1, name: 'Main Site Blog' },{ id: 2, site_id: 1, name: 'Alternate Site Blog' }] } }, sqlite3: { result: { id: 1, name: 'knexjs.org', blogs: [{ id: 1, site_id: 1, name: 'Main Site Blog' },{ id: 2, site_id: 1, name: 'Alternate Site Blog' }] } } }, 'eager loads "belongsToMany" models correctly (posts -> tags)': { mysql: { result: [{ id: 1, owner_id: 1, blog_id: 1, name: 'This is a new Title!', content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.', tags: [{ id: 1, name: 'cool', _pivot_post_id: 1, _pivot_tag_id: 1 },{ id: 2, name: 'boring', _pivot_post_id: 1, _pivot_tag_id: 2 },{ id: 3, name: 'exciting', _pivot_post_id: 1, _pivot_tag_id: 3 }] },{ id: 3, owner_id: 2, blog_id: 1, name: 'This is a new Title 3!', content: 'Lorem ipsum Reprehenderit esse esse consectetur aliquip magna.', tags: [] }] }, postgresql: { result: [{ id: 1, owner_id: 1, blog_id: 1, name: 'This is a new Title!', content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.', tags: [{ id: 1, name: 'cool', _pivot_post_id: 1, _pivot_tag_id: 1 },{ id: 2, name: 'boring', _pivot_post_id: 1, _pivot_tag_id: 2 },{ id: 3, name: 'exciting', _pivot_post_id: 1, _pivot_tag_id: 3 }] },{ id: 3, owner_id: 2, blog_id: 1, name: 'This is a new Title 3!', content: 'Lorem ipsum Reprehenderit esse esse consectetur aliquip magna.', tags: [] }] }, sqlite3: { result: [{ id: 1, owner_id: 1, blog_id: 1, name: 'This is a new Title!', content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.', tags: [{ id: 1, name: 'cool', _pivot_post_id: 1, _pivot_tag_id: 1 },{ id: 2, name: 'boring', _pivot_post_id: 1, _pivot_tag_id: 2 },{ id: 3, name: 'exciting', _pivot_post_id: 1, _pivot_tag_id: 3 }] },{ id: 3, owner_id: 2, blog_id: 1, name: 'This is a new Title 3!', content: 'Lorem ipsum Reprehenderit esse esse consectetur aliquip magna.', tags: [] }] } }, 'eager loads "hasMany" -> "hasMany" (site -> authors.ownPosts)': { mysql: { result: { id: 1, name: 'knexjs.org', authors: [{ id: 1, site_id: 1, first_name: 'Tim', last_name: 'Griesser', ownPosts: [{ id: 1, owner_id: 1, blog_id: 1, name: 'This is a new Title!', content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.' }] },{ id: 2, site_id: 1, first_name: 'Bazooka', last_name: 'Joe', ownPosts: [{ id: 2, owner_id: 2, blog_id: 2, name: 'This is a new Title 2!', content: 'Lorem ipsum Veniam ex amet occaecat dolore in pariatur minim est exercitation deserunt Excepteur enim officia occaecat in exercitation aute et ad esse ex in in dolore amet consequat quis sed mollit et id incididunt sint dolore velit officia dolor dolore laboris dolor Duis ea ex quis deserunt anim nisi qui culpa laboris nostrud Duis anim deserunt esse laboris nulla qui in dolor voluptate aute reprehenderit amet ut et non voluptate elit irure mollit dolor consectetur nisi adipisicing commodo et mollit dolore incididunt cupidatat nulla ut irure deserunt non officia laboris fugiat ut pariatur ut non aliqua eiusmod dolor et nostrud minim elit occaecat commodo consectetur cillum elit laboris mollit dolore amet id qui eiusmod nulla elit eiusmod est ad aliqua aute enim ut aliquip ex in Ut nisi sint exercitation est mollit veniam cupidatat adipisicing occaecat dolor irure in aute aliqua ullamco.' },{ id: 3, owner_id: 2, blog_id: 1, name: 'This is a new Title 3!', content: 'Lorem ipsum Reprehenderit esse esse consectetur aliquip magna.' }] }] } }, postgresql: { result: { id: 1, name: 'knexjs.org', authors: [{ id: 1, site_id: 1, first_name: 'Tim', last_name: 'Griesser', ownPosts: [{ id: 1, owner_id: 1, blog_id: 1, name: 'This is a new Title!', content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.' }] },{ id: 2, site_id: 1, first_name: 'Bazooka', last_name: 'Joe', ownPosts: [{ id: 2, owner_id: 2, blog_id: 2, name: 'This is a new Title 2!', content: 'Lorem ipsum Veniam ex amet occaecat dolore in pariatur minim est exercitation deserunt Excepteur enim officia occaecat in exercitation aute et ad esse ex in in dolore amet consequat quis sed mollit et id incididunt sint dolore velit officia dolor dolore laboris dolor Duis ea ex quis deserunt anim nisi qui culpa laboris nostrud Duis anim deserunt esse laboris nulla qui in dolor voluptate aute reprehenderit amet ut et non voluptate elit irure mollit dolor consectetur nisi adipisicing commodo et mollit dolore incididunt cupidatat nulla ut irure deserunt non officia laboris fugiat ut pariatur ut non aliqua eiusmod dolor et nostrud minim elit occaecat commodo consectetur cillum elit laboris mollit dolore amet id qui eiusmod nulla elit eiusmod est ad aliqua aute enim ut aliquip ex in Ut nisi sint exercitation est mollit veniam cupidatat adipisicing occaecat dolor irure in aute aliqua ullamco.' },{ id: 3, owner_id: 2, blog_id: 1, name: 'This is a new Title 3!', content: 'Lorem ipsum Reprehenderit esse esse consectetur aliquip magna.' }] }] } }, sqlite3: { result: { id: 1, name: 'knexjs.org', authors: [{ id: 1, site_id: 1, first_name: 'Tim', last_name: 'Griesser', ownPosts: [{ id: 1, owner_id: 1, blog_id: 1, name: 'This is a new Title!', content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.' }] },{ id: 2, site_id: 1, first_name: 'Bazooka', last_name: 'Joe', ownPosts: [{ id: 2, owner_id: 2, blog_id: 2, name: 'This is a new Title 2!', content: 'Lorem ipsum Veniam ex amet occaecat dolore in pariatur minim est exercitation deserunt Excepteur enim officia occaecat in exercitation aute et ad esse ex in in dolore amet consequat quis sed mollit et id incididunt sint dolore velit officia dolor dolore laboris dolor Duis ea ex quis deserunt anim nisi qui culpa laboris nostrud Duis anim deserunt esse laboris nulla qui in dolor voluptate aute reprehenderit amet ut et non voluptate elit irure mollit dolor consectetur nisi adipisicing commodo et mollit dolore incididunt cupidatat nulla ut irure deserunt non officia laboris fugiat ut pariatur ut non aliqua eiusmod dolor et nostrud minim elit occaecat commodo consectetur cillum elit laboris mollit dolore amet id qui eiusmod nulla elit eiusmod est ad aliqua aute enim ut aliquip ex in Ut nisi sint exercitation est mollit veniam cupidatat adipisicing occaecat dolor irure in aute aliqua ullamco.' },{ id: 3, owner_id: 2, blog_id: 1, name: 'This is a new Title 3!', content: 'Lorem ipsum Reprehenderit esse esse consectetur aliquip magna.' }] }] } } }, 'eager loads "hasMany" -> "belongsToMany" (site -> authors.posts)': { mysql: { result: { id: 1, name: 'knexjs.org', authors: [{ id: 1, site_id: 1, first_name: 'Tim', last_name: 'Griesser', posts: [{ id: 1, owner_id: 1, blog_id: 1, name: 'This is a new Title!', content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.', _pivot_author_id: 1, _pivot_post_id: 1 }] },{ id: 2, site_id: 1, first_name: 'Bazooka', last_name: 'Joe', posts: [{ id: 1, owner_id: 1, blog_id: 1, name: 'This is a new Title!', content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.', _pivot_author_id: 2, _pivot_post_id: 1 },{ id: 2, owner_id: 2, blog_id: 2, name: 'This is a new Title 2!', content: 'Lorem ipsum Veniam ex amet occaecat dolore in pariatur minim est exercitation deserunt Excepteur enim officia occaecat in exercitation aute et ad esse ex in in dolore amet consequat quis sed mollit et id incididunt sint dolore velit officia dolor dolore laboris dolor Duis ea ex quis deserunt anim nisi qui culpa laboris nostrud Duis anim deserunt esse laboris nulla qui in dolor voluptate aute reprehenderit amet ut et non voluptate elit irure mollit dolor consectetur nisi adipisicing commodo et mollit dolore incididunt cupidatat nulla ut irure deserunt non officia laboris fugiat ut pariatur ut non aliqua eiusmod dolor et nostrud minim elit occaecat commodo consectetur cillum elit laboris mollit dolore amet id qui eiusmod nulla elit eiusmod est ad aliqua aute enim ut aliquip ex in Ut nisi sint exercitation est mollit veniam cupidatat adipisicing occaecat dolor irure in aute aliqua ullamco.', _pivot_author_id: 2, _pivot_post_id: 2 }] }] } }, postgresql: { result: { id: 1, name: 'knexjs.org', authors: [{ id: 1, site_id: 1, first_name: 'Tim', last_name: 'Griesser', posts: [{ id: 1, owner_id: 1, blog_id: 1, name: 'This is a new Title!', content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.', _pivot_author_id: 1, _pivot_post_id: 1 }] },{ id: 2, site_id: 1, first_name: 'Bazooka', last_name: 'Joe', posts: [{ id: 1, owner_id: 1, blog_id: 1, name: 'This is a new Title!', content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.', _pivot_author_id: 2, _pivot_post_id: 1 },{ id: 2, owner_id: 2, blog_id: 2, name: 'This is a new Title 2!', content: 'Lorem ipsum Veniam ex amet occaecat dolore in pariatur minim est exercitation deserunt Excepteur enim officia occaecat in exercitation aute et ad esse ex in in dolore amet consequat quis sed mollit et id incididunt sint dolore velit officia dolor dolore laboris dolor Duis ea ex quis deserunt anim nisi qui culpa laboris nostrud Duis anim deserunt esse laboris nulla qui in dolor voluptate aute reprehenderit amet ut et non voluptate elit irure mollit dolor consectetur nisi adipisicing commodo et mollit dolore incididunt cupidatat nulla ut irure deserunt non officia laboris fugiat ut pariatur ut non aliqua eiusmod dolor et nostrud minim elit occaecat commodo consectetur cillum elit laboris mollit dolore amet id qui eiusmod nulla elit eiusmod est ad aliqua aute enim ut aliquip ex in Ut nisi sint exercitation est mollit veniam cupidatat adipisicing occaecat dolor irure in aute aliqua ullamco.', _pivot_author_id: 2, _pivot_post_id: 2 }] }] } }, sqlite3: { result: { id: 1, name: 'knexjs.org', authors: [{ id: 1, site_id: 1, first_name: 'Tim', last_name: 'Griesser', posts: [{ id: 1, owner_id: 1, blog_id: 1, name: 'This is a new Title!', content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.', _pivot_author_id: 1, _pivot_post_id: 1 }] },{ id: 2, site_id: 1, first_name: 'Bazooka', last_name: 'Joe', posts: [{ id: 2, owner_id: 2, blog_id: 2, name: 'This is a new Title 2!', content: 'Lorem ipsum Veniam ex amet occaecat dolore in pariatur minim est exercitation deserunt Excepteur enim officia occaecat in exercitation aute et ad esse ex in in dolore amet consequat quis sed mollit et id incididunt sint dolore velit officia dolor dolore laboris dolor Duis ea ex quis deserunt anim nisi qui culpa laboris nostrud Duis anim deserunt esse laboris nulla qui in dolor voluptate aute reprehenderit amet ut et non voluptate elit irure mollit dolor consectetur nisi adipisicing commodo et mollit dolore incididunt cupidatat nulla ut irure deserunt non officia laboris fugiat ut pariatur ut non aliqua eiusmod dolor et nostrud minim elit occaecat commodo consectetur cillum elit laboris mollit dolore amet id qui eiusmod nulla elit eiusmod est ad aliqua aute enim ut aliquip ex in Ut nisi sint exercitation est mollit veniam cupidatat adipisicing occaecat dolor irure in aute aliqua ullamco.', _pivot_author_id: 2, _pivot_post_id: 2 },{ id: 1, owner_id: 1, blog_id: 1, name: 'This is a new Title!', content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.', _pivot_author_id: 2, _pivot_post_id: 1 }] }] } } }, 'does multi deep eager loads (site -> authors.ownPosts, authors.site, blogs.posts)': { mysql: { result: { id: 1, name: 'knexjs.org', authors: [{ id: 1, site_id: 1, first_name: 'Tim', last_name: 'Griesser', ownPosts: [{ id: 1, owner_id: 1, blog_id: 1, name: 'This is a new Title!', content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.' }], site: { id: 1, name: 'knexjs.org' } },{ id: 2, site_id: 1, first_name: 'Bazooka', last_name: 'Joe', ownPosts: [{ id: 2, owner_id: 2, blog_id: 2, name: 'This is a new Title 2!', content: 'Lorem ipsum Veniam ex amet occaecat dolore in pariatur minim est exercitation deserunt Excepteur enim officia occaecat in exercitation aute et ad esse ex in in dolore amet consequat quis sed mollit et id incididunt sint dolore velit officia dolor dolore laboris dolor Duis ea ex quis deserunt anim nisi qui culpa laboris nostrud Duis anim deserunt esse laboris nulla qui in dolor voluptate aute reprehenderit amet ut et non voluptate elit irure mollit dolor consectetur nisi adipisicing commodo et mollit dolore incididunt cupidatat nulla ut irure deserunt non officia laboris fugiat ut pariatur ut non aliqua eiusmod dolor et nostrud minim elit occaecat commodo consectetur cillum elit laboris mollit dolore amet id qui eiusmod nulla elit eiusmod est ad aliqua aute enim ut aliquip ex in Ut nisi sint exercitation est mollit veniam cupidatat adipisicing occaecat dolor irure in aute aliqua ullamco.' },{ id: 3, owner_id: 2, blog_id: 1, name: 'This is a new Title 3!', content: 'Lorem ipsum Reprehenderit esse esse consectetur aliquip magna.' }], site: { id: 1, name: 'knexjs.org' } }], blogs: [{ id: 1, site_id: 1, name: 'Main Site Blog', posts: [{ id: 1, owner_id: 1, blog_id: 1, name: 'This is a new Title!', content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.' },{ id: 3, owner_id: 2, blog_id: 1, name: 'This is a new Title 3!', content: 'Lorem ipsum Reprehenderit esse esse consectetur aliquip magna.' }] },{ id: 2, site_id: 1, name: 'Alternate Site Blog', posts: [{ id: 2, owner_id: 2, blog_id: 2, name: 'This is a new Title 2!', content: 'Lorem ipsum Veniam ex amet occaecat dolore in pariatur minim est exercitation deserunt Excepteur enim officia occaecat in exercitation aute et ad esse ex in in dolore amet consequat quis sed mollit et id incididunt sint dolore velit officia dolor dolore laboris dolor Duis ea ex quis deserunt anim nisi qui culpa laboris nostrud Duis anim deserunt esse laboris nulla qui in dolor voluptate aute reprehenderit amet ut et non voluptate elit irure mollit dolor consectetur nisi adipisicing commodo et mollit dolore incididunt cupidatat nulla ut irure deserunt non officia laboris fugiat ut pariatur ut non aliqua eiusmod dolor et nostrud minim elit occaecat commodo consectetur cillum elit laboris mollit dolore amet id qui eiusmod nulla elit eiusmod est ad aliqua aute enim ut aliquip ex in Ut nisi sint exercitation est mollit veniam cupidatat adipisicing occaecat dolor irure in aute aliqua ullamco.' }] }] } }, postgresql: { result: { id: 1, name: 'knexjs.org', authors: [{ id: 1, site_id: 1, first_name: 'Tim', last_name: 'Griesser', site: { id: 1, name: 'knexjs.org' }, ownPosts: [{ id: 1, owner_id: 1, blog_id: 1, name: 'This is a new Title!', content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.' }] },{ id: 2, site_id: 1, first_name: 'Bazooka', last_name: 'Joe', site: { id: 1, name: 'knexjs.org' }, ownPosts: [{ id: 2, owner_id: 2, blog_id: 2, name: 'This is a new Title 2!', content: 'Lorem ipsum Veniam ex amet occaecat dolore in pariatur minim est exercitation deserunt Excepteur enim officia occaecat in exercitation aute et ad esse ex in in dolore amet consequat quis sed mollit et id incididunt sint dolore velit officia dolor dolore laboris dolor Duis ea ex quis deserunt anim nisi qui culpa laboris nostrud Duis anim deserunt esse laboris nulla qui in dolor voluptate aute reprehenderit amet ut et non voluptate elit irure mollit dolor consectetur nisi adipisicing commodo et mollit dolore incididunt cupidatat nulla ut irure deserunt non officia laboris fugiat ut pariatur ut non aliqua eiusmod dolor et nostrud minim elit occaecat commodo consectetur cillum elit laboris mollit dolore amet id qui eiusmod nulla elit eiusmod est ad aliqua aute enim ut aliquip ex in Ut nisi sint exercitation est mollit veniam cupidatat adipisicing occaecat dolor irure in aute aliqua ullamco.' },{ id: 3, owner_id: 2, blog_id: 1, name: 'This is a new Title 3!', content: 'Lorem ipsum Reprehenderit esse esse consectetur aliquip magna.' }] }], blogs: [{ id: 1, site_id: 1, name: 'Main Site Blog', posts: [{ id: 1, owner_id: 1, blog_id: 1, name: 'This is a new Title!', content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.' },{ id: 3, owner_id: 2, blog_id: 1, name: 'This is a new Title 3!', content: 'Lorem ipsum Reprehenderit esse esse consectetur aliquip magna.' }] },{ id: 2, site_id: 1, name: 'Alternate Site Blog', posts: [{ id: 2, owner_id: 2, blog_id: 2, name: 'This is a new Title 2!', content: 'Lorem ipsum Veniam ex amet occaecat dolore in pariatur minim est exercitation deserunt Excepteur enim officia occaecat in exercitation aute et ad esse ex in in dolore amet consequat quis sed mollit et id incididunt sint dolore velit officia dolor dolore laboris dolor Duis ea ex quis deserunt anim nisi qui culpa laboris nostrud Duis anim deserunt esse laboris nulla qui in dolor voluptate aute reprehenderit amet ut et non voluptate elit irure mollit dolor consectetur nisi adipisicing commodo et mollit dolore incididunt cupidatat nulla ut irure deserunt non officia laboris fugiat ut pariatur ut non aliqua eiusmod dolor et nostrud minim elit occaecat commodo consectetur cillum elit laboris mollit dolore amet id qui eiusmod nulla elit eiusmod est ad aliqua aute enim ut aliquip ex in Ut nisi sint exercitation est mollit veniam cupidatat adipisicing occaecat dolor irure in aute aliqua ullamco.' }] }] } }, sqlite3: { result: { id: 1, name: 'knexjs.org', authors: [{ id: 1, site_id: 1, first_name: 'Tim', last_name: 'Griesser', ownPosts: [{ id: 1, owner_id: 1, blog_id: 1, name: 'This is a new Title!', content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.' }], site: { id: 1, name: 'knexjs.org' } },{ id: 2, site_id: 1, first_name: 'Bazooka', last_name: 'Joe', ownPosts: [{ id: 2, owner_id: 2, blog_id: 2, name: 'This is a new Title 2!', content: 'Lorem ipsum Veniam ex amet occaecat dolore in pariatur minim est exercitation deserunt Excepteur enim officia occaecat in exercitation aute et ad esse ex in in dolore amet consequat quis sed mollit et id incididunt sint dolore velit officia dolor dolore laboris dolor Duis ea ex quis deserunt anim nisi qui culpa laboris nostrud Duis anim deserunt esse laboris nulla qui in dolor voluptate aute reprehenderit amet ut et non voluptate elit irure mollit dolor consectetur nisi adipisicing commodo et mollit dolore incididunt cupidatat nulla ut irure deserunt non officia laboris fugiat ut pariatur ut non aliqua eiusmod dolor et nostrud minim elit occaecat commodo consectetur cillum elit laboris mollit dolore amet id qui eiusmod nulla elit eiusmod est ad aliqua aute enim ut aliquip ex in Ut nisi sint exercitation est mollit veniam cupidatat adipisicing occaecat dolor irure in aute aliqua ullamco.' },{ id: 3, owner_id: 2, blog_id: 1, name: 'This is a new Title 3!', content: 'Lorem ipsum Reprehenderit esse esse consectetur aliquip magna.' }], site: { id: 1, name: 'knexjs.org' } }], blogs: [{ id: 1, site_id: 1, name: 'Main Site Blog', posts: [{ id: 1, owner_id: 1, blog_id: 1, name: 'This is a new Title!', content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.' },{ id: 3, owner_id: 2, blog_id: 1, name: 'This is a new Title 3!', content: 'Lorem ipsum Reprehenderit esse esse consectetur aliquip magna.' }] },{ id: 2, site_id: 1, name: 'Alternate Site Blog', posts: [{ id: 2, owner_id: 2, blog_id: 2, name: 'This is a new Title 2!', content: 'Lorem ipsum Veniam ex amet occaecat dolore in pariatur minim est exercitation deserunt Excepteur enim officia occaecat in exercitation aute et ad esse ex in in dolore amet consequat quis sed mollit et id incididunt sint dolore velit officia dolor dolore laboris dolor Duis ea ex quis deserunt anim nisi qui culpa laboris nostrud Duis anim deserunt esse laboris nulla qui in dolor voluptate aute reprehenderit amet ut et non voluptate elit irure mollit dolor consectetur nisi adipisicing commodo et mollit dolore incididunt cupidatat nulla ut irure deserunt non officia laboris fugiat ut pariatur ut non aliqua eiusmod dolor et nostrud minim elit occaecat commodo consectetur cillum elit laboris mollit dolore amet id qui eiusmod nulla elit eiusmod est ad aliqua aute enim ut aliquip ex in Ut nisi sint exercitation est mollit veniam cupidatat adipisicing occaecat dolor irure in aute aliqua ullamco.' }] }] } } }, 'eager loads "hasMany" -> "hasMany" (sites -> authors.ownPosts)': { mysql: { result: [{ id: 1, name: 'knexjs.org', authors: [{ id: 1, site_id: 1, first_name: 'Tim', last_name: 'Griesser', ownPosts: [{ id: 1, owner_id: 1, blog_id: 1, name: 'This is a new Title!', content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.' }] },{ id: 2, site_id: 1, first_name: 'Bazooka', last_name: 'Joe', ownPosts: [{ id: 2, owner_id: 2, blog_id: 2, name: 'This is a new Title 2!', content: 'Lorem ipsum Veniam ex amet occaecat dolore in pariatur minim est exercitation deserunt Excepteur enim officia occaecat in exercitation aute et ad esse ex in in dolore amet consequat quis sed mollit et id incididunt sint dolore velit officia dolor dolore laboris dolor Duis ea ex quis deserunt anim nisi qui culpa laboris nostrud Duis anim deserunt esse laboris nulla qui in dolor voluptate aute reprehenderit amet ut et non voluptate elit irure mollit dolor consectetur nisi adipisicing commodo et mollit dolore incididunt cupidatat nulla ut irure deserunt non officia laboris fugiat ut pariatur ut non aliqua eiusmod dolor et nostrud minim elit occaecat commodo consectetur cillum elit laboris mollit dolore amet id qui eiusmod nulla elit eiusmod est ad aliqua aute enim ut aliquip ex in Ut nisi sint exercitation est mollit veniam cupidatat adipisicing occaecat dolor irure in aute aliqua ullamco.' },{ id: 3, owner_id: 2, blog_id: 1, name: 'This is a new Title 3!', content: 'Lorem ipsum Reprehenderit esse esse consectetur aliquip magna.' }] }] },{ id: 2, name: 'bookshelfjs.org', authors: [{ id: 3, site_id: 2, first_name: 'Charlie', last_name: 'Brown', ownPosts: [{ id: 4, owner_id: 3, blog_id: 3, name: 'This is a new Title 4!', content: 'Lorem ipsum Anim sed eu sint aute.' }] },{ id: 4, site_id: 2, first_name: 'Ron', last_name: 'Burgundy', ownPosts: [{ id: 5, owner_id: 4, blog_id: 4, name: 'This is a new Title 5!', content: 'Lorem ipsum Commodo consectetur eu ea amet laborum nulla eiusmod minim veniam ullamco nostrud sed mollit consectetur veniam mollit Excepteur quis cupidatat.' }] }] },{ id: 3, name: 'backbonejs.org', authors: [] }] }, postgresql: { result: [{ id: 1, name: 'knexjs.org', authors: [{ id: 1, site_id: 1, first_name: 'Tim', last_name: 'Griesser', ownPosts: [{ id: 1, owner_id: 1, blog_id: 1, name: 'This is a new Title!', content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.' }] },{ id: 2, site_id: 1, first_name: 'Bazooka', last_name: 'Joe', ownPosts: [{ id: 2, owner_id: 2, blog_id: 2, name: 'This is a new Title 2!', content: 'Lorem ipsum Veniam ex amet occaecat dolore in pariatur minim est exercitation deserunt Excepteur enim officia occaecat in exercitation aute et ad esse ex in in dolore amet consequat quis sed mollit et id incididunt sint dolore velit officia dolor dolore laboris dolor Duis ea ex quis deserunt anim nisi qui culpa laboris nostrud Duis anim deserunt esse laboris nulla qui in dolor voluptate aute reprehenderit amet ut et non voluptate elit irure mollit dolor consectetur nisi adipisicing commodo et mollit dolore incididunt cupidatat nulla ut irure deserunt non officia laboris fugiat ut pariatur ut non aliqua eiusmod dolor et nostrud minim elit occaecat commodo consectetur cillum elit laboris mollit dolore amet id qui eiusmod nulla elit eiusmod est ad aliqua aute enim ut aliquip ex in Ut nisi sint exercitation est mollit veniam cupidatat adipisicing occaecat dolor irure in aute aliqua ullamco.' },{ id: 3, owner_id: 2, blog_id: 1, name: 'This is a new Title 3!', content: 'Lorem ipsum Reprehenderit esse esse consectetur aliquip magna.' }] }] },{ id: 2, name: 'bookshelfjs.org', authors: [{ id: 3, site_id: 2, first_name: 'Charlie', last_name: 'Brown', ownPosts: [{ id: 4, owner_id: 3, blog_id: 3, name: 'This is a new Title 4!', content: 'Lorem ipsum Anim sed eu sint aute.' }] },{ id: 4, site_id: 2, first_name: 'Ron', last_name: 'Burgundy', ownPosts: [{ id: 5, owner_id: 4, blog_id: 4, name: 'This is a new Title 5!', content: 'Lorem ipsum Commodo consectetur eu ea amet laborum nulla eiusmod minim veniam ullamco nostrud sed mollit consectetur veniam mollit Excepteur quis cupidatat.' }] }] },{ id: 3, name: 'backbonejs.org', authors: [] }] }, sqlite3: { result: [{ id: 1, name: 'knexjs.org', authors: [{ id: 1, site_id: 1, first_name: 'Tim', last_name: 'Griesser', ownPosts: [{ id: 1, owner_id: 1, blog_id: 1, name: 'This is a new Title!', content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.' }] },{ id: 2, site_id: 1, first_name: 'Bazooka', last_name: 'Joe', ownPosts: [{ id: 2, owner_id: 2, blog_id: 2, name: 'This is a new Title 2!', content: 'Lorem ipsum Veniam ex amet occaecat dolore in pariatur minim est exercitation deserunt Excepteur enim officia occaecat in exercitation aute et ad esse ex in in dolore amet consequat quis sed mollit et id incididunt sint dolore velit officia dolor dolore laboris dolor Duis ea ex quis deserunt anim nisi qui culpa laboris nostrud Duis anim deserunt esse laboris nulla qui in dolor voluptate aute reprehenderit amet ut et non voluptate elit irure mollit dolor consectetur nisi adipisicing commodo et mollit dolore incididunt cupidatat nulla ut irure deserunt non officia laboris fugiat ut pariatur ut non aliqua eiusmod dolor et nostrud minim elit occaecat commodo consectetur cillum elit laboris mollit dolore amet id qui eiusmod nulla elit eiusmod est ad aliqua aute enim ut aliquip ex in Ut nisi sint exercitation est mollit veniam cupidatat adipisicing occaecat dolor irure in aute aliqua ullamco.' },{ id: 3, owner_id: 2, blog_id: 1, name: 'This is a new Title 3!', content: 'Lorem ipsum Reprehenderit esse esse consectetur aliquip magna.' }] }] },{ id: 2, name: 'bookshelfjs.org', authors: [{ id: 3, site_id: 2, first_name: 'Charlie', last_name: 'Brown', ownPosts: [{ id: 4, owner_id: 3, blog_id: 3, name: 'This is a new Title 4!', content: 'Lorem ipsum Anim sed eu sint aute.' }] },{ id: 4, site_id: 2, first_name: 'Ron', last_name: 'Burgundy', ownPosts: [{ id: 5, owner_id: 4, blog_id: 4, name: 'This is a new Title 5!', content: 'Lorem ipsum Commodo consectetur eu ea amet laborum nulla eiusmod minim veniam ullamco nostrud sed mollit consectetur veniam mollit Excepteur quis cupidatat.' }] }] },{ id: 3, name: 'backbonejs.org', authors: [] }] } }, 'eager loads relations on a populated model (site -> blogs, authors.site)': { mysql: { result: { id: 1, name: 'knexjs.org' } }, postgresql: { result: { id: 1, name: 'knexjs.org' } }, sqlite3: { result: { id: 1, name: 'knexjs.org' } } }, 'eager loads attributes on a collection (sites -> blogs, authors.site)': { mysql: { result: [{ id: 1, name: 'knexjs.org' },{ id: 2, name: 'bookshelfjs.org' },{ id: 3, name: 'backbonejs.org' }] }, postgresql: { result: [{ id: 1, name: 'knexjs.org' },{ id: 2, name: 'bookshelfjs.org' },{ id: 3, name: 'backbonejs.org' }] }, sqlite3: { result: [{ id: 1, name: 'knexjs.org' },{ id: 2, name: 'bookshelfjs.org' },{ id: 3, name: 'backbonejs.org' }] } }, 'works with many-to-many (user -> roles)': { mysql: { result: [{ rid: 4, name: 'admin', _pivot_uid: 1, _pivot_rid: 4 }] }, postgresql: { result: [{ rid: 4, name: 'admin', _pivot_uid: 1, _pivot_rid: 4 }] }, sqlite3: { result: [{ rid: 4, name: 'admin', _pivot_uid: 1, _pivot_rid: 4 }] } }, 'works with eager loaded many-to-many (user -> roles)': { mysql: { result: { uid: 1, username: 'root', roles: [{ rid: 4, name: 'admin', _pivot_uid: 1, _pivot_rid: 4 }] } }, postgresql: { result: { uid: 1, username: 'root', roles: [{ rid: 4, name: 'admin', _pivot_uid: 1, _pivot_rid: 4 }] } }, sqlite3: { result: { uid: 1, username: 'root', roles: [{ rid: 4, name: 'admin', _pivot_uid: 1, _pivot_rid: 4 }] } } }, 'handles morphOne (photo)': { mysql: { result: { id: 1, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'authors' } }, postgresql: { result: { id: 1, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'authors' } }, sqlite3: { result: { id: 1, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'authors' } } }, 'handles morphMany (photo)': { mysql: { result: [{ id: 3, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'sites' },{ id: 4, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'sites' }] }, postgresql: { result: [{ id: 3, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'sites' },{ id: 4, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'sites' }] }, sqlite3: { result: [{ id: 3, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'sites' },{ id: 4, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'sites' }] } }, 'handles morphTo (imageable "authors")': { mysql: { result: { id: 1, site_id: 1, first_name: 'Tim', last_name: 'Griesser' } }, postgresql: { result: { id: 1, site_id: 1, first_name: 'Tim', last_name: 'Griesser' } }, sqlite3: { result: { id: 1, site_id: 1, first_name: 'Tim', last_name: 'Griesser' } } }, 'handles morphTo (imageable "sites")': { mysql: { result: { id: 1, name: 'knexjs.org' } }, postgresql: { result: { id: 1, name: 'knexjs.org' } }, sqlite3: { result: { id: 1, name: 'knexjs.org' } } }, 'eager loads morphMany (sites -> photos)': { mysql: { result: [{ id: 1, name: 'knexjs.org', photos: [{ id: 3, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'sites' },{ id: 4, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'sites' }] },{ id: 2, name: 'bookshelfjs.org', photos: [{ id: 5, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 2, imageable_type: 'sites' },{ id: 6, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 2, imageable_type: 'sites' }] },{ id: 3, name: 'backbonejs.org', photos: [] }] }, postgresql: { result: [{ id: 1, name: 'knexjs.org', photos: [{ id: 3, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'sites' },{ id: 4, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'sites' }] },{ id: 2, name: 'bookshelfjs.org', photos: [{ id: 5, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 2, imageable_type: 'sites' },{ id: 6, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 2, imageable_type: 'sites' }] },{ id: 3, name: 'backbonejs.org', photos: [] }] }, sqlite3: { result: [{ id: 1, name: 'knexjs.org', photos: [{ id: 3, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'sites' },{ id: 4, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'sites' }] },{ id: 2, name: 'bookshelfjs.org', photos: [{ id: 5, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 2, imageable_type: 'sites' },{ id: 6, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 2, imageable_type: 'sites' }] },{ id: 3, name: 'backbonejs.org', photos: [] }] } }, 'eager loads morphTo (photos -> imageable)': { mysql: { result: [{ id: 1, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'authors', imageable: { id: 1, site_id: 1, first_name: 'Tim', last_name: 'Griesser' } },{ id: 2, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 2, imageable_type: 'authors', imageable: { id: 2, site_id: 1, first_name: 'Bazooka', last_name: 'Joe' } },{ id: 3, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'sites', imageable: { id: 1, name: 'knexjs.org' } },{ id: 4, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'sites', imageable: { id: 1, name: 'knexjs.org' } },{ id: 5, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 2, imageable_type: 'sites', imageable: { id: 2, name: 'bookshelfjs.org' } },{ id: 6, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 2, imageable_type: 'sites', imageable: { id: 2, name: 'bookshelfjs.org' } },{ id: 7, url: 'http://image.dev', caption: 'this is a test image', imageable_id: 10, imageable_type: 'sites', imageable: { } }] }, postgresql: { result: [{ id: 1, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'authors', imageable: { id: 1, site_id: 1, first_name: 'Tim', last_name: 'Griesser' } },{ id: 2, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 2, imageable_type: 'authors', imageable: { id: 2, site_id: 1, first_name: 'Bazooka', last_name: 'Joe' } },{ id: 3, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'sites', imageable: { id: 1, name: 'knexjs.org' } },{ id: 4, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'sites', imageable: { id: 1, name: 'knexjs.org' } },{ id: 5, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 2, imageable_type: 'sites', imageable: { id: 2, name: 'bookshelfjs.org' } },{ id: 6, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 2, imageable_type: 'sites', imageable: { id: 2, name: 'bookshelfjs.org' } },{ id: 7, url: 'http://image.dev', caption: 'this is a test image', imageable_id: 10, imageable_type: 'sites', imageable: { } }] }, sqlite3: { result: [{ id: 1, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'authors', imageable: { id: 1, site_id: 1, first_name: 'Tim', last_name: 'Griesser' } },{ id: 2, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 2, imageable_type: 'authors', imageable: { id: 2, site_id: 1, first_name: 'Bazooka', last_name: 'Joe' } },{ id: 3, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'sites', imageable: { id: 1, name: 'knexjs.org' } },{ id: 4, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'sites', imageable: { id: 1, name: 'knexjs.org' } },{ id: 5, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 2, imageable_type: 'sites', imageable: { id: 2, name: 'bookshelfjs.org' } },{ id: 6, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 2, imageable_type: 'sites', imageable: { id: 2, name: 'bookshelfjs.org' } },{ id: 7, url: 'http://image.dev', caption: 'this is a test image', imageable_id: 10, imageable_type: 'sites', imageable: { } }] } }, 'eager loads beyond the morphTo, where possible': { mysql: { result: [{ id: 1, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'authors', imageable: { id: 1, site_id: 1, first_name: 'Tim', last_name: 'Griesser' } },{ id: 2, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 2, imageable_type: 'authors', imageable: { id: 2, site_id: 1, first_name: 'Bazooka', last_name: 'Joe' } },{ id: 3, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'sites', imageable: { id: 1, name: 'knexjs.org', authors: [{ id: 1, site_id: 1, first_name: 'Tim', last_name: 'Griesser' },{ id: 2, site_id: 1, first_name: 'Bazooka', last_name: 'Joe' }] } },{ id: 4, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'sites', imageable: { id: 1, name: 'knexjs.org', authors: [{ id: 1, site_id: 1, first_name: 'Tim', last_name: 'Griesser' },{ id: 2, site_id: 1, first_name: 'Bazooka', last_name: 'Joe' }] } },{ id: 5, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 2, imageable_type: 'sites', imageable: { id: 2, name: 'bookshelfjs.org', authors: [{ id: 3, site_id: 2, first_name: 'Charlie', last_name: 'Brown' },{ id: 4, site_id: 2, first_name: 'Ron', last_name: 'Burgundy' }] } },{ id: 6, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 2, imageable_type: 'sites', imageable: { id: 2, name: 'bookshelfjs.org', authors: [{ id: 3, site_id: 2, first_name: 'Charlie', last_name: 'Brown' },{ id: 4, site_id: 2, first_name: 'Ron', last_name: 'Burgundy' }] } },{ id: 7, url: 'http://image.dev', caption: 'this is a test image', imageable_id: 10, imageable_type: 'sites', imageable: { } }] }, postgresql: { result: [{ id: 1, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'authors', imageable: { id: 1, site_id: 1, first_name: 'Tim', last_name: 'Griesser' } },{ id: 2, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 2, imageable_type: 'authors', imageable: { id: 2, site_id: 1, first_name: 'Bazooka', last_name: 'Joe' } },{ id: 3, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'sites', imageable: { id: 1, name: 'knexjs.org', authors: [{ id: 1, site_id: 1, first_name: 'Tim', last_name: 'Griesser' },{ id: 2, site_id: 1, first_name: 'Bazooka', last_name: 'Joe' }] } },{ id: 4, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'sites', imageable: { id: 1, name: 'knexjs.org', authors: [{ id: 1, site_id: 1, first_name: 'Tim', last_name: 'Griesser' },{ id: 2, site_id: 1, first_name: 'Bazooka', last_name: 'Joe' }] } },{ id: 5, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 2, imageable_type: 'sites', imageable: { id: 2, name: 'bookshelfjs.org', authors: [{ id: 3, site_id: 2, first_name: 'Charlie', last_name: 'Brown' },{ id: 4, site_id: 2, first_name: 'Ron', last_name: 'Burgundy' }] } },{ id: 6, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 2, imageable_type: 'sites', imageable: { id: 2, name: 'bookshelfjs.org', authors: [{ id: 3, site_id: 2, first_name: 'Charlie', last_name: 'Brown' },{ id: 4, site_id: 2, first_name: 'Ron', last_name: 'Burgundy' }] } },{ id: 7, url: 'http://image.dev', caption: 'this is a test image', imageable_id: 10, imageable_type: 'sites', imageable: { } }] }, sqlite3: { result: [{ id: 1, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'authors', imageable: { id: 1, site_id: 1, first_name: 'Tim', last_name: 'Griesser' } },{ id: 2, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 2, imageable_type: 'authors', imageable: { id: 2, site_id: 1, first_name: 'Bazooka', last_name: 'Joe' } },{ id: 3, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'sites', imageable: { id: 1, name: 'knexjs.org', authors: [{ id: 1, site_id: 1, first_name: 'Tim', last_name: 'Griesser' },{ id: 2, site_id: 1, first_name: 'Bazooka', last_name: 'Joe' }] } },{ id: 4, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'sites', imageable: { id: 1, name: 'knexjs.org', authors: [{ id: 1, site_id: 1, first_name: 'Tim', last_name: 'Griesser' },{ id: 2, site_id: 1, first_name: 'Bazooka', last_name: 'Joe' }] } },{ id: 5, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 2, imageable_type: 'sites', imageable: { id: 2, name: 'bookshelfjs.org', authors: [{ id: 3, site_id: 2, first_name: 'Charlie', last_name: 'Brown' },{ id: 4, site_id: 2, first_name: 'Ron', last_name: 'Burgundy' }] } },{ id: 6, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 2, imageable_type: 'sites', imageable: { id: 2, name: 'bookshelfjs.org', authors: [{ id: 3, site_id: 2, first_name: 'Charlie', last_name: 'Brown' },{ id: 4, site_id: 2, first_name: 'Ron', last_name: 'Burgundy' }] } },{ id: 7, url: 'http://image.dev', caption: 'this is a test image', imageable_id: 10, imageable_type: 'sites', imageable: { } }] } }, 'handles hasMany `through`': { mysql: { result: [{ id: 1, post_id: 1, name: '(blank)', email: 'test@example.com', comment: 'this is neat.', _pivot_id: 1, _pivot_blog_id: 1 }] }, postgresql: { result: [{ id: 1, post_id: 1, name: '(blank)', email: 'test@example.com', comment: 'this is neat.', _pivot_id: 1, _pivot_blog_id: 1 }] }, sqlite3: { result: [{ id: 1, post_id: 1, name: '(blank)', email: 'test@example.com', comment: 'this is neat.', _pivot_id: 1, _pivot_blog_id: 1 }] } }, 'eager loads hasMany `through`': { mysql: { result: [{ id: 1, site_id: 1, name: 'Main Site Blog', comments: [{ id: 1, post_id: 1, name: '(blank)', email: 'test@example.com', comment: 'this is neat.', _pivot_id: 1, _pivot_blog_id: 1 }] },{ id: 2, site_id: 1, name: 'Alternate Site Blog', comments: [] }] }, postgresql: { result: [{ id: 1, site_id: 1, name: 'Main Site Blog', comments: [{ id: 1, post_id: 1, name: '(blank)', email: 'test@example.com', comment: 'this is neat.', _pivot_id: 1, _pivot_blog_id: 1 }] },{ id: 2, site_id: 1, name: 'Alternate Site Blog', comments: [] }] }, sqlite3: { result: [{ id: 1, site_id: 1, name: 'Main Site Blog', comments: [{ id: 1, post_id: 1, name: '(blank)', email: 'test@example.com', comment: 'this is neat.', _pivot_id: 1, _pivot_blog_id: 1 }] },{ id: 2, site_id: 1, name: 'Alternate Site Blog', comments: [] }] } }, 'handles hasOne `through`': { mysql: { result: { id: 1, meta_id: 1, other_description: 'This is an info block for hasOne -> through test', _pivot_id: 1, _pivot_site_id: 1 } }, postgresql: { result: { id: 1, meta_id: 1, other_description: 'This is an info block for hasOne -> through test', _pivot_id: 1, _pivot_site_id: 1 } }, sqlite3: { result: { id: 1, meta_id: 1, other_description: 'This is an info block for hasOne -> through test', _pivot_id: 1, _pivot_site_id: 1 } } }, 'eager loads hasOne `through`': { mysql: { result: [{ id: 1, name: 'knexjs.org', info: { id: 1, meta_id: 1, other_description: 'This is an info block for hasOne -> through test', _pivot_id: 1, _pivot_site_id: 1 } },{ id: 2, name: 'bookshelfjs.org', info: { id: 2, meta_id: 2, other_description: 'This is an info block for an eager hasOne -> through test', _pivot_id: 2, _pivot_site_id: 2 } }] }, postgresql: { result: [{ id: 1, name: 'knexjs.org', info: { id: 1, meta_id: 1, other_description: 'This is an info block for hasOne -> through test', _pivot_id: 1, _pivot_site_id: 1 } },{ id: 2, name: 'bookshelfjs.org', info: { id: 2, meta_id: 2, other_description: 'This is an info block for an eager hasOne -> through test', _pivot_id: 2, _pivot_site_id: 2 } }] }, sqlite3: { result: [{ id: 1, name: 'knexjs.org', info: { id: 1, meta_id: 1, other_description: 'This is an info block for hasOne -> through test', _pivot_id: 1, _pivot_site_id: 1 } },{ id: 2, name: 'bookshelfjs.org', info: { id: 2, meta_id: 2, other_description: 'This is an info block for an eager hasOne -> through test', _pivot_id: 2, _pivot_site_id: 2 } }] } }, 'eager loads belongsToMany `through`': { mysql: { result: [{ id: 1, site_id: 1, first_name: 'Tim', last_name: 'Griesser', blogs: [{ id: 1, site_id: 1, name: 'Main Site Blog', _pivot_id: 1, _pivot_owner_id: 1, _pivot_blog_id: 1 }] },{ id: 2, site_id: 1, first_name: 'Bazooka', last_name: 'Joe', blogs: [{ id: 1, site_id: 1, name: 'Main Site Blog', _pivot_id: 3, _pivot_owner_id: 2, _pivot_blog_id: 1 },{ id: 2, site_id: 1, name: 'Alternate Site Blog', _pivot_id: 2, _pivot_owner_id: 2, _pivot_blog_id: 2 }] },{ id: 3, site_id: 2, first_name: 'Charlie', last_name: 'Brown', blogs: [{ id: 3, site_id: 2, name: 'Main Site Blog', _pivot_id: 4, _pivot_owner_id: 3, _pivot_blog_id: 3 }] },{ id: 4, site_id: 2, first_name: 'Ron', last_name: 'Burgundy', blogs: [{ id: 4, site_id: 2, name: 'Alternate Site Blog', _pivot_id: 5, _pivot_owner_id: 4, _pivot_blog_id: 4 }] }] }, postgresql: { result: [{ id: 1, site_id: 1, first_name: 'Tim', last_name: 'Griesser', blogs: [{ id: 1, site_id: 1, name: 'Main Site Blog', _pivot_id: 1, _pivot_owner_id: 1, _pivot_blog_id: 1 }] },{ id: 2, site_id: 1, first_name: 'Bazooka', last_name: 'Joe', blogs: [{ id: 1, site_id: 1, name: 'Main Site Blog', _pivot_id: 3, _pivot_owner_id: 2, _pivot_blog_id: 1 },{ id: 2, site_id: 1, name: 'Alternate Site Blog', _pivot_id: 2, _pivot_owner_id: 2, _pivot_blog_id: 2 }] },{ id: 3, site_id: 2, first_name: 'Charlie', last_name: 'Brown', blogs: [{ id: 3, site_id: 2, name: 'Main Site Blog', _pivot_id: 4, _pivot_owner_id: 3, _pivot_blog_id: 3 }] },{ id: 4, site_id: 2, first_name: 'Ron', last_name: 'Burgundy', blogs: [{ id: 4, site_id: 2, name: 'Alternate Site Blog', _pivot_id: 5, _pivot_owner_id: 4, _pivot_blog_id: 4 }] }] }, sqlite3: { result: [{ id: 1, site_id: 1, first_name: 'Tim', last_name: 'Griesser', blogs: [{ id: 1, site_id: 1, name: 'Main Site Blog', _pivot_id: 1, _pivot_owner_id: 1, _pivot_blog_id: 1 }] },{ id: 2, site_id: 1, first_name: 'Bazooka', last_name: 'Joe', blogs: [{ id: 2, site_id: 1, name: 'Alternate Site Blog', _pivot_id: 2, _pivot_owner_id: 2, _pivot_blog_id: 2 },{ id: 1, site_id: 1, name: 'Main Site Blog', _pivot_id: 3, _pivot_owner_id: 2, _pivot_blog_id: 1 }] },{ id: 3, site_id: 2, first_name: 'Charlie', last_name: 'Brown', blogs: [{ id: 3, site_id: 2, name: 'Main Site Blog', _pivot_id: 4, _pivot_owner_id: 3, _pivot_blog_id: 3 }] },{ id: 4, site_id: 2, first_name: 'Ron', last_name: 'Burgundy', blogs: [{ id: 4, site_id: 2, name: 'Alternate Site Blog', _pivot_id: 5, _pivot_owner_id: 4, _pivot_blog_id: 4 }] }] } }, '#65 - should eager load correctly for models': { mysql: { result: { hostname: 'google.com', instance_id: 3, route: null, instance: { id: 3, name: 'search engine' } } }, postgresql: { result: { hostname: 'google.com', instance_id: 3, route: null, instance: { id: '3', name: 'search engine' } } }, sqlite3: { result: { hostname: 'google.com', instance_id: 3, route: null, instance: { id: 3, name: 'search engine' } } } }, '#65 - should eager load correctly for collections': { mysql: { result: [{ hostname: 'google.com', instance_id: 3, route: null, instance: { id: 3, name: 'search engine' } },{ hostname: 'apple.com', instance_id: 10, route: null, instance: { id: 10, name: 'computers' } }] }, postgresql: { result: [{ hostname: 'google.com', instance_id: 3, route: null, instance: { id: '3', name: 'search engine' } },{ hostname: 'apple.com', instance_id: 10, route: null, instance: { id: '10', name: 'computers' } }] }, sqlite3: { result: [{ hostname: 'google.com', instance_id: 3, route: null, instance: { id: 3, name: 'search engine' } },{ hostname: 'apple.com', instance_id: 10, route: null, instance: { id: 10, name: 'computers' } }] } }, 'parses eager-loaded morphTo relations (model)': { mysql: { result: [{ id: 1, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'authors', imageableParsed: { id_parsed: 1, site_id_parsed: 1, first_name_parsed: 'Tim', last_name_parsed: 'Griesser' } },{ id: 2, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 2, imageable_type: 'authors', imageableParsed: { id_parsed: 2, site_id_parsed: 1, first_name_parsed: 'Bazooka', last_name_parsed: 'Joe' } },{ id: 3, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'sites', imageableParsed: { id_parsed: 1, name_parsed: 'knexjs.org', meta: { id: 1, site_id: 1, description: 'This is a description for the Knexjs Site' } } },{ id: 4, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'sites', imageableParsed: { id_parsed: 1, name_parsed: 'knexjs.org', meta: { id: 1, site_id: 1, description: 'This is a description for the Knexjs Site' } } },{ id: 5, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 2, imageable_type: 'sites', imageableParsed: { id_parsed: 2, name_parsed: 'bookshelfjs.org', meta: { id: 2, site_id: 2, description: 'This is a description for the Bookshelfjs Site' } } },{ id: 6, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 2, imageable_type: 'sites', imageableParsed: { id_parsed: 2, name_parsed: 'bookshelfjs.org', meta: { id: 2, site_id: 2, description: 'This is a description for the Bookshelfjs Site' } } },{ id: 7, url: 'http://image.dev', caption: 'this is a test image', imageable_id: 10, imageable_type: 'sites', imageableParsed: { } }] }, postgresql: { result: [{ id: 1, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'authors', imageableParsed: { id_parsed: 1, site_id_parsed: 1, first_name_parsed: 'Tim', last_name_parsed: 'Griesser' } },{ id: 2, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 2, imageable_type: 'authors', imageableParsed: { id_parsed: 2, site_id_parsed: 1, first_name_parsed: 'Bazooka', last_name_parsed: 'Joe' } },{ id: 3, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'sites', imageableParsed: { id_parsed: 1, name_parsed: 'knexjs.org', meta: { id: 1, site_id: 1, description: 'This is a description for the Knexjs Site' } } },{ id: 4, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'sites', imageableParsed: { id_parsed: 1, name_parsed: 'knexjs.org', meta: { id: 1, site_id: 1, description: 'This is a description for the Knexjs Site' } } },{ id: 5, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 2, imageable_type: 'sites', imageableParsed: { id_parsed: 2, name_parsed: 'bookshelfjs.org', meta: { id: 2, site_id: 2, description: 'This is a description for the Bookshelfjs Site' } } },{ id: 6, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 2, imageable_type: 'sites', imageableParsed: { id_parsed: 2, name_parsed: 'bookshelfjs.org', meta: { id: 2, site_id: 2, description: 'This is a description for the Bookshelfjs Site' } } },{ id: 7, url: 'http://image.dev', caption: 'this is a test image', imageable_id: 10, imageable_type: 'sites', imageableParsed: { } }] }, sqlite3: { result: [{ id: 1, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'authors', imageableParsed: { id_parsed: 1, site_id_parsed: 1, first_name_parsed: 'Tim', last_name_parsed: 'Griesser' } },{ id: 2, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 2, imageable_type: 'authors', imageableParsed: { id_parsed: 2, site_id_parsed: 1, first_name_parsed: 'Bazooka', last_name_parsed: 'Joe' } },{ id: 3, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'sites', imageableParsed: { id_parsed: 1, name_parsed: 'knexjs.org', meta: { id: 1, site_id: 1, description: 'This is a description for the Knexjs Site' } } },{ id: 4, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'sites', imageableParsed: { id_parsed: 1, name_parsed: 'knexjs.org', meta: { id: 1, site_id: 1, description: 'This is a description for the Knexjs Site' } } },{ id: 5, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 2, imageable_type: 'sites', imageableParsed: { id_parsed: 2, name_parsed: 'bookshelfjs.org', meta: { id: 2, site_id: 2, description: 'This is a description for the Bookshelfjs Site' } } },{ id: 6, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 2, imageable_type: 'sites', imageableParsed: { id_parsed: 2, name_parsed: 'bookshelfjs.org', meta: { id: 2, site_id: 2, description: 'This is a description for the Bookshelfjs Site' } } },{ id: 7, url: 'http://image.dev', caption: 'this is a test image', imageable_id: 10, imageable_type: 'sites', imageableParsed: { } }] } } };
viniborges/designizando
node_modules/bookshelf/test/integration/output/Relations.js
JavaScript
mit
97,438
/** * Module dependencies */ var Server = require('annex-ws-node').Server; var http = require('http'); var stack = require('connect-stack'); var pns = require('pack-n-stack'); module.exports = function createServer(opts) { var server = http.createServer(); server.stack = []; server.handle = stack(server.stack); server.use = function(fn) { fn.handle = fn; server.stack.push(fn); return server; }; var routes = server.routes = {}; var hasPushedRouter = false; server.register = server.fn = function(modName, fnName, cb) { var mod = routes[modName] = routes[modName] || {}; var fn = mod[fnName] = mod[fnName] || []; fn.push(cb); server.emit('register:call', modName, fnName); if (hasPushedRouter) return server; server.use(router); hasPushedRouter = true; return server; }; function router(req, res, next) { var mod = routes[req.module]; if (!mod) return next(); var fn = mod[req.method]; if (!fn) return next(); // TODO support next('route') fn[0](req, res, next); } var wss = new Server({server: server, marshal: opts.marshal}); wss.listen(function(req, res) { // TODO do a domain here server.handle(req, res, function(err) { if (!res._sent) { err ? res.error(err.message) : res.error(req.module + ':' + req.method + ' not implemented'); if (err) console.error(err.stack || err.message); } }); }); return server; }
poegroup/poe-service-node
server.js
JavaScript
mit
1,468
(function () { 'use strict'; /* Controllers */ var pollsControllers = angular.module('pollsControllers', []); var author = 'Patrick Nicholls'; pollsControllers.controller('PollListCtrl', ['$scope', '$http', function ($scope, $http) { var resource = "/~pjn59/365/polls/index.php/services/polls"; $scope.polls = undefined; $scope.author = author; $http.get(resource) .success(function(data){ $scope.polls = data; }) .error(function(){ console.log("Couldn't get data"); }); }]); pollsControllers.controller('PollDetailCtrl', ['$scope', '$routeParams', '$http', function($scope, $routeParams, $http) { $scope.pollId = $routeParams.pollId; $scope.title = undefined; $scope.quesiton = undefined; $scope.choice = undefined; var base_url = "/~pjn59/365/polls/index.php/services/"; $http.get(base_url + "polls/" + $scope.pollId) .success(function(data){ console.log(data); var choices = []; for (var i = 0; i < data.choices.length; i++) { choices[i] = { 'choice': data.choices[i], 'votes' : parseInt(data.votes[i]) }; } $scope.choices = choices; $scope.question = data.question; $scope.title = data.title; console.log($scope.choices); }) .error(function(){ console.log("Couldn't get data"); }); $scope.vote = function() { //Increment database through PHP somehow $scope.choices[$scope.choice-1].votes += 1; $http.post(base_url + "votes/" + $scope.pollId + "/" + $scope.choice) .success(function(data){ console.log("Vote succeeded") }) .error(function(){ console.log("Vote unsuccessful"); }); }; $scope.reset = function() { for (var i = 0; i < $scope.choices.length; i++) { $scope.choices[i].votes = 0; } $http.delete(base_url + "votes/" + $scope.pollId) .success(function(data){ console.log("Reset succeeded") }) .error(function(){ console.log("Reset unsuccessful"); }); } }]); pollsControllers.controller('AboutCtrl', ['$scope', function ($scope) { $scope.author = author; }]); }())
agronauts/poll
angularjs/js/controllers.js
JavaScript
mit
2,957
// Generated by CoffeeScript 1.7.1 (function() { var ERROR, IGNORE, WARN; ERROR = 'error'; WARN = 'warn'; IGNORE = 'ignore'; module.exports = { coffeescript_error: { level: ERROR, message: '' } }; }).call(this);
prehnRA/lintron
src/coffeelint/lib/rules.js
JavaScript
mit
249
/** * Run the APP */ app.run();
bordeux/GeekShare
src/Acme/GeekShareBundle/Angular/init/run.js
JavaScript
mit
34
/* * slush-ml-3t * https://github.com/edmacabebe/slush-ml-3t * * Copyright (c) 2017, edmacabebe * Licensed under the MIT license. */ 'use strict'; var gulp = require('gulp'), install = require('gulp-install'), conflict = require('gulp-conflict'), template = require('gulp-template'), rename = require('gulp-rename'), _ = require('underscore.string'), inquirer = require('inquirer'), path = require('path'); function format(string) { var username = string.toLowerCase(); return username.replace(/\s/g, ''); } var defaults = (function () { var workingDirName = path.basename(process.cwd()), homeDir, osUserName, configFile, user; if (process.platform === 'win32') { homeDir = process.env.USERPROFILE; osUserName = process.env.USERNAME || path.basename(homeDir).toLowerCase(); } else { homeDir = process.env.HOME || process.env.HOMEPATH; osUserName = homeDir && homeDir.split('/').pop() || 'root'; } configFile = path.join(homeDir, '.gitconfig'); user = {}; if (require('fs').existsSync(configFile)) { user = require('iniparser').parseSync(configFile).user; } return { appName: workingDirName, userName: osUserName || format(user.name || ''), authorName: user.name || '', authorEmail: user.email || '' }; })(); gulp.task('default', function (done) { var prompts = [{ name: 'appName', message: 'What is the name of your project?', default: defaults.appName }, { name: 'appDescription', message: 'What is the description?' }, { name: 'appVersion', message: 'What is the version of your project?', default: '0.1.0' }, { name: 'authorName', message: 'What is the author name?', default: defaults.authorName }, { name: 'authorEmail', message: 'What is the author email?', default: defaults.authorEmail }, { name: 'userName', message: 'What is the github username?', default: defaults.userName }, { type: 'confirm', name: 'moveon', message: 'Continue?' }]; //Ask inquirer.prompt(prompts, function (answers) { if (!answers.moveon) { return done(); } answers.appNameSlug = _.slugify(answers.appName); gulp.src(__dirname + '/templates/**') .pipe(template(answers)) .pipe(rename(function (file) { if (file.basename[0] === '_') { file.basename = '.' + file.basename.slice(1); } })) .pipe(conflict('./')) .pipe(gulp.dest('./')) .pipe(install()) .on('end', function () { done(); }); }); });
edmacabebe/ML-3T-Dev
slushfile.js
JavaScript
mit
2,940
angular.module('streama').controller('adminVideosCtrl', ['$scope', 'apiService', 'modalService', '$state', function ($scope, apiService, modalService, $state) { $scope.loading = true; apiService.genericVideo.list().then(function (response) { $scope.videos = response.data; $scope.loading = false; }); $scope.openGenericVideoModal = function () { modalService.genericVideoModal(null, function (data) { $state.go('admin.video', {videoId: data.id}); }); }; $scope.addFromSuggested = function (movie, redirect) { var tempMovie = angular.copy(movie); var apiId = tempMovie.id; delete tempMovie.id; tempMovie.apiId = apiId; apiService.movie.save(tempMovie).then(function (response) { if(redirect){ $state.go('admin.movie', {movieId: response.data.id}); }else{ $scope.movies.push(response.data); } }); }; $scope.alreadyAdded = function (movie) { console.log('%c movie', 'color: deeppink; font-weight: bold; text-shadow: 0 0 5px deeppink;', movie); return movie.id && _.find($scope.movies, {apiId: movie.id.toString()}); }; }]);
dularion/streama
grails-app/assets/javascripts/streama/controllers/admin-videos-ctrl.js
JavaScript
mit
1,084
var cookie = require('../index'); chai.should(); describe('cookie monster', function() { it('sets a cookie', function (){ cookie.setItem('cookieKey', 'cookieVal'); document.cookie.should.contain('cookieKey=cookieVal'); }); it('gets a cookie', function (){ document.cookie = 'dumby=mcdumberson;'; cookie.getItem('dumby').should.equal('mcdumberson'); }); it('sets and gets cookie with `=` in value', function (){ cookie.setItem('key', 'val=ue'); cookie.getItem('key').should.equal('val=ue'); }); it('removes a cookie', function (){ document.cookie = 'dumby=mcdumberson;'; document.cookie.should.contain('dumby=mcdumberson'); cookie.removeItem('dumby'); document.cookie.should.not.contain('dumby=mcdumberson'); }); it('sets 30 cookies and clears all of them', function (){ for (var i = 0; i++; i < 30){ cookie.setItem('key' + i, 'value' + i); } for (var i = 0; i++; i < 30){ cookie.getItem('key' + i).should.equal('value' + i); } cookie.clear(); document.cookie.should.equal(''); }); });
kahnjw/cookie-monster
test/cookie-monster-spec.js
JavaScript
mit
1,068
/** * * Store transaction * * Programmer By Emay Komarudin. * 2013 * * Description Store transaction * * **/ var data_gen = generate_transaction_list(30); Ext.define('App.store.transaction.sListTrx',{ extend : 'Ext.data.Store', // groupField: 'trx_no', // model : 'App.model.transaction.mOrders', fields : ['trx_no','user_name','status','count_orders','count_items','order_no'], data : data_gen });
emayk/ics
public/frontend/app/store/transaction/sListTrx.js
JavaScript
mit
405
'use strict' const { Message: MessageModel } = require('../model') module.exports = exports = { sendAtMessage: (masterId, authorId, topicId, replyId) => { return exports.sendMessage('at', masterId, authorId, topicId, replyId) }, sendReplyMessage: (masterId, authorId, topicId, replyId) => { return exports.sendMessage('reply', masterId, authorId, topicId, replyId) }, sendMessage: (type, masterId, authorId, topicId, replyId) => { return new MessageModel({ type: type, master_id: masterId, author_id: authorId, topic_id: topicId, reply_id: replyId }).save() } }
xiedacon/nodeclub-koa
app/common/message.js
JavaScript
mit
622
export { default as Toolbar } from './Toolbar'; export { default as ToolbarSection } from './ToolbarSection'; export { default as ToolbarTitle } from './ToolbarTitle'; export { default as ToolbarRow } from './ToolbarRow'; export { default as ToolbarIcon } from './ToolbarIcon';
kradio3/react-mdc-web
src/Toolbar/index.js
JavaScript
mit
278
var SanctuaryApp = angular.module('SanctuaryApp', [ 'ngRoute', 'SanctuaryControllers' ]); SanctuaryApp.config(['$routeProvider', function($routeProvider) { $routeProvider .when('/youtubelist', { templateUrl: 'partials/youtubelist.html', controller: 'YoutubeListController' }) .otherwise({ redirectTo: '/youtubelist' }); }]);
Josh-x/sanctuarywebapp
app/app.js
JavaScript
mit
386
/* * stylie.treeview * https://github.com/typesettin/stylie.treeview * * Copyright (c) 2015 Yaw Joseph Etse. All rights reserved. */ 'use strict'; var extend = require('util-extend'), CodeMirror = require('codemirror'), StylieModals = require('stylie.modals'), editorModals, events = require('events'), classie = require('classie'), util = require('util'); require('../../node_modules/codemirror/addon/edit/matchbrackets'); require('../../node_modules/codemirror/addon/hint/css-hint'); require('../../node_modules/codemirror/addon/hint/html-hint'); require('../../node_modules/codemirror/addon/hint/javascript-hint'); require('../../node_modules/codemirror/addon/hint/show-hint'); require('../../node_modules/codemirror/addon/lint/css-lint'); require('../../node_modules/codemirror/addon/lint/javascript-lint'); // require('../../node_modules/codemirror/addon/lint/json-lint'); require('../../node_modules/codemirror/addon/lint/lint'); // require('../../node_modules/codemirror/addon/lint/html-lint'); require('../../node_modules/codemirror/addon/comment/comment'); require('../../node_modules/codemirror/addon/comment/continuecomment'); require('../../node_modules/codemirror/addon/fold/foldcode'); require('../../node_modules/codemirror/addon/fold/comment-fold'); require('../../node_modules/codemirror/addon/fold/indent-fold'); require('../../node_modules/codemirror/addon/fold/brace-fold'); require('../../node_modules/codemirror/addon/fold/foldgutter'); require('../../node_modules/codemirror/mode/css/css'); require('../../node_modules/codemirror/mode/htmlembedded/htmlembedded'); require('../../node_modules/codemirror/mode/htmlmixed/htmlmixed'); require('../../node_modules/codemirror/mode/javascript/javascript'); var saveSelection = function () { if (window.getSelection) { var sel = window.getSelection(); if (sel.getRangeAt && sel.rangeCount) { return sel.getRangeAt(0); } } else if (document.selection && document.selection.createRange) { return document.selection.createRange(); } return null; }; var restoreSelection = function (range) { if (range) { if (window.getSelection) { var sel = window.getSelection(); sel.removeAllRanges(); sel.addRange(range); } else if (document.selection && range.select) { range.select(); } } }; var getInsertTextModal = function (orignialid, mtype) { var returnDiv = document.createElement('div'), modaltype = (mtype === 'image') ? 'image' : 'text', // execcmd = (mtype === 'image') ? 'insertImage' : 'createLink', samplelink = (mtype === 'image') ? 'https://developers.google.com/+/images/branding/g+138.png' : 'http://example.com', linktype = (mtype === 'image') ? 'image' : 'link'; returnDiv.setAttribute('id', orignialid + '-insert' + modaltype + '-modal'); returnDiv.setAttribute('data-name', orignialid + '-insert' + modaltype + '-modal'); returnDiv.setAttribute('class', 'ts-modal ts-modal-effect-1 insert' + modaltype + '-modal'); var divInnerHTML = '<section class="ts-modal-content ts-bg-text-primary-color ts-no-heading-margin ts-padding-lg ts-shadow ">'; divInnerHTML += '<div class="ts-form">'; divInnerHTML += '<div class="ts-row">'; divInnerHTML += '<div class="ts-col-span12">'; divInnerHTML += '<h6>Insert a link</h6>'; divInnerHTML += '</div>'; divInnerHTML += '</div>'; // divInnerHTML += '<div class="ts-row">'; // divInnerHTML += '<div class="ts-col-span4">'; // divInnerHTML += '<label class="ts-label">text</label>'; // divInnerHTML += '</div>'; // divInnerHTML += '<div class="ts-col-span8">'; // divInnerHTML += '<input type="text" name="link_url" placeholder="some web link" value="some web link"/>'; // divInnerHTML += '</div>'; // divInnerHTML += '</div>'; divInnerHTML += '<div class="ts-row">'; divInnerHTML += '<div class="ts-col-span4">'; divInnerHTML += '<label class="ts-label">url</label>'; divInnerHTML += '</div>'; divInnerHTML += '<div class="ts-col-span8">'; divInnerHTML += '<input type="text" class="ts-input ts-' + linktype + '_url" name="' + linktype + '_url" placeholder="' + samplelink + '" value="' + samplelink + '"/>'; divInnerHTML += '</div>'; divInnerHTML += '</div>'; divInnerHTML += '<div class="ts-row ts-text-center">'; divInnerHTML += '<div class="ts-col-span6">'; // divInnerHTML += '<button type="button" class="ts-button ts-modal-close ts-button-primary-color" onclick="document.execCommand(\'insertImage\', false, \'http://lorempixel.com/40/20/sports/\');">insert link</button>'; divInnerHTML += '<button type="button" class="ts-button ts-modal-close ts-button-primary-color add-' + linktype + '-button" >insert ' + linktype + '</button>'; divInnerHTML += '</div>'; divInnerHTML += '<div class="ts-col-span6">'; divInnerHTML += '<a class="ts-button ts-modal-close">close</a>'; divInnerHTML += '</div>'; divInnerHTML += '</div>'; divInnerHTML += '</div>'; divInnerHTML += '</section>'; returnDiv.innerHTML = divInnerHTML; return returnDiv; }; /** * A module that represents a StylieTextEditor object, a componentTab is a page composition tool. * @{@link https://github.com/typesettin/stylie.treeview} * @author Yaw Joseph Etse * @copyright Copyright (c) 2015 Typesettin. All rights reserved. * @license MIT * @constructor StylieTextEditor * @requires module:util-extent * @requires module:util * @requires module:events * @param {object} el element of tab container * @param {object} options configuration options */ var StylieTextEditor = function (options) { events.EventEmitter.call(this); var defaultOptions = { type: 'html', updateOnChange: true }; this.options = extend(defaultOptions, options); return this; // this.getTreeHTML = this.getTreeHTML; }; util.inherits(StylieTextEditor, events.EventEmitter); var createButton = function (options) { var buttonElement = document.createElement('button'); buttonElement.setAttribute('class', 'ts-button ts-text-xs ' + options.classes); buttonElement.setAttribute('type', 'button'); buttonElement.innerHTML = options.innerHTML; for (var key in options) { if (key !== 'classes' && key !== 'innerHTML' && key !== 'innerhtml') { buttonElement.setAttribute(key, options[key]); } } return buttonElement; }; StylieTextEditor.prototype.addMenuButtons = function () { this.options.buttons.boldButton = createButton({ classes: ' flaticon-bold17 ', title: 'Bold text', innerHTML: ' ', 'data-attribute-action': 'bold' }); this.options.buttons.italicButton = createButton({ classes: ' flaticon-italic9 ', title: 'Italic text', innerHTML: ' ', 'data-attribute-action': 'italic' }); this.options.buttons.underlineButton = createButton({ classes: ' flaticon-underlined5 ', title: 'Underline text', innerHTML: ' ', 'data-attribute-action': 'underline' }); this.options.buttons.unorderedLIButton = createButton({ classes: ' flaticon-list82 ', innerHTML: ' ', title: ' Insert unordered list ', 'data-attribute-action': 'unorderedLI' }); this.options.buttons.orderedLIButton = createButton({ classes: ' flaticon-numbered8 ', title: ' Insert ordered list ', innerHTML: ' ', 'data-attribute-action': 'orderedLI' }); this.options.buttons.lefttextalignButton = createButton({ classes: ' flaticon-text141 ', innerHTML: ' ', title: ' left align text ', 'data-attribute-action': 'left-textalign' }); //flaticon-text141 this.options.buttons.centertextalignButton = createButton({ classes: ' flaticon-text136 ', innerHTML: ' ', title: ' center align text ', 'data-attribute-action': 'center-textalign' }); //flaticon-text136 this.options.buttons.righttextalignButton = createButton({ classes: ' flaticon-text134 ', innerHTML: ' ', title: ' right align text ', 'data-attribute-action': 'right-textalign' }); //flaticon-text134 this.options.buttons.justifytextalignButton = createButton({ classes: ' flaticon-text146 ', innerHTML: ' ', title: ' justify align text ', 'data-attribute-action': 'justify-textalign' }); //flaticon-text146 //flaticon-characters - font this.options.buttons.textcolorButton = createButton({ classes: ' flaticon-text137 ', innerHTML: ' ', title: ' change text color ', 'data-attribute-action': 'text-color' }); //flaticon-text137 - text color this.options.buttons.texthighlightButton = createButton({ classes: ' flaticon-paintbrush13 ', innerHTML: ' ', title: ' change text highlight ', 'data-attribute-action': 'text-highlight' }); //flaticon-paintbrush13 - text background color(highlight) this.options.buttons.linkButton = createButton({ classes: ' flaticon-link56 ', title: ' Insert a link ', innerHTML: ' ', 'data-attribute-action': 'link' }); this.options.buttons.imageButton = createButton({ classes: ' flaticon-images25 ', title: ' Insert image ', innerHTML: ' ', 'data-attribute-action': 'image' }); this.options.buttons.codeButton = createButton({ innerHTML: ' ', classes: ' flaticon-code39 ', title: 'Source code editor', 'data-attribute-action': 'code' }); this.options.buttons.fullscreenButton = createButton({ title: 'Maximize and fullscreen editor', classes: ' flaticon-logout18 ', innerHTML: ' ', 'data-attribute-action': 'fullscreen' }); this.options.buttons.outdentButton = createButton({ title: 'Outdent button', classes: ' flaticon-paragraph19 ', innerHTML: ' ', 'data-attribute-action': 'outdent' }); this.options.buttons.indentButton = createButton({ title: 'Indent button', classes: ' flaticon-right195 ', innerHTML: ' ', 'data-attribute-action': 'indent' }); }; var button_gobold = function () { document.execCommand('bold', false, ''); }; var button_gounderline = function () { document.execCommand('underline', false, ''); }; var button_goitalic = function () { document.execCommand('italic', false, ''); }; var button_golink = function () { document.execCommand('createLink', true, ''); }; var button_golist = function () { document.execCommand('insertOrderedList', true, ''); }; var button_gobullet = function () { document.execCommand('insertUnorderedList', true, ''); }; var button_goimg = function () { // document.execCommand('insertImage', false, 'http://lorempixel.com/40/20/sports/'); this.saveSelection(); window.editorModals.show(this.options.elementContainer.getAttribute('data-original-id') + '-insertimage-modal'); }; var button_gotextlink = function () { // console.log(this.options.elementContainer.getAttribute('data-original-id')); this.saveSelection(); window.editorModals.show(this.options.elementContainer.getAttribute('data-original-id') + '-inserttext-modal'); }; var add_link_to_editor = function () { this.restoreSelection(); document.execCommand('createLink', false, this.options.forms.add_link_form.querySelector('.ts-link_url').value); }; var add_image_to_editor = function () { this.restoreSelection(); document.execCommand('insertImage', false, this.options.forms.add_image_form.querySelector('.ts-image_url').value); }; var button_gofullscreen = function () { // console.log('button_gofullscreen this', this); // if() classie.toggle(this.options.elementContainer, 'ts-editor-fullscreen'); classie.toggle(this.options.buttons.fullscreenButton, 'ts-button-primary-text-color'); }; var button_togglecodeeditor = function () { classie.toggle(this.options.codemirror.getWrapperElement(), 'ts-hidden'); classie.toggle(this.options.buttons.codeButton, 'ts-button-primary-text-color'); this.options.codemirror.refresh(); }; var button_gotext_left = function () { document.execCommand('justifyLeft', true, ''); }; var button_gotext_center = function () { document.execCommand('justifyCenter', true, ''); }; var button_gotext_right = function () { document.execCommand('justifyRight', true, ''); }; var button_gotext_justifyfull = function () { document.execCommand('justifyFull', true, ''); }; // var button_gotext_left = function () { // document.execCommand('justifyLeft', true, ''); // }; var button_go_outdent = function () { document.execCommand('outdent', true, ''); }; var button_go_indent = function () { document.execCommand('indent', true, ''); }; StylieTextEditor.prototype.initButtonEvents = function () { this.options.buttons.boldButton.addEventListener('click', button_gobold, false); this.options.buttons.underlineButton.addEventListener('click', button_gounderline, false); this.options.buttons.italicButton.addEventListener('click', button_goitalic, false); this.options.buttons.linkButton.addEventListener('click', button_golink, false); this.options.buttons.unorderedLIButton.addEventListener('click', button_gobullet, false); this.options.buttons.orderedLIButton.addEventListener('click', button_golist, false); this.options.buttons.imageButton.addEventListener('click', button_goimg.bind(this), false); this.options.buttons.linkButton.addEventListener('click', button_gotextlink.bind(this), false); this.options.buttons.lefttextalignButton.addEventListener('click', button_gotext_left, false); this.options.buttons.centertextalignButton.addEventListener('click', button_gotext_center, false); this.options.buttons.righttextalignButton.addEventListener('click', button_gotext_right, false); this.options.buttons.justifytextalignButton.addEventListener('click', button_gotext_justifyfull, false); this.options.buttons.outdentButton.addEventListener('click', button_go_outdent, false); this.options.buttons.indentButton.addEventListener('click', button_go_indent, false); this.options.buttons.fullscreenButton.addEventListener('click', button_gofullscreen.bind(this), false); this.options.buttons.codeButton.addEventListener('click', button_togglecodeeditor.bind(this), false); this.options.buttons.addlinkbutton.addEventListener('click', add_link_to_editor.bind(this), false); this.options.buttons.addimagebutton.addEventListener('click', add_image_to_editor.bind(this), false); }; StylieTextEditor.prototype.init = function () { try { var previewEditibleDiv = document.createElement('div'), previewEditibleMenu = document.createElement('div'), insertImageURLModal = getInsertTextModal(this.options.element.getAttribute('id'), 'image'), insertTextLinkModal = getInsertTextModal(this.options.element.getAttribute('id'), 'text'), previewEditibleContainer = document.createElement('div'); this.options.buttons = {}; this.addMenuButtons(); previewEditibleMenu.appendChild(this.options.buttons.boldButton); previewEditibleMenu.appendChild(this.options.buttons.italicButton); previewEditibleMenu.appendChild(this.options.buttons.underlineButton); previewEditibleMenu.appendChild(this.options.buttons.unorderedLIButton); previewEditibleMenu.appendChild(this.options.buttons.orderedLIButton); previewEditibleMenu.appendChild(this.options.buttons.lefttextalignButton); previewEditibleMenu.appendChild(this.options.buttons.centertextalignButton); previewEditibleMenu.appendChild(this.options.buttons.righttextalignButton); previewEditibleMenu.appendChild(this.options.buttons.justifytextalignButton); // previewEditibleMenu.appendChild(this.options.buttons.textcolorButton); // previewEditibleMenu.appendChild(this.options.buttons.texthighlightButton); previewEditibleMenu.appendChild(this.options.buttons.outdentButton); previewEditibleMenu.appendChild(this.options.buttons.indentButton); previewEditibleMenu.appendChild(this.options.buttons.linkButton); previewEditibleMenu.appendChild(this.options.buttons.imageButton); previewEditibleMenu.appendChild(this.options.buttons.codeButton); previewEditibleMenu.appendChild(this.options.buttons.fullscreenButton); previewEditibleMenu.setAttribute('class', 'ts-input ts-editor-menu ts-padding-sm'); previewEditibleMenu.setAttribute('style', 'font-family: monospace, Arial,"Times New Roman";'); previewEditibleDiv.setAttribute('class', 'ts-input ts-texteditor'); previewEditibleDiv.setAttribute('contenteditable', 'true'); previewEditibleDiv.setAttribute('tabindex', '1'); previewEditibleContainer.setAttribute('id', this.options.element.getAttribute('id') + '_container'); previewEditibleContainer.setAttribute('data-original-id', this.options.element.getAttribute('id')); previewEditibleContainer.setAttribute('class', 'ts-editor-container'); previewEditibleContainer.appendChild(previewEditibleMenu); previewEditibleContainer.appendChild(previewEditibleDiv); document.querySelector('.ts-modal-hidden-container').appendChild(insertTextLinkModal); document.querySelector('.ts-modal-hidden-container').appendChild(insertImageURLModal); this.options.element = this.options.element || document.querySelector(this.options.elementSelector); previewEditibleDiv.innerHTML = this.options.element.innerText; this.options.previewElement = previewEditibleDiv; this.options.forms = { add_link_form: document.querySelector('.inserttext-modal .ts-form'), add_image_form: document.querySelector('.insertimage-modal .ts-form') }; this.options.buttons.addlinkbutton = document.querySelector('.inserttext-modal').querySelector('.add-link-button'); this.options.buttons.addimagebutton = document.querySelector('.insertimage-modal').querySelector('.add-image-button'); //now add code mirror this.options.elementContainer = previewEditibleContainer; this.options.element.parentNode.appendChild(previewEditibleContainer); previewEditibleContainer.appendChild(this.options.element); this.options.codemirror = CodeMirror.fromTextArea( this.options.element, { lineNumbers: true, lineWrapping: true, matchBrackets: true, autoCloseBrackets: true, mode: (this.options.type === 'ejs') ? 'text/ejs' : 'text/html', indentUnit: 2, indentWithTabs: true, 'overflow-y': 'hidden', 'overflow-x': 'auto', lint: true, gutters: [ 'CodeMirror-linenumbers', 'CodeMirror-foldgutter', // 'CodeMirror-lint-markers' ], foldGutter: true } ); // this.options.element.parentNode.insertBefore(previewEditibleDiv, this.options.element); this.options.codemirror.on('blur', function (instance) { // console.log('editor lost focuss', instance, change); this.options.previewElement.innerHTML = instance.getValue(); }.bind(this)); this.options.previewElement.addEventListener('blur', function () { this.options.codemirror.getDoc().setValue(this.options.previewElement.innerHTML); }.bind(this)); if (this.options.updateOnChange) { this.options.codemirror.on('change', function (instance) { // console.log('editor lost focuss', instance, change); // console.log('document.activeElement === this.options.previewElement', document.activeElement === this.options.previewElement); setTimeout(function () { if (document.activeElement !== this.options.previewElement) { this.options.previewElement.innerHTML = instance.getValue(); } }.bind(this), 5000); }.bind(this)); this.options.previewElement.addEventListener('change', function () { this.options.codemirror.getDoc().setValue(this.options.previewElement.innerHTML); }.bind(this)); } //set initial code mirror this.options.codemirror.getDoc().setValue(this.options.previewElement.innerHTML); this.options.codemirror.refresh(); classie.add(this.options.codemirror.getWrapperElement(), 'ts-hidden'); // setTimeout(this.options.codemirror.refresh, 1000); this.initButtonEvents(); editorModals = new StylieModals({}); window.editorModals = editorModals; return this; } catch (e) { console.error(e); } }; StylieTextEditor.prototype.getValue = function () { return this.options.previewElement.innerText || this.options.codemirror.getValue(); }; StylieTextEditor.prototype.saveSelection = function () { this.options.selection = (saveSelection()) ? saveSelection() : null; }; StylieTextEditor.prototype.restoreSelection = function () { this.options.preview_selection = this.options.selection; restoreSelection(this.options.selection); }; module.exports = StylieTextEditor;
typesettin/periodicjs.ext.asyncadmin
resources/js/stylieeditor.js
JavaScript
mit
19,967
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var ShapeType_1 = require("../Enums/ShapeType"); var Updater_1 = require("./Particle/Updater"); var Utils_1 = require("../Utils/Utils"); var PolygonMaskType_1 = require("../Enums/PolygonMaskType"); var RotateDirection_1 = require("../Enums/RotateDirection"); var ColorUtils_1 = require("../Utils/ColorUtils"); var Particles_1 = require("../Options/Classes/Particles/Particles"); var SizeAnimationStatus_1 = require("../Enums/SizeAnimationStatus"); var OpacityAnimationStatus_1 = require("../Enums/OpacityAnimationStatus"); var Shape_1 = require("../Options/Classes/Particles/Shape/Shape"); var StartValueType_1 = require("../Enums/StartValueType"); var CanvasUtils_1 = require("../Utils/CanvasUtils"); var Particle = (function () { function Particle(container, position, overrideOptions) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p; this.container = container; this.fill = true; this.close = true; this.links = []; this.lastNoiseTime = 0; this.destroyed = false; var options = container.options; var particlesOptions = new Particles_1.Particles(); particlesOptions.load(options.particles); if ((overrideOptions === null || overrideOptions === void 0 ? void 0 : overrideOptions.shape) !== undefined) { var shapeType = (_a = overrideOptions.shape.type) !== null && _a !== void 0 ? _a : particlesOptions.shape.type; this.shape = shapeType instanceof Array ? Utils_1.Utils.itemFromArray(shapeType) : shapeType; var shapeOptions = new Shape_1.Shape(); shapeOptions.load(overrideOptions.shape); if (this.shape !== undefined) { var shapeData = shapeOptions.options[this.shape]; if (shapeData !== undefined) { this.shapeData = Utils_1.Utils.deepExtend({}, shapeData instanceof Array ? Utils_1.Utils.itemFromArray(shapeData) : shapeData); this.fill = (_c = (_b = this.shapeData) === null || _b === void 0 ? void 0 : _b.fill) !== null && _c !== void 0 ? _c : this.fill; this.close = (_e = (_d = this.shapeData) === null || _d === void 0 ? void 0 : _d.close) !== null && _e !== void 0 ? _e : this.close; } } } else { var shapeType = particlesOptions.shape.type; this.shape = shapeType instanceof Array ? Utils_1.Utils.itemFromArray(shapeType) : shapeType; var shapeData = particlesOptions.shape.options[this.shape]; if (shapeData) { this.shapeData = Utils_1.Utils.deepExtend({}, shapeData instanceof Array ? Utils_1.Utils.itemFromArray(shapeData) : shapeData); this.fill = (_g = (_f = this.shapeData) === null || _f === void 0 ? void 0 : _f.fill) !== null && _g !== void 0 ? _g : this.fill; this.close = (_j = (_h = this.shapeData) === null || _h === void 0 ? void 0 : _h.close) !== null && _j !== void 0 ? _j : this.close; } } if (overrideOptions !== undefined) { particlesOptions.load(overrideOptions); } this.particlesOptions = particlesOptions; var noiseDelay = this.particlesOptions.move.noise.delay; this.noiseDelay = (noiseDelay.random.enable ? Utils_1.Utils.randomInRange(noiseDelay.random.minimumValue, noiseDelay.value) : noiseDelay.value) * 1000; container.retina.initParticle(this); var color = this.particlesOptions.color; var sizeValue = ((_k = this.sizeValue) !== null && _k !== void 0 ? _k : container.retina.sizeValue); var randomSize = typeof this.particlesOptions.size.random === "boolean" ? this.particlesOptions.size.random : this.particlesOptions.size.random.enable; this.size = { value: randomSize && this.randomMinimumSize !== undefined ? Utils_1.Utils.randomInRange(this.randomMinimumSize, sizeValue) : sizeValue, }; this.direction = this.particlesOptions.move.direction; this.bubble = {}; this.angle = this.particlesOptions.rotate.random ? Math.random() * 360 : this.particlesOptions.rotate.value; if (this.particlesOptions.rotate.direction == RotateDirection_1.RotateDirection.random) { var index = Math.floor(Math.random() * 2); if (index > 0) { this.rotateDirection = RotateDirection_1.RotateDirection.counterClockwise; } else { this.rotateDirection = RotateDirection_1.RotateDirection.clockwise; } } else { this.rotateDirection = this.particlesOptions.rotate.direction; } if (this.particlesOptions.size.animation.enable) { switch (this.particlesOptions.size.animation.startValue) { case StartValueType_1.StartValueType.min: if (!randomSize) { var pxRatio = container.retina.pixelRatio; this.size.value = this.particlesOptions.size.animation.minimumValue * pxRatio; } break; } this.size.status = SizeAnimationStatus_1.SizeAnimationStatus.increasing; this.size.velocity = ((_l = this.sizeAnimationSpeed) !== null && _l !== void 0 ? _l : container.retina.sizeAnimationSpeed) / 100; if (!this.particlesOptions.size.animation.sync) { this.size.velocity = this.size.velocity * Math.random(); } } if (this.particlesOptions.rotate.animation.enable) { if (!this.particlesOptions.rotate.animation.sync) { this.angle = Math.random() * 360; } } this.position = this.calcPosition(this.container, position); if (options.polygon.enable && options.polygon.type === PolygonMaskType_1.PolygonMaskType.inline) { this.initialPosition = { x: this.position.x, y: this.position.y, }; } this.offset = { x: 0, y: 0, }; if (this.particlesOptions.collisions.enable) { this.checkOverlap(position); } if (color instanceof Array) { this.color = ColorUtils_1.ColorUtils.colorToRgb(Utils_1.Utils.itemFromArray(color)); } else { this.color = ColorUtils_1.ColorUtils.colorToRgb(color); } var randomOpacity = this.particlesOptions.opacity.random; var opacityValue = this.particlesOptions.opacity.value; this.opacity = { value: randomOpacity.enable ? Utils_1.Utils.randomInRange(randomOpacity.minimumValue, opacityValue) : opacityValue, }; if (this.particlesOptions.opacity.animation.enable) { this.opacity.status = OpacityAnimationStatus_1.OpacityAnimationStatus.increasing; this.opacity.velocity = this.particlesOptions.opacity.animation.speed / 100; if (!this.particlesOptions.opacity.animation.sync) { this.opacity.velocity *= Math.random(); } } this.initialVelocity = this.calculateVelocity(); this.velocity = { horizontal: this.initialVelocity.horizontal, vertical: this.initialVelocity.vertical, }; var drawer = container.drawers[this.shape]; if (!drawer) { drawer = CanvasUtils_1.CanvasUtils.getShapeDrawer(this.shape); container.drawers[this.shape] = drawer; } if (this.shape === ShapeType_1.ShapeType.image || this.shape === ShapeType_1.ShapeType.images) { var shape = this.particlesOptions.shape; var imageDrawer = drawer; var imagesOptions = shape.options[this.shape]; var images = imageDrawer.getImages(container).images; var index = Utils_1.Utils.arrayRandomIndex(images); var image_1 = images[index]; var optionsImage = (imagesOptions instanceof Array ? imagesOptions.filter(function (t) { return t.src === image_1.source; })[0] : imagesOptions); this.image = { data: image_1, ratio: optionsImage.width / optionsImage.height, replaceColor: (_m = optionsImage.replaceColor) !== null && _m !== void 0 ? _m : optionsImage.replace_color, source: optionsImage.src, }; if (!this.image.ratio) { this.image.ratio = 1; } this.fill = (_o = optionsImage.fill) !== null && _o !== void 0 ? _o : this.fill; this.close = (_p = optionsImage.close) !== null && _p !== void 0 ? _p : this.close; } this.stroke = this.particlesOptions.stroke instanceof Array ? Utils_1.Utils.itemFromArray(this.particlesOptions.stroke) : this.particlesOptions.stroke; this.strokeColor = typeof this.stroke.color === "string" ? ColorUtils_1.ColorUtils.stringToRgb(this.stroke.color) : ColorUtils_1.ColorUtils.colorToRgb(this.stroke.color); this.shadowColor = typeof this.particlesOptions.shadow.color === "string" ? ColorUtils_1.ColorUtils.stringToRgb(this.particlesOptions.shadow.color) : ColorUtils_1.ColorUtils.colorToRgb(this.particlesOptions.shadow.color); this.updater = new Updater_1.Updater(this.container, this); } Particle.prototype.update = function (index, delta) { this.links = []; this.updater.update(delta); }; Particle.prototype.draw = function (delta) { this.container.canvas.drawParticle(this, delta); }; Particle.prototype.isOverlapping = function () { var container = this.container; var p = this; var collisionFound = false; var iterations = 0; for (var _i = 0, _a = container.particles.array.filter(function (t) { return t != p; }); _i < _a.length; _i++) { var p2 = _a[_i]; iterations++; var pos1 = { x: p.position.x + p.offset.x, y: p.position.y + p.offset.y }; var pos2 = { x: p2.position.x + p2.offset.x, y: p2.position.y + p2.offset.y }; var dist = Utils_1.Utils.getDistanceBetweenCoordinates(pos1, pos2); if (dist <= p.size.value + p2.size.value) { collisionFound = true; break; } } return { collisionFound: collisionFound, iterations: iterations, }; }; Particle.prototype.checkOverlap = function (position) { var container = this.container; var p = this; var overlapResult = p.isOverlapping(); if (overlapResult.iterations >= container.particles.count) { container.particles.remove(this); } else if (overlapResult.collisionFound) { p.position.x = position ? position.x : Math.random() * container.canvas.size.width; p.position.y = position ? position.y : Math.random() * container.canvas.size.height; p.checkOverlap(); } }; Particle.prototype.startInfection = function (stage) { var container = this.container; var options = container.options; var stages = options.infection.stages; var stagesCount = stages.length; if (stage > stagesCount || stage < 0) { return; } this.infectionDelay = 0; this.infectionDelayStage = stage; }; Particle.prototype.updateInfectionStage = function (stage) { var container = this.container; var options = container.options; var stagesCount = options.infection.stages.length; if (stage > stagesCount || stage < 0 || (this.infectionStage !== undefined && this.infectionStage > stage)) { return; } if (this.infectionTimeout !== undefined) { window.clearTimeout(this.infectionTimeout); } this.infectionStage = stage; this.infectionTime = 0; }; Particle.prototype.updateInfection = function (delta) { var container = this.container; var options = container.options; var infection = options.infection; var stages = options.infection.stages; var stagesCount = stages.length; if (this.infectionDelay !== undefined && this.infectionDelayStage !== undefined) { var stage = this.infectionDelayStage; if (stage > stagesCount || stage < 0) { return; } if (this.infectionDelay > infection.delay * 1000) { this.infectionStage = stage; this.infectionTime = 0; delete this.infectionDelay; delete this.infectionDelayStage; } else { this.infectionDelay += delta; } } else { delete this.infectionDelay; delete this.infectionDelayStage; } if (this.infectionStage !== undefined && this.infectionTime !== undefined) { var infectionStage = stages[this.infectionStage]; if (infectionStage.duration !== undefined && infectionStage.duration >= 0) { if (this.infectionTime > infectionStage.duration * 1000) { this.nextInfectionStage(); } else { this.infectionTime += delta; } } else { this.infectionTime += delta; } } else { delete this.infectionStage; delete this.infectionTime; } }; Particle.prototype.nextInfectionStage = function () { var container = this.container; var options = container.options; var stagesCount = options.infection.stages.length; if (stagesCount <= 0 || this.infectionStage === undefined) { return; } this.infectionTime = 0; if (stagesCount <= ++this.infectionStage) { if (options.infection.cure) { delete this.infectionStage; delete this.infectionTime; return; } else { this.infectionStage = 0; this.infectionTime = 0; } } }; Particle.prototype.destroy = function () { this.destroyed = true; }; Particle.prototype.calcPosition = function (container, position) { for (var _i = 0, _a = container.plugins; _i < _a.length; _i++) { var plugin = _a[_i]; var pluginPos = plugin.particlePosition !== undefined ? plugin.particlePosition(position) : undefined; if (pluginPos !== undefined) { return pluginPos; } } var pos = { x: 0, y: 0 }; pos.x = position ? position.x : Math.random() * container.canvas.size.width; pos.y = position ? position.y : Math.random() * container.canvas.size.height; if (pos.x > container.canvas.size.width - this.size.value * 2) { pos.x -= this.size.value; } else if (pos.x < this.size.value * 2) { pos.x += this.size.value; } if (pos.y > container.canvas.size.height - this.size.value * 2) { pos.y -= this.size.value; } else if (pos.y < this.size.value * 2) { pos.y += this.size.value; } return pos; }; Particle.prototype.calculateVelocity = function () { var baseVelocity = Utils_1.Utils.getParticleBaseVelocity(this); var res = { horizontal: 0, vertical: 0, }; if (this.particlesOptions.move.straight) { res.horizontal = baseVelocity.x; res.vertical = baseVelocity.y; if (this.particlesOptions.move.random) { res.horizontal *= Math.random(); res.vertical *= Math.random(); } } else { res.horizontal = baseVelocity.x + Math.random() - 0.5; res.vertical = baseVelocity.y + Math.random() - 0.5; } return res; }; return Particle; }()); exports.Particle = Particle;
cdnjs/cdnjs
ajax/libs/tsparticles/1.14.0-alpha.6/Core/Particle.js
JavaScript
mit
16,661
'use strict'; require('angular/angular'); angular.module('<%= name %>Module', []) .directive('<%= name %>', [ function() { return { restrict: 'E', replace: true, templateUrl: 'src/<%= name %>/<%= name %>.tpl.html', scope: {}, link: function(scope, element, attrs) { scope.directiveTitle = 'dummy'; } }; } ]);
hung-phan/generator-angular-with-browserify
directive/templates/directive-template.js
JavaScript
mit
475
import Ember from 'ember'; import AuthenticatedRouteMixin from 'simple-auth/mixins/authenticated-route-mixin'; import InfinityRoute from "../../../../mixins/infinity-route"; export default Ember.Route.extend(InfinityRoute, AuthenticatedRouteMixin, { _listName: 'model', model: function() { return this.infinityModel("report", { perPage: 10, startingPage: 1}); }, actions: { remove: function(model) { if(confirm('Are you sure?')) { model.destroyRecord(); } }, search: function () { this.set('_listName', 'model.content'); var filter = { perPage: 10, startingPage: 1}; this.get('controller').set('model', this.infinityModel("report", filter)) } } });
Goblab/observatorio-electoral
front/app/routes/data-entry/elections/reports/index.js
JavaScript
mit
729
/** * @file theme loader * * @desc 向每个.vue文件中注入样式相关的变量,不需要手动import * @author echaoo(1299529160@qq.com) */ /* eslint-disable fecs-no-require, fecs-prefer-destructure */ 'use strict'; const theme = require('../../config/theme'); const loaderUtils = require('loader-utils'); const STYLE_TAG_REG = /(\<style.*?lang="styl(?:us)?".*?\>)([\S\s]*?)(\<\/style\>)/g; // 定义在vuetify中默认的两组stylus hash:主题色和material相关 let defaultVuetifyVariables = { themeColor: { primary: '$blue.darken-2', accent: '$blue.accent-2', secondary: '$grey.darken-3', info: '$blue.base', warning: '$amber.base', error: '$red.accent-2', success: '$green.base' }, materialDesign: { 'bg-color': '#fff', 'fg-color': '#000', 'text-color': '#000', 'primary-text-percent': .87, 'secondary-text-percent': .54, 'disabledORhints-text-percent': .38, 'divider-percent': .12, 'active-icon-percent': .54, 'inactive-icon-percent': .38 } }; // 使用用户定义在config/theme.js中的变量覆盖默认值 let themeColor = Object.assign( {}, defaultVuetifyVariables.themeColor, theme.theme.themeColor ); // 最终输出的stylus hash(themeColor部分) let themeColorTemplate = ` $theme := { primary: ${themeColor.primary} accent: ${themeColor.accent} secondary: ${themeColor.secondary} info: ${themeColor.info} warning: ${themeColor.warning} error: ${themeColor.error} success: ${themeColor.success} } `; let materialDesign = Object.assign( {}, defaultVuetifyVariables.materialDesign, theme.theme.materialDesign ); let materialDesignTemplate = ` $material-custom := { bg-color: ${materialDesign['bg-color']} fg-color: ${materialDesign['fg-color']} text-color: ${materialDesign['text-color']} primary-text-percent: ${materialDesign['primary-text-percent']} secondary-text-percent: ${materialDesign['secondary-text-percent']} disabledORhints-text-percent: ${materialDesign['disabledORhints-text-percent']} divider-percent: ${materialDesign['divider-percent']} active-icon-percent: ${materialDesign['active-icon-percent']} inactive-icon-percent: ${materialDesign['inactive-icon-percent']} } $material-theme := $material-custom `; // 引入项目变量和vuetify中使用的颜色变量 let importVariablesTemplate = ` @import '~@/assets/styles/variables'; @import '~vuetify/src/stylus/settings/_colors'; `; let injectedTemplate = importVariablesTemplate + themeColorTemplate + materialDesignTemplate; module.exports = function (source) { this.cacheable(); let options = loaderUtils.getOptions(this); if (options && options.injectInVueFile) { // 向每一个.vue文件的<style>块中注入 return source.replace(STYLE_TAG_REG, `$1${injectedTemplate}$2$3`); } return injectedTemplate + source; };
echaoo/doubanMovie_PWA
build/loaders/theme-loader.js
JavaScript
mit
3,098
/* * Kendo UI v2014.2.1008 (http://www.telerik.com/kendo-ui) * Copyright 2014 Telerik AD. All rights reserved. * * Kendo UI commercial licenses may be obtained at * http://www.telerik.com/purchase/license-agreement/kendo-ui-complete * If you do not own a commercial license, this file shall be governed by the trial license terms. */ (function(f, define){ define([], f); })(function(){ (function( window, undefined ) { var kendo = window.kendo || (window.kendo = { cultures: {} }); kendo.cultures["ms-BN"] = { name: "ms-BN", numberFormat: { pattern: ["-n"], decimals: 2, ",": ".", ".": ",", groupSize: [3], percent: { pattern: ["-n %","n %"], decimals: 2, ",": ".", ".": ",", groupSize: [3], symbol: "%" }, currency: { pattern: ["($n)","$n"], decimals: 0, ",": ".", ".": ",", groupSize: [3], symbol: "$" } }, calendars: { standard: { days: { names: ["Ahad","Isnin","Selasa","Rabu","Khamis","Jumaat","Sabtu"], namesAbbr: ["Ahad","Isnin","Sel","Rabu","Khamis","Jumaat","Sabtu"], namesShort: ["A","I","S","R","K","J","S"] }, months: { names: ["Januari","Februari","Mac","April","Mei","Jun","Julai","Ogos","September","Oktober","November","Disember",""], namesAbbr: ["Jan","Feb","Mac","Apr","Mei","Jun","Jul","Ogos","Sept","Okt","Nov","Dis",""] }, AM: [""], PM: [""], patterns: { d: "dd/MM/yyyy", D: "dd MMMM yyyy", F: "dd MMMM yyyy H:mm:ss", g: "dd/MM/yyyy H:mm", G: "dd/MM/yyyy H:mm:ss", m: "dd MMMM", M: "dd MMMM", s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss", t: "H:mm", T: "H:mm:ss", u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'", y: "MMMM yyyy", Y: "MMMM yyyy" }, "/": "/", ":": ":", firstDay: 1 } } } })(this); return window.kendo; }, typeof define == 'function' && define.amd ? define : function(_, f){ f(); });
shriramdevanathan/FactoryOfTheFuture
vendor/kendoui-2014.2.1008/src/js/cultures/kendo.culture.ms-BN.js
JavaScript
mit
2,615
// This file was automatically generated. Do not modify. 'use strict'; goog.provide('Blockly.Msg.az-latn'); goog.require('Blockly.Msg'); Blockly.Msg.ADD_COMMENT = "Şərh əlavə et"; Blockly.Msg.CHANGE_VALUE_TITLE = "Qiyməti dəyiş:"; Blockly.Msg.COLLAPSE_ALL = "Blokları yığ"; Blockly.Msg.COLLAPSE_BLOCK = "Bloku yığ"; Blockly.Msg.COLOUR_BLEND_COLOUR1 = "rəng 1"; Blockly.Msg.COLOUR_BLEND_COLOUR2 = "rəng 2"; Blockly.Msg.COLOUR_BLEND_HELPURL = "http://meyerweb.com/eric/tools/color-blend/"; Blockly.Msg.COLOUR_BLEND_RATIO = "nisbət"; Blockly.Msg.COLOUR_BLEND_TITLE = "qarışdır"; Blockly.Msg.COLOUR_BLEND_TOOLTIP = "İki rəngi verilmiş nisbətdə (0,0 - 1,0) qarışdırır."; Blockly.Msg.COLOUR_PICKER_HELPURL = "https://en.wikipedia.org/wiki/Color"; Blockly.Msg.COLOUR_PICKER_TOOLTIP = "Palitradan bir rəng seçin."; Blockly.Msg.COLOUR_RANDOM_HELPURL = "http://randomcolour.com"; Blockly.Msg.COLOUR_RANDOM_TITLE = "təsadüfi rəng"; Blockly.Msg.COLOUR_RANDOM_TOOLTIP = "Təsadüfi bir rəng seçin."; Blockly.Msg.COLOUR_RGB_BLUE = "mavi"; Blockly.Msg.COLOUR_RGB_GREEN = "yaşıl"; Blockly.Msg.COLOUR_RGB_HELPURL = "http://www.december.com/html/spec/colorper.html"; Blockly.Msg.COLOUR_RGB_RED = "qırmızı"; Blockly.Msg.COLOUR_RGB_TITLE = "rəngin komponentləri:"; Blockly.Msg.COLOUR_RGB_TOOLTIP = "Qırmızı, yaşıl və mavinin göstərilən miqdarı ilə bir rəng düzəlt. Bütün qiymətlər 0 ilə 100 arasında olmalıdır."; Blockly.Msg.CONTROLS_FLOW_STATEMENTS_HELPURL = "https://code.google.com/p/blockly/wiki/Loops#Loop_Termination_Blocks"; Blockly.Msg.CONTROLS_FLOW_STATEMENTS_OPERATOR_BREAK = "dövrdən çıx"; Blockly.Msg.CONTROLS_FLOW_STATEMENTS_OPERATOR_CONTINUE = "dövrün növbəti addımından davam et"; Blockly.Msg.CONTROLS_FLOW_STATEMENTS_TOOLTIP_BREAK = "Cari dövrdən çıx."; Blockly.Msg.CONTROLS_FLOW_STATEMENTS_TOOLTIP_CONTINUE = "Bu dövrün qalanını ötür və növbəti addımla davam et."; Blockly.Msg.CONTROLS_FLOW_STATEMENTS_WARNING = "Xəbərdarlıq: Bu blok ancaq dövr daxilində istifadə oluna bilər."; Blockly.Msg.CONTROLS_FOREACH_HELPURL = "https://code.google.com/p/blockly/wiki/Loops#for_each"; Blockly.Msg.CONTROLS_FOREACH_INPUT_INLIST = "siyahıda"; Blockly.Msg.CONTROLS_FOREACH_INPUT_INLIST_TAIL = ""; Blockly.Msg.CONTROLS_FOREACH_INPUT_ITEM = "hər element üçün"; Blockly.Msg.CONTROLS_FOREACH_TOOLTIP = "Siyahıdakı hər element üçün \"%1\" dəyişənini elementə mənimsət və bundan sonra bəzi əmrləri yerinə yetir."; Blockly.Msg.CONTROLS_FOR_HELPURL = "https://code.google.com/p/blockly/wiki/Loops#count_with"; Blockly.Msg.CONTROLS_FOR_INPUT_FROM_TO_BY = "%1 ilə başlayıb, %2 qiymətinə kimi %3 qədır dəyiş"; Blockly.Msg.CONTROLS_FOR_INPUT_WITH = "say:"; Blockly.Msg.CONTROLS_FOR_TOOLTIP = "%1 dəyişəni başlanğıc ədəddən son ədədə qədər göstərilən aralıqla qiymətlər aldıqca göstərilən blokları yerinə yetir."; Blockly.Msg.CONTROLS_IF_ELSEIF_TOOLTIP = "\"Əgər\" blokuna bir şərt əlavə et."; Blockly.Msg.CONTROLS_IF_ELSE_TOOLTIP = "\"Əgər\" blokuna qalan bütün halları əhatə edəb son bir şərt əlavə et."; Blockly.Msg.CONTROLS_IF_HELPURL = "http://code.google.com/p/blockly/wiki/If_Then"; Blockly.Msg.CONTROLS_IF_IF_TOOLTIP = "Bu \"əgər\" blokunu dəyişdirmək üçün bölümlərin yenisini əlavə et, sil və ya yerini dəyiş."; Blockly.Msg.CONTROLS_IF_MSG_ELSE = "əks halda"; Blockly.Msg.CONTROLS_IF_MSG_ELSEIF = "əks halda əgər"; Blockly.Msg.CONTROLS_IF_MSG_IF = "əgər"; Blockly.Msg.CONTROLS_IF_TOOLTIP_1 = "Əgər qiymət doğrudursa, onda bəzi əmrləri yerinə yetir."; Blockly.Msg.CONTROLS_IF_TOOLTIP_2 = "Əgər qiymət doğrudursa, onda birinci əmrlər blokunu yerinə yetir. Əks halda isə ikinci əmrlər blokunu yerinə yetir."; Blockly.Msg.CONTROLS_IF_TOOLTIP_3 = "Əgər birinci qiymət doğrudursa, onda birinci əmrlər blokunu yerinə yetir. Əks halda əgər ikinci qiymət doğrudursa, onda ikinci əmrlər blokunu yerinə yetir."; Blockly.Msg.CONTROLS_IF_TOOLTIP_4 = "Əgər birinci qiymət doğrudursa, onda birinci əmrlər blokunu yerinə yetir. Əks halda əgər ikinci qiymət doğrudursa, onda ikinci əmrlər blokunu yerinə yetir. Əgər qiymətlərdən heç biri doğru deyilsə, onda axırıncı əmrlər blokunu yerinə yetir."; Blockly.Msg.CONTROLS_REPEAT_HELPURL = "https://en.wikipedia.org/wiki/For_loop"; Blockly.Msg.CONTROLS_REPEAT_INPUT_DO = "yerinə yetir"; Blockly.Msg.CONTROLS_REPEAT_TITLE = "%1 dəfə təkrar et"; Blockly.Msg.CONTROLS_REPEAT_TITLE_REPEAT = "təkrar et"; Blockly.Msg.CONTROLS_REPEAT_TITLE_TIMES = "dəfə"; Blockly.Msg.CONTROLS_REPEAT_TOOLTIP = "Bəzi əmrləri bir neçə dəfə yerinə yetir."; Blockly.Msg.CONTROLS_WHILEUNTIL_HELPURL = "http://code.google.com/p/blockly/wiki/Repeat"; Blockly.Msg.CONTROLS_WHILEUNTIL_OPERATOR_UNTIL = "təkrar et, o vaxta qədər ki"; Blockly.Msg.CONTROLS_WHILEUNTIL_OPERATOR_WHILE = "təkrar et, hələ ki"; Blockly.Msg.CONTROLS_WHILEUNTIL_TOOLTIP_UNTIL = "Hələ ki, qiymət \"yalan\"dır, bəzi əmrləri yerinə yetir."; Blockly.Msg.CONTROLS_WHILEUNTIL_TOOLTIP_WHILE = "Hələ ki, qiymət \"doğru\"dur, bəzi əmrləri yerinə yetir."; Blockly.Msg.DELETE_BLOCK = "Bloku sil"; Blockly.Msg.DELETE_X_BLOCKS = "%1 bloku sil"; Blockly.Msg.DISABLE_BLOCK = "Bloku söndür"; Blockly.Msg.DUPLICATE_BLOCK = "Dublikatını düzəlt"; Blockly.Msg.ENABLE_BLOCK = "Bloku aktivləşdir"; Blockly.Msg.EXPAND_ALL = "Blokları aç"; Blockly.Msg.EXPAND_BLOCK = "Bloku aç"; Blockly.Msg.EXTERNAL_INPUTS = "Xarici girişlər"; Blockly.Msg.HELP = "Kömək"; Blockly.Msg.INLINE_INPUTS = "Sətiriçi girişlər"; Blockly.Msg.LISTS_CREATE_EMPTY_HELPURL = "https://en.wikipedia.org/wiki/Linked_list#Empty_lists"; Blockly.Msg.LISTS_CREATE_EMPTY_TITLE = "boş siyahı düzəlt"; Blockly.Msg.LISTS_CREATE_EMPTY_TOOLTIP = "Heç bir verilən qeyd olunmamış, uzunluğu 0 olan bir siyahı verir"; Blockly.Msg.LISTS_CREATE_WITH_CONTAINER_TITLE_ADD = "siyahı"; Blockly.Msg.LISTS_CREATE_WITH_CONTAINER_TOOLTIP = "Bu siyahı blokunu yenidən konfigurasiya etmək üçün bölmələri əlavə edin, silin və ya yerlərini dəyişin."; Blockly.Msg.LISTS_CREATE_WITH_INPUT_WITH = "bunlardan siyahı düzəlt"; Blockly.Msg.LISTS_CREATE_WITH_ITEM_TOOLTIP = "Siyahıya element əlavə edin."; Blockly.Msg.LISTS_CREATE_WITH_TOOLTIP = "İstənilən ölçülü siyahı yaradın."; Blockly.Msg.LISTS_GET_INDEX_FIRST = "birinci"; Blockly.Msg.LISTS_GET_INDEX_FROM_END = "sondan # nömrəli"; Blockly.Msg.LISTS_GET_INDEX_FROM_START = "#"; Blockly.Msg.LISTS_GET_INDEX_GET = "Götürün"; Blockly.Msg.LISTS_GET_INDEX_GET_REMOVE = "Götür və sil"; Blockly.Msg.LISTS_GET_INDEX_LAST = "axırıncı"; Blockly.Msg.LISTS_GET_INDEX_RANDOM = "təsadüfi"; Blockly.Msg.LISTS_GET_INDEX_REMOVE = "Sil"; Blockly.Msg.LISTS_GET_INDEX_TAIL = ""; Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_FIRST = "Siyahının ilk elementini qaytarır."; Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_FROM_END = "Siyahıdan təyin olunmuş indeksli elementi qaytarır. #1 son elementdir."; Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_FROM_START = "Siyahıdan təyin olunmuş indeksli elementi qaytarır. #1 ilk elementdir."; Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_LAST = "Siyahının son elementini qaytarır."; Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_RANDOM = "Siyahıdan hər hansı təsadüfi elementi qaytarır."; Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FIRST = "Siyahıdan ilk elementi silir və qaytarır."; Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FROM_END = "Siyahıdan təyin olunmuş indeksli elementi silir və qaytarır. #1 son elementdir."; Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FROM_START = "Siyahıdan təyin olunmuş indeksli elementi silir və qaytarır. #1 ilk elementdir."; Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_LAST = "Siyahıdan son elementi silir və qaytarır."; Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_RANDOM = "Siyahıdan təsadufi elementi silir və qaytarır."; Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_FIRST = "Siyahıdan ilk elementi silir."; Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_FROM_END = "Siyahıdan təyin olunmuş indeksli elementi silir. #1 son elementdir."; Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_FROM_START = "Siyahıdan təyin olunmuş indeksli elementi silir. #1 ilk elementdir."; Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_LAST = "Siyahıdan son elementi silir."; Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_RANDOM = "Siyahıdan təsadüfi elementi silir."; Blockly.Msg.LISTS_GET_SUBLIST_END_FROM_END = "sondan # nömrəliyə"; Blockly.Msg.LISTS_GET_SUBLIST_END_FROM_START = "# nömrəliyə"; Blockly.Msg.LISTS_GET_SUBLIST_END_LAST = "Sonuncuya"; Blockly.Msg.LISTS_GET_SUBLIST_HELPURL = "https://code.google.com/p/blockly/wiki/Lists#Getting_a_sublist"; Blockly.Msg.LISTS_GET_SUBLIST_START_FIRST = "Birincidən alt-siyahını alın"; Blockly.Msg.LISTS_GET_SUBLIST_START_FROM_END = "# sonuncudan alt-siyahını alın"; Blockly.Msg.LISTS_GET_SUBLIST_START_FROM_START = "# - dən alt-siyahını alın"; Blockly.Msg.LISTS_GET_SUBLIST_TAIL = ""; Blockly.Msg.LISTS_GET_SUBLIST_TOOLTIP = "Siyahının təyin olunmuş hissəsinin surətini yaradın."; Blockly.Msg.LISTS_INDEX_OF_FIRST = "Element ilə ilk rastlaşma indeksini müəyyən edin"; Blockly.Msg.LISTS_INDEX_OF_HELPURL = "https://code.google.com/p/blockly/wiki/Lists#Getting_Items_from_a_List"; Blockly.Msg.LISTS_INDEX_OF_LAST = "Element ilə son rastlaşma indeksini müəyyən edin"; Blockly.Msg.LISTS_INDEX_OF_TOOLTIP = "Siyahıda element ilə ilk/son rastlaşma indeksini qaytarır. Əgər tekst siyahıda tapılmazsa, 0 qaytarılır."; Blockly.Msg.LISTS_INLIST = "siyahıda"; Blockly.Msg.LISTS_IS_EMPTY_HELPURL = "https://code.google.com/p/blockly/wiki/Lists#is_empty"; Blockly.Msg.LISTS_IS_EMPTY_TITLE = "%1 boşdur"; Blockly.Msg.LISTS_LENGTH_HELPURL = "https://code.google.com/p/blockly/wiki/Lists#length_of"; Blockly.Msg.LISTS_LENGTH_TITLE = "%1 siyahısının uzunluğu"; Blockly.Msg.LISTS_LENGTH_TOOLTIP = "Siyahının uzunluğunu verir."; Blockly.Msg.LISTS_REPEAT_HELPURL = "https://code.google.com/p/blockly/wiki/Lists#create_list_with"; Blockly.Msg.LISTS_REPEAT_TITLE = "%1 elementinin siyahıda %2 dəfə təkrarlandığı siyahı yaradım"; Blockly.Msg.LISTS_REPEAT_TOOLTIP = "Təyin olunmuş elementin/qiymətin təyin olunmuş sayda təkrarlandığı siyahını yaradır."; Blockly.Msg.LISTS_SET_INDEX_HELPURL = "https://code.google.com/p/blockly/wiki/Lists#in_list_..._set"; Blockly.Msg.LISTS_SET_INDEX_INPUT_TO = "Kimi"; Blockly.Msg.LISTS_SET_INDEX_INSERT = "daxil et"; Blockly.Msg.LISTS_SET_INDEX_SET = "təyin et"; Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_FIRST = "Elementi siyahının əvvəlinə daxil edir."; Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_FROM_END = "Elementi siyahıda göstərilən yerə daxil edir. #1 axırıncı elementdir."; Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_FROM_START = "Elementi siyahıda göstərilən yerə daxil edir. #1 birinci elementdir."; Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_LAST = "Elementi siyahının sonuna artırır."; Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_RANDOM = "Elementi siyahıda təsadüfi seçilmiş bir yerə atır."; Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_FIRST = "Siyahıda birinci elementi təyin edir."; Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_FROM_END = "Siyahının göstərilən yerdəki elementini təyin edir. #1 axırıncı elementdir."; Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_FROM_START = "Siyahının göstərilən yerdəki elementini təyin edir. #1 birinci elementdir."; Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_LAST = "Siyahının sonuncu elementini təyin edir."; Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_RANDOM = "Siyahının təsadüfi seçilmiş bir elementini təyin edir."; Blockly.Msg.LISTS_TOOLTIP = "Siyahı boşdursa \"doğru\" cavabını qaytarır."; Blockly.Msg.LOGIC_BOOLEAN_FALSE = "yalan"; Blockly.Msg.LOGIC_BOOLEAN_HELPURL = "http://code.google.com/p/blockly/wiki/True_False"; Blockly.Msg.LOGIC_BOOLEAN_TOOLTIP = "\"doğru\" və ya \"yalan\" cavanını qaytarır."; Blockly.Msg.LOGIC_BOOLEAN_TRUE = "doğru"; Blockly.Msg.LOGIC_COMPARE_HELPURL = "https://en.wikipedia.org/wiki/Inequality_(mathematics)"; Blockly.Msg.LOGIC_COMPARE_TOOLTIP_EQ = "Girişlər bir birinə bərabərdirsə \"doğru\" cavabını qaytarır."; Blockly.Msg.LOGIC_COMPARE_TOOLTIP_GT = "Birinci giriş ikincidən böyükdürsə \"doğru\" cavabını qaytarır."; Blockly.Msg.LOGIC_COMPARE_TOOLTIP_GTE = "Birinci giriş ikincidən böyük və ya bərarbərdirsə \"doğru\" cavabını qaytarır."; Blockly.Msg.LOGIC_COMPARE_TOOLTIP_LT = "Birinci giriş ikincidən kiçikdirsə \"doğru\" cavabını qaytarır."; Blockly.Msg.LOGIC_COMPARE_TOOLTIP_LTE = "Birinci giriş ikincidən kiçik və ya bərarbərdirsə \"doğru\" cavabını qaytarır."; Blockly.Msg.LOGIC_COMPARE_TOOLTIP_NEQ = "Girişlər bərabər deyillərsə \"doğru\" cavabını qaytarır."; Blockly.Msg.LOGIC_NEGATE_HELPURL = "http://code.google.com/p/blockly/wiki/Not"; Blockly.Msg.LOGIC_NEGATE_TITLE = "%1 deyil"; Blockly.Msg.LOGIC_NEGATE_TOOLTIP = "Giriş \"yalan\"-dursa \"doğru\" cavabını qaytarır. Giriş \"doğru\"-dursa \"yalan\" cavabını qaytarır."; Blockly.Msg.LOGIC_NULL = "boş"; Blockly.Msg.LOGIC_NULL_HELPURL = "https://en.wikipedia.org/wiki/Nullable_type"; Blockly.Msg.LOGIC_NULL_TOOLTIP = "Boş cavab qaytarır."; Blockly.Msg.LOGIC_OPERATION_AND = "və"; Blockly.Msg.LOGIC_OPERATION_HELPURL = "http://code.google.com/p/blockly/wiki/And_Or"; Blockly.Msg.LOGIC_OPERATION_OR = "və ya"; Blockly.Msg.LOGIC_OPERATION_TOOLTIP_AND = "Hər iki giriş \"doğru\"-dursa \"doğru\" cavabını qaytarır."; Blockly.Msg.LOGIC_OPERATION_TOOLTIP_OR = "Girişlərdən heç olmasa biri \"doğru\"-dursa \"doğru\" cavabını qaytarır."; Blockly.Msg.LOGIC_TERNARY_CONDITION = "yoxla"; Blockly.Msg.LOGIC_TERNARY_HELPURL = "https://en.wikipedia.org/wiki/%3F:"; Blockly.Msg.LOGIC_TERNARY_IF_FALSE = "əgər yalandırsa"; Blockly.Msg.LOGIC_TERNARY_IF_TRUE = "əgər doğrudursa"; Blockly.Msg.LOGIC_TERNARY_TOOLTIP = "'Yoxla' əmrindəki şərtə nəzər yetirin. Əgər şərt \"doğru\"-dursa \"əgər doğru\", əks halda isə \"əgər yalan\" cavabını qaytarır."; Blockly.Msg.MATH_ADDITION_SYMBOL = "+"; Blockly.Msg.MATH_ARITHMETIC_HELPURL = "https://az.wikipedia.org/wiki/Hesab"; Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_ADD = "İki ədədin cəmini qaytarır."; Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_DIVIDE = "İki ədədin nisbətini qaytarır."; Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_MINUS = "İki ədədin fərqini qaytarır."; Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_MULTIPLY = "İki ədədin hasilini verir."; Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_POWER = "Birinci ədədin ikinci ədəd dərəcəsindən qüvvətini qaytarır."; Blockly.Msg.MATH_CHANGE_HELPURL = "https://en.wikipedia.org/wiki/Programming_idiom#Incrementing_a_counter"; Blockly.Msg.MATH_CHANGE_INPUT_BY = "buna:"; Blockly.Msg.MATH_CHANGE_TITLE_CHANGE = "dəyiş:"; Blockly.Msg.MATH_CHANGE_TOOLTIP = "'%1' dəyişəninin üzərinə bir ədəd artır."; Blockly.Msg.MATH_CONSTANT_HELPURL = "https://en.wikipedia.org/wiki/Mathematical_constant"; Blockly.Msg.MATH_CONSTANT_TOOLTIP = "Ümumi sabitlərdən birini qaytarır π (3.141…), e (2.718…), φ (1.618…), sqrt(2) (1.414…), sqrt(½) (0.707…), və ya ∞ (sonsuzluq)."; Blockly.Msg.MATH_CONSTRAIN_HELPURL = "https://en.wikipedia.org/wiki/Clamping_%28graphics%29"; Blockly.Msg.MATH_CONSTRAIN_TITLE = "%1 üçün ən aşağı %2, ən yuxarı %3 olmağı tələb et"; Blockly.Msg.MATH_CONSTRAIN_TOOLTIP = "Bir ədədin verilmiş iki ədəd arasında olmasını tələb edir (sərhədlər də daxil olmaqla)."; Blockly.Msg.MATH_DIVISION_SYMBOL = "÷"; Blockly.Msg.MATH_IS_DIVISIBLE_BY = "bölünür"; Blockly.Msg.MATH_IS_EVEN = "cütdür"; Blockly.Msg.MATH_IS_NEGATIVE = "mənfidir"; Blockly.Msg.MATH_IS_ODD = "təkdir"; Blockly.Msg.MATH_IS_POSITIVE = "müsətdir"; Blockly.Msg.MATH_IS_PRIME = "sadədir"; Blockly.Msg.MATH_IS_TOOLTIP = "Bir ədədin cüt, tək, sadə, mürəkkəb, mənfi, müsbət olmasını və ya müəyyən bir ədədə bölünməsini yoxlayır. \"Doğru\" və ya \"yalan\" cavablarını qaytarır."; Blockly.Msg.MATH_IS_WHOLE = "mürəkkəbdir"; Blockly.Msg.MATH_MODULO_HELPURL = "https://en.wikipedia.org/wiki/Modulo_operation"; Blockly.Msg.MATH_MODULO_TITLE = "%1 ÷ %2 bölməsinin qalığı"; Blockly.Msg.MATH_MODULO_TOOLTIP = "İki ədədin nisbətindən alınan qalığı qaytarır."; Blockly.Msg.MATH_MULTIPLICATION_SYMBOL = "×"; Blockly.Msg.MATH_NUMBER_HELPURL = "https://en.wikipedia.org/wiki/Number"; Blockly.Msg.MATH_NUMBER_TOOLTIP = "Ədəd."; Blockly.Msg.MATH_ONLIST_HELPURL = ""; Blockly.Msg.MATH_ONLIST_OPERATOR_AVERAGE = "siyahının ədədi ortası"; Blockly.Msg.MATH_ONLIST_OPERATOR_MAX = "siyahının maksimumu"; Blockly.Msg.MATH_ONLIST_OPERATOR_MEDIAN = "siyahının medianı"; Blockly.Msg.MATH_ONLIST_OPERATOR_MIN = "siyahının minimumu"; Blockly.Msg.MATH_ONLIST_OPERATOR_MODE = "Siyahı modları( Ən çox rastlaşılan elementləri)"; Blockly.Msg.MATH_ONLIST_OPERATOR_RANDOM = "siyahıdan təsadüfi seçilmiş bir element"; Blockly.Msg.MATH_ONLIST_OPERATOR_STD_DEV = "Siyahının standart deviasiyası"; Blockly.Msg.MATH_ONLIST_OPERATOR_SUM = "Siyahının cəmi"; Blockly.Msg.MATH_ONLIST_TOOLTIP_AVERAGE = "Siyahıdaki ədədlərin ədədi ortasını qaytarır."; Blockly.Msg.MATH_ONLIST_TOOLTIP_MAX = "Siyahıdaki ən böyük elementi qaytarır."; Blockly.Msg.MATH_ONLIST_TOOLTIP_MEDIAN = "Siyahının median elementini qaytarır."; Blockly.Msg.MATH_ONLIST_TOOLTIP_MIN = "Siyahıdaki ən kiçik ədədi qaytarır."; Blockly.Msg.MATH_ONLIST_TOOLTIP_MODE = "Siyahıdaki ən çox rastlanan element(lər)dən ibarət siyahı qaytarır."; Blockly.Msg.MATH_ONLIST_TOOLTIP_RANDOM = "Siyahıdan təsadüfi bir element qaytarır."; Blockly.Msg.MATH_ONLIST_TOOLTIP_STD_DEV = "Siyahının standart deviasiyasını qaytarır."; Blockly.Msg.MATH_ONLIST_TOOLTIP_SUM = "Siyahıdakı bütün ədədlərin cəmini qaytarır."; Blockly.Msg.MATH_POWER_SYMBOL = "^"; Blockly.Msg.MATH_RANDOM_FLOAT_HELPURL = "https://en.wikipedia.org/wiki/Random_number_generation"; Blockly.Msg.MATH_RANDOM_FLOAT_TITLE_RANDOM = "təsadüfi kəsr"; Blockly.Msg.MATH_RANDOM_FLOAT_TOOLTIP = "0.0 (daxil olmaqla) və 1.0 (daxil olmamaqla) ədədlərinin arasından təsadüfi bir kəsr ədəd qaytarır."; Blockly.Msg.MATH_RANDOM_INT_HELPURL = "https://en.wikipedia.org/wiki/Random_number_generation"; Blockly.Msg.MATH_RANDOM_INT_TITLE = "%1 ilə %2 arasından təsadüfi tam ədəd"; Blockly.Msg.MATH_RANDOM_INT_TOOLTIP = "Verilmiş iki ədəd arasından (ədədrlər də daxil olmaqla) təsadüfi bir tam ədəd qaytarır."; Blockly.Msg.MATH_ROUND_HELPURL = "https://en.wikipedia.org/wiki/Rounding"; Blockly.Msg.MATH_ROUND_OPERATOR_ROUND = "yuvarlaq"; Blockly.Msg.MATH_ROUND_OPERATOR_ROUNDDOWN = "aşağı yuvarlaqlaşdır"; Blockly.Msg.MATH_ROUND_OPERATOR_ROUNDUP = "yuxarı yuvarlaqlaşdır"; Blockly.Msg.MATH_ROUND_TOOLTIP = "Ədədi aşağı və ya yuxari yuvarlaqşdır."; Blockly.Msg.MATH_SINGLE_HELPURL = "https://en.wikipedia.org/wiki/Square_root"; Blockly.Msg.MATH_SINGLE_OP_ABSOLUTE = "modul"; Blockly.Msg.MATH_SINGLE_OP_ROOT = "kvadrat kök"; Blockly.Msg.MATH_SINGLE_TOOLTIP_ABS = "Ədədin modulunu qaytarır."; Blockly.Msg.MATH_SINGLE_TOOLTIP_EXP = "e sabitinin verilmiş ədədə qüvvətini qaytarır."; Blockly.Msg.MATH_SINGLE_TOOLTIP_LN = "Ədədin natural loqarifmini tapır."; Blockly.Msg.MATH_SINGLE_TOOLTIP_LOG10 = "Ədədin 10-cu dərəcədən loqarifmini tapır."; Blockly.Msg.MATH_SINGLE_TOOLTIP_NEG = "Ədədin əksini qaytarır."; Blockly.Msg.MATH_SINGLE_TOOLTIP_POW10 = "10-un verilmiş ədədə qüvvətini qaytarır."; Blockly.Msg.MATH_SINGLE_TOOLTIP_ROOT = "Ədədin kvadrat kökünü qaytarır."; Blockly.Msg.MATH_SUBTRACTION_SYMBOL = "-"; Blockly.Msg.MATH_TRIG_ACOS = "arccos"; Blockly.Msg.MATH_TRIG_ASIN = "arcsin"; Blockly.Msg.MATH_TRIG_ATAN = "arctan"; Blockly.Msg.MATH_TRIG_COS = "cos"; Blockly.Msg.MATH_TRIG_HELPURL = "https://en.wikipedia.org/wiki/Trigonometric_functions"; Blockly.Msg.MATH_TRIG_SIN = "sin"; Blockly.Msg.MATH_TRIG_TAN = "tg"; Blockly.Msg.MATH_TRIG_TOOLTIP_ACOS = "Ədədin arccosinusunu qaytarır."; Blockly.Msg.MATH_TRIG_TOOLTIP_ASIN = "Ədədin arcsinusunu qaytarır."; Blockly.Msg.MATH_TRIG_TOOLTIP_ATAN = "Ədədin arctanqensini qaytarır."; Blockly.Msg.MATH_TRIG_TOOLTIP_COS = "Dərəcənin kosinusunu qaytarır (radianın yox)."; Blockly.Msg.MATH_TRIG_TOOLTIP_SIN = "Dərəcənin sinusunu qaytar (radianın yox)."; Blockly.Msg.MATH_TRIG_TOOLTIP_TAN = "Dərəcənin tangensini qaytar (radianın yox)."; Blockly.Msg.NEW_VARIABLE = "Yeni dəyişən..."; Blockly.Msg.NEW_VARIABLE_TITLE = "Yeni dəyişənin adı:"; Blockly.Msg.ORDINAL_NUMBER_SUFFIX = ""; Blockly.Msg.PROCEDURES_BEFORE_PARAMS = "ilə:"; Blockly.Msg.PROCEDURES_CALLNORETURN_CALL = ""; Blockly.Msg.PROCEDURES_CALLNORETURN_HELPURL = "https://en.wikipedia.org/wiki/Procedure_%28computer_science%29"; Blockly.Msg.PROCEDURES_CALLNORETURN_TOOLTIP = "Yaradılmış '%1' funksiyasını çalışdır."; Blockly.Msg.PROCEDURES_CALLRETURN_HELPURL = "https://en.wikipedia.org/wiki/Procedure_%28computer_science%29"; Blockly.Msg.PROCEDURES_CALLRETURN_TOOLTIP = "Yaradılmış '%1' funksiyasını çalışdır və nəticəni istifadə et."; Blockly.Msg.PROCEDURES_CREATE_DO = "'%1' yarat"; Blockly.Msg.PROCEDURES_DEFNORETURN_DO = ""; Blockly.Msg.PROCEDURES_DEFNORETURN_HELPURL = "https://en.wikipedia.org/wiki/Procedure_%28computer_science%29"; Blockly.Msg.PROCEDURES_DEFNORETURN_PROCEDURE = "hansısa əməliyyat"; Blockly.Msg.PROCEDURES_DEFNORETURN_TITLE = "icra et:"; Blockly.Msg.PROCEDURES_DEFNORETURN_TOOLTIP = "Nəticəsi olmayan funksiya yaradır."; Blockly.Msg.PROCEDURES_DEFRETURN_HELPURL = "https://en.wikipedia.org/wiki/Procedure_%28computer_science%29"; Blockly.Msg.PROCEDURES_DEFRETURN_RETURN = "qaytar"; Blockly.Msg.PROCEDURES_DEFRETURN_TOOLTIP = "Nəticəsi olan funksiya yaradır."; Blockly.Msg.PROCEDURES_DEF_DUPLICATE_WARNING = "Xəbərdarlıq: Bu funksiyanın təkrar olunmuş parametrləri var."; Blockly.Msg.PROCEDURES_HIGHLIGHT_DEF = "Funksiyanın təyinatını vurğula"; Blockly.Msg.PROCEDURES_IFRETURN_TOOLTIP = "Əgər bir dəyər \"doğru\"-dursa onda ikinci dəyəri qaytar."; Blockly.Msg.PROCEDURES_IFRETURN_WARNING = "Xəbərdarlıq: Bu blok ancaq bir funksiyanın təyinatı daxilində işlədilə bilər."; Blockly.Msg.PROCEDURES_MUTATORARG_TITLE = "Giriş adı:"; Blockly.Msg.PROCEDURES_MUTATORCONTAINER_TITLE = "girişlər"; Blockly.Msg.REMOVE_COMMENT = "Şərhi sil"; Blockly.Msg.RENAME_VARIABLE = "Dəyişənin adını dəyiş..."; Blockly.Msg.RENAME_VARIABLE_TITLE = "Bütün '%1' dəyişənlərinin adını buna dəyiş:"; Blockly.Msg.TEXT_APPEND_APPENDTEXT = "bu mətni əlavə et:"; Blockly.Msg.TEXT_APPEND_HELPURL = "https://code.google.com/p/blockly/wiki/Text#Text_modification"; Blockly.Msg.TEXT_APPEND_TO = "bu mətnin sonuna:"; Blockly.Msg.TEXT_APPEND_TOOLTIP = "'%1' dəyişəninin sonuna nəsə əlavə et."; Blockly.Msg.TEXT_CHANGECASE_HELPURL = "https://code.google.com/p/blockly/wiki/Text#Adjusting_text_case"; Blockly.Msg.TEXT_CHANGECASE_OPERATOR_LOWERCASE = "kiçik hərflərlə"; Blockly.Msg.TEXT_CHANGECASE_OPERATOR_TITLECASE = "Baş Hərflərlə"; Blockly.Msg.TEXT_CHANGECASE_OPERATOR_UPPERCASE = "BÖYÜK HƏRFLƏRLƏ"; Blockly.Msg.TEXT_CHANGECASE_TOOLTIP = "Mətndə hərflərin böyük-kiçikliyini dəyiş."; Blockly.Msg.TEXT_CHARAT_FIRST = "birinci hərfi götür"; Blockly.Msg.TEXT_CHARAT_FROM_END = "axırdan bu nömrəli hərfi götür"; Blockly.Msg.TEXT_CHARAT_FROM_START = "bu nömrəli hərfi götür"; Blockly.Msg.TEXT_CHARAT_HELPURL = "https://code.google.com/p/blockly/wiki/Text#Extracting_text"; Blockly.Msg.TEXT_CHARAT_INPUT_INTEXT = "növbəti mətndə"; Blockly.Msg.TEXT_CHARAT_LAST = "axırıncı hərfi götür"; Blockly.Msg.TEXT_CHARAT_RANDOM = "təsadüfi hərf götür"; Blockly.Msg.TEXT_CHARAT_TAIL = ""; Blockly.Msg.TEXT_CHARAT_TOOLTIP = "Göstərilən mövqedəki hərfi qaytarır."; Blockly.Msg.TEXT_CREATE_JOIN_ITEM_TOOLTIP = "Mətnə bir element əlavə et."; Blockly.Msg.TEXT_CREATE_JOIN_TITLE_JOIN = "birləşdir"; Blockly.Msg.TEXT_CREATE_JOIN_TOOLTIP = "Bu mətn blokunu yenidən konfigurasiya etmək üçün bölmələri əlavə edin, silin və ya yerlərini dəyişin."; Blockly.Msg.TEXT_GET_SUBSTRING_END_FROM_END = "axırdan bu nömrəli hərfə qədər"; Blockly.Msg.TEXT_GET_SUBSTRING_END_FROM_START = "bu nömrəli hərfə qədər"; Blockly.Msg.TEXT_GET_SUBSTRING_END_LAST = "son hərfə qədər"; Blockly.Msg.TEXT_GET_SUBSTRING_HELPURL = "http://code.google.com/p/blockly/wiki/Text#Extracting_a_region_of_text"; Blockly.Msg.TEXT_GET_SUBSTRING_INPUT_IN_TEXT = "mətndə"; Blockly.Msg.TEXT_GET_SUBSTRING_START_FIRST = "Mətnin surətini ilk hərfdən"; Blockly.Msg.TEXT_GET_SUBSTRING_START_FROM_END = "Mətnin surətini sondan bu nömrəli # hərfdən"; Blockly.Msg.TEXT_GET_SUBSTRING_START_FROM_START = "Mətnin surətini bu nömrəli hərfdən"; Blockly.Msg.TEXT_GET_SUBSTRING_TAIL = ""; Blockly.Msg.TEXT_GET_SUBSTRING_TOOLTIP = "Mətnin təyin olunmuş hissəsini qaytarır."; Blockly.Msg.TEXT_INDEXOF_HELPURL = "https://code.google.com/p/blockly/wiki/Text#Finding_text"; Blockly.Msg.TEXT_INDEXOF_INPUT_INTEXT = "mətndə"; Blockly.Msg.TEXT_INDEXOF_OPERATOR_FIRST = "Bu mətn ilə ilk rastlaşmanı tap:"; Blockly.Msg.TEXT_INDEXOF_OPERATOR_LAST = "Bu mətn ilə son rastlaşmanı tap:"; Blockly.Msg.TEXT_INDEXOF_TAIL = ""; Blockly.Msg.TEXT_INDEXOF_TOOLTIP = "Birinci mətnin ikinci mətndə ilk/son rastlaşma indeksini qaytarır. Əgər rastlaşma baş verməzsə, 0 qaytarır."; Blockly.Msg.TEXT_ISEMPTY_HELPURL = "https://code.google.com/p/blockly/wiki/Text#Checking_for_empty_text"; Blockly.Msg.TEXT_ISEMPTY_TITLE = "%1 boşdur"; Blockly.Msg.TEXT_ISEMPTY_TOOLTIP = "Verilmiş mətn boşdursa, doğru qiymətini qaytarır."; Blockly.Msg.TEXT_JOIN_HELPURL = "https://code.google.com/p/blockly/wiki/Text#Text_creation"; Blockly.Msg.TEXT_JOIN_TITLE_CREATEWITH = "Verilmişlərlə mətn yarat"; Blockly.Msg.TEXT_JOIN_TOOLTIP = "İxtiyari sayda elementlərinin birləşməsi ilə mətn parçası yarat."; Blockly.Msg.TEXT_LENGTH_HELPURL = "https://code.google.com/p/blockly/wiki/Text#Text_modification"; Blockly.Msg.TEXT_LENGTH_TITLE = "%1 - ın uzunluğu"; Blockly.Msg.TEXT_LENGTH_TOOLTIP = "Verilmiş mətndəki hərflərin(sözlər arası boşluqlar sayılmaqla) sayını qaytarır."; Blockly.Msg.TEXT_PRINT_HELPURL = "https://code.google.com/p/blockly/wiki/Text#Printing_text"; Blockly.Msg.TEXT_PRINT_TITLE = "%1 - i çap elə"; Blockly.Msg.TEXT_PRINT_TOOLTIP = "Təyin olunmuş mətn, ədəd və ya hər hansı bir başqa elementi çap elə."; Blockly.Msg.TEXT_PROMPT_HELPURL = "https://code.google.com/p/blockly/wiki/Text#Getting_input_from_the_user"; Blockly.Msg.TEXT_PROMPT_TOOLTIP_NUMBER = "İstifadəçiyə ədəd daxil etməsi üçün sorğu/tələb göndərin."; Blockly.Msg.TEXT_PROMPT_TOOLTIP_TEXT = "İstifadəçiyə mətn daxil etməsi üçün sorğu/tələb göndərin."; Blockly.Msg.TEXT_PROMPT_TYPE_NUMBER = "İstifadəçiyə ədəd daxil etməsi üçün sorğunu/tələbi ismarıc kimi göndərin"; Blockly.Msg.TEXT_PROMPT_TYPE_TEXT = "İstifadəçiyə mətn daxil etməsi üçün sorğunu/tələbi ismarıc ilə göndərin"; Blockly.Msg.TEXT_TEXT_HELPURL = "https://en.wikipedia.org/wiki/String_(computer_science)"; Blockly.Msg.TEXT_TEXT_TOOLTIP = "Mətndəki hərf, söz və ya sətir."; Blockly.Msg.TEXT_TRIM_HELPURL = "https://code.google.com/p/blockly/wiki/Text#Trimming_%28removing%29_spaces"; Blockly.Msg.TEXT_TRIM_OPERATOR_BOTH = "Boşluqları hər iki tərəfdən pozun"; Blockly.Msg.TEXT_TRIM_OPERATOR_LEFT = "Boşluqlari yalnız sol tərəfdən pozun"; Blockly.Msg.TEXT_TRIM_OPERATOR_RIGHT = "Boşluqları yalnız sağ tərəfdən pozun"; Blockly.Msg.TEXT_TRIM_TOOLTIP = "Mətnin hər iki və ya yalnız bir tərəfdən olan boşluqları pozulmuş surətini qaytarın."; Blockly.Msg.VARIABLES_DEFAULT_NAME = "element"; Blockly.Msg.VARIABLES_GET_CREATE_SET = "'%1 - i təyin et' - i yarat"; Blockly.Msg.VARIABLES_GET_HELPURL = "http://code.google.com/p/blockly/wiki/Variables#Get"; Blockly.Msg.VARIABLES_GET_TAIL = ""; Blockly.Msg.VARIABLES_GET_TITLE = ""; Blockly.Msg.VARIABLES_GET_TOOLTIP = "Bu dəyişənin qiymətini qaytarır."; Blockly.Msg.VARIABLES_SET_CREATE_GET = "'%1 - i götür' - ü yarat"; Blockly.Msg.VARIABLES_SET_HELPURL = "http://code.google.com/p/blockly/wiki/Variables#Set"; Blockly.Msg.VARIABLES_SET_TAIL = "- i bu qiymət ilə təyin et:"; Blockly.Msg.VARIABLES_SET_TITLE = " "; Blockly.Msg.VARIABLES_SET_TOOLTIP = "Bu dəyişəni daxil edilmiş qiymətə bərabər edir."; Blockly.Msg.PROCEDURES_DEFRETURN_TITLE = Blockly.Msg.PROCEDURES_DEFNORETURN_TITLE; Blockly.Msg.LISTS_GET_SUBLIST_INPUT_IN_LIST = Blockly.Msg.LISTS_INLIST; Blockly.Msg.LISTS_SET_INDEX_INPUT_IN_LIST = Blockly.Msg.LISTS_INLIST; Blockly.Msg.PROCEDURES_DEFRETURN_PROCEDURE = Blockly.Msg.PROCEDURES_DEFNORETURN_PROCEDURE; Blockly.Msg.VARIABLES_SET_ITEM = Blockly.Msg.VARIABLES_DEFAULT_NAME; Blockly.Msg.LISTS_CREATE_WITH_ITEM_TITLE = Blockly.Msg.VARIABLES_DEFAULT_NAME; Blockly.Msg.MATH_CHANGE_TITLE_ITEM = Blockly.Msg.VARIABLES_DEFAULT_NAME; Blockly.Msg.VARIABLES_GET_ITEM = Blockly.Msg.VARIABLES_DEFAULT_NAME; Blockly.Msg.PROCEDURES_DEFRETURN_DO = Blockly.Msg.PROCEDURES_DEFNORETURN_DO; Blockly.Msg.LISTS_GET_INDEX_HELPURL = Blockly.Msg.LISTS_INDEX_OF_HELPURL; Blockly.Msg.TEXT_CREATE_JOIN_ITEM_TITLE_ITEM = Blockly.Msg.VARIABLES_DEFAULT_NAME; Blockly.Msg.CONTROLS_IF_MSG_THEN = Blockly.Msg.CONTROLS_REPEAT_INPUT_DO; Blockly.Msg.LISTS_INDEX_OF_INPUT_IN_LIST = Blockly.Msg.LISTS_INLIST; Blockly.Msg.PROCEDURES_CALLRETURN_CALL = Blockly.Msg.PROCEDURES_CALLNORETURN_CALL; Blockly.Msg.LISTS_GET_INDEX_INPUT_IN_LIST = Blockly.Msg.LISTS_INLIST; Blockly.Msg.CONTROLS_FOR_INPUT_DO = Blockly.Msg.CONTROLS_REPEAT_INPUT_DO; Blockly.Msg.CONTROLS_FOREACH_INPUT_DO = Blockly.Msg.CONTROLS_REPEAT_INPUT_DO; Blockly.Msg.CONTROLS_IF_IF_TITLE_IF = Blockly.Msg.CONTROLS_IF_MSG_IF; Blockly.Msg.CONTROLS_WHILEUNTIL_INPUT_DO = Blockly.Msg.CONTROLS_REPEAT_INPUT_DO; Blockly.Msg.CONTROLS_IF_ELSEIF_TITLE_ELSEIF = Blockly.Msg.CONTROLS_IF_MSG_ELSEIF; Blockly.Msg.TEXT_APPEND_VARIABLE = Blockly.Msg.VARIABLES_DEFAULT_NAME; Blockly.Msg.CONTROLS_IF_ELSE_TITLE_ELSE = Blockly.Msg.CONTROLS_IF_MSG_ELSE;
lekster/md_new
blockly/msg/js/az-latn.js
JavaScript
mit
30,766
"use strict"; var m = require("mithril"), assign = require("lodash.assign"), id = require("./lib/id"), hide = require("./lib/hide"), label = require("./lib/label"), css = require("./textarea.css"); module.exports = { controller : function(options) { var ctrl = this; ctrl.id = id(options); ctrl.text = options.data || ""; ctrl.resize = function(opt, value) { opt.update(opt.path, value); ctrl.text = value; }; }, view : function(ctrl, options) { var field = options.field, hidden = hide(options); if(hidden) { return hidden; } return m("div", { class : options.class }, label(ctrl, options), m("div", { class : css.expander }, m("pre", { class : css.shadow }, m("span", ctrl.text), m("br")), m("textarea", assign({ // attrs id : ctrl.id, class : css.textarea, required : field.required ? "required" : null, // events oninput : m.withAttr("value", ctrl.resize.bind(null, options)) }, field.attrs || {} ), options.data || "") ) ); } };
Ryan-McMillan/crucible
src/types/textarea.js
JavaScript
mit
1,402
(function() { "use strict"; angular .module('app.users', [ 'app.core' ]); })();
belicka/tia-rezervacny-system
client/app/users/users.module.js
JavaScript
mit
117
var Plugin = require('./baseplugin'), request = require('request-promise'); class Spotify extends Plugin { init() { this.httpRegex = /(?:https?:\/\/)?open\.spotify\.com\/(album|track|user\/[^\/]+\/playlist)\/([a-zA-Z0-9]+)/; this.uriRegex = /^spotify:(album|track|user:[^:]+:playlist):([a-zA-Z0-9]+)$/; } canHandle(url) { return this.httpRegex.test(url) || this.uriRegex.test(url); } run(url) { var options = { url: `https://embed.spotify.com/oembed/?url=${url}`, headers: {'User-Agent': 'request'} }; return request.get(options) .then(body => JSON.parse(body).html) .then(html => ({ type: 'spotify', html: html })); } } module.exports = Spotify;
d3estudio/d3-digest
src/prefetch/plugins/spotify.js
JavaScript
mit
776
'use strict'; const fs = require('fs'), _ = require('lodash'); let config = require('./_default'); const ENV_NAME = process.env.NODE_ENV || process.env.ENV; const ENVIRONMENT_FILE = `${__dirname}/_${ENV_NAME}.js`; // Merge with ENV file if exits. if (fs.existsSync(ENVIRONMENT_FILE)) { const env = require(ENVIRONMENT_FILE); config = _.mergeWith(config, env); } module.exports = config;
JoTrdl/netflix-top
src/config/index.js
JavaScript
mit
402
import now from './now.js'; /** * This function transforms stored pixel values into a canvas image data buffer * by using a LUT. * * @param {Image} image A Cornerstone Image Object * @param {Array} lut Lookup table array * @param {Uint8ClampedArray} canvasImageDataData canvasImageData.data buffer filled with white pixels * * @returns {void} */ export default function (image, lut, canvasImageDataData) { let start = now(); const pixelData = image.getPixelData(); image.stats.lastGetPixelDataTime = now() - start; const numPixels = pixelData.length; const minPixelValue = image.minPixelValue; let canvasImageDataIndex = 0; let storedPixelDataIndex = 0; let pixelValue; // NOTE: As of Nov 2014, most javascript engines have lower performance when indexing negative indexes. // We have a special code path for this case that improves performance. Thanks to @jpambrun for this enhancement // Added two paths (Int16Array, Uint16Array) to avoid polymorphic deoptimization in chrome. start = now(); if (pixelData instanceof Int16Array) { if (minPixelValue < 0) { while (storedPixelDataIndex < numPixels) { pixelValue = lut[pixelData[storedPixelDataIndex++] + (-minPixelValue)]; canvasImageDataData[canvasImageDataIndex++] = pixelValue; canvasImageDataData[canvasImageDataIndex++] = pixelValue; canvasImageDataData[canvasImageDataIndex++] = pixelValue; canvasImageDataData[canvasImageDataIndex++] = 255; // Alpha } } else { while (storedPixelDataIndex < numPixels) { pixelValue = lut[pixelData[storedPixelDataIndex++]]; canvasImageDataData[canvasImageDataIndex++] = pixelValue; canvasImageDataData[canvasImageDataIndex++] = pixelValue; canvasImageDataData[canvasImageDataIndex++] = pixelValue; canvasImageDataData[canvasImageDataIndex++] = 255; // Alpha } } } else if (pixelData instanceof Uint16Array) { while (storedPixelDataIndex < numPixels) { pixelValue = lut[pixelData[storedPixelDataIndex++]]; canvasImageDataData[canvasImageDataIndex++] = pixelValue; canvasImageDataData[canvasImageDataIndex++] = pixelValue; canvasImageDataData[canvasImageDataIndex++] = pixelValue; canvasImageDataData[canvasImageDataIndex++] = 255; // Alpha } } else if (minPixelValue < 0) { while (storedPixelDataIndex < numPixels) { pixelValue = lut[pixelData[storedPixelDataIndex++] + (-minPixelValue)]; canvasImageDataData[canvasImageDataIndex++] = pixelValue; canvasImageDataData[canvasImageDataIndex++] = pixelValue; canvasImageDataData[canvasImageDataIndex++] = pixelValue; canvasImageDataData[canvasImageDataIndex++] = 255; // Alpha } } else { while (storedPixelDataIndex < numPixels) { pixelValue = lut[pixelData[storedPixelDataIndex++]]; canvasImageDataData[canvasImageDataIndex++] = pixelValue; canvasImageDataData[canvasImageDataIndex++] = pixelValue; canvasImageDataData[canvasImageDataIndex++] = pixelValue; canvasImageDataData[canvasImageDataIndex++] = 255; // Alpha } } image.stats.lastStoredPixelDataToCanvasImageDataTime = now() - start; }
google/cornerstone
src/internal/storedPixelDataToCanvasImageDataRGBA.js
JavaScript
mit
3,211
module.exports = function() { function CreditsCommand() { return { name: 'credits', params: '[none]', execute: function(data, sandbox) { var msg = '\nCREDITS:\n'; msg += 'Hack Bot\n'; msg += 'version: v1\n'; msg += 'created by: R.M.C. (hacktastic)\n\n\n'; sandbox.sendChannelMessage(msg); } }; } return new CreditsCommand(); };
ryanmcoble/LiveCoding.tv-Chat-Bot
modules/commands/credits/credits.js
JavaScript
mit
375
'use strict'; const Bluebird = require('bluebird'); const Book = require('./helpers/book'); const Counter = require('../lib/counter'); const Genre = require('./helpers/genre'); const Redis = require('./helpers/redis'); describe('counter', () => { describe('count', () => { it('returns the count for a model without a filter function', () => { const request = {}; return Counter.count(Genre, request) .then((count) => { expect(count).to.eql(3); }); }); it('returns the count for a model with a filter function', () => { const request = { query: { filter: { year: 1984 } }, auth: { credentials: {} } }; return Counter.count(Book, request) .then((count) => { expect(count).to.eql(2); }); }); it('saves the count to redis under the given key with a ttl when a redis client is given', () => { const key = 'key'; const ttl = () => 10; const request = { query: { filter: { year: 1984 } }, auth: { credentials: {} } }; return Counter.count(Book, request, Redis, key, ttl) .then(() => { return Bluebird.all([ Redis.getAsync(key), Redis.ttlAsync(key) ]); }) .spread((cachedCount, cachedTtl) => { expect(cachedCount).to.eql('2'); expect(cachedTtl).to.eql(10); }); }); }); });
lob/hapi-bookshelf-total-count
test/counter.test.js
JavaScript
mit
1,376
// Dependencies let builder = require('focus').component.builder; let React = require('react'); let checkIsNotNull = require('focus').util.object.checkIsNotNull; let type = require('focus').component.types; let find = require('lodash/collection/find'); // Mixins let translationMixin = require('../../common/i18n').mixin; let infiniteScrollMixin = require('../mixin/infinite-scroll').mixin; let referenceMixin = require('../../common/mixin/reference-property'); // Components let Button = require('../../common/button/action').component; let listMixin = { /** * Display name. */ displayName: 'selection-list', /** * Mixin dependancies. */ mixins: [translationMixin, infiniteScrollMixin, referenceMixin], /** * Default properties for the list. * @returns {{isSelection: boolean}} the default properties */ getDefaultProps: function getListDefaultProps(){ return { data: [], isSelection: true, selectionStatus: 'partial', selectionData: [], isLoading: false, operationList: [], idField: 'id' }; }, /** * list property validation. * @type {Object} */ propTypes: { data: type('array'), idField: type('string'), isLoading: type('bool'), isSelection: type('bool'), lineComponent: type('func', true), loader: type('func'), onLineClick: type('func'), onSelection: type('func'), operationList: type('array'), selectionData: type('array'), selectionStatus: type('string') }, /** * called before component mount */ componentWillMount() { checkIsNotNull('lineComponent', this.props.lineComponent); }, /** * Return selected items in the list. * @return {Array} selected items */ getSelectedItems() { let selected = []; for(let i = 1; i < this.props.data.length + 1; i++){ let lineName = 'line' + i; let lineValue = this.refs[lineName].getValue(); if(lineValue.isSelected){ selected.push(lineValue.item); } } return selected; }, /** * Render lines of the list. * @returns {*} DOM for lines */ _renderLines() { let lineCount = 1; let {data, lineComponent, selectionStatus, idField, isSelection, selectionData, onSelection, onLineClick, operationList} = this.props; return data.map((line) => { let isSelected; let selection = find(selectionData, {[idField]: line[idField]}); if (selection) { isSelected = selection.isSelected; } else { switch(selectionStatus){ case 'none': isSelected = false; break; case 'selected': isSelected = true; break; case 'partial': isSelected = undefined; break; default: isSelected = false; } } return React.createElement(lineComponent, { key: line[idField], data: line, ref: `line${lineCount++}`, isSelection: isSelection, isSelected: isSelected, onSelection: onSelection, onLineClick: onLineClick, operationList: operationList, reference: this._getReference() }); }); }, _renderLoading() { if(this.props.isLoading){ if(this.props.loader){ return this.props.loader(); } return ( <li className='sl-loading'>{this.i18n('list.loading')} ...</li> ); } }, _renderManualFetch() { if(this.props.isManualFetch && this.props.hasMoreData){ let style = {className: 'primary'}; return ( <li className='sl-button'> <Button handleOnClick={this.handleShowMore} label='list.button.showMore' style={style} type='button' /> </li> ); } }, /** * Render the list. * @returns {XML} DOM of the component */ render() { return ( <ul data-focus='selection-list'> {this._renderLines()} {this._renderLoading()} {this._renderManualFetch()} </ul> ); } }; module.exports = builder(listMixin);
Jerom138/focus-components
src/list/selection/list.js
JavaScript
mit
4,831
import { createAction } from 'redux-actions'; import axios from '../../../utils/APIHelper'; export const CATEGORY_FORM_UPDATE = 'CATEGORY_FORM_UPDATE'; export const CATEGORY_FORM_RESET = 'CATEGORY_FORM_RESET'; export const categoryFormUpdate = createAction(CATEGORY_FORM_UPDATE); export const categoryFormReset = createAction(CATEGORY_FORM_RESET); export function requestCreateCategory(attrs) { return (dispatch) => { dispatch(categoryFormUpdate()); return axios.post('/api/categories', { category: attrs }) .then(response => { dispatch(categoryFormReset()); return response.data.category; }, e => dispatch(categoryFormUpdate(e))); }; }
fdietz/whistler_news_reader
client/js/modules/categoryForm/actions/index.js
JavaScript
mit
681
'use strict'; /** * Module dependencies */ var forumsPolicy = require('../policies/forums.server.policy'), forums = require('../controllers/forums.server.controller'); module.exports = function (app) { // Forums collection routes app.route('/api/forums').all(forumsPolicy.isAllowed) .get(forums.list) .post(forums.create); // Single forum routes app.route('/api/forums/:forumId').all(forumsPolicy.isAllowed) .get(forums.read) .put(forums.update) .delete(forums.delete); // Finish by binding the forum middleware app.param('forumId', forums.forumByID); };
jecp/mean
modules/forums/server/routes/forums.server.routes.js
JavaScript
mit
595
(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _index = _interopRequireDefault(require("../../index")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); } function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var Custom = /*#__PURE__*/ function (_Smooth) { _inherits(Custom, _Smooth); function Custom(opt) { var _this; _classCallCheck(this, Custom); _this = _possibleConstructorReturn(this, _getPrototypeOf(Custom).call(this, opt)); _this.perfs = { now: null, last: null }; _this.dom.section = opt.section; return _this; } _createClass(Custom, [{ key: "init", value: function init() { _get(_getPrototypeOf(Custom.prototype), "init", this).call(this); } }, { key: "run", value: function run() { this.perfs.now = window.performance.now(); _get(_getPrototypeOf(Custom.prototype), "run", this).call(this); this.dom.section.style[this.prefix] = this.getTransform(-this.vars.current.toFixed(2)); console.log(this.perfs.now - this.perfs.last); this.perfs.last = this.perfs.now; } }, { key: "resize", value: function resize() { this.vars.bounding = this.dom.section.getBoundingClientRect().height - this.vars.height; _get(_getPrototypeOf(Custom.prototype), "resize", this).call(this); } }]); return Custom; }(_index["default"]); var _default = Custom; exports["default"] = _default; },{"../../index":3}],2:[function(require,module,exports){ "use strict"; var _custom = _interopRequireDefault(require("./custom")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } var scroll = new _custom["default"]({ "extends": true, section: document.querySelector('.vs-section') }); scroll.init(); },{"./custom":1}],3:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _domClasses = _interopRequireDefault(require("dom-classes")); var _domCreateElement = _interopRequireDefault(require("dom-create-element")); var _prefix = _interopRequireDefault(require("prefix")); var _virtualScroll = _interopRequireDefault(require("virtual-scroll")); var _domEvents = _interopRequireDefault(require("dom-events")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } var Smooth = /*#__PURE__*/ function () { function Smooth() { var opt = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; _classCallCheck(this, Smooth); this.createBound(); this.options = opt; this.prefix = (0, _prefix["default"])('transform'); this.rAF = undefined; // It seems that under heavy load, Firefox will still call the RAF callback even though the RAF has been canceled // To prevent that we set a flag to prevent any callback to be executed when RAF is removed this.isRAFCanceled = false; var constructorName = this.constructor.name ? this.constructor.name : 'Smooth'; this["extends"] = typeof opt["extends"] === 'undefined' ? this.constructor !== Smooth : opt["extends"]; this.callback = this.options.callback || null; this.vars = { direction: this.options.direction || 'vertical', "native": this.options["native"] || false, ease: this.options.ease || 0.075, preload: this.options.preload || false, current: 0, last: 0, target: 0, height: window.innerHeight, width: window.innerWidth, bounding: 0, timer: null, ticking: false }; this.vs = this.vars["native"] ? null : new _virtualScroll["default"]({ limitInertia: this.options.vs && this.options.vs.limitInertia || false, mouseMultiplier: this.options.vs && this.options.vs.mouseMultiplier || 1, touchMultiplier: this.options.vs && this.options.vs.touchMultiplier || 1.5, firefoxMultiplier: this.options.vs && this.options.vs.firefoxMultiplier || 30, preventTouch: this.options.vs && this.options.vs.preventTouch || true }); this.dom = { listener: this.options.listener || document.body, section: this.options.section || document.querySelector('.vs-section') || null, scrollbar: this.vars["native"] || this.options.noscrollbar ? null : { state: { clicked: false, x: 0 }, el: (0, _domCreateElement["default"])({ selector: 'div', styles: "vs-scrollbar vs-".concat(this.vars.direction, " vs-scrollbar-").concat(constructorName.toLowerCase()) }), drag: { el: (0, _domCreateElement["default"])({ selector: 'div', styles: 'vs-scrolldrag' }), delta: 0, height: 50 } } }; } _createClass(Smooth, [{ key: "createBound", value: function createBound() { var _this = this; ['run', 'calc', 'debounce', 'resize', 'mouseUp', 'mouseDown', 'mouseMove', 'calcScroll', 'scrollTo'].forEach(function (fn) { return _this[fn] = _this[fn].bind(_this); }); } }, { key: "init", value: function init() { this.addClasses(); this.vars.preload && this.preloadImages(); this.vars["native"] ? this.addFakeScrollHeight() : !this.options.noscrollbar && this.addFakeScrollBar(); this.addEvents(); this.resize(); } }, { key: "addClasses", value: function addClasses() { var type = this.vars["native"] ? 'native' : 'virtual'; var direction = this.vars.direction === 'vertical' ? 'y' : 'x'; _domClasses["default"].add(this.dom.listener, "is-".concat(type, "-scroll")); _domClasses["default"].add(this.dom.listener, "".concat(direction, "-scroll")); } }, { key: "preloadImages", value: function preloadImages() { var _this2 = this; var images = Array.prototype.slice.call(this.dom.listener.querySelectorAll('img'), 0); images.forEach(function (image) { var img = document.createElement('img'); _domEvents["default"].once(img, 'load', function () { images.splice(images.indexOf(image), 1); images.length === 0 && _this2.resize(); }); img.src = image.getAttribute('src'); }); } }, { key: "calc", value: function calc(e) { var delta = this.vars.direction == 'horizontal' ? e.deltaX : e.deltaY; this.vars.target += delta * -1; this.clampTarget(); } }, { key: "debounce", value: function debounce() { var _this3 = this; var win = this.dom.listener === document.body; this.vars.target = this.vars.direction === 'vertical' ? win ? window.scrollY || window.pageYOffset : this.dom.listener.scrollTop : win ? window.scrollX || window.pageXOffset : this.dom.listener.scrollLeft; clearTimeout(this.vars.timer); if (!this.vars.ticking) { this.vars.ticking = true; _domClasses["default"].add(this.dom.listener, 'is-scrolling'); } this.vars.timer = setTimeout(function () { _this3.vars.ticking = false; _domClasses["default"].remove(_this3.dom.listener, 'is-scrolling'); }, 200); } }, { key: "run", value: function run() { if (this.isRAFCanceled) return; this.vars.current += (this.vars.target - this.vars.current) * this.vars.ease; this.vars.current < .1 && (this.vars.current = 0); this.requestAnimationFrame(); if (!this["extends"]) { this.dom.section.style[this.prefix] = this.getTransform(-this.vars.current.toFixed(2)); } if (!this.vars["native"] && !this.options.noscrollbar) { var size = this.dom.scrollbar.drag.height; var bounds = this.vars.direction === 'vertical' ? this.vars.height : this.vars.width; var value = Math.abs(this.vars.current) / (this.vars.bounding / (bounds - size)) + size / .5 - size; var clamp = Math.max(0, Math.min(value - size, value + size)); this.dom.scrollbar.drag.el.style[this.prefix] = this.getTransform(clamp.toFixed(2)); } if (this.callback && this.vars.current !== this.vars.last) { this.callback(this.vars.current); } this.vars.last = this.vars.current; } }, { key: "getTransform", value: function getTransform(value) { return this.vars.direction === 'vertical' ? "translate3d(0,".concat(value, "px,0)") : "translate3d(".concat(value, "px,0,0)"); } }, { key: "on", value: function on() { var requestAnimationFrame = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true; if (this.isRAFCanceled) { this.isRAFCanceled = false; } var node = this.dom.listener === document.body ? window : this.dom.listener; this.vars["native"] ? _domEvents["default"].on(node, 'scroll', this.debounce) : this.vs && this.vs.on(this.calc); requestAnimationFrame && this.requestAnimationFrame(); } }, { key: "off", value: function off() { var cancelAnimationFrame = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true; var node = this.dom.listener === document.body ? window : this.dom.listener; this.vars["native"] ? _domEvents["default"].off(node, 'scroll', this.debounce) : this.vs && this.vs.off(this.calc); cancelAnimationFrame && this.cancelAnimationFrame(); } }, { key: "requestAnimationFrame", value: function (_requestAnimationFrame) { function requestAnimationFrame() { return _requestAnimationFrame.apply(this, arguments); } requestAnimationFrame.toString = function () { return _requestAnimationFrame.toString(); }; return requestAnimationFrame; }(function () { this.rAF = requestAnimationFrame(this.run); }) }, { key: "cancelAnimationFrame", value: function (_cancelAnimationFrame) { function cancelAnimationFrame() { return _cancelAnimationFrame.apply(this, arguments); } cancelAnimationFrame.toString = function () { return _cancelAnimationFrame.toString(); }; return cancelAnimationFrame; }(function () { this.isRAFCanceled = true; cancelAnimationFrame(this.rAF); }) }, { key: "addEvents", value: function addEvents() { this.on(); _domEvents["default"].on(window, 'resize', this.resize); } }, { key: "removeEvents", value: function removeEvents() { this.off(); _domEvents["default"].off(window, 'resize', this.resize); } }, { key: "addFakeScrollBar", value: function addFakeScrollBar() { this.dom.listener.appendChild(this.dom.scrollbar.el); this.dom.scrollbar.el.appendChild(this.dom.scrollbar.drag.el); _domEvents["default"].on(this.dom.scrollbar.el, 'click', this.calcScroll); _domEvents["default"].on(this.dom.scrollbar.el, 'mousedown', this.mouseDown); _domEvents["default"].on(document, 'mousemove', this.mouseMove); _domEvents["default"].on(document, 'mouseup', this.mouseUp); } }, { key: "removeFakeScrollBar", value: function removeFakeScrollBar() { _domEvents["default"].off(this.dom.scrollbar.el, 'click', this.calcScroll); _domEvents["default"].off(this.dom.scrollbar.el, 'mousedown', this.mouseDown); _domEvents["default"].off(document, 'mousemove', this.mouseMove); _domEvents["default"].off(document, 'mouseup', this.mouseUp); this.dom.listener.removeChild(this.dom.scrollbar.el); } }, { key: "mouseDown", value: function mouseDown(e) { e.preventDefault(); e.which == 1 && (this.dom.scrollbar.state.clicked = true); } }, { key: "mouseUp", value: function mouseUp(e) { this.dom.scrollbar.state.clicked = false; _domClasses["default"].remove(this.dom.listener, 'is-dragging'); } }, { key: "mouseMove", value: function mouseMove(e) { this.dom.scrollbar.state.clicked && this.calcScroll(e); } }, { key: "addFakeScrollHeight", value: function addFakeScrollHeight() { this.dom.scroll = (0, _domCreateElement["default"])({ selector: 'div', styles: 'vs-scroll-view' }); this.dom.listener.appendChild(this.dom.scroll); } }, { key: "removeFakeScrollHeight", value: function removeFakeScrollHeight() { this.dom.listener.removeChild(this.dom.scroll); } }, { key: "calcScroll", value: function calcScroll(e) { var client = this.vars.direction == 'vertical' ? e.clientY : e.clientX; var bounds = this.vars.direction == 'vertical' ? this.vars.height : this.vars.width; var delta = client * (this.vars.bounding / bounds); _domClasses["default"].add(this.dom.listener, 'is-dragging'); this.vars.target = delta; this.clampTarget(); this.dom.scrollbar && (this.dom.scrollbar.drag.delta = this.vars.target); } }, { key: "scrollTo", value: function scrollTo(offset) { if (this.vars["native"]) { this.vars.direction == 'vertical' ? window.scrollTo(0, offset) : window.scrollTo(offset, 0); } else { this.vars.target = offset; this.clampTarget(); } } }, { key: "resize", value: function resize() { var prop = this.vars.direction === 'vertical' ? 'height' : 'width'; this.vars.height = window.innerHeight; this.vars.width = window.innerWidth; if (!this["extends"]) { var bounding = this.dom.section.getBoundingClientRect(); this.vars.bounding = this.vars.direction === 'vertical' ? bounding.height - (this.vars["native"] ? 0 : this.vars.height) : bounding.right - (this.vars["native"] ? 0 : this.vars.width); } if (!this.vars["native"] && !this.options.noscrollbar) { this.dom.scrollbar.drag.height = this.vars.height * (this.vars.height / (this.vars.bounding + this.vars.height)); this.dom.scrollbar.drag.el.style[prop] = "".concat(this.dom.scrollbar.drag.height, "px"); } else if (this.vars["native"]) { this.dom.scroll.style[prop] = "".concat(this.vars.bounding, "px"); } !this.vars["native"] && this.clampTarget(); } }, { key: "clampTarget", value: function clampTarget() { this.vars.target = Math.round(Math.max(0, Math.min(this.vars.target, this.vars.bounding))); } }, { key: "destroy", value: function destroy() { if (this.vars["native"]) { _domClasses["default"].remove(this.dom.listener, 'is-native-scroll'); this.removeFakeScrollHeight(); } else { _domClasses["default"].remove(this.dom.listener, 'is-virtual-scroll'); !this.options.noscrollbar && this.removeFakeScrollBar(); } this.vars.direction === 'vertical' ? _domClasses["default"].remove(this.dom.listener, 'y-scroll') : _domClasses["default"].remove(this.dom.listener, 'x-scroll'); this.vars.current = 0; this.vs && (this.vs.destroy(), this.vs = null); this.removeEvents(); } }]); return Smooth; }(); exports["default"] = Smooth; window.Smooth = Smooth; },{"dom-classes":5,"dom-create-element":6,"dom-events":7,"prefix":11,"virtual-scroll":17}],4:[function(require,module,exports){ 'use strict'; var toString = Object.prototype.toString, hasOwnProperty = Object.prototype.hasOwnProperty; module.exports = function(object) { if(!object) return console.warn('bindAll requires at least one argument.'); var functions = Array.prototype.slice.call(arguments, 1); if (functions.length === 0) { for (var method in object) { if(hasOwnProperty.call(object, method)) { if(typeof object[method] == 'function' && toString.call(object[method]) == "[object Function]") { functions.push(method); } } } } for(var i = 0; i < functions.length; i++) { var f = functions[i]; object[f] = bind(object[f], object); } }; /* Faster bind without specific-case checking. (see https://coderwall.com/p/oi3j3w). bindAll is only needed for events binding so no need to make slow fixes for constructor or partial application. */ function bind(func, context) { return function() { return func.apply(context, arguments); }; } },{}],5:[function(require,module,exports){ /** * Module dependencies. */ var index = require('indexof'); /** * Whitespace regexp. */ var whitespaceRe = /\s+/; /** * toString reference. */ var toString = Object.prototype.toString; module.exports = classes; module.exports.add = add; module.exports.contains = has; module.exports.has = has; module.exports.toggle = toggle; module.exports.remove = remove; module.exports.removeMatching = removeMatching; function classes (el) { if (el.classList) { return el.classList; } var str = el.className.replace(/^\s+|\s+$/g, ''); var arr = str.split(whitespaceRe); if ('' === arr[0]) arr.shift(); return arr; } function add (el, name) { // classList if (el.classList) { el.classList.add(name); return; } // fallback var arr = classes(el); var i = index(arr, name); if (!~i) arr.push(name); el.className = arr.join(' '); } function has (el, name) { return el.classList ? el.classList.contains(name) : !! ~index(classes(el), name); } function remove (el, name) { if ('[object RegExp]' == toString.call(name)) { return removeMatching(el, name); } // classList if (el.classList) { el.classList.remove(name); return; } // fallback var arr = classes(el); var i = index(arr, name); if (~i) arr.splice(i, 1); el.className = arr.join(' '); } function removeMatching (el, re, ref) { var arr = Array.prototype.slice.call(classes(el)); for (var i = 0; i < arr.length; i++) { if (re.test(arr[i])) { remove(el, arr[i]); } } } function toggle (el, name) { // classList if (el.classList) { return el.classList.toggle(name); } // fallback if (has(el, name)) { remove(el, name); } else { add(el, name); } } },{"indexof":8}],6:[function(require,module,exports){ /* `dom-create-element` var create = require('dom-create-element'); var el = create({ selector: 'div', styles: 'preloader', html: '<span>Text</span>' }); */ module.exports = create; function create(opt) { opt = opt || {}; var el = document.createElement(opt.selector); if(opt.attr) for(var index in opt.attr) opt.attr.hasOwnProperty(index) && el.setAttribute(index, opt.attr[index]); "a" == opt.selector && opt.link && ( el.href = opt.link, opt.target && el.setAttribute("target", opt.target) ); "img" == opt.selector && opt.src && ( el.src = opt.src, opt.lazyload && ( el.style.opacity = 0, el.onload = function(){ el.style.opacity = 1; } ) ); opt.id && (el.id = opt.id); opt.styles && (el.className = opt.styles); opt.html && (el.innerHTML = opt.html); opt.children && (el.appendChild(opt.children)); return el; }; },{}],7:[function(require,module,exports){ var synth = require('synthetic-dom-events'); var on = function(element, name, fn, capture) { return element.addEventListener(name, fn, capture || false); }; var off = function(element, name, fn, capture) { return element.removeEventListener(name, fn, capture || false); }; var once = function (element, name, fn, capture) { function tmp (ev) { off(element, name, tmp, capture); fn(ev); } on(element, name, tmp, capture); }; var emit = function(element, name, opt) { var ev = synth(name, opt); element.dispatchEvent(ev); }; if (!document.addEventListener) { on = function(element, name, fn) { return element.attachEvent('on' + name, fn); }; } if (!document.removeEventListener) { off = function(element, name, fn) { return element.detachEvent('on' + name, fn); }; } if (!document.dispatchEvent) { emit = function(element, name, opt) { var ev = synth(name, opt); return element.fireEvent('on' + ev.type, ev); }; } module.exports = { on: on, off: off, once: once, emit: emit }; },{"synthetic-dom-events":12}],8:[function(require,module,exports){ var indexOf = [].indexOf; module.exports = function(arr, obj){ if (indexOf) return arr.indexOf(obj); for (var i = 0; i < arr.length; ++i) { if (arr[i] === obj) return i; } return -1; }; },{}],9:[function(require,module,exports){ // Generated by CoffeeScript 1.9.2 (function() { var root; root = typeof exports !== "undefined" && exports !== null ? exports : this; root.Lethargy = (function() { function Lethargy(stability, sensitivity, tolerance, delay) { this.stability = stability != null ? Math.abs(stability) : 8; this.sensitivity = sensitivity != null ? 1 + Math.abs(sensitivity) : 100; this.tolerance = tolerance != null ? 1 + Math.abs(tolerance) : 1.1; this.delay = delay != null ? delay : 150; this.lastUpDeltas = (function() { var i, ref, results; results = []; for (i = 1, ref = this.stability * 2; 1 <= ref ? i <= ref : i >= ref; 1 <= ref ? i++ : i--) { results.push(null); } return results; }).call(this); this.lastDownDeltas = (function() { var i, ref, results; results = []; for (i = 1, ref = this.stability * 2; 1 <= ref ? i <= ref : i >= ref; 1 <= ref ? i++ : i--) { results.push(null); } return results; }).call(this); this.deltasTimestamp = (function() { var i, ref, results; results = []; for (i = 1, ref = this.stability * 2; 1 <= ref ? i <= ref : i >= ref; 1 <= ref ? i++ : i--) { results.push(null); } return results; }).call(this); } Lethargy.prototype.check = function(e) { var lastDelta; e = e.originalEvent || e; if (e.wheelDelta != null) { lastDelta = e.wheelDelta; } else if (e.deltaY != null) { lastDelta = e.deltaY * -40; } else if ((e.detail != null) || e.detail === 0) { lastDelta = e.detail * -40; } this.deltasTimestamp.push(Date.now()); this.deltasTimestamp.shift(); if (lastDelta > 0) { this.lastUpDeltas.push(lastDelta); this.lastUpDeltas.shift(); return this.isInertia(1); } else { this.lastDownDeltas.push(lastDelta); this.lastDownDeltas.shift(); return this.isInertia(-1); } return false; }; Lethargy.prototype.isInertia = function(direction) { var lastDeltas, lastDeltasNew, lastDeltasOld, newAverage, newSum, oldAverage, oldSum; lastDeltas = direction === -1 ? this.lastDownDeltas : this.lastUpDeltas; if (lastDeltas[0] === null) { return direction; } if (this.deltasTimestamp[(this.stability * 2) - 2] + this.delay > Date.now() && lastDeltas[0] === lastDeltas[(this.stability * 2) - 1]) { return false; } lastDeltasOld = lastDeltas.slice(0, this.stability); lastDeltasNew = lastDeltas.slice(this.stability, this.stability * 2); oldSum = lastDeltasOld.reduce(function(t, s) { return t + s; }); newSum = lastDeltasNew.reduce(function(t, s) { return t + s; }); oldAverage = oldSum / lastDeltasOld.length; newAverage = newSum / lastDeltasNew.length; if (Math.abs(oldAverage) < Math.abs(newAverage * this.tolerance) && (this.sensitivity < Math.abs(newAverage))) { return direction; } else { return false; } }; Lethargy.prototype.showLastUpDeltas = function() { return this.lastUpDeltas; }; Lethargy.prototype.showLastDownDeltas = function() { return this.lastDownDeltas; }; return Lethargy; })(); }).call(this); },{}],10:[function(require,module,exports){ /* object-assign (c) Sindre Sorhus @license MIT */ 'use strict'; /* eslint-disable no-unused-vars */ var getOwnPropertySymbols = Object.getOwnPropertySymbols; var hasOwnProperty = Object.prototype.hasOwnProperty; var propIsEnumerable = Object.prototype.propertyIsEnumerable; function toObject(val) { if (val === null || val === undefined) { throw new TypeError('Object.assign cannot be called with null or undefined'); } return Object(val); } function shouldUseNative() { try { if (!Object.assign) { return false; } // Detect buggy property enumeration order in older V8 versions. // https://bugs.chromium.org/p/v8/issues/detail?id=4118 var test1 = new String('abc'); // eslint-disable-line no-new-wrappers test1[5] = 'de'; if (Object.getOwnPropertyNames(test1)[0] === '5') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test2 = {}; for (var i = 0; i < 10; i++) { test2['_' + String.fromCharCode(i)] = i; } var order2 = Object.getOwnPropertyNames(test2).map(function (n) { return test2[n]; }); if (order2.join('') !== '0123456789') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test3 = {}; 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { test3[letter] = letter; }); if (Object.keys(Object.assign({}, test3)).join('') !== 'abcdefghijklmnopqrst') { return false; } return true; } catch (err) { // We don't expect any of the above to throw, but better to be safe. return false; } } module.exports = shouldUseNative() ? Object.assign : function (target, source) { var from; var to = toObject(target); var symbols; for (var s = 1; s < arguments.length; s++) { from = Object(arguments[s]); for (var key in from) { if (hasOwnProperty.call(from, key)) { to[key] = from[key]; } } if (getOwnPropertySymbols) { symbols = getOwnPropertySymbols(from); for (var i = 0; i < symbols.length; i++) { if (propIsEnumerable.call(from, symbols[i])) { to[symbols[i]] = from[symbols[i]]; } } } } return to; }; },{}],11:[function(require,module,exports){ // check document first so it doesn't error in node.js var style = typeof document != 'undefined' ? document.createElement('p').style : {} var prefixes = ['O', 'ms', 'Moz', 'Webkit'] var upper = /([A-Z])/g var memo = {} /** * prefix `key` * * prefix('transform') // => WebkitTransform * * @param {String} key * @return {String} * @api public */ function prefix(key){ // Camel case key = key.replace(/-([a-z])/g, function(_, char){ return char.toUpperCase() }) // Without prefix if (style[key] !== undefined) return key // With prefix var Key = key.charAt(0).toUpperCase() + key.slice(1) var i = prefixes.length while (i--) { var name = prefixes[i] + Key if (style[name] !== undefined) return name } return key } /** * Memoized version of `prefix` * * @param {String} key * @return {String} * @api public */ function prefixMemozied(key){ return key in memo ? memo[key] : memo[key] = prefix(key) } /** * Create a dashed prefix * * @param {String} key * @return {String} * @api public */ function prefixDashed(key){ key = prefix(key) if (upper.test(key)) { key = '-' + key.replace(upper, '-$1') upper.lastIndex = 0 } return key.toLowerCase() } module.exports = prefixMemozied module.exports.dash = prefixDashed },{}],12:[function(require,module,exports){ // for compression var win = window; var doc = document || {}; var root = doc.documentElement || {}; // detect if we need to use firefox KeyEvents vs KeyboardEvents var use_key_event = true; try { doc.createEvent('KeyEvents'); } catch (err) { use_key_event = false; } // Workaround for https://bugs.webkit.org/show_bug.cgi?id=16735 function check_kb(ev, opts) { if (ev.ctrlKey != (opts.ctrlKey || false) || ev.altKey != (opts.altKey || false) || ev.shiftKey != (opts.shiftKey || false) || ev.metaKey != (opts.metaKey || false) || ev.keyCode != (opts.keyCode || 0) || ev.charCode != (opts.charCode || 0)) { ev = document.createEvent('Event'); ev.initEvent(opts.type, opts.bubbles, opts.cancelable); ev.ctrlKey = opts.ctrlKey || false; ev.altKey = opts.altKey || false; ev.shiftKey = opts.shiftKey || false; ev.metaKey = opts.metaKey || false; ev.keyCode = opts.keyCode || 0; ev.charCode = opts.charCode || 0; } return ev; } // modern browsers, do a proper dispatchEvent() var modern = function(type, opts) { opts = opts || {}; // which init fn do we use var family = typeOf(type); var init_fam = family; if (family === 'KeyboardEvent' && use_key_event) { family = 'KeyEvents'; init_fam = 'KeyEvent'; } var ev = doc.createEvent(family); var init_fn = 'init' + init_fam; var init = typeof ev[init_fn] === 'function' ? init_fn : 'initEvent'; var sig = initSignatures[init]; var args = []; var used = {}; opts.type = type; for (var i = 0; i < sig.length; ++i) { var key = sig[i]; var val = opts[key]; // if no user specified value, then use event default if (val === undefined) { val = ev[key]; } used[key] = true; args.push(val); } ev[init].apply(ev, args); // webkit key event issue workaround if (family === 'KeyboardEvent') { ev = check_kb(ev, opts); } // attach remaining unused options to the object for (var key in opts) { if (!used[key]) { ev[key] = opts[key]; } } return ev; }; var legacy = function (type, opts) { opts = opts || {}; var ev = doc.createEventObject(); ev.type = type; for (var key in opts) { if (opts[key] !== undefined) { ev[key] = opts[key]; } } return ev; }; // expose either the modern version of event generation or legacy // depending on what we support // avoids if statements in the code later module.exports = doc.createEvent ? modern : legacy; var initSignatures = require('./init.json'); var types = require('./types.json'); var typeOf = (function () { var typs = {}; for (var key in types) { var ts = types[key]; for (var i = 0; i < ts.length; i++) { typs[ts[i]] = key; } } return function (name) { return typs[name] || 'Event'; }; })(); },{"./init.json":13,"./types.json":14}],13:[function(require,module,exports){ module.exports={ "initEvent" : [ "type", "bubbles", "cancelable" ], "initUIEvent" : [ "type", "bubbles", "cancelable", "view", "detail" ], "initMouseEvent" : [ "type", "bubbles", "cancelable", "view", "detail", "screenX", "screenY", "clientX", "clientY", "ctrlKey", "altKey", "shiftKey", "metaKey", "button", "relatedTarget" ], "initMutationEvent" : [ "type", "bubbles", "cancelable", "relatedNode", "prevValue", "newValue", "attrName", "attrChange" ], "initKeyboardEvent" : [ "type", "bubbles", "cancelable", "view", "ctrlKey", "altKey", "shiftKey", "metaKey", "keyCode", "charCode" ], "initKeyEvent" : [ "type", "bubbles", "cancelable", "view", "ctrlKey", "altKey", "shiftKey", "metaKey", "keyCode", "charCode" ] } },{}],14:[function(require,module,exports){ module.exports={ "MouseEvent" : [ "click", "mousedown", "mouseup", "mouseover", "mousemove", "mouseout" ], "KeyboardEvent" : [ "keydown", "keyup", "keypress" ], "MutationEvent" : [ "DOMSubtreeModified", "DOMNodeInserted", "DOMNodeRemoved", "DOMNodeRemovedFromDocument", "DOMNodeInsertedIntoDocument", "DOMAttrModified", "DOMCharacterDataModified" ], "HTMLEvents" : [ "load", "unload", "abort", "error", "select", "change", "submit", "reset", "focus", "blur", "resize", "scroll" ], "UIEvent" : [ "DOMFocusIn", "DOMFocusOut", "DOMActivate" ] } },{}],15:[function(require,module,exports){ function E () { // Keep this empty so it's easier to inherit from // (via https://github.com/lipsmack from https://github.com/scottcorgan/tiny-emitter/issues/3) } E.prototype = { on: function (name, callback, ctx) { var e = this.e || (this.e = {}); (e[name] || (e[name] = [])).push({ fn: callback, ctx: ctx }); return this; }, once: function (name, callback, ctx) { var self = this; function listener () { self.off(name, listener); callback.apply(ctx, arguments); }; listener._ = callback return this.on(name, listener, ctx); }, emit: function (name) { var data = [].slice.call(arguments, 1); var evtArr = ((this.e || (this.e = {}))[name] || []).slice(); var i = 0; var len = evtArr.length; for (i; i < len; i++) { evtArr[i].fn.apply(evtArr[i].ctx, data); } return this; }, off: function (name, callback) { var e = this.e || (this.e = {}); var evts = e[name]; var liveEvents = []; if (evts && callback) { for (var i = 0, len = evts.length; i < len; i++) { if (evts[i].fn !== callback && evts[i].fn._ !== callback) liveEvents.push(evts[i]); } } // Remove event from queue to prevent memory leak // Suggested by https://github.com/lazd // Ref: https://github.com/scottcorgan/tiny-emitter/commit/c6ebfaa9bc973b33d110a84a307742b7cf94c953#commitcomment-5024910 (liveEvents.length) ? e[name] = liveEvents : delete e[name]; return this; } }; module.exports = E; },{}],16:[function(require,module,exports){ 'use strict'; module.exports = function(source) { return JSON.parse(JSON.stringify(source)); }; },{}],17:[function(require,module,exports){ 'use strict'; var objectAssign = require('object-assign'); var Emitter = require('tiny-emitter'); var Lethargy = require('lethargy').Lethargy; var support = require('./support'); var clone = require('./clone'); var bindAll = require('bindall-standalone'); var EVT_ID = 'virtualscroll'; module.exports = VirtualScroll; var keyCodes = { LEFT: 37, UP: 38, RIGHT: 39, DOWN: 40, SPACE: 32 }; function VirtualScroll(options) { bindAll(this, '_onWheel', '_onMouseWheel', '_onTouchStart', '_onTouchMove', '_onKeyDown'); this.el = window; if (options && options.el) { this.el = options.el; delete options.el; } this.options = objectAssign({ mouseMultiplier: 1, touchMultiplier: 2, firefoxMultiplier: 15, keyStep: 120, preventTouch: false, unpreventTouchClass: 'vs-touchmove-allowed', limitInertia: false }, options); if (this.options.limitInertia) this._lethargy = new Lethargy(); this._emitter = new Emitter(); this._event = { y: 0, x: 0, deltaX: 0, deltaY: 0 }; this.touchStartX = null; this.touchStartY = null; this.bodyTouchAction = null; if (this.options.passive !== undefined) { this.listenerOptions = {passive: this.options.passive}; } } VirtualScroll.prototype._notify = function(e) { var evt = this._event; evt.x += evt.deltaX; evt.y += evt.deltaY; this._emitter.emit(EVT_ID, { x: evt.x, y: evt.y, deltaX: evt.deltaX, deltaY: evt.deltaY, originalEvent: e }); }; VirtualScroll.prototype._onWheel = function(e) { var options = this.options; if (this._lethargy && this._lethargy.check(e) === false) return; var evt = this._event; // In Chrome and in Firefox (at least the new one) evt.deltaX = e.wheelDeltaX || e.deltaX * -1; evt.deltaY = e.wheelDeltaY || e.deltaY * -1; // for our purpose deltamode = 1 means user is on a wheel mouse, not touch pad // real meaning: https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent#Delta_modes if(support.isFirefox && e.deltaMode == 1) { evt.deltaX *= options.firefoxMultiplier; evt.deltaY *= options.firefoxMultiplier; } evt.deltaX *= options.mouseMultiplier; evt.deltaY *= options.mouseMultiplier; this._notify(e); }; VirtualScroll.prototype._onMouseWheel = function(e) { if (this.options.limitInertia && this._lethargy.check(e) === false) return; var evt = this._event; // In Safari, IE and in Chrome if 'wheel' isn't defined evt.deltaX = (e.wheelDeltaX) ? e.wheelDeltaX : 0; evt.deltaY = (e.wheelDeltaY) ? e.wheelDeltaY : e.wheelDelta; this._notify(e); }; VirtualScroll.prototype._onTouchStart = function(e) { var t = (e.targetTouches) ? e.targetTouches[0] : e; this.touchStartX = t.pageX; this.touchStartY = t.pageY; }; VirtualScroll.prototype._onTouchMove = function(e) { var options = this.options; if(options.preventTouch && !e.target.classList.contains(options.unpreventTouchClass)) { e.preventDefault(); } var evt = this._event; var t = (e.targetTouches) ? e.targetTouches[0] : e; evt.deltaX = (t.pageX - this.touchStartX) * options.touchMultiplier; evt.deltaY = (t.pageY - this.touchStartY) * options.touchMultiplier; this.touchStartX = t.pageX; this.touchStartY = t.pageY; this._notify(e); }; VirtualScroll.prototype._onKeyDown = function(e) { var evt = this._event; evt.deltaX = evt.deltaY = 0; var windowHeight = window.innerHeight - 40 switch(e.keyCode) { case keyCodes.LEFT: case keyCodes.UP: evt.deltaY = this.options.keyStep; break; case keyCodes.RIGHT: case keyCodes.DOWN: evt.deltaY = - this.options.keyStep; break; case keyCodes.SPACE && e.shiftKey: evt.deltaY = windowHeight; break; case keyCodes.SPACE: evt.deltaY = - windowHeight; break; default: return; } this._notify(e); }; VirtualScroll.prototype._bind = function() { if(support.hasWheelEvent) this.el.addEventListener('wheel', this._onWheel, this.listenerOptions); if(support.hasMouseWheelEvent) this.el.addEventListener('mousewheel', this._onMouseWheel, this.listenerOptions); if(support.hasTouch) { this.el.addEventListener('touchstart', this._onTouchStart, this.listenerOptions); this.el.addEventListener('touchmove', this._onTouchMove, this.listenerOptions); } if(support.hasPointer && support.hasTouchWin) { this.bodyTouchAction = document.body.style.msTouchAction; document.body.style.msTouchAction = 'none'; this.el.addEventListener('MSPointerDown', this._onTouchStart, true); this.el.addEventListener('MSPointerMove', this._onTouchMove, true); } if(support.hasKeyDown) document.addEventListener('keydown', this._onKeyDown); }; VirtualScroll.prototype._unbind = function() { if(support.hasWheelEvent) this.el.removeEventListener('wheel', this._onWheel); if(support.hasMouseWheelEvent) this.el.removeEventListener('mousewheel', this._onMouseWheel); if(support.hasTouch) { this.el.removeEventListener('touchstart', this._onTouchStart); this.el.removeEventListener('touchmove', this._onTouchMove); } if(support.hasPointer && support.hasTouchWin) { document.body.style.msTouchAction = this.bodyTouchAction; this.el.removeEventListener('MSPointerDown', this._onTouchStart, true); this.el.removeEventListener('MSPointerMove', this._onTouchMove, true); } if(support.hasKeyDown) document.removeEventListener('keydown', this._onKeyDown); }; VirtualScroll.prototype.on = function(cb, ctx) { this._emitter.on(EVT_ID, cb, ctx); var events = this._emitter.e; if (events && events[EVT_ID] && events[EVT_ID].length === 1) this._bind(); }; VirtualScroll.prototype.off = function(cb, ctx) { this._emitter.off(EVT_ID, cb, ctx); var events = this._emitter.e; if (!events[EVT_ID] || events[EVT_ID].length <= 0) this._unbind(); }; VirtualScroll.prototype.reset = function() { var evt = this._event; evt.x = 0; evt.y = 0; }; VirtualScroll.prototype.destroy = function() { this._emitter.off(); this._unbind(); }; },{"./clone":16,"./support":18,"bindall-standalone":4,"lethargy":9,"object-assign":10,"tiny-emitter":15}],18:[function(require,module,exports){ 'use strict'; module.exports = (function getSupport() { return { hasWheelEvent: 'onwheel' in document, hasMouseWheelEvent: 'onmousewheel' in document, hasTouch: 'ontouchstart' in document, hasTouchWin: navigator.msMaxTouchPoints && navigator.msMaxTouchPoints > 1, hasPointer: !!window.navigator.msPointerEnabled, hasKeyDown: 'onkeydown' in document, isFirefox: navigator.userAgent.indexOf('Firefox') > -1 }; })(); },{}]},{},[2]);
baptistebriel/smooth-scrolling
demos/performances/build.js
JavaScript
mit
45,174