code
stringlengths
2
1.05M
/** * Holds all the data necessary to show an OpenDialog, which includes a list of local files and the cloud account the * user is signed into (if any}. A list of cloud files is downloaded later. * @param {string} jsonString - String representation of object containing the above information * @constructor */ function FileList(jsonString) { const object = JSON.parse(jsonString); this.localFiles = FileList.getSortedList(object.files); //this.localFiles = object.files; //if (this.localFiles == null) { // this.localFiles = [] //} this.signedIn = object.signedIn === true; if (!GuiElements.isAndroid) { // We only show this information on Android this.signedIn = false; } this.account = object.account; if (this.account == null || !this.signedIn) { this.account = null; } } /** * Gets the string to show in the Cloud tab. Only relevant on Android. * @return {string} */ FileList.prototype.getCloudTitle = function(){ if (this.account != null) { return this.account; } return Language.getStr("Cloud"); }; /** * Sort file names for display */ FileList.getSortedList = function(list){ var unsortedList = list; if (unsortedList == null) { unsortedList = []; } return unsortedList.sort(function(a, b) { //Sort case insensitive. //TODO: make this specific to language setting - must use correct language codes. return a.localeCompare(b, 'en', {'sensitivity': 'base', 'numeric' : 'true'}); }); }
/* * Universal markup editor for Jeditable * * Copyright (c) 2008 Mika Tuupola * * Licensed under the MIT license: * http://www.opensource.org/licenses/mit-license.php * * Depends on markItUp! jQuery plugin by Jay Salvat: * http://markitup.jaysalvat.com/ * * Project home: * http://www.appelsiini.net/projects/jeditable * * Revision: $Id: jquery.jeditable.markitup.js 350 2008-04-08 07:02:29Z tuupola $ * */ $.editable.addInputType('markitup', { element : $.editable.types.textarea.element, plugin : function(settings, original) { $('textarea', this).markItUp(settings.markitup); } });
import * as ActionTypes from '../constants'; import initialState from '../../initialState'; import _ from 'lodash'; const compilationPages = (state = initialState.compilationPages, action) => { switch (action.type) { case ActionTypes.SET_COMPILATION_PAGES : { return action.pages; } case ActionTypes.REMOVE_COMPILATION_PAGE : { const pageIndex = _.findIndex(state, { _id: action.page._id }); if (pageIndex > -1) { return [ ...state.slice(0, pageIndex), ...state.slice(pageIndex + 1), ]; } return state; } case ActionTypes.SET_PROPERTY_FOR_COMPILATION_PAGE : { const propPageIndex = _.findIndex(state, { _id: action.page._id }); if (propPageIndex > -1) { const email = Object.assign({}, state[propPageIndex]); email[action.prop] = action.val; return [ ...state.slice(0, propPageIndex), email, ...state.slice(propPageIndex + 1), ]; } return state; } case ActionTypes.UPDATE_PAGE_IN_COMPILATION_PAGES : { const updatedPageIndex = _.findIndex(state, { _id: action.page._id }); if (updatedPageIndex > -1) { return [ ...state.slice(0, updatedPageIndex), action.page, ...state.slice(updatedPageIndex + 1), ]; } return state; } case ActionTypes.UPDATE_PAGE_PDFS : { return _.map(state, (page) => { const updatedPage = _.find(action.pages, ['_id', page._id]); if (updatedPage) { const pageCopy = Object.assign({}, page); pageCopy.pdf = updatedPage.pdf; return pageCopy; } return page; }); } default: { return state; } } }; export default compilationPages;
import path from 'path'; import cp from 'child_process'; import replace from 'replace'; // TODO: this could probably be better... const branchName = cp.execSync('git rev-parse --abbrev-ref HEAD', { encoding: 'utf8' }) .match(/.+/g)[0]; // Find all occurrences of PROJECT_NAME in ~/src and replace them with // the branch name in proper case. replace({ regex: 'PROJECT_NAME', replacement: branchName .match(/\w+/g) .map((word) => word[0].toUpperCase() + word.slice(1)) .join(' '), paths: [ path.resolve(__dirname, '..', 'src') ], recursive: true, silent: false }); // For package.json replace({ regex: 'PROJECT_DASHED_NAME', replacement: branchName, paths: [ path.resolve(__dirname, '..', 'package.json') ], recursive: false, silent: false });
'use strict'; var gulp = require('gulp'); var jshint = require('gulp-jshint'); var mocha = require('gulp-mocha'); gulp.task('jshint', function() { return gulp.src(['./lib/*.js', './test/*.js']) .pipe(jshint('.jshint')) .pipe(jshint.reporter('jshint-stylish')); }); gulp.task('mocha', function () { return gulp.src('test/*.js', {read: false}) // gulp-mocha needs filepaths so you can't have any plugins before it .pipe(mocha({reporter: 'nyan'})) .once('error', function (err) { console.error(err.stack); process.exit(1); }) .once('end', function () { process.exit(); }); });
const path = require('path'); const { runTests, downloadAndUnzipVSCode } = require('vscode-test'); async function main() { try { // The folder containing the Extension Manifest package.json // Passed to `--extensionDevelopmentPath` const extensionDevelopmentPath = path.resolve(__dirname, '../'); const testWorkspace = path.resolve(__dirname, './suite/fixture'); // The path to the extension test script // Passed to --extensionTestsPath const extensionTestsPath = path.resolve(__dirname, './suite/index'); // Version const version = '1.42.0'; // Manually download version const vscodeExecutablePath = await downloadAndUnzipVSCode(version); // Download VS Code, unzip it and run the integration test await runTests({ vscodeExecutablePath, extensionDevelopmentPath, extensionTestsPath, launchArgs: [ testWorkspace, // This disables all extensions except the one being testing '--disable-extensions' ] }); } catch (err) { console.error('Failed to run tests'); process.exit(1); } } main();
var mongo = require('mongoskin') , Device = require("./models/device") , _ = require("underscore"); var PersistenceManager = function(server){ this.server = server; this.config = server.config; this.uri = this.config.get("mongo.uri"); } module.exports = PersistenceManager; PersistenceManager.prototype.start = function(){ this.db = mongo.db(this.uri); this.devices = this.db.collection("devices"); this.devices.ensureIndex([['id',1]], true, function (err, replies) {}); } PersistenceManager.prototype.findOrCreateDevice = function(manager, deviceData, callback){ var self = this; var opts = { new:true, upsert:true }; this.devices.findAndModify({id:deviceData.id},[],deviceData,opts, function(err,doc){ var device = null; if (!err) device = new Device(manager,doc); callback(err, device); }); } PersistenceManager.prototype.findDevice = function(manager, deviceId, callback){ var self = this; this.devices.findOne({id:deviceId},function(err,doc){ var device = null; if(!err && doc) device = new Device(manager, doc); callback(err,device); }); }
/* eslint-env jest */ import _ from 'lodash' import { expect } from 'chai' import { Graph } from 'graphlibrary' import dagre from '../index' const { layout } = dagre describe('layout', function () { let g beforeEach(function () { g = new Graph({ multigraph: true, compound: true }) .setGraph({}) .setDefaultEdgeLabel(function () { return {} }) }) it('can layout a single node', function () { g.setNode('a', { width: 50, height: 100 }) layout(g) expect(extractCoordinates(g)).to.eql({ a: { x: 50 / 2, y: 100 / 2 } }) expect(g.node('a').x).to.equal(50 / 2) expect(g.node('a').y).to.equal(100 / 2) }) it('can layout two nodes on the same rank', function () { g.graph().nodesep = 200 g.setNode('a', { width: 50, height: 100 }) g.setNode('b', { width: 75, height: 200 }) layout(g) expect(extractCoordinates(g)).to.eql({ a: { x: 50 / 2, y: 200 / 2 }, b: { x: 50 + 200 + 75 / 2, y: 200 / 2 } }) }) it('can layout two nodes connected by an edge', function () { g.graph().ranksep = 300 g.setNode('a', { width: 50, height: 100 }) g.setNode('b', { width: 75, height: 200 }) g.setEdge('a', 'b') layout(g) expect(extractCoordinates(g)).to.eql({ a: { x: 75 / 2, y: 100 / 2 }, b: { x: 75 / 2, y: 100 + 300 + 200 / 2 } }) // We should not get x, y coordinates if the edge has no label expect(g.edge('a', 'b')).to.not.have.property('x') expect(g.edge('a', 'b')).to.not.have.property('y') }) it('can layout an edge with a label', function () { g.graph().ranksep = 300 g.setNode('a', { width: 50, height: 100 }) g.setNode('b', { width: 75, height: 200 }) g.setEdge('a', 'b', { width: 60, height: 70, labelpos: 'c' }) layout(g) expect(extractCoordinates(g)).to.eql({ a: { x: 75 / 2, y: 100 / 2 }, b: { x: 75 / 2, y: 100 + 150 + 70 + 150 + 200 / 2 } }) expect(_.pick(g.edge('a', 'b'), ['x', 'y'])) .eqls({ x: 75 / 2, y: 100 + 150 + 70 / 2 }) }) describe('can layout an edge with a long label, with rankdir =', function () { _.forEach(['TB', 'BT', 'LR', 'RL'], function (rankdir) { it(rankdir, function () { g.graph().nodesep = g.graph().edgesep = 10 g.graph().rankdir = rankdir _.forEach(['a', 'b', 'c', 'd'], function (v) { g.setNode(v, { width: 10, height: 10 }) }) g.setEdge('a', 'c', { width: 2000, height: 10, labelpos: 'c' }) g.setEdge('b', 'd', { width: 1, height: 1 }) layout(g) let p1 let p2 if (rankdir === 'TB' || rankdir === 'BT') { p1 = g.edge('a', 'c') p2 = g.edge('b', 'd') } else { p1 = g.node('a') p2 = g.node('c') } expect(Math.abs(p1.x - p2.x)).gt(1000) }) }) }) describe('can apply an offset, with rankdir =', function () { _.forEach(['TB', 'BT', 'LR', 'RL'], function (rankdir) { it(rankdir, function () { g.graph().nodesep = g.graph().edgesep = 10 g.graph().rankdir = rankdir _.forEach(['a', 'b', 'c', 'd'], function (v) { g.setNode(v, { width: 10, height: 10 }) }) g.setEdge('a', 'b', { width: 10, height: 10, labelpos: 'l', labeloffset: 1000 }) g.setEdge('c', 'd', { width: 10, height: 10, labelpos: 'r', labeloffset: 1000 }) layout(g) if (rankdir === 'TB' || rankdir === 'BT') { expect(g.edge('a', 'b').x - g.edge('a', 'b').points[0].x).equals(-1000 - 10 / 2) expect(g.edge('c', 'd').x - g.edge('c', 'd').points[0].x).equals(1000 + 10 / 2) } else { expect(g.edge('a', 'b').y - g.edge('a', 'b').points[0].y).equals(-1000 - 10 / 2) expect(g.edge('c', 'd').y - g.edge('c', 'd').points[0].y).equals(1000 + 10 / 2) } }) }) }) it('can layout a long edge with a label', function () { g.graph().ranksep = 300 g.setNode('a', { width: 50, height: 100 }) g.setNode('b', { width: 75, height: 200 }) g.setEdge('a', 'b', { width: 60, height: 70, minlen: 2, labelpos: 'c' }) layout(g) expect(g.edge('a', 'b').x).to.equal(75 / 2) expect(g.edge('a', 'b').y) .to.be.gt(g.node('a').y) .to.be.lt(g.node('b').y) }) it('can layout out a short cycle', function () { g.graph().ranksep = 200 g.setNode('a', { width: 100, height: 100 }) g.setNode('b', { width: 100, height: 100 }) g.setEdge('a', 'b', { weight: 2 }) g.setEdge('b', 'a') layout(g) expect(extractCoordinates(g)).to.eql({ a: { x: 100 / 2, y: 100 / 2 }, b: { x: 100 / 2, y: 100 + 200 + 100 / 2 } }) // One arrow should point down, one up expect(g.edge('a', 'b').points[1].y).gt(g.edge('a', 'b').points[0].y) expect(g.edge('b', 'a').points[0].y).gt(g.edge('b', 'a').points[1].y) }) it('adds rectangle intersects for edges', function () { g.graph().ranksep = 200 g.setNode('a', { width: 100, height: 100 }) g.setNode('b', { width: 100, height: 100 }) g.setEdge('a', 'b') layout(g) const points = g.edge('a', 'b').points expect(points).to.have.length(3) expect(points).eqls([ { x: 100 / 2, y: 100 }, // intersect with bottom of a { x: 100 / 2, y: 100 + 200 / 2 }, // point for edge label { x: 100 / 2, y: 100 + 200 } // intersect with top of b ]) }) it('adds rectangle intersects for edges spanning multiple ranks', function () { g.graph().ranksep = 200 g.setNode('a', { width: 100, height: 100 }) g.setNode('b', { width: 100, height: 100 }) g.setEdge('a', 'b', { minlen: 2 }) layout(g) const points = g.edge('a', 'b').points expect(points).to.have.length(5) expect(points).eqls([ { x: 100 / 2, y: 100 }, // intersect with bottom of a { x: 100 / 2, y: 100 + 200 / 2 }, // bend #1 { x: 100 / 2, y: 100 + 400 / 2 }, // point for edge label { x: 100 / 2, y: 100 + 600 / 2 }, // bend #2 { x: 100 / 2, y: 100 + 800 / 2 } // intersect with top of b ]) }) describe('can layout a self loop', function () { _.forEach(['TB', 'BT', 'LR', 'RL'], function (rankdir) { it('in rankdir = ' + rankdir, function () { g.graph().edgesep = 75 g.graph().rankdir = rankdir g.setNode('a', { width: 100, height: 100 }) g.setEdge('a', 'a', { width: 50, height: 50 }) layout(g) const nodeA = g.node('a') const points = g.edge('a', 'a').points expect(points).to.have.length(7) _.forEach(points, function (point) { if (rankdir !== 'LR' && rankdir !== 'RL') { expect(point.x).gt(nodeA.x) expect(Math.abs(point.y - nodeA.y)).lte(nodeA.height / 2) } else { expect(point.y).gt(nodeA.y) expect(Math.abs(point.x - nodeA.x)).lte(nodeA.width / 2) } }) }) }) }) it('can layout a graph with subgraphs', function () { // To be expanded, this primarily ensures nothing blows up for the moment. g.setNode('a', { width: 50, height: 50 }) g.setParent('a', 'sg1') layout(g) }) it('minimizes the height of subgraphs', function () { _.forEach(['a', 'b', 'c', 'd', 'x', 'y'], function (v) { g.setNode(v, { width: 50, height: 50 }) }) g.setPath(['a', 'b', 'c', 'd']) g.setEdge('a', 'x', { weight: 100 }) g.setEdge('y', 'd', { weight: 100 }) g.setParent('x', 'sg') g.setParent('y', 'sg') // We did not set up an edge (x, y), and we set up high-weight edges from // outside of the subgraph to nodes in the subgraph. This is to try to // force nodes x and y to be on different ranks, which we want our ranker // to avoid. layout(g) expect(g.node('x').y).to.equal(g.node('y').y) }) it('can layout subgraphs with different rankdirs', function () { g.setNode('a', { width: 50, height: 50 }) g.setNode('sg', {}) g.setParent('a', 'sg') function check (rankdir) { expect(g.node('sg').width, 'width ' + rankdir).gt(50) expect(g.node('sg').height, 'height ' + rankdir).gt(50) expect(g.node('sg').x, 'x ' + rankdir).gt(50 / 2) expect(g.node('sg').y, 'y ' + rankdir).gt(50 / 2) } _.forEach(['tb', 'bt', 'lr', 'rl'], function (rankdir) { g.graph().rankdir = rankdir layout(g) check(rankdir) }) }) it('adds dimensions to the graph', function () { g.setNode('a', { width: 100, height: 50 }) layout(g) expect(g.graph().width).equals(100) expect(g.graph().height).equals(50) }) describe('ensures all coordinates are in the bounding box for the graph', function () { _.forEach(['TB', 'BT', 'LR', 'RL'], function (rankdir) { describe(rankdir, function () { beforeEach(function () { g.graph().rankdir = rankdir }) it('node', function () { g.setNode('a', { width: 100, height: 200 }) layout(g) expect(g.node('a').x).equals(100 / 2) expect(g.node('a').y).equals(200 / 2) }) it('edge, labelpos = l', function () { g.setNode('a', { width: 100, height: 100 }) g.setNode('b', { width: 100, height: 100 }) g.setEdge('a', 'b', { width: 1000, height: 2000, labelpos: 'l', labeloffset: 0 }) layout(g) if (rankdir === 'TB' || rankdir === 'BT') { expect(g.edge('a', 'b').x).equals(1000 / 2) } else { expect(g.edge('a', 'b').y).equals(2000 / 2) } }) }) }) }) it('treats attributes with case-insensitivity', function () { g.graph().nodeSep = 200 // note the capital S g.setNode('a', { width: 50, height: 100 }) g.setNode('b', { width: 75, height: 200 }) layout(g) expect(extractCoordinates(g)).to.eql({ a: { x: 50 / 2, y: 200 / 2 }, b: { x: 50 + 200 + 75 / 2, y: 200 / 2 } }) }) }) function extractCoordinates (g) { const nodes = g.nodes() return _.zipObject(nodes, _.map(nodes, function (v) { return _.pick(g.node(v), ['x', 'y']) })) }
$(function() { "use strict"; var $origContent = $(".original-content"), $form = $("form"), $textarea = $form.find("textarea"), $locale = $form.find(".locale"), $preview = $(".preview-content"), $save = $(".btn.save"), $spinner = $("<img src='/img/spinner.gif'>"), $noteSave = $(".saved-note"), $noteUnSave = $(".unsaved-note"), $switcher = $(".locale-switcher"), url = $form.attr("action"), saveContent = $save.html(), speed = 400; function renderPreview (firstRun) { var content = $textarea.val(); $.ajax("/preview", { method: "post", type: "text", data: { content: content }, success: function (data) { $preview.html(data); } }); return false; } function performSave () { var content = $textarea.val(), locale = $locale.val(), showSuccess = false; $.ajax(url, { method: "post", type: "text", data: { content: content, locale: locale }, beforeSend: function () { $save.html( $spinner ); }, success: function () { showSuccess = true; }, complete: function () { // A delay to give the user feedback setTimeout(function() { $save.html( saveContent ); if ( showSuccess ) { $noteSave .fadeIn(speed) .delay(2000) .fadeOut(speed); $noteUnSave.fadeOut(speed); } }, 1000); } }); return false; } function loadContent () { var content = $origContent.text(), lines = content.split("\n"), parts = [], offset = 8; for ( var i = 0, j = lines.length; i < j; i++ ) { var line = lines[ i ], contentTest = line.match(/\S+/); if ( line && line.length && i > 0 ) { line = line.substring(offset, line.length); } if ( i === 0 && line === "" ) { continue;} parts.push(line); } $textarea.val( parts.join("\n") ); renderPreview(true); } function showLocaleMenu () { $switcher.find(".available-locales").show(); } $textarea.on("keyup", function() { renderPreview(); $noteUnSave.fadeIn(speed); }); $form.on("submit", performSave); $switcher.on("click", showLocaleMenu); loadContent(); });
/* vim: set tabstop=4 softtabstop=4 shiftwidth=4 noexpandtab: */ // documentation on writing tests here: http://docs.jquery.com/QUnit // example tests: https://github.com/jquery/qunit/blob/master/test/same.js // more examples: https://github.com/jquery/jquery/tree/master/test/unit // jQueryUI examples: https://github.com/jquery/jquery-ui/tree/master/tests/unit //sessionStorage.clear(); if ( !window.console ) { var names = [ 'log', 'debug', 'info', 'warn', 'error', 'assert', 'dir', 'dirxml', 'group', 'groupEnd', 'time', 'timeEnd', 'count', 'trace', 'profile', 'profileEnd' ]; window.console = {}; for ( var i = 0; i < names.length; ++i ) window.console[ names[i] ] = function() {}; } $(document).ready(function() { window.requests = []; Backbone.ajax = function( request ) { // If a `response` has been defined, execute it. // If status < 299, trigger 'success'; otherwise, trigger 'error' if ( request.response && request.response.status ) { var response = request.response; // Define a `getResponseHeader` function on `response`; used in some tests. // See https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#getResponseHeader%28%29 response.getResponseHeader = function( headerName ) { return response.headers && response.headers[ headerName ] || null; }; // Add the request before triggering callbacks that may get us in here again window.requests.push( request ); /** * Trigger success/error with arguments like jQuery would: * // Success/Error * if ( isSuccess ) { * deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); * } else { * deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); * } */ if ( response.status >= 200 && response.status < 300 || response.status === 304 ) { request.success( response.responseText, 'success', response ); } else { request.error( response, 'error', 'Internal Server Error' ); } } else { window.requests.push( request ); } return request; }; Backbone.Model.prototype.url = function() { // Use the 'resource_uri' if possible var url = this.get( 'resource_uri' ); // Try to have the collection construct a url if ( !url && this.collection ) { url = this.collection.url && _.isFunction( this.collection.url ) ? this.collection.url() : this.collection.url; } // Fallback to 'urlRoot' if ( !url && this.urlRoot ) { url = this.urlRoot + this.id; } if ( !url ) { throw new Error( 'Url could not be determined!' ); } return url; }; /** * 'Zoo' */ window.Zoo = Backbone.RelationalModel.extend({ urlRoot: '/zoo/', relations: [ { type: Backbone.HasMany, key: 'animals', relatedModel: 'Animal', includeInJSON: [ 'id', 'species' ], collectionType: 'AnimalCollection', collectionOptions: function( instance ) { return { 'url': 'zoo/' + instance.cid + '/animal/' } }, reverseRelation: { key: 'livesIn', includeInJSON: [ 'id', 'name' ] } }, { // A simple HasMany without reverse relation type: Backbone.HasMany, key: 'visitors', relatedModel: 'Visitor' } ], toString: function() { return 'Zoo (' + this.id + ')'; } }); window.Animal = Backbone.RelationalModel.extend({ urlRoot: '/animal/', // For validation testing. Wikipedia says elephants are reported up to 12.000 kg. Any more, we must've weighted wrong ;). validate: function( attrs ) { if ( attrs.species === 'elephant' && attrs.weight && attrs.weight > 12000 ) { return "Too heavy."; } }, toString: function() { return 'Animal (' + this.id + ')'; } }); window.AnimalCollection = Backbone.Collection.extend({ model: Animal, initialize: function( models, options ) { options || (options = {}); this.url = options.url; } }); window.Visitor = Backbone.RelationalModel.extend(); /** * House/Person/Job/Company */ window.House = Backbone.RelationalModel.extend({ relations: [{ type: Backbone.HasMany, key: 'occupants', relatedModel: 'Person', reverseRelation: { key: 'livesIn', includeInJSON: false } }], toString: function() { return 'House (' + this.id + ')'; } }); window.User = Backbone.RelationalModel.extend({ urlRoot: '/user/', toString: function() { return 'User (' + this.id + ')'; } }); window.Person = Backbone.RelationalModel.extend({ relations: [ { // Create a cozy, recursive, one-to-one relationship type: Backbone.HasOne, key: 'likesALot', relatedModel: 'Person', reverseRelation: { type: Backbone.HasOne, key: 'likedALotBy' } }, { type: Backbone.HasOne, key: 'user', keyDestination: 'user_id', relatedModel: 'User', includeInJSON: Backbone.Model.prototype.idAttribute, reverseRelation: { type: Backbone.HasOne, includeInJSON: 'name', key: 'person' } }, { type: 'HasMany', key: 'jobs', relatedModel: 'Job', reverseRelation: { key: 'person' } } ], toString: function() { return 'Person (' + this.id + ')'; } }); window.PersonCollection = Backbone.Collection.extend({ model: Person }); window.Password = Backbone.RelationalModel.extend({ relations: [{ type: Backbone.HasOne, key: 'user', relatedModel: 'User', reverseRelation: { type: Backbone.HasOne, key: 'password' } }], toString: function() { return 'Password (' + this.id + ')'; } }); // A link table between 'Person' and 'Company', to achieve many-to-many relations window.Job = Backbone.RelationalModel.extend({ defaults: { 'startDate': null, 'endDate': null }, toString: function() { return 'Job (' + this.id + ')'; } }); window.Company = Backbone.RelationalModel.extend({ relations: [{ type: 'HasMany', key: 'employees', relatedModel: 'Job', reverseRelation: { key: 'company' } }, { type: 'HasOne', key: 'ceo', relatedModel: 'Person', reverseRelation: { key: 'runs' } } ], toString: function() { return 'Company (' + this.id + ')'; } }); /** * Node/NodeList */ window.Node = Backbone.RelationalModel.extend({ urlRoot: '/node/', relations: [{ type: Backbone.HasOne, key: 'parent', relatedModel: 'Node', reverseRelation: { key: 'children' } } ], toString: function() { return 'Node (' + this.id + ')'; } }); window.NodeList = Backbone.Collection.extend({ model: Node }); /** * Customer/Address/Shop/Agent */ window.Customer = Backbone.RelationalModel.extend({ urlRoot: '/customer/', toString: function() { return 'Customer (' + this.id + ')'; } }); window.Address = Backbone.RelationalModel.extend({ urlRoot: '/address/', toString: function() { return 'Address (' + this.id + ')'; } }); window.Shop = Backbone.RelationalModel.extend({ relations: [ { type: Backbone.HasMany, key: 'customers', relatedModel: 'Customer', autoFetch: true }, { type: Backbone.HasOne, key: 'address', relatedModel: 'Address', autoFetch: { success: function(model, response){ response.successOK = true; }, error: function(model, response){ response.errorOK = true; } } } ], toString: function() { return 'Shop (' + this.id + ')'; } }); window.Agent = Backbone.RelationalModel.extend({ urlRoot: '/agent/', relations: [ { type: Backbone.HasMany, key: 'customers', relatedModel: 'Customer', includeInJSON: Backbone.RelationalModel.prototype.idAttribute }, { type: Backbone.HasOne, key: 'address', relatedModel: 'Address', autoFetch: false } ], toString: function() { return 'Agent (' + this.id + ')'; } }); /** * Reset variables that are persistent across tests, specifically `window.requests` and the state of * `Backbone.Relational.store`. */ function reset() { // Reset last ajax requests window.requests = []; Backbone.Relational.store.reset(); Backbone.Relational.eventQueue = new Backbone.BlockingQueue(); } /** * Initialize a few models that are used in a large number of tests */ function initObjects() { reset(); window.person1 = new Person({ id: 'person-1', name: 'boy', likesALot: 'person-2', resource_uri: 'person-1', user: { id: 'user-1', login: 'dude', email: 'me@gmail.com', resource_uri: 'user-1' } }); window.person2 = new Person({ id: 'person-2', name: 'girl', likesALot: 'person-1', resource_uri: 'person-2' }); window.person3 = new Person({ id: 'person-3', resource_uri: 'person-3' }); window.oldCompany = new Company({ id: 'company-1', name: 'Big Corp.', ceo: { name: 'Big Boy' }, employees: [ { person: 'person-3' } ], // uses the 'Job' link table to achieve many-to-many. No 'id' specified! resource_uri: 'company-1' }); window.newCompany = new Company({ id: 'company-2', name: 'New Corp.', employees: [ { person: 'person-2' } ], resource_uri: 'company-2' }); window.ourHouse = new House({ id: 'house-1', location: 'in the middle of the street', occupants: ['person-2'], resource_uri: 'house-1' }); window.theirHouse = new House({ id: 'house-2', location: 'outside of town', occupants: [], resource_uri: 'house-2' }); } module ( "General / Backbone", { setup: reset } ); test( "Prototypes, constructors and inheritance", function() { // This stuff makes my brain hurt a bit. So, for reference: var Model = Backbone.Model.extend(), i = new Backbone.Model(), iModel = new Model(); var RelModel= Backbone.RelationalModel.extend(), iRel = new Backbone.RelationalModel(), iRelModel = new RelModel(); // Both are functions, so their `constructor` is `Function` ok( Backbone.Model.constructor == Backbone.RelationalModel.constructor ); ok( Backbone.Model != Backbone.RelationalModel ); ok( Backbone.Model == Backbone.Model.prototype.constructor ); ok( Backbone.RelationalModel == Backbone.RelationalModel.prototype.constructor ); ok( Backbone.Model.prototype.constructor != Backbone.RelationalModel.prototype.constructor ); ok( Model.prototype instanceof Backbone.Model ); ok( !( Model.prototype instanceof Backbone.RelationalModel ) ); ok( RelModel.prototype instanceof Backbone.Model ); ok( Backbone.RelationalModel.prototype instanceof Backbone.Model ); ok( RelModel.prototype instanceof Backbone.RelationalModel ); ok( i instanceof Backbone.Model ); ok( !( i instanceof Backbone.RelationalModel ) ); ok( iRel instanceof Backbone.Model ); ok( iRel instanceof Backbone.RelationalModel ); ok( iModel instanceof Backbone.Model ); ok( !( iModel instanceof Backbone.RelationalModel ) ); ok( iRelModel instanceof Backbone.Model ); ok( iRelModel instanceof Backbone.RelationalModel ); }); test('Collection#set', 1, function() { var a = new Backbone.Model({id: 3, label: 'a'} ), b = new Backbone.Model({id: 2, label: 'b'} ), col = new Backbone.Collection([a]); col.set([a,b], {add: true, merge: false, remove: true}); ok( col.length == 2 ); }); module( "Backbone.Semaphore", { setup: reset } ); test( "Unbounded", 10, function() { var semaphore = _.extend( {}, Backbone.Semaphore ); ok( !semaphore.isLocked(), 'Semaphore is not locked initially' ); semaphore.acquire(); ok( semaphore.isLocked(), 'Semaphore is locked after acquire' ); semaphore.acquire(); equal( semaphore._permitsUsed, 2 ,'_permitsUsed should be incremented 2 times' ); semaphore.setAvailablePermits( 4 ); equal( semaphore._permitsAvailable, 4 ,'_permitsAvailable should be 4' ); semaphore.acquire(); semaphore.acquire(); equal( semaphore._permitsUsed, 4 ,'_permitsUsed should be incremented 4 times' ); try { semaphore.acquire(); } catch( ex ) { ok( true, 'Error thrown when attempting to acquire too often' ); } semaphore.release(); equal( semaphore._permitsUsed, 3 ,'_permitsUsed should be decremented to 3' ); semaphore.release(); semaphore.release(); semaphore.release(); equal( semaphore._permitsUsed, 0 ,'_permitsUsed should be decremented to 0' ); ok( !semaphore.isLocked(), 'Semaphore is not locked when all permits are released' ); try { semaphore.release(); } catch( ex ) { ok( true, 'Error thrown when attempting to release too often' ); } }); module( "Backbone.BlockingQueue", { setup: reset } ); test( "Block", function() { var queue = new Backbone.BlockingQueue(); var count = 0; var increment = function() { count++; }; var decrement = function() { count--; }; queue.add( increment ); ok( count === 1, 'Increment executed right away' ); queue.add( decrement ); ok( count === 0, 'Decrement executed right away' ); queue.block(); queue.add( increment ); ok( queue.isLocked(), 'Queue is blocked' ); equal( count, 0, 'Increment did not execute right away' ); queue.block(); queue.block(); equal( queue._permitsUsed, 3 ,'_permitsUsed should be incremented to 3' ); queue.unblock(); queue.unblock(); queue.unblock(); equal( count, 1, 'Increment executed' ); }); module( "Backbone.Store", { setup: initObjects } ); test( "Initialized", function() { // `initObjects` instantiates models of the following types: `Person`, `Job`, `Company`, `User`, `House` and `Password`. equal( Backbone.Relational.store._collections.length, 6, "Store contains 6 collections" ); }); test( "getObjectByName", function() { equal( Backbone.Relational.store.getObjectByName( 'Backbone.RelationalModel' ), Backbone.RelationalModel ); }); test( "Add and remove from store", function() { var coll = Backbone.Relational.store.getCollection( person1 ); var length = coll.length; var person = new Person({ id: 'person-10', name: 'Remi', resource_uri: 'person-10' }); ok( coll.length === length + 1, "Collection size increased by 1" ); var request = person.destroy(); // Trigger the 'success' callback to fire the 'destroy' event request.success(); ok( coll.length === length, "Collection size decreased by 1" ); }); test( "addModelScope", function() { var models = {}; Backbone.Relational.store.addModelScope( models ); models.Book = Backbone.RelationalModel.extend({ relations: [{ type: Backbone.HasMany, key: 'pages', relatedModel: 'Page', createModels: false, reverseRelation: { key: 'book' } }] }); models.Page = Backbone.RelationalModel.extend(); var book = new models.Book(); var page = new models.Page({ book: book }); ok( book.relations.length === 1 ); ok( book.get( 'pages' ).length === 1 ); }); test( "addModelScope with submodels and namespaces", function() { var ns = {}; ns.People = {}; Backbone.Relational.store.addModelScope( ns ); ns.People.Person = Backbone.RelationalModel.extend({ subModelTypes: { 'Student': 'People.Student' }, iam: function() { return "I am an abstract person"; } }); ns.People.Student = ns.People.Person.extend({ iam: function() { return "I am a student"; } }); ns.People.PersonCollection = Backbone.Collection.extend({ model: ns.People.Person }); var people = new ns.People.PersonCollection([{name: "Bob", type: "Student"}]); ok( people.at(0).iam() == "I am a student" ); }); test( "removeModelScope", function() { var models = {}; Backbone.Relational.store.addModelScope( models ); models.Page = Backbone.RelationalModel.extend(); ok( Backbone.Relational.store.getObjectByName( 'Page' ) === models.Page ); ok( Backbone.Relational.store.getObjectByName( 'Person' ) === window.Person ); Backbone.Relational.store.removeModelScope( models ); ok( !Backbone.Relational.store.getObjectByName( 'Page' ) ); ok( Backbone.Relational.store.getObjectByName( 'Person' ) === window.Person ); Backbone.Relational.store.removeModelScope( window ); ok( !Backbone.Relational.store.getObjectByName( 'Person' ) ); }); test( "`eventQueue` is unblocked again after a duplicate id error", 3, function() { var node = new Node( { id: 1 } ); ok( Backbone.Relational.eventQueue.isBlocked() === false ); try { duplicateNode = new Node( { id: 1 } ); } catch( error ) { ok( true, "Duplicate id error thrown" ); } ok( Backbone.Relational.eventQueue.isBlocked() === false ); }); test( "Don't allow setting a duplicate `id`", 4, function() { var a = new Zoo(); // This object starts with no id. var b = new Zoo( { 'id': 42 } ); // This object starts with an id of 42. equal( b.id, 42 ); try { a.set( 'id', 42 ); } catch( error ) { ok( true, "Duplicate id error thrown" ); } ok( !a.id, "a.id=" + a.id ); equal( b.id, 42 ); }); test( "Models are created from objects, can then be found, destroyed, cannot be found anymore", function() { var houseId = 'house-10'; var personId = 'person-10'; var anotherHouse = new House({ id: houseId, location: 'no country for old men', resource_uri: houseId, occupants: [{ id: personId, name: 'Remi', resource_uri: personId }] }); ok( anotherHouse.get('occupants') instanceof Backbone.Collection, "Occupants is a Collection" ); ok( anotherHouse.get('occupants').get( personId ) instanceof Person, "Occupants contains the Person with id='" + personId + "'" ); var person = Backbone.Relational.store.find( Person, personId ); ok( person, "Person with id=" + personId + " is found in the store" ); var request = person.destroy(); // Trigger the 'success' callback to fire the 'destroy' event request.success(); person = Backbone.Relational.store.find( Person, personId ); ok( !person, personId + " is not found in the store anymore" ); ok( !anotherHouse.get('occupants').get( personId ), "Occupants no longer contains the Person with id='" + personId + "'" ); request = anotherHouse.destroy(); // Trigger the 'success' callback to fire the 'destroy' event request.success(); var house = Backbone.Relational.store.find( House, houseId ); ok( !house, houseId + " is not found in the store anymore" ); }); test( "Model.collection is the first collection a Model is added to by an end-user (not it's Backbone.Store collection!)", function() { var person = new Person( { name: 'New guy' } ); var personColl = new PersonCollection(); personColl.add( person ); ok( person.collection === personColl ); }); test( "All models can be found after adding them to a Collection via 'Collection.reset'", function() { var nodes = [ { id: 1, parent: null }, { id: 2, parent: 1 }, { id: 3, parent: 4 }, { id: 4, parent: 1 } ]; var nodeList = new NodeList(); nodeList.reset( nodes ); var storeColl = Backbone.Relational.store.getCollection( Node ); equal( storeColl.length, 4, "Every Node is in Backbone.Relational.store" ); ok( Backbone.Relational.store.find( Node, 1 ) instanceof Node, "Node 1 can be found" ); ok( Backbone.Relational.store.find( Node, 2 ) instanceof Node, "Node 2 can be found" ); ok( Backbone.Relational.store.find( Node, 3 ) instanceof Node, "Node 3 can be found" ); ok( Backbone.Relational.store.find( Node, 4 ) instanceof Node, "Node 4 can be found" ); }); test( "Inheritance creates and uses a separate collection", function() { var whale = new Animal( { id: 1, species: 'whale' } ); ok( Backbone.Relational.store.find( Animal, 1 ) === whale ); var numCollections = Backbone.Relational.store._collections.length; var Mammal = Animal.extend({ urlRoot: '/mammal/' }); var lion = new Mammal( { id: 1, species: 'lion' } ); var donkey = new Mammal( { id: 2, species: 'donkey' } ); equal( Backbone.Relational.store._collections.length, numCollections + 1 ); ok( Backbone.Relational.store.find( Animal, 1 ) === whale ); ok( Backbone.Relational.store.find( Mammal, 1 ) === lion ); ok( Backbone.Relational.store.find( Mammal, 2 ) === donkey ); var Primate = Mammal.extend({ urlRoot: '/primate/' }); var gorilla = new Primate( { id: 1, species: 'gorilla' } ); equal( Backbone.Relational.store._collections.length, numCollections + 2 ); ok( Backbone.Relational.store.find( Primate, 1 ) === gorilla ); }); test( "Inheritance with `subModelTypes` uses the same collection as the model's super", function() { var Mammal = Animal.extend({ subModelTypes: { 'primate': 'Primate', 'carnivore': 'Carnivore' } }); window.Primate = Mammal.extend(); window.Carnivore = Mammal.extend(); var lion = new Carnivore( { id: 1, species: 'lion' } ); var wolf = new Carnivore( { id: 2, species: 'wolf' } ); var numCollections = Backbone.Relational.store._collections.length; var whale = new Mammal( { id: 3, species: 'whale' } ); equal( Backbone.Relational.store._collections.length, numCollections, "`_collections` should have remained the same" ); ok( Backbone.Relational.store.find( Mammal, 1 ) === lion ); ok( Backbone.Relational.store.find( Mammal, 2 ) === wolf ); ok( Backbone.Relational.store.find( Mammal, 3 ) === whale ); ok( Backbone.Relational.store.find( Carnivore, 1 ) === lion ); ok( Backbone.Relational.store.find( Carnivore, 2 ) === wolf ); ok( Backbone.Relational.store.find( Carnivore, 3 ) !== whale ); var gorilla = new Primate( { id: 4, species: 'gorilla' } ); equal( Backbone.Relational.store._collections.length, numCollections, "`_collections` should have remained the same" ); ok( Backbone.Relational.store.find( Animal, 4 ) !== gorilla ); ok( Backbone.Relational.store.find( Mammal, 4 ) === gorilla ); ok( Backbone.Relational.store.find( Primate, 4 ) === gorilla ); delete window.Primate; delete window.Carnivore; }); test( "findOrCreate does not modify attributes hash if parse is used, prior to creating new model", function () { var model = Backbone.RelationalModel.extend({ parse: function( response ) { response.id = response.id + 'something'; return response; } }); var attributes = {id: 42, foo: "bar"}; var testAttributes = {id: 42, foo: "bar"}; model.findOrCreate( attributes, { parse: true, merge: false, create: false } ); ok( _.isEqual( attributes, testAttributes ), "attributes hash should not be modified" ); }); module( "Backbone.RelationalModel", { setup: initObjects } ); test( "Return values: set returns the Model", function() { var personId = 'person-10'; var person = new Person({ id: personId, name: 'Remi', resource_uri: personId }); var result = person.set( { 'name': 'Hector' } ); ok( result === person, "Set returns the model" ); }); test( "getRelations", function() { var relations = person1.getRelations(); equal( relations.length, 6 ); ok( _.every( relations, function( rel ) { return rel instanceof Backbone.Relation; }) ); }); test( "getRelation", function() { var userRel = person1.getRelation( 'user' ); ok( userRel instanceof Backbone.HasOne ); equal( userRel.key, 'user' ); var jobsRel = person1.getRelation( 'jobs' ); ok( jobsRel instanceof Backbone.HasMany ); equal( jobsRel.key, 'jobs' ); ok( person1.getRelation( 'nope' ) == null ); }); test( "fetchRelated on a HasOne relation", function() { var errorCount = 0; var person = new Person({ id: 'person-10', resource_uri: 'person-10', user: 'user-10' }); var requests = person.fetchRelated( 'user', { error: function() { errorCount++; } }); ok( _.isArray( requests ) ); equal( requests.length, 1, "A request has been made" ); ok( person.get( 'user' ) instanceof User ); // Triggering the 'error' callback should destroy the model requests[ 0 ].error(); // Trigger the 'success' callback to fire the 'destroy' event window.requests[ window.requests.length - 1 ].success(); ok( !person.get( 'user' ), "User has been destroyed & removed" ); equal( errorCount, 1, "The error callback executed successfully" ); var person2 = new Person({ id: 'person-11', resource_uri: 'person-11' }); requests = person2.fetchRelated( 'user' ); equal( requests.length, 0, "No request was made" ); }); test( "fetchRelated on a HasMany relation", function() { var errorCount = 0; var zoo = new Zoo({ animals: [ { id: 'monkey-1' }, 'lion-1', 'zebra-1' ] }); // // Case 1: separate requests for each model // var requests = zoo.fetchRelated( 'animals', { error: function() { errorCount++; } } ); ok( _.isArray( requests ) ); equal( requests.length, 2, "Two requests have been made (a separate one for each animal)" ); equal( zoo.get( 'animals' ).length, 3, "Three animals in the zoo" ); // Triggering the 'error' callback for a request should destroy the model requests[ 0 ].error(); // Trigger the 'success' callback on the `destroy` call to fire the 'destroy' event _.last( window.requests ).success(); equal( zoo.get( 'animals' ).length, 2, "Two animals left in the zoo" ); equal( errorCount, 1, "The error callback executed successfully" ); // // Case 2: one request per fetch (generated by the collection) // // Give 'zoo' a custom url function that builds a url to fetch a set of models from their ids errorCount = 0; zoo.get( 'animals' ).url = function( models ) { return '/animal/' + ( models ? 'set/' + _.pluck( models, 'id' ).join(';') + '/' : '' ); }; // Set two new animals to be fetched; both should be fetched in a single request zoo.set( { animals: [ 'monkey-1', 'lion-2', 'zebra-2' ] } ); equal( zoo.get( 'animals' ).length, 1 ); // `fetchRelated` creates two placeholder models for the ids present in the relation. requests = zoo.fetchRelated( 'animals', { error: function() { errorCount++; } } ); ok( _.isArray( requests ) ); equal( requests.length, 1 ); equal( requests[ 0 ].url, '/animal/set/lion-2;zebra-2/' ); equal( zoo.get('animals').length, 3 ); // Triggering the 'error' callback (some error occured during fetching) should trigger the 'destroy' event // on both fetched models, but should NOT actually make 'delete' requests to the server! var numRequests = window.requests.length; requests[ 0 ].error(); ok( window.requests.length === numRequests, "An error occured when fetching, but no DELETE requests are made to the server while handling local cleanup." ); equal( zoo.get( 'animals' ).length, 1, "Both animals are destroyed" ); equal( errorCount, 2, "The error callback executed successfully for both models" ); // Try to re-fetch; nothing left to get though requests = zoo.fetchRelated( 'animals' ); equal( requests.length, 0 ); equal( zoo.get( 'animals' ).length, 1 ); // Re-fetch the existing model requests = zoo.fetchRelated( 'animals', null, true ); equal( requests.length, 1 ); equal( requests[ 0 ].url, '/animal/set/monkey-1/' ); equal( zoo.get( 'animals' ).length, 1 ); // An error while refreshing an existing model shouldn't affect it requests[ 0 ].error(); equal( zoo.get( 'animals' ).length, 1 ); }); test( "autoFetch a HasMany relation", function() { var shopOne = new Shop({ id: 'shop-1', customers: ['customer-1', 'customer-2'] }); equal( requests.length, 2, "Two requests to fetch the users has been made" ); requests.length = 0; var shopTwo = new Shop({ id: 'shop-2', customers: ['customer-1', 'customer-3'] }); equal( requests.length, 1, "A request to fetch a user has been made" ); //as customer-1 has already been fetched }); test( "autoFetch on a HasOne relation (with callbacks)", function() { var shopThree = new Shop({ id: 'shop-3', address: 'address-3' }); equal( requests.length, 1, "A request to fetch the address has been made" ); var res = { successOK: false, errorOK: false }; requests[0].success( res ); equal( res.successOK, true, "The success() callback has been called" ); requests.length = 0; var shopFour = new Shop({ id: 'shop-4', address: 'address-4' }); equal( requests.length, 1, "A request to fetch the address has been made" ); requests[0].error( res ); equal( res.errorOK, true, "The error() callback has been called" ); }); test( "autoFetch false by default", function() { var agentOne = new Agent({ id: 'agent-1', customers: ['customer-4', 'customer-5'] }); equal( requests.length, 0, "No requests to fetch the customers has been made as autoFetch was not defined" ); agentOne = new Agent({ id: 'agent-2', address: 'address-5' }); equal( requests.length, 0, "No requests to fetch the customers has been made as autoFetch was set to false" ); }); test( "clone", function() { var user = person1.get( 'user' ); // HasOne relations should stay with the original model var newPerson = person1.clone(); ok( newPerson.get( 'user' ) === null ); ok( person1.get( 'user' ) === user ); }); test( "`toJSON`: simple cases", function() { var node = new Node({ id: '1', parent: '3', name: 'First node' }); new Node({ id: '2', parent: '1', name: 'Second node' }); new Node({ id: '3', parent: '2', name: 'Third node' }); var json = node.toJSON(); ok( json.children.length === 1 ); }); test("'toJSON' should return null for relations that are set to null, even when model is not fetched", function() { var person = new Person( { user : 'u1' } ); equal( person.toJSON().user_id, 'u1' ); person.set( 'user', null ); equal( person.toJSON().user_id, null ); person = new Person( { user: new User( { id : 'u2' } ) } ); equal( person.toJSON().user_id, 'u2' ); person.set( { user: 'unfetched_user_id' } ); equal( person.toJSON().user_id, 'unfetched_user_id' ); }); test( "`toJSON` should include ids for 'unknown' or 'missing' models (if `includeInJSON` is `idAttribute`)", function() { // See GH-191 // `Zoo` shouldn't be affected; `animals.includeInJSON` is not equal to `idAttribute` var zoo = new Zoo({ id: 'z1', animals: [ 'a1', 'a2' ] }), zooJSON = zoo.toJSON(); ok( _.isArray( zooJSON.animals ) ); equal( zooJSON.animals.length, 0, "0 animals in zooJSON; it serializes an array of attributes" ); var a1 = new Animal( { id: 'a1' } ); zooJSON = zoo.toJSON(); equal( zooJSON.animals.length, 1, "1 animals in zooJSON; it serializes an array of attributes" ); // Agent -> Customer; `idAttribute` on a HasMany var agent = new Agent({ id: 'a1', customers: [ 'c1', 'c2' ] } ), agentJSON = agent.toJSON(); ok( _.isArray( agentJSON.customers ) ); equal( agentJSON.customers.length, 2, "2 customers in agentJSON; it serializes the `idAttribute`" ); var c1 = new Customer( { id: 'c1' } ); equal( agent.get( 'customers' ).length, 1, '1 customer in agent' ); agentJSON = agent.toJSON(); equal( agentJSON.customers.length, 2, "2 customers in agentJSON; `idAttribute` for 1 missing, other existing" ); //c1.destroy(); //agentJSON = agent.toJSON(); //equal( agentJSON.customers.length, 1, "1 customer in agentJSON; `idAttribute` for 1 missing, other destroyed" ); agent.set( 'customers', [ 'c1', 'c3' ] ); var c3 = new Customer( { id: 'c3' } ); agentJSON = agent.toJSON(); equal( agentJSON.customers.length, 2, "2 customers in agentJSON; 'c1' already existed, 'c3' created" ); agent.get( 'customers' ).remove( c1 ); agentJSON = agent.toJSON(); equal( agentJSON.customers.length, 1, "1 customer in agentJSON; 'c1' removed, 'c3' still in there" ); // Person -> User; `idAttribute` on a HasOne var person = new Person({ id: 'p1', user: 'u1' } ), personJSON = person.toJSON(); equal( personJSON.user_id, 'u1', "`user_id` gets set in JSON" ); var u1 = new User( { id: 'u1' } ); personJSON = person.toJSON(); ok( u1.get( 'person' ) === person ); equal( personJSON.user_id, 'u1', "`user_id` gets set in JSON" ); person.set( 'user', 'u1' ); personJSON = person.toJSON(); equal( personJSON.user_id, 'u1', "`user_id` gets set in JSON" ); u1.destroy(); personJSON = person.toJSON(); ok( !u1.get( 'person' ) ); equal( personJSON.user_id, 'u1', "`user_id` still gets set in JSON" ); }); test( "`toJSON` should include ids for unregistered models (if `includeInJSON` is `idAttribute`)", function() { // Person -> User; `idAttribute` on a HasOne var person = new Person({ id: 'p1', user: 'u1' } ), personJSON = person.toJSON(); equal( personJSON.user_id, 'u1', "`user_id` gets set in JSON even though no user obj exists" ); var u1 = new User( { id: 'u1' } ); personJSON = person.toJSON(); ok( u1.get( 'person' ) === person ); equal( personJSON.user_id, 'u1', "`user_id` gets set in JSON after matching user obj is created" ); Backbone.Relational.store.unregister(u1); personJSON = person.toJSON(); equal( personJSON.user_id, 'u1', "`user_id` gets set in JSON after user was unregistered from store" ); }); test( "`parse` gets called through `findOrCreate`", function() { var parseCalled = 0; Zoo.prototype.parse = Animal.prototype.parse = function( resp, options ) { parseCalled++; return resp; }; var zoo = Zoo.findOrCreate({ id: '1', name: 'San Diego Zoo', animals: [ { id: 'a' } ] }, { parse: true } ); var animal = zoo.get( 'animals' ).first(); ok( animal.get( 'livesIn' ) ); ok( animal.get( 'livesIn' ) instanceof Zoo ); ok( animal.get( 'livesIn' ).get( 'animals' ).get( animal ) === animal ); // `parse` gets called once by `findOrCreate` directly when trying to lookup `1`, // once when `build` (called from `findOrCreate`) calls the Zoo constructor with `{ parse: true}`. ok( parseCalled === 2, 'parse called 2 times? ' + parseCalled ); parseCalled = 0; animal = new Animal({ id: 'b' }); animal.set({ id: 'b', livesIn: { id: '2', name: 'San Diego Zoo', animals: [ 'b' ] } }, { parse: true } ); ok( animal.get( 'livesIn' ) ); ok( animal.get( 'livesIn' ) instanceof Zoo ); ok( animal.get( 'livesIn' ).get( 'animals' ).get( animal ) === animal ); ok( parseCalled === 0, 'parse called 0 times? ' + parseCalled ); // Reset `parse` methods Zoo.prototype.parse = Animal.prototype.parse = Backbone.RelationalModel.prototype.parse; }); test( "`Collection#parse` with RelationalModel simple case", function() { var Contact = Backbone.RelationalModel.extend({ parse: function( response ) { response.bar = response.foo * 2; return response; } }); var Contacts = Backbone.Collection.extend({ model: Contact, url: '/contacts', parse: function( response ) { return response.items; } }); var contacts = new Contacts(); contacts.fetch({ // fake response for testing response: { status: 200, responseText: { items: [ { foo: 1 }, { foo: 2 } ] } } }); equal( contacts.length, 2, 'Collection response was fetched properly' ); var contact = contacts.first(); ok( contact , 'Collection has a non-null item' ); ok( contact instanceof Contact, '... of the type type' ); equal( contact.get('foo'), 1, '... with correct fetched value' ); equal( contact.get('bar'), 2, '... with correct parsed value' ); }); test( "By default, `parse` should only get called on top-level objects; not for nested models and collections", function() { var companyData = { 'data': { 'id': 'company-1', 'contacts': [ { 'id': '1' }, { 'id': '2' } ] } }; var Contact = Backbone.RelationalModel.extend(); var Contacts = Backbone.Collection.extend({ model: Contact }); var Company = Backbone.RelationalModel.extend({ urlRoot: '/company/', relations: [{ type: Backbone.HasMany, key: 'contacts', relatedModel: Contact, collectionType: Contacts }] }); var parseCalled = 0; Company.prototype.parse = Contact.prototype.parse = Contacts.prototype.parse = function( resp, options ) { parseCalled++; return resp.data || resp; }; var company = new Company( companyData, { parse: true } ), contacts = company.get( 'contacts' ), contact = contacts.first(); ok( company.id === 'company-1' ); ok( contact && contact.id === '1', 'contact exists' ); ok( parseCalled === 1, 'parse called 1 time? ' + parseCalled ); // simulate what would happen if company.fetch() was called. company.fetch({ parse: true, response: { status: 200, responseText: _.clone( companyData ) } }); ok( parseCalled === 2, 'parse called 2 times? ' + parseCalled ); ok( contacts === company.get( 'contacts' ), 'contacts collection is same instance after fetch' ); equal( contacts.length, 2, '... with correct length' ); ok( contact && contact.id === '1', 'contact exists' ); ok( contact === contacts.first(), '... and same model instances' ); }); test( "constructor.findOrCreate", function() { var personColl = Backbone.Relational.store.getCollection( person1 ), origPersonCollSize = personColl.length; // Just find an existing model var person = Person.findOrCreate( person1.id ); ok( person === person1 ); ok( origPersonCollSize === personColl.length, "Existing person was found (none created)" ); // Update an existing model person = Person.findOrCreate( { id: person1.id, name: 'dude' } ); equal( person.get( 'name' ), 'dude' ); equal( person1.get( 'name' ), 'dude' ); ok( origPersonCollSize === personColl.length, "Existing person was updated (none created)" ); // Look for a non-existent person; 'options.create' is false person = Person.findOrCreate( { id: 5001 }, { create: false } ); ok( !person ); ok( origPersonCollSize === personColl.length, "No person was found (none created)" ); // Create a new model person = Person.findOrCreate( { id: 5001 } ); ok( person instanceof Person ); ok( origPersonCollSize + 1 === personColl.length, "No person was found (1 created)" ); // Find when options.merge is false person = Person.findOrCreate( { id: person1.id, name: 'phil' }, { merge: false } ); equal( person.get( 'name' ), 'dude' ); equal( person1.get( 'name' ), 'dude' ); }); test( "constructor.find", function() { var personColl = Backbone.Relational.store.getCollection( person1 ), origPersonCollSize = personColl.length; // Look for a non-existent person person = Person.find( { id: 5001 } ); ok( !person ); }); test( "change events in relation can use changedAttributes properly", function() { var scope = {}; Backbone.Relational.store.addModelScope( scope ); scope.PetAnimal = Backbone.RelationalModel.extend({ subModelTypes: { 'cat': 'Cat', 'dog': 'Dog' } }); scope.Dog = scope.PetAnimal.extend(); scope.Cat = scope.PetAnimal.extend(); scope.PetOwner = Backbone.RelationalModel.extend({ relations: [{ type: Backbone.HasMany, key: 'pets', relatedModel: scope.PetAnimal, reverseRelation: { key: 'owner' } }] }); var owner = new scope.PetOwner( { id: 'owner-2354' } ); var animal = new scope.Dog( { type: 'dog', id: '238902', color: 'blue' } ); equal( animal.get('color'), 'blue', 'animal starts out blue' ); var changes = 0, changedAttrs; animal.on('change', function(model, options) { changes++; changedAttrs = model.changedAttributes(); }); animal.set( { color: 'green' } ); equal( changes, 1, 'change event gets called after animal.set' ); equal( changedAttrs.color, 'green', '... with correct properties in "changedAttributes"' ); owner.set(owner.parse({ id: 'owner-2354', pets: [ { id: '238902', type: 'dog', color: 'red' } ] })); equal( animal.get('color'), 'red', 'color gets updated properly' ); equal( changes, 2, 'change event gets called after owner.set' ); equal( changedAttrs.color, 'red', '... with correct properties in "changedAttributes"' ); }); test( 'change events should not fire on new items in Collection#set', function() { var modelChangeEvents = 0, collectionChangeEvents = 0; var Animal2 = Animal.extend({ initialize: function(options) { this.on( 'all', function( name, event ) { //console.log( 'Animal2: %o', arguments ); if ( name.indexOf( 'change' ) === 0 ) { modelChangeEvents++; } }); } }); var AnimalCollection2 = AnimalCollection.extend({ model: Animal2, initialize: function(options) { this.on( 'all', function( name, event ) { //console.log( 'AnimalCollection2: %o', arguments ); if ( name.indexOf('change') === 0 ) { collectionChangeEvents++; } }); } }); var zoo = new Zoo( { id: 'zoo-1' } ); var coll = new AnimalCollection2(); coll.set( [{ id: 'animal-1', livesIn: 'zoo-1' }] ); equal( collectionChangeEvents, 0, 'no change event should be triggered on the collection' ); modelChangeEvents = collectionChangeEvents = 0; coll.at( 0 ).set( 'name', 'Willie' ); equal( modelChangeEvents, 2, 'change event should be triggered' ); }); module( "Backbone.RelationalModel inheritance (`subModelTypes`)", { setup: reset } ); test( "Object building based on type, when using explicit collections" , function() { var scope = {}; Backbone.Relational.store.addModelScope( scope ); scope.Mammal = Animal.extend({ subModelTypes: { 'primate': 'Primate', 'carnivore': 'Carnivore' } }); scope.Primate = scope.Mammal.extend({ subModelTypes: { 'human': 'Human' } }); scope.Human = scope.Primate.extend(); scope.Carnivore = scope.Mammal.extend(); var MammalCollection = AnimalCollection.extend({ model: scope.Mammal }); var mammals = new MammalCollection( [ { id: 5, species: 'chimp', type: 'primate' }, { id: 6, species: 'panther', type: 'carnivore' }, { id: 7, species: 'person', type: 'human' } ]); ok( mammals.at( 0 ) instanceof scope.Primate ); ok( mammals.at( 1 ) instanceof scope.Carnivore ); ok( mammals.at( 2 ) instanceof scope.Human ); }); test( "Object building based on type, when used in relations" , function() { var scope = {}; Backbone.Relational.store.addModelScope( scope ); var PetAnimal = scope.PetAnimal = Backbone.RelationalModel.extend({ subModelTypes: { 'cat': 'Cat', 'dog': 'Dog' } }); var Dog = scope.Dog = PetAnimal.extend({ subModelTypes: { 'poodle': 'Poodle' } }); var Cat = scope.Cat = PetAnimal.extend(); var Poodle = scope.Poodle = Dog.extend(); var PetPerson = scope.PetPerson = Backbone.RelationalModel.extend({ relations: [{ type: Backbone.HasMany, key: 'pets', relatedModel: PetAnimal, reverseRelation: { key: 'owner' } }] }); var petPerson = new scope.PetPerson({ pets: [ { type: 'dog', name: 'Spot' }, { type: 'cat', name: 'Whiskers' }, { type: 'poodle', name: 'Mitsy' } ] }); ok( petPerson.get( 'pets' ).at( 0 ) instanceof Dog ); ok( petPerson.get( 'pets' ).at( 1 ) instanceof Cat ); ok( petPerson.get( 'pets' ).at( 2 ) instanceof Poodle ); petPerson.get( 'pets' ).add([{ type: 'dog', name: 'Spot II' },{ type: 'poodle', name: 'Mitsy II' }]); ok( petPerson.get( 'pets' ).at( 3 ) instanceof Dog ); ok( petPerson.get( 'pets' ).at( 4 ) instanceof Poodle ); }); test( "Object building based on type in a custom field, when used in relations" , function() { var scope = {}; Backbone.Relational.store.addModelScope( scope ); var Caveman = scope.Caveman = Backbone.RelationalModel.extend({ subModelTypes: { 'rubble': 'Rubble', 'flintstone': 'Flintstone' }, subModelTypeAttribute: "caveman_type" }); var Flintstone = scope.Flintstone = Caveman.extend(); var Rubble = scope.Rubble = Caveman.extend(); var Cartoon = scope.Cartoon = Backbone.RelationalModel.extend({ relations: [{ type: Backbone.HasMany, key: 'cavemen', relatedModel: Caveman }] }); var captainCaveman = new scope.Cartoon({ cavemen: [ { type: 'rubble', name: 'CaptainCaveman' } ] }); ok( !(captainCaveman.get( "cavemen" ).at( 0 ) instanceof Rubble) ) var theFlintstones = new scope.Cartoon({ cavemen: [ { caveman_type: 'rubble', name: 'Barney', }, { caveman_type: 'flintstone', name: 'Wilma' } ] }); ok( theFlintstones.get( "cavemen" ).at( 0 ) instanceof Rubble ) ok( theFlintstones.get( "cavemen" ).at( 1 ) instanceof Flintstone ) }); test( "Automatic sharing of 'superModel' relations" , function() { var scope = {}; Backbone.Relational.store.addModelScope( scope ); scope.PetPerson = Backbone.RelationalModel.extend({}); scope.PetAnimal = Backbone.RelationalModel.extend({ subModelTypes: { 'dog': 'Dog' }, relations: [{ type: Backbone.HasOne, key: 'owner', relatedModel: scope.PetPerson, reverseRelation: { type: Backbone.HasMany, key: 'pets' } }] }); scope.Flea = Backbone.RelationalModel.extend({}); scope.Dog = scope.PetAnimal.extend({ subModelTypes: { 'poodle': 'Poodle' }, relations: [{ type: Backbone.HasMany, key: 'fleas', relatedModel: scope.Flea, reverseRelation: { key: 'host' } }] }); scope.Poodle = scope.Dog.extend(); var dog = new scope.Dog({ name: 'Spot' }); var poodle = new scope.Poodle({ name: 'Mitsy' }); var person = new scope.PetPerson({ pets: [ dog, poodle ] }); ok( dog.get( 'owner' ) === person, "Dog has a working owner relation." ); ok( poodle.get( 'owner' ) === person, "Poodle has a working owner relation." ); var flea = new scope.Flea({ host: dog }); var flea2 = new scope.Flea({ host: poodle }); ok( dog.get( 'fleas' ).at( 0 ) === flea, "Dog has a working fleas relation." ); ok( poodle.get( 'fleas' ).at( 0 ) === flea2, "Poodle has a working fleas relation." ); }); test( "Initialization and sharing of 'superModel' reverse relations from a 'leaf' child model" , function() { var scope = {}; Backbone.Relational.store.addModelScope( scope ); scope.PetAnimal = Backbone.RelationalModel.extend({ subModelTypes: { 'dog': 'Dog' } }); scope.Flea = Backbone.RelationalModel.extend({}); scope.Dog = scope.PetAnimal.extend({ subModelTypes: { 'poodle': 'Poodle' }, relations: [{ type: Backbone.HasMany, key: 'fleas', relatedModel: scope.Flea, reverseRelation: { key: 'host' } }] }); scope.Poodle = scope.Dog.extend(); // Define the PetPerson after defining all of the Animal models. Include the 'owner' as a reverse-relation. scope.PetPerson = Backbone.RelationalModel.extend({ relations: [{ type: Backbone.HasMany, key: 'pets', relatedModel: scope.PetAnimal, reverseRelation: { type: Backbone.HasOne, key: 'owner' } }] }); // Initialize the models starting from the deepest descendant and working your way up to the root parent class. var poodle = new scope.Poodle({ name: 'Mitsy' }); var dog = new scope.Dog({ name: 'Spot' }); var person = new scope.PetPerson({ pets: [ dog, poodle ] }); ok( dog.get( 'owner' ) === person, "Dog has a working owner relation." ); ok( poodle.get( 'owner' ) === person, "Poodle has a working owner relation." ); var flea = new scope.Flea({ host: dog }); var flea2 = new scope.Flea({ host: poodle }); ok( dog.get( 'fleas' ).at( 0 ) === flea, "Dog has a working fleas relation." ); ok( poodle.get( 'fleas' ).at( 0 ) === flea2, "Poodle has a working fleas relation." ); }); test( "Initialization and sharing of 'superModel' reverse relations by adding to a polymorphic HasMany" , function() { var scope = {}; Backbone.Relational.store.addModelScope( scope ); scope.PetAnimal = Backbone.RelationalModel.extend({ // The order in which these are defined matters for this regression test. subModelTypes: { 'dog': 'Dog', 'fish': 'Fish' } }); // This looks unnecessary but it's for this regression test there has to be multiple subModelTypes. scope.Fish = scope.PetAnimal.extend({}); scope.Flea = Backbone.RelationalModel.extend({}); scope.Dog = scope.PetAnimal.extend({ subModelTypes: { 'poodle': 'Poodle' }, relations: [{ type: Backbone.HasMany, key: 'fleas', relatedModel: scope.Flea, reverseRelation: { key: 'host' } }] }); scope.Poodle = scope.Dog.extend({}); // Define the PetPerson after defining all of the Animal models. Include the 'owner' as a reverse-relation. scope.PetPerson = Backbone.RelationalModel.extend({ relations: [{ type: Backbone.HasMany, key: 'pets', relatedModel: scope.PetAnimal, reverseRelation: { type: Backbone.HasOne, key: 'owner' } }] }); // We need to initialize a model through the root-parent-model's build method by adding raw-attributes for a // leaf-child-class to a polymorphic HasMany. var person = new scope.PetPerson({ pets: [{ type: 'poodle', name: 'Mitsy' }] }); var poodle = person.get('pets').first(); ok( poodle.get( 'owner' ) === person, "Poodle has a working owner relation." ); }); test( "Overriding of supermodel relations", function() { var models = {}; Backbone.Relational.store.addModelScope( models ); models.URL = Backbone.RelationalModel.extend({}); models.File = Backbone.RelationalModel.extend({ subModelTypes: { 'video': 'Video', 'publication': 'Publication' }, relations: [{ type: Backbone.HasOne, key: 'url', relatedModel: models.URL }] }); models.Video = models.File.extend({}); // Publication redefines the `url` relation models.Publication = Backbone.RelationalModel.extend({ relations: [{ type: Backbone.HasMany, key: 'url', relatedModel: models.URL }] }); models.Project = Backbone.RelationalModel.extend({ relations: [{ type: Backbone.HasMany, key: 'files', relatedModel: models.File, reverseRelation: { key: 'project' } }] }); equal( models.File.prototype.relations.length, 2, "2 relations on File" ); equal( models.Video.prototype.relations.length, 1, "1 relation on Video" ); equal( models.Publication.prototype.relations.length, 1, "1 relation on Publication" ); // Instantiating the superModel should instantiate the modelHierarchy, and copy relations over to subModels var file = new models.File(); equal( models.File.prototype.relations.length, 2, "2 relations on File" ); equal( models.Video.prototype.relations.length, 2, "2 relations on Video" ); equal( models.Publication.prototype.relations.length, 2, "2 relations on Publication" ); var projectDecription = { name: 'project1', files: [ { name: 'file1 - video subclass', type: 'video', url: { location: 'http://www.myurl.com/file1.avi' } }, { name: 'file2 - file baseclass', url: { location: 'http://www.myurl.com/file2.jpg' } }, { name: 'file3 - publication', type: 'publication', url: [ { location: 'http://www.myurl.com/file3.pdf' }, { location: 'http://www.anotherurl.com/file3.doc' } ] } ] }; var project = new models.Project( projectDecription ), files = project.get( 'files' ), file1 = files.at( 0 ), file2 = files.at( 1 ), file3 = files.at( 2 ); equal( models.File.prototype.relations.length, 2, "2 relations on File" ); equal( models.Video.prototype.relations.length, 2, "2 relations on Video" ); equal( models.Publication.prototype.relations.length, 2, "2 relations on Publication" ); equal( _.size( file1._relations ), 2 ); equal( _.size( file2._relations ), 2 ); equal( _.size( file3._relations ), 2 ); ok( file1.get( 'url' ) instanceof Backbone.Model, '`url` on Video is a model' ); ok( file1.getRelation( 'url' ) instanceof Backbone.HasOne, '`url` relation on Video is HasOne' ); ok( file3.get( 'url' ) instanceof Backbone.Collection, '`url` on Publication is a collection' ); ok( file3.getRelation( 'url' ) instanceof Backbone.HasMany, '`url` relation on Publication is HasMany' ); }); test( "toJSON includes the type", function() { var scope = {}; Backbone.Relational.store.addModelScope( scope ); scope.PetAnimal = Backbone.RelationalModel.extend({ subModelTypes: { 'dog': 'Dog' } }); scope.Dog = scope.PetAnimal.extend(); var dog = new scope.Dog({ name: 'Spot' }); var json = dog.toJSON(); equal( json.type, 'dog', "The value of 'type' is the pet animal's type." ); }); module( "Backbone.Relation options", { setup: initObjects } ); test( "`includeInJSON` (Person to JSON)", function() { var json = person1.toJSON(); equal( json.user_id, 'user-1', "The value of 'user_id' is the user's id (not an object, since 'includeInJSON' is set to the idAttribute)" ); ok ( json.likesALot instanceof Object, "The value of 'likesALot' is an object ('includeInJSON' is 'true')" ); equal( json.likesALot.likesALot, 'person-1', "Person is serialized only once" ); json = person1.get( 'user' ).toJSON(); equal( json.person, 'boy', "The value of 'person' is the person's name (`includeInJSON` is set to 'name')" ); json = person2.toJSON(); ok( person2.get('livesIn') instanceof House, "'person2' has a 'livesIn' relation" ); equal( json.livesIn, undefined , "The value of 'livesIn' is not serialized (`includeInJSON` is 'false')" ); json = person3.toJSON(); ok( json.user_id === null, "The value of 'user_id' is null"); ok( json.likesALot === null, "The value of 'likesALot' is null"); }); test( "`includeInJSON` (Zoo to JSON)", function() { var zoo = new Zoo({ id: 0, name: 'Artis', city: 'Amsterdam', animals: [ new Animal( { id: 1, species: 'bear', name: 'Baloo' } ), new Animal( { id: 2, species: 'tiger', name: 'Shere Khan' } ) ] }); var jsonZoo = zoo.toJSON(), jsonBear = jsonZoo.animals[ 0 ]; ok( _.isArray( jsonZoo.animals ), "animals is an Array" ); equal( jsonZoo.animals.length, 2 ); equal( jsonBear.id, 1, "animal's id has been included in the JSON" ); equal( jsonBear.species, 'bear', "animal's species has been included in the JSON" ); ok( !jsonBear.name, "animal's name has not been included in the JSON" ); var tiger = zoo.get( 'animals' ).get( 1 ), jsonTiger = tiger.toJSON(); ok( _.isObject( jsonTiger.livesIn ) && !_.isArray( jsonTiger.livesIn ), "zoo is an Object" ); equal( jsonTiger.livesIn.id, 0, "zoo.id is included in the JSON" ); equal( jsonTiger.livesIn.name, 'Artis', "zoo.name is included in the JSON" ); ok( !jsonTiger.livesIn.city, "zoo.city is not included in the JSON" ); }); test( "'createModels' is false", function() { var NewUser = Backbone.RelationalModel.extend({}); var NewPerson = Backbone.RelationalModel.extend({ relations: [{ type: Backbone.HasOne, key: 'user', relatedModel: NewUser, createModels: false }] }); var person = new NewPerson({ id: 'newperson-1', resource_uri: 'newperson-1', user: { id: 'newuser-1', resource_uri: 'newuser-1' } }); ok( person.get( 'user' ) == null ); var user = new NewUser( { id: 'newuser-1', name: 'SuperUser' } ); ok( person.get( 'user' ) === user ); // Old data gets overwritten by the explicitly created user, since a model was never created from the old data ok( person.get( 'user' ).get( 'resource_uri' ) == null ); }); test("'dotNotation' is true", function(){ var Role = Backbone.RelationalModel.extend({}); var Roles = Backbone.Collection.extend({ model: Role }); var NewUser = Backbone.RelationalModel.extend({}); var NewPerson = Backbone.RelationalModel.extend({ dotNotation: true, relations: [{ type: Backbone.HasOne, key: 'user', relatedModel: NewUser }, { type: Backbone.HasMany, key: 'roles', relatedModel: Role, collectionType: Roles }] }); var person = new NewPerson({ "normal": true, "user.over": 2, user: {name: "John", "over" : 1}, roles: [ {name: 'publisher'}, {name: 'moderator'} ] }); ok( person.get( 'normal' ) === true, "getting normal attributes works as usual" ); ok( person.get( 'user.name' ) === "John", "attributes of nested models can be get via dot notation: nested.attribute"); ok(oldCompany.get( 'ceo.name' ) === undefined, "no dotNotation when not enabled"); ok( person.get( 'user.fake.attribute') === undefined, "undefined when path doesn't exist"); raises( function() { person.get( 'user.over' ); }, "getting ambiguous nested attributes raises an exception"); ok( person.get('roles.0') instanceof Role, "get by index works for nested collections"); ok( person.get('roles.0.name') === "publisher", "attributes of models of nested collections can be get via dot notation: nested.0.attribute"); ok( person.get('roles.100') === undefined, "undefined when index is out of bounds"); ok( person.get('roles.100.name') === undefined, "attributes of out-of-bounds models of nested collections are undefined"); }); test( "Relations load from both `keySource` and `key`", function() { var Property = Backbone.RelationalModel.extend({ idAttribute: 'property_id' }); var View = Backbone.RelationalModel.extend({ idAttribute: 'id', relations: [{ type: Backbone.HasMany, key: 'properties', keySource: 'property_ids', relatedModel: Property, reverseRelation: { key: 'view', keySource: 'view_id' } }] }); var property1 = new Property({ property_id: 1, key: 'width', value: 500, view_id: 5 }); var view = new View({ id: 5, property_ids: [ 2 ] }); var property2 = new Property({ property_id: 2, key: 'height', value: 400 }); // The values from view.property_ids should be loaded into view.properties ok( view.get( 'properties' ) && view.get( 'properties' ).length === 2, "'view' has two 'properties'" ); ok( typeof view.get( 'property_ids' ) === 'undefined', "'view' does not have 'property_ids'" ); view.set( 'properties', [ property1, property2 ] ); ok( view.get( 'properties' ) && view.get( 'properties' ).length === 2, "'view' has two 'properties'" ); view.set( 'property_ids', [ 1, 2 ] ); ok( view.get( 'properties' ) && view.get( 'properties' ).length === 2, "'view' has two 'properties'" ); }); test( "`keySource` is emptied after a set, doesn't get confused by `unset`", function() { var SubModel = Backbone.RelationalModel.extend(); var Model = Backbone.RelationalModel.extend({ relations: [{ type: Backbone.HasOne, key: 'submodel', keySource: 'sub_data', relatedModel: SubModel }] }); var inst = new Model( {'id': 123} ); // `set` may be called from fetch inst.set({ 'id': 123, 'some_field': 'some_value', 'sub_data': { 'id': 321, 'key': 'value' }, 'to_unset': 'unset value' }); ok( inst.get('submodel').get('key') === 'value', "value of submodule.key should be 'value'" ); inst.set( { 'to_unset': '' }, { 'unset': true } ); ok( inst.get('submodel').get('key') === 'value', "after unset value of submodule.key should be still 'value'" ); ok( typeof inst.get('sub_data') === 'undefined', "keySource field should be removed from model" ); ok( typeof inst.get('submodel') !== 'undefined', "key field should be added..." ); ok( inst.get('submodel') instanceof SubModel, "... and should be model instance" ); // set called from fetch inst.set({ 'sub_data': { 'id': 321, 'key': 'value2' } }); ok( typeof inst.get('sub_data') === 'undefined', "keySource field should be removed from model" ); ok( typeof inst.get('submodel') !== 'undefined', "key field should be present..." ); ok( inst.get('submodel').get('key') == 'value2', "... and should be updated" ); }); test( "'keyDestination' saves to 'key'", function() { var Property = Backbone.RelationalModel.extend({ idAttribute: 'property_id' }); var View = Backbone.RelationalModel.extend({ idAttribute: 'id', relations: [{ type: Backbone.HasMany, key: 'properties', keyDestination: 'properties_attributes', relatedModel: Property, reverseRelation: { key: 'view', keyDestination: 'view_attributes', includeInJSON: true } }] }); var property1 = new Property({ property_id: 1, key: 'width', value: 500, view: 5 }); var view = new View({ id: 5, properties: [ 2 ] }); var property2 = new Property({ property_id: 2, key: 'height', value: 400 }); var viewJSON = view.toJSON(); ok( viewJSON.properties_attributes && viewJSON.properties_attributes.length === 2, "'viewJSON' has two 'properties_attributes'" ); ok( typeof viewJSON.properties === 'undefined', "'viewJSON' does not have 'properties'" ); }); test( "'collectionOptions' sets the options on the created HasMany Collections", function() { var zoo = new Zoo(); ok( zoo.get("animals").url === "zoo/" + zoo.cid + "/animal/"); }); test( "`parse` with deeply nested relations", function() { var collParseCalled = 0, modelParseCalled = 0; var Job = Backbone.RelationalModel.extend({}); var JobCollection = Backbone.Collection.extend({ model: Job, parse: function( resp, options ) { collParseCalled++; return resp.data || resp; } }); var Company = Backbone.RelationalModel.extend({ relations: [{ type: 'HasMany', key: 'employees', parse: true, relatedModel: Job, collectionType: JobCollection, reverseRelation: { key: 'company' } }] }); var Person = Backbone.RelationalModel.extend({ relations: [{ type: 'HasMany', key: 'jobs', parse: true, relatedModel: Job, collectionType: JobCollection, reverseRelation: { key: 'person', parse: false } }], parse: function( resp, options ) { modelParseCalled++; return resp; } }); Company.prototype.parse = Job.prototype.parse = function( resp, options ) { modelParseCalled++; var data = _.clone( resp.model ); data.id = data.id.uri; return data; }; var data = { model: { id: { uri: 'c1' }, employees: [ { model: { id: { uri: 'e1' }, person: { id: 'p1', jobs: [ 'e1', { model: { id: { uri: 'e3' } } } ] } } }, { model: { id: { uri: 'e2' }, person: { id: 'p2' } } } ] } }; var company = new Company( data, { parse: true } ), employees = company.get( 'employees' ), job = employees.first(), person = job.get( 'person' ); ok( job && job.id === 'e1', 'job exists' ); ok( person && person.id === 'p1', 'person exists' ); ok( modelParseCalled === 7, 'model.parse called 7 times? ' + modelParseCalled ); ok( collParseCalled === 0, 'coll.parse called 0 times? ' + collParseCalled ); }); module( "Backbone.Relation preconditions", { setup: reset } ); test( "'type', 'key', 'relatedModel' are required properties", function() { var Properties = Backbone.RelationalModel.extend({}); var View = Backbone.RelationalModel.extend({ relations: [ { key: 'listProperties', relatedModel: Properties } ] }); var view = new View(); ok( _.size( view._relations ) === 0 ); ok( view.getRelations().length === 0 ); View = Backbone.RelationalModel.extend({ relations: [ { type: Backbone.HasOne, relatedModel: Properties } ] }); view = new View(); ok( _.size( view._relations ) === 0 ); View = Backbone.RelationalModel.extend({ relations: [ { type: Backbone.HasOne, key: 'listProperties' } ] }); view = new View(); ok( _.size( view._relations ) === 0 ); }); test( "'type' can be a string or an object reference", function() { var Properties = Backbone.RelationalModel.extend({}); var View = Backbone.RelationalModel.extend({ relations: [ { type: 'Backbone.HasOne', key: 'listProperties', relatedModel: Properties } ] }); var view = new View(); ok( _.size( view._relations ) === 1 ); View = Backbone.RelationalModel.extend({ relations: [ { type: 'HasOne', key: 'listProperties', relatedModel: Properties } ] }); view = new View(); ok( _.size( view._relations ) === 1 ); View = Backbone.RelationalModel.extend({ relations: [ { type: Backbone.HasOne, key: 'listProperties', relatedModel: Properties } ] }); view = new View(); ok( _.size( view._relations ) === 1 ); }); test( "'key' can be a string or an object reference", function() { var Properties = Backbone.RelationalModel.extend({}); var View = Backbone.RelationalModel.extend({ relations: [ { type: Backbone.HasOne, key: 'listProperties', relatedModel: Properties } ] }); var view = new View(); ok( _.size( view._relations ) === 1 ); View = Backbone.RelationalModel.extend({ relations: [ { type: Backbone.HasOne, key: 'listProperties', relatedModel: Properties } ] }); view = new View(); ok( _.size( view._relations ) === 1 ); }); test( "HasMany with a reverseRelation HasMany is not allowed", function() { var User = Backbone.RelationalModel.extend({}); var Password = Backbone.RelationalModel.extend({ relations: [{ type: 'HasMany', key: 'users', relatedModel: User, reverseRelation: { type: 'HasMany', key: 'passwords' } }] }); var password = new Password({ plaintext: 'qwerty', users: [ 'person-1', 'person-2', 'person-3' ] }); ok( _.size( password._relations ) === 0, "No _relations created on Password" ); }); test( "Duplicate relations not allowed (two simple relations)", function() { var Properties = Backbone.RelationalModel.extend({}); var View = Backbone.RelationalModel.extend({ relations: [ { type: Backbone.HasOne, key: 'properties', relatedModel: Properties }, { type: Backbone.HasOne, key: 'properties', relatedModel: Properties } ] }); var view = new View(); view.set( { properties: new Properties() } ); ok( _.size( view._relations ) === 1 ); }); test( "Duplicate relations not allowed (one relation with a reverse relation, one without)", function() { var Properties = Backbone.RelationalModel.extend({}); var View = Backbone.RelationalModel.extend({ relations: [ { type: Backbone.HasOne, key: 'properties', relatedModel: Properties, reverseRelation: { type: Backbone.HasOne, key: 'view' } }, { type: Backbone.HasOne, key: 'properties', relatedModel: Properties } ] }); var view = new View(); view.set( { properties: new Properties() } ); ok( _.size( view._relations ) === 1 ); }); test( "Duplicate relations not allowed (two relations with reverse relations)", function() { var Properties = Backbone.RelationalModel.extend({}); var View = Backbone.RelationalModel.extend({ relations: [ { type: Backbone.HasOne, key: 'properties', relatedModel: Properties, reverseRelation: { type: Backbone.HasOne, key: 'view' } }, { type: Backbone.HasOne, key: 'properties', relatedModel: Properties, reverseRelation: { type: Backbone.HasOne, key: 'view' } } ] }); var view = new View(); view.set( { properties: new Properties() } ); ok( _.size( view._relations ) === 1 ); }); test( "Duplicate relations not allowed (different relations, reverse relations)", function() { var Properties = Backbone.RelationalModel.extend({}); var View = Backbone.RelationalModel.extend({ relations: [ { type: Backbone.HasOne, key: 'listProperties', relatedModel: Properties, reverseRelation: { type: Backbone.HasOne, key: 'view' } }, { type: Backbone.HasOne, key: 'windowProperties', relatedModel: Properties, reverseRelation: { type: Backbone.HasOne, key: 'view' } } ] }); var view = new View(), prop1 = new Properties( { name: 'a' } ), prop2 = new Properties( { name: 'b' } ); view.set( { listProperties: prop1, windowProperties: prop2 } ); ok( _.size( view._relations ) === 2 ); ok( _.size( prop1._relations ) === 1 ); ok( view.get( 'listProperties' ).get( 'name' ) === 'a' ); ok( view.get( 'windowProperties' ).get( 'name' ) === 'b' ); }); module( "Backbone.Relation general", { setup: reset } ); test( "Only valid models (no validation failure) should be added to a relation", function() { var zoo = new Zoo(); zoo.on( 'add:animals', function( animal ) { ok( animal instanceof Animal ); }); var smallElephant = new Animal( { name: 'Jumbo', species: 'elephant', weight: 2000, livesIn: zoo } ); equal( zoo.get( 'animals' ).length, 1, "Just 1 elephant in the zoo" ); // should fail validation, so it shouldn't be added zoo.get( 'animals' ).add( { name: 'Big guy', species: 'elephant', weight: 13000 }, { validate: true } ); equal( zoo.get( 'animals' ).length, 1, "Still just 1 elephant in the zoo" ); }); test( "Updating (retrieving) a model keeps relation consistency intact", function() { var zoo = new Zoo(); var lion = new Animal({ species: 'Lion', livesIn: zoo }); equal( zoo.get( 'animals' ).length, 1 ); lion.set({ id: 5, species: 'Lion', livesIn: zoo }); equal( zoo.get( 'animals' ).length, 1 ); zoo.set({ name: 'Dierenpark Amersfoort', animals: [ 5 ] }); equal( zoo.get( 'animals' ).length, 1 ); ok( zoo.get( 'animals' ).at( 0 ) === lion, "lion is in zoo" ); ok( lion.get( 'livesIn' ) === zoo ); var elephant = new Animal({ species: 'Elephant', livesIn: zoo }); equal( zoo.get( 'animals' ).length, 2 ); ok( elephant.get( 'livesIn' ) === zoo ); zoo.set({ id: 2 }); equal( zoo.get( 'animals' ).length, 2 ); ok( lion.get( 'livesIn' ) === zoo ); ok( elephant.get( 'livesIn' ) === zoo ); }); test( "Setting id on objects with reverse relations updates related collection correctly", function() { var zoo1 = new Zoo(); ok( zoo1.get( 'animals' ).size() === 0, "zoo has no animals" ); var lion = new Animal( { livesIn: 2 } ); zoo1.set( 'id', 2 ); ok( lion.get( 'livesIn' ) === zoo1, "zoo1 connected to lion" ); ok( zoo1.get( 'animals' ).length === 1, "zoo1 has one Animal" ); ok( zoo1.get( 'animals' ).at( 0 ) === lion, "lion added to zoo1" ); ok( zoo1.get( 'animals' ).get( lion ) === lion, "lion can be retrieved from zoo1" ); lion.set( { id: 5, livesIn: 2 } ); ok( lion.get( 'livesIn' ) === zoo1, "zoo1 connected to lion" ); ok( zoo1.get( 'animals' ).length === 1, "zoo1 has one Animal" ); ok( zoo1.get( 'animals' ).at( 0 ) === lion, "lion added to zoo1" ); ok( zoo1.get( 'animals' ).get( lion ) === lion, "lion can be retrieved from zoo1" ); // Other way around var elephant = new Animal( { id: 6 } ), tiger = new Animal( { id: 7 } ), zoo2 = new Zoo( { animals: [ 6 ] } ); ok( elephant.get( 'livesIn' ) === zoo2, "zoo2 connected to elephant" ); ok( zoo2.get( 'animals' ).length === 1, "zoo2 has one Animal" ); ok( zoo2.get( 'animals' ).at( 0 ) === elephant, "elephant added to zoo2" ); ok( zoo2.get( 'animals' ).get( elephant ) === elephant, "elephant can be retrieved from zoo2" ); zoo2.set( { id: 5, animals: [ 6, 7 ] } ); ok( elephant.get( 'livesIn' ) === zoo2, "zoo2 connected to elephant" ); ok( tiger.get( 'livesIn' ) === zoo2, "zoo2 connected to tiger" ); ok( zoo2.get( 'animals' ).length === 2, "zoo2 has one Animal" ); ok( zoo2.get( 'animals' ).at( 0 ) === elephant, "elephant added to zoo2" ); ok( zoo2.get( 'animals' ).at( 1 ) === tiger, "tiger added to zoo2" ); ok( zoo2.get( 'animals' ).get( elephant ) === elephant, "elephant can be retrieved from zoo2" ); ok( zoo2.get( 'animals' ).get( tiger ) === tiger, "tiger can be retrieved from zoo2" ); }); test( "Collections can be passed as attributes on creation", function() { var animals = new AnimalCollection([ { id: 1, species: 'Lion' }, { id: 2 ,species: 'Zebra' } ]); var zoo = new Zoo( { animals: animals } ); equal( zoo.get( 'animals' ), animals, "The 'animals' collection has been set as the zoo's animals" ); equal( zoo.get( 'animals' ).length, 2, "Two animals in 'zoo'" ); zoo.destroy(); var newZoo = new Zoo( { animals: animals.models } ); ok( newZoo.get( 'animals' ).length === 2, "Two animals in the 'newZoo'" ); }); test( "Models can be passed as attributes on creation", function() { var artis = new Zoo( { name: 'Artis' } ); var animal = new Animal( { species: 'Hippo', livesIn: artis }); equal( artis.get( 'animals' ).at( 0 ), animal, "Artis has a Hippo" ); equal( animal.get( 'livesIn' ), artis, "The Hippo is in Artis" ); }); test( "id checking handles `undefined`, `null`, `0` ids properly", function() { var parent = new Node(); var child = new Node( { parent: parent } ); ok( child.get( 'parent' ) === parent ); parent.destroy(); ok( child.get( 'parent' ) === null, child.get( 'parent' ) + ' === null' ); // It used to be the case that `randomOtherNode` became `child`s parent here, since both the `parent.id` // (which is stored as the relation's `keyContents`) and `randomOtherNode.id` were undefined. var randomOtherNode = new Node(); ok( child.get( 'parent' ) === null, child.get( 'parent' ) + ' === null' ); // Create a child with parent id=0, then create the parent child = new Node( { parent: 0 } ); ok( child.get( 'parent' ) === null, child.get( 'parent' ) + ' === null' ); parent = new Node( { id: 0 } ); ok( child.get( 'parent' ) === parent ); child.destroy(); parent.destroy(); // The other way around; create the parent with id=0, then the child parent = new Node( { id: 0 } ); equal( parent.get( 'children' ).length, 0 ); child = new Node( { parent: 0 } ); ok( child.get( 'parent' ) === parent ); }); test( "Relations are not affected by `silent: true`", function() { var ceo = new Person( { id: 1 } ); var company = new Company( { employees: [ { id: 2 }, { id: 3 }, 4 ], ceo: 1 }, { silent: true } ), employees = company.get( 'employees' ), employee = employees.first(); ok( company.get( 'ceo' ) === ceo ); ok( employees instanceof Backbone.Collection ); equal( employees.length, 2 ); employee.set( 'company', null, { silent: true } ); equal( employees.length, 1 ); employees.add( employee, { silent: true } ); ok( employee.get( 'company' ) === company ); ceo.set( 'runs', null, { silent: true } ); ok( !company.get( 'ceo' ) ); var employee4 = new Job( { id: 4 } ); equal( employees.length, 3 ); }); test( "Repeated model initialization and a collection should not break existing models", function () { var dataCompanyA = { id: 'company-a', name: 'Big Corp.', employees: [ { id: 'job-a' }, { id: 'job-b' } ] }; var dataCompanyB = { id: 'company-b', name: 'Small Corp.', employees: [] }; var companyA = new Company( dataCompanyA ); // Attempting to instantiate another model with the same data will throw an error raises( function() { new Company( dataCompanyA ); }, "Can only instantiate one model for a given `id` (per model type)" ); // init-ed a lead and its nested contacts are a collection ok( companyA.get('employees') instanceof Backbone.Collection, "Company's employees should be a collection" ); equal(companyA.get('employees').length, 2, 'with elements'); var CompanyCollection = Backbone.Collection.extend({ model: Company }); var companyCollection = new CompanyCollection( [ dataCompanyA, dataCompanyB ] ); // After loading a collection with models of the same type // the existing company should still have correct collections ok( companyCollection.get( dataCompanyA.id ) === companyA ); ok( companyA.get('employees') instanceof Backbone.Collection, "Company's employees should still be a collection" ); equal( companyA.get('employees').length, 2, 'with elements' ); }); test( "Destroy removes models from (non-reverse) relations", function() { var agent = new Agent( { id: 1, customers: [ 2, 3, 4 ], address: { city: 'Utrecht' } } ); var c2 = new Customer( { id: 2 } ); var c3 = new Customer( { id: 3 } ); var c4 = new Customer( { id: 4 } ); ok( agent.get( 'customers' ).length === 3 ); c2.destroy(); ok( agent.get( 'customers' ).length === 2 ); ok( agent.get( 'customers' ).get( c3 ) === c3 ); ok( agent.get( 'customers' ).get( c4 ) === c4 ); agent.get( 'customers' ).remove( c3 ); ok( agent.get( 'customers' ).length === 1 ); ok( agent.get( 'address' ) instanceof Address ); agent.get( 'address' ).destroy(); ok( !agent.get( 'address' ) ); agent.destroy(); equal( agent.get( 'customers' ).length, 0 ); }); test( "If keySource is used don't remove a model that is present in the key attribute", function() { var ForumPost = Backbone.RelationalModel.extend({ // Normally would set something here, not needed for test }); var ForumPostCollection = Backbone.Collection.extend({ model: ForumPost }); var Forum = Backbone.RelationalModel.extend({ relations: [{ type: Backbone.HasMany, key: 'posts', relatedModel: ForumPost, collectionType: ForumPostCollection, reverseRelation: { key: 'forum', keySource: 'forum_id' } }] }); var TestPost = new ForumPost({ id: 1, title: "Hello World", forum: {id: 1, title: "Cupcakes"} }); var TestForum = Forum.findOrCreate(1); notEqual( TestPost.get('forum'), null, "The post's forum is not null" ); equal( TestPost.get('forum').get('title'), "Cupcakes", "The post's forum title is Cupcakes" ); equal( TestForum.get('title'), "Cupcakes", "A forum of id 1 has the title cupcakes" ); }); // GH-187 test( "Can pass related model in constructor", function() { var A = Backbone.RelationalModel.extend(); var B = Backbone.RelationalModel.extend({ relations: [{ type: Backbone.HasOne, key: 'a', keySource: 'a_id', relatedModel: A }] }); var a1 = new A({ id: 'a1' }); var b1 = new B(); b1.set( 'a', a1 ); ok( b1.get( 'a' ) instanceof A ); ok( b1.get( 'a' ).id == 'a1' ); var a2 = new A({ id: 'a2' }); var b2 = new B({ a: a2 }); ok( b2.get( 'a' ) instanceof A ); ok( b2.get( 'a' ).id == 'a2' ); }); module( "Backbone.HasOne", { setup: initObjects } ); test( "HasOne relations on Person are set up properly", function() { ok( person1.get('likesALot') === person2 ); equal( person1.get('user').id, 'user-1', "The id of 'person1's user is 'user-1'" ); ok( person2.get('likesALot') === person1 ); }); test( "Reverse HasOne relations on Person are set up properly", function() { ok( person1.get( 'likedALotBy' ) === person2 ); ok( person1.get( 'user' ).get( 'person' ) === person1, "The person belonging to 'person1's user is 'person1'" ); ok( person2.get( 'likedALotBy' ) === person1 ); }); test( "'set' triggers 'change' and 'update', on a HasOne relation, for a Model with multiple relations", 9, function() { // triggers initialization of the reverse relation from User to Password var password = new Password( { plaintext: 'asdf' } ); person1.on( 'change', function( model, options ) { ok( model.get( 'user' ) instanceof User, "In 'change', model.user is an instance of User" ); equal( model.previous( 'user' ).get( 'login' ), oldLogin, "previousAttributes is available on 'change'" ); }); person1.on( 'change:user', function( model, options ) { ok( model.get( 'user' ) instanceof User, "In 'change:user', model.user is an instance of User" ); equal( model.previous( 'user' ).get( 'login' ), oldLogin, "previousAttributes is available on 'change'" ); }); person1.on( 'change:user', function( model, attr, options ) { ok( model.get( 'user' ) instanceof User, "In 'change:user', model.user is an instance of User" ); ok( attr.get( 'person' ) === person1, "The user's 'person' is 'person1'" ); ok( attr.get( 'password' ) instanceof Password, "The user's password attribute is a model of type Password"); equal( attr.get( 'password' ).get( 'plaintext' ), 'qwerty', "The user's password is ''qwerty'" ); }); var user = { login: 'me@hotmail.com', password: { plaintext: 'qwerty' } }; var oldLogin = person1.get( 'user' ).get( 'login' ); // Triggers assertions for 'change' and 'change:user' person1.set( { user: user } ); user = person1.get( 'user' ).on( 'change:password', function( model, attr, options ) { equal( attr.get( 'plaintext' ), 'asdf', "The user's password is ''qwerty'" ); }); // Triggers assertions for 'change:user' user.set( { password: password } ); }); test( "'set' doesn't triggers 'change' and 'change:' when passed `silent: true`", 2, function() { person1.on( 'change', function( model, options ) { ok( false, "'change' should not get triggered" ); }); person1.on( 'change:user', function( model, attr, options ) { ok( false, "'change:user' should not get triggered" ); }); person1.on( 'change:user', function( model, attr, options ) { ok( false, "'change:user' should not get triggered" ); }); ok( person1.get( 'user' ) instanceof User, "person1 has a 'user'" ); var user = new User({ login: 'me@hotmail.com', password: { plaintext: 'qwerty' } }); person1.set( 'user', user, { silent: true } ); equal( person1.get( 'user' ), user ); }); test( "'unset' triggers 'change' and 'change:<key>'", 4, function() { person1.on( 'change', function( model, options ) { equal( model.get('user'), null, "model.user is unset" ); }); person1.on( 'change:user', function( model, attr, options ) { equal( attr, null, "new value of attr (user) is null" ); }); ok( person1.get( 'user' ) instanceof User, "person1 has a 'user'" ); var user = person1.get( 'user' ); person1.unset( 'user' ); equal( user.get( 'person' ), null, "person1 is not set on 'user' anymore" ); }); test( "'clear' triggers 'change' and 'change:<key>'", 4, function() { person1.on( 'change', function( model, options ) { equal( model.get('user'), null, "model.user is unset" ); }); person1.on( 'change:user', function( model, attr, options ) { equal( attr, null, "new value of attr (user) is null" ); }); ok( person1.get( 'user' ) instanceof User, "person1 has a 'user'" ); var user = person1.get( 'user' ); person1.clear(); equal( user.get( 'person' ), null, "person1 is not set on 'user' anymore" ); }); module( "Backbone.HasMany", { setup: initObjects } ); test( "Listeners on 'add'/'remove'", 7, function() { ourHouse .on( 'add:occupants', function( model, coll ) { ok( model === person1, "model === person1" ); }) .on( 'remove:occupants', function( model, coll ) { ok( model === person1, "model === person1" ); }); theirHouse .on( 'add:occupants', function( model, coll ) { ok( model === person1, "model === person1" ); }) .on( 'remove:occupants', function( model, coll ) { ok( model === person1, "model === person1" ); }); var count = 0; person1.on( 'change:livesIn', function( model, attr ) { if ( count === 0 ) { ok( attr === ourHouse, "model === ourHouse" ); } else if ( count === 1 ) { ok( attr === theirHouse, "model === theirHouse" ); } else if ( count === 2 ) { ok( attr === null, "model === null" ); } count++; }); ourHouse.get( 'occupants' ).add( person1 ); person1.set( { 'livesIn': theirHouse } ); theirHouse.get( 'occupants' ).remove( person1 ); }); test( "Listeners for 'add'/'remove', on a HasMany relation, for a Model with multiple relations", function() { var job1 = { company: oldCompany }; var job2 = { company: oldCompany, person: person1 }; var job3 = { person: person1 }; var newJob = null; newCompany.on( 'add:employees', function( model, coll ) { ok( false, "person1 should only be added to 'oldCompany'." ); }); // Assert that all relations on a Model are set up, before notifying related models. oldCompany.on( 'add:employees', function( model, coll ) { newJob = model; ok( model instanceof Job ); ok( model.get('company') instanceof Company && model.get('person') instanceof Person, "Both Person and Company are set on the Job instance" ); }); person1.on( 'add:jobs', function( model, coll ) { ok( model.get( 'company' ) === oldCompany && model.get( 'person' ) === person1, "Both Person and Company are set on the Job instance" ); }); // Add job1 and job2 to the 'Person' side of the relation var jobs = person1.get( 'jobs' ); jobs.add( job1 ); ok( jobs.length === 1, "jobs.length is 1" ); newJob.destroy(); ok( jobs.length === 0, "jobs.length is 0" ); jobs.add( job2 ); ok( jobs.length === 1, "jobs.length is 1" ); newJob.destroy(); ok( jobs.length === 0, "jobs.length is 0" ); // Add job1 and job2 to the 'Company' side of the relation var employees = oldCompany.get('employees'); employees.add( job3 ); ok( employees.length === 2, "employees.length is 2" ); newJob.destroy(); ok( employees.length === 1, "employees.length is 1" ); employees.add( job2 ); ok( employees.length === 2, "employees.length is 2" ); newJob.destroy(); ok( employees.length === 1, "employees.length is 1" ); // Create a stand-alone Job ;) new Job({ person: person1, company: oldCompany }); ok( jobs.length === 1 && employees.length === 2, "jobs.length is 1 and employees.length is 2" ); }); test( "The Collections used for HasMany relations are re-used if possible", function() { var collId = ourHouse.get( 'occupants' ).id = 1; ourHouse.get( 'occupants' ).add( person1 ); ok( ourHouse.get( 'occupants' ).id === collId ); // Set a value on 'occupants' that would cause the relation to be reset. // The collection itself should be kept (along with it's properties) ourHouse.set( { 'occupants': [ 'person-1' ] } ); ok( ourHouse.get( 'occupants' ).id === collId ); ok( ourHouse.get( 'occupants' ).length === 1 ); // Setting a new collection loses the original collection ourHouse.set( { 'occupants': new Backbone.Collection() } ); ok( ourHouse.get( 'occupants' ).id === undefined ); }); test( "On `set`, or creation, accept a collection or an array of ids/objects/models", function() { // Handle an array of ids var visitor1 = new Visitor( { id: 'visitor-1', name: 'Mr. Pink' } ), visitor2 = new Visitor( { id: 'visitor-2' } ); var zoo = new Zoo( { visitors: [ 'visitor-1', 'visitor-3' ] } ), visitors = zoo.get( 'visitors' ); equal( visitors.length, 1 ); var visitor3 = new Visitor( { id: 'visitor-3' } ); equal( visitors.length, 2 ); zoo.set( 'visitors', [ { name: 'Incognito' } ] ); equal( visitors.length, 1 ); zoo.set( 'visitors', [] ); equal( visitors.length, 0 ); // Handle an array of objects zoo = new Zoo( { visitors: [ { id: 'visitor-1' }, { id: 'visitor-4' } ] } ); visitors = zoo.get( 'visitors' ); equal( visitors.length, 2 ); equal( visitors.get( 'visitor-1' ).get( 'name' ), 'Mr. Pink', 'visitor-1 is Mr. Pink' ); zoo.set( 'visitors', [ { id: 'visitor-1' }, { id: 'visitor-5' } ] ); equal( visitors.length, 2 ); // Handle an array of models zoo = new Zoo( { visitors: [ visitor1 ] } ); visitors = zoo.get( 'visitors' ); equal( visitors.length, 1 ); ok( visitors.first() === visitor1 ); zoo.set( 'visitors', [ visitor2 ] ); equal( visitors.length, 1 ); ok( visitors.first() === visitor2 ); // Handle a Collection var visitorColl = new Backbone.Collection( [ visitor1, visitor2 ] ); zoo = new Zoo( { visitors: visitorColl } ); visitors = zoo.get( 'visitors' ); equal( visitors.length, 2 ); zoo.set( 'visitors', false ); equal( visitors.length, 0 ); visitorColl = new Backbone.Collection( [ visitor2 ] ); zoo.set( 'visitors', visitorColl ); ok( visitorColl === zoo.get( 'visitors' ) ); equal( zoo.get( 'visitors' ).length, 1 ); }); test( "On `set`, or creation, handle edge-cases where the server supplies a single object/id", function() { // Handle single objects var zoo = new Zoo({ animals: { id: 'lion-1' } }); var animals = zoo.get( 'animals' ); equal( animals.length, 1, "There is 1 animal in the zoo" ); zoo.set( 'animals', { id: 'lion-2' } ); equal( animals.length, 1, "There is 1 animal in the zoo" ); // Handle single models var lion3 = new Animal( { id: 'lion-3' } ); zoo = new Zoo({ animals: lion3 }); animals = zoo.get( 'animals' ); equal( animals.length, 1, "There is 1 animal in the zoo" ); zoo.set( 'animals', null ); equal( animals.length, 0, "No animals in the zoo" ); zoo.set( 'animals', lion3 ); equal( animals.length, 1, "There is 1 animal in the zoo" ); // Handle single ids zoo = new Zoo({ animals: 'lion-4' }); animals = zoo.get( 'animals' ); equal( animals.length, 0, "No animals in the zoo" ); var lion4 = new Animal( { id: 'lion-4' } ); equal( animals.length, 1, "There is 1 animal in the zoo" ); zoo.set( 'animals', 'lion-5' ); equal( animals.length, 0, "No animals in the zoo" ); var lion5 = new Animal( { id: 'lion-5' } ); equal( animals.length, 1, "There is 1 animal in the zoo" ); zoo.set( 'animals', null ); equal( animals.length, 0, "No animals in the zoo" ); zoo = new Zoo({ animals: 'lion-4' }); animals = zoo.get( 'animals' ); equal( animals.length, 1, "There is 1 animal in the zoo" ); // Bulletproof? zoo = new Zoo({ animals: '' }); animals = zoo.get( 'animals' ); ok( animals instanceof AnimalCollection ); equal( animals.length, 0, "No animals in the zoo" ); }); test( "Setting a custom collection in 'collectionType' uses that collection for instantiation", function() { var zoo = new Zoo(); // Set values so that the relation gets filled zoo.set({ animals: [ { species: 'Lion' }, { species: 'Zebra' } ] }); // Check that the animals were created ok( zoo.get( 'animals' ).at( 0 ).get( 'species' ) === 'Lion' ); ok( zoo.get( 'animals' ).at( 1 ).get( 'species' ) === 'Zebra' ); // Check that the generated collection is of the correct kind ok( zoo.get( 'animals' ) instanceof AnimalCollection ); }); test( "Setting a new collection maintains that collection's current 'models'", function() { var zoo = new Zoo(); var animals = new AnimalCollection([ { id: 1, species: 'Lion' }, { id: 2 ,species: 'Zebra' } ]); zoo.set( 'animals', animals ); equal( zoo.get( 'animals' ).length, 2 ); var newAnimals = new AnimalCollection([ { id: 2, species: 'Zebra' }, { id: 3, species: 'Elephant' }, { id: 4, species: 'Tiger' } ]); zoo.set( 'animals', newAnimals ); equal( zoo.get( 'animals' ).length, 3 ); }); test( "Models found in 'findRelated' are all added in one go (so 'sort' will only be called once)", function() { var count = 0, sort = Backbone.Collection.prototype.sort; Backbone.Collection.prototype.sort = function() { count++; }; AnimalCollection.prototype.comparator = $.noop; var zoo = new Zoo({ animals: [ { id: 1, species: 'Lion' }, { id: 2 ,species: 'Zebra' } ] }); equal( count, 1, "Sort is called only once" ); Backbone.Collection.prototype.sort = sort; delete AnimalCollection.prototype.comparator; }); test( "Raw-models set to a hasMany relation do trigger an add event in the underlying Collection with a correct index", function() { var zoo = new Zoo(); var indexes = []; zoo.get( 'animals' ).on( 'add', function( model, collection, options ) { var index = collection.indexOf( model ); indexes.push(index); }); zoo.set( 'animals', [ { id : 1, species : 'Lion' }, { id : 2, species : 'Zebra' } ]); equal( indexes[0], 0, "First item has index 0" ); equal( indexes[1], 1, "Second item has index 1" ); }); test( "Models set to a hasMany relation do trigger an add event in the underlying Collection with a correct index", function() { var zoo = new Zoo(); var indexes = []; zoo.get("animals").on("add", function(model, collection, options) { var index = collection.indexOf(model); indexes.push(index); }); zoo.set("animals", [ new Animal({ id : 1, species : 'Lion' }), new Animal({ id : 2, species : 'Zebra'}) ]); equal( indexes[0], 0, "First item has index 0" ); equal( indexes[1], 1, "Second item has index 1" ); }); test( "Sort event should be fired after the add event that caused it, even when using 'set'", function() { var zoo = new Zoo(); var animals = zoo.get('animals'); var events = []; animals.comparator = 'id'; animals.on('add', function() { events.push('add'); }); animals.on('sort', function() { events.push('sort'); }); zoo.set('animals' , [ {id : 'lion-2'}, {id : 'lion-1'} ]); equal(animals.at(0).id, 'lion-1'); deepEqual(events, ['add', 'sort', 'add', 'sort']); }); test( "The 'collectionKey' options is used to create references on generated Collections back to its RelationalModel", function() { var zoo = new Zoo({ animals: [ 'lion-1', 'zebra-1' ] }); equal( zoo.get( 'animals' ).livesIn, zoo ); equal( zoo.get( 'animals' ).zoo, undefined ); var FarmAnimal = Backbone.RelationalModel.extend(); var Barn = Backbone.RelationalModel.extend({ relations: [{ type: Backbone.HasMany, key: 'animals', relatedModel: FarmAnimal, collectionKey: 'barn', reverseRelation: { key: 'livesIn', includeInJSON: 'id' } }] }); var barn = new Barn({ animals: [ 'chicken-1', 'cow-1' ] }); equal( barn.get( 'animals' ).livesIn, undefined ); equal( barn.get( 'animals' ).barn, barn ); FarmAnimal = Backbone.RelationalModel.extend(); var BarnNoKey = Backbone.RelationalModel.extend({ relations: [{ type: Backbone.HasMany, key: 'animals', relatedModel: FarmAnimal, collectionKey: false, reverseRelation: { key: 'livesIn', includeInJSON: 'id' } }] }); var barnNoKey = new BarnNoKey({ animals: [ 'chicken-1', 'cow-1' ] }); equal( barnNoKey.get( 'animals' ).livesIn, undefined ); equal( barnNoKey.get( 'animals' ).barn, undefined ); }); test( "Polymorhpic relations", function() { var Location = Backbone.RelationalModel.extend(); var Locatable = Backbone.RelationalModel.extend({ relations: [ { key: 'locations', type: 'HasMany', relatedModel: Location, reverseRelation: { key: 'locatable' } } ] }); var FirstLocatable = Locatable.extend(); var SecondLocatable = Locatable.extend(); var firstLocatable = new FirstLocatable(); var secondLocatable = new SecondLocatable(); var firstLocation = new Location( { id: 1, locatable: firstLocatable } ); var secondLocation = new Location( { id: 2, locatable: secondLocatable } ); ok( firstLocatable.get( 'locations' ).at( 0 ) === firstLocation ); ok( firstLocatable.get( 'locations' ).at( 0 ).get( 'locatable' ) === firstLocatable ); ok( secondLocatable.get( 'locations' ).at( 0 ) === secondLocation ); ok( secondLocatable.get( 'locations' ).at( 0 ).get( 'locatable' ) === secondLocatable ); }); test( "Cloned instances of persisted models should not be added to any existing collections", function() { var addedModels = 0; var zoo = new window.Zoo({ visitors : [ { name : "Incognito" } ] }); var visitor = new window.Visitor(); zoo.get( 'visitors' ).on( 'add', function( model, coll ) { addedModels++; }); visitor.clone(); equal( addedModels, 0, "A new visitor should not be forced to go to the zoo!" ); }); module( "Reverse relations", { setup: initObjects } ); test( "Add and remove", function() { equal( ourHouse.get( 'occupants' ).length, 1, "ourHouse has 1 occupant" ); equal( person1.get( 'livesIn' ), null, "Person 1 doesn't live anywhere" ); ourHouse.get( 'occupants' ).add( person1 ); equal( ourHouse.get( 'occupants' ).length, 2, "Our House has 2 occupants" ); equal( person1.get( 'livesIn' ) && person1.get('livesIn').id, ourHouse.id, "Person 1 lives in ourHouse" ); person1.set( { 'livesIn': theirHouse } ); equal( theirHouse.get( 'occupants' ).length, 1, "theirHouse has 1 occupant" ); equal( ourHouse.get( 'occupants' ).length, 1, "ourHouse has 1 occupant" ); equal( person1.get( 'livesIn' ) && person1.get('livesIn').id, theirHouse.id, "Person 1 lives in theirHouse" ); }); test( "Destroy removes models from reverse relations", function() { var zoo = new Zoo( { id:1, animals: [ 2, 3, 4 ] } ); var rhino = new Animal( { id: 2, species: 'rhino' } ); var baboon = new Animal( { id: 3, species: 'baboon' } ); var hippo = new Animal( { id: 4, species: 'hippo' } ); ok( zoo.get( 'animals' ).length === 3 ); rhino.destroy(); ok( zoo.get( 'animals' ).length === 2 ); ok( zoo.get( 'animals' ).get( baboon ) === baboon ); ok( !rhino.get( 'zoo' ) ); zoo.get( 'animals' ).remove( hippo ); ok( zoo.get( 'animals' ).length === 1 ); ok( !hippo.get( 'zoo' ) ); zoo.destroy(); ok( zoo.get( 'animals' ).length === 0 ); ok( !baboon.get( 'zoo' ) ); }); test( "HasOne relations to self (tree stucture)", function() { var child1 = new Node({ id: '2', parent: '1', name: 'First child' }); var parent = new Node({ id: '1', name: 'Parent' }); var child2 = new Node({ id: '3', parent: '1', name: 'Second child' }); equal( parent.get( 'children' ).length, 2 ); ok( parent.get( 'children' ).include( child1 ) ); ok( parent.get( 'children' ).include( child2 ) ); ok( child1.get( 'parent' ) === parent ); equal( child1.get( 'children' ).length, 0 ); ok( child2.get( 'parent' ) === parent ); equal( child2.get( 'children' ).length, 0 ); }); test( "Models referencing each other in the same relation", function() { var parent = new Node({ id: 1 }); var child = new Node({ id: 2 }); child.set( 'parent', parent ); parent.save( { 'parent': child } ); ok( parent.get( 'parent' ) === child ); ok( child.get( 'parent' ) === parent ); }); test( "HasMany relations to self (tree structure)", function() { var child1 = new Node({ id: '2', name: 'First child' }); var parent = new Node({ id: '1', children: [ '2', '3' ], name: 'Parent' }); var child2 = new Node({ id: '3', name: 'Second child' }); equal( parent.get( 'children' ).length, 2 ); ok( parent.get( 'children' ).include( child1 ) ); ok( parent.get( 'children' ).include( child2 ) ); ok( child1.get( 'parent' ) === parent ); equal( child1.get( 'children' ).length, 0 ); ok( child2.get( 'parent' ) === parent ); equal( child2.get( 'children' ).length, 0 ); }); test( "HasOne relations to self (cycle, directed graph structure)", function() { var node1 = new Node({ id: '1', parent: '3', name: 'First node' }); var node2 = new Node({ id: '2', parent: '1', name: 'Second node' }); var node3 = new Node({ id: '3', parent: '2', name: 'Third node' }); ok( node1.get( 'parent' ) === node3 ); equal( node1.get( 'children' ).length, 1 ); ok( node1.get( 'children' ).at(0) === node2 ); ok( node2.get( 'parent' ) === node1 ); equal( node2.get( 'children' ).length, 1 ); ok( node2.get( 'children' ).at(0) === node3 ); ok( node3.get( 'parent' ) === node2 ); equal( node3.get( 'children' ).length, 1 ); ok( node3.get( 'children' ).at(0) === node1 ); }); test( "New objects (no 'id' yet) have working relations", function() { var person = new Person({ name: 'Remi' }); person.set( { user: { login: '1', email: '1' } } ); var user1 = person.get( 'user' ); ok( user1 instanceof User, "User created on Person" ); equal( user1.get('login'), '1', "person.user is the correct User" ); var user2 = new User({ login: '2', email: '2' }); ok( user2.get( 'person' ) === null, "'user' doesn't belong to a 'person' yet" ); person.set( { user: user2 } ); ok( user1.get( 'person' ) === null ); ok( person.get( 'user' ) === user2 ); ok( user2.get( 'person' ) === person ); person2.set( { user: user2 } ); ok( person.get( 'user' ) === null ); ok( person2.get( 'user' ) === user2 ); ok( user2.get( 'person' ) === person2 ); }); test( "'Save' objects (performing 'set' multiple times without and with id)", 4, function() { person3 .on( 'add:jobs', function( model, coll ) { var company = model.get('company'); ok( company instanceof Company && company.get('ceo').get('name') === 'Lunar boy' && model.get('person') === person3, "add:jobs: Both Person and Company are set on the Job instance once the event gets fired" ); }) .on( 'remove:jobs', function( model, coll ) { ok( false, "remove:jobs: 'person3' should not lose his job" ); }); // Create Models from an object. Should trigger `add:jobs` on `person3` var company = new Company({ name: 'Luna Corp.', ceo: { name: 'Lunar boy' }, employees: [ { person: 'person-3' } ] }); company .on( 'add:employees', function( model, coll ) { var company = model.get('company'); ok( company instanceof Company && company.get('ceo').get('name') === 'Lunar boy' && model.get('person') === person3, "add:employees: Both Person and Company are set on the Company instance once the event gets fired" ); }) .on( 'remove:employees', function( model, coll ) { ok( true, "'remove:employees: person3' should lose a job once" ); }); // Backbone.save executes "model.set(model.parse(resp), options)". Set a full map over object, but now with ids. // Should trigger `remove:employees`, `add:employees`, and `add:jobs` company.set({ id: 'company-3', name: 'Big Corp.', ceo: { id: 'person-4', name: 'Lunar boy', resource_uri: 'person-4' }, employees: [ { id: 'job-1', person: 'person-3', resource_uri: 'job-1' } ], resource_uri: 'company-3' }); // This should not trigger additional `add`/`remove` events company.set({ employees: [ 'job-1' ] }); }); test( "Set the same value a couple of time, by 'id' and object", function() { person1.set( { likesALot: 'person-2' } ); person1.set( { likesALot: person2 } ); ok( person1.get('likesALot') === person2 ); ok( person2.get('likedALotBy' ) === person1 ); person1.set( { likesALot: 'person-2' } ); ok( person1.get('likesALot') === person2 ); ok( person2.get('likedALotBy' ) === person1 ); }); test( "Numerical keys", function() { var child1 = new Node({ id: 2, name: 'First child' }); var parent = new Node({ id: 1, children: [2, 3], name: 'Parent' }); var child2 = new Node({ id: 3, name: 'Second child' }); equal( parent.get('children').length, 2 ); ok( parent.get('children').include( child1 ) ); ok( parent.get('children').include( child2 ) ); ok( child1.get('parent') === parent ); equal( child1.get('children').length, 0 ); ok( child2.get('parent') === parent ); equal( child2.get('children').length, 0 ); }); test( "Relations that use refs to other models (instead of keys)", function() { var child1 = new Node({ id: 2, name: 'First child' }); var parent = new Node({ id: 1, children: [child1, 3], name: 'Parent' }); var child2 = new Node({ id: 3, name: 'Second child' }); ok( child1.get('parent') === parent ); equal( child1.get('children').length, 0 ); equal( parent.get('children').length, 2 ); ok( parent.get('children').include( child1 ) ); ok( parent.get('children').include( child2 ) ); var child3 = new Node({ id: 4, parent: parent, name: 'Second child' }); equal( parent.get('children').length, 3 ); ok( parent.get('children').include( child3 ) ); ok( child3.get('parent') === parent ); equal( child3.get('children').length, 0 ); }); test( "Add an already existing model (reverseRelation shouldn't exist yet) to a relation as a hash", function() { // This test caused a race condition to surface: // The 'relation's constructor initializes the 'reverseRelation', which called 'relation.addRelated' in it's 'initialize'. // However, 'relation's 'initialize' has not been executed yet, so it doesn't have a 'related' collection yet. var Properties = Backbone.RelationalModel.extend({}); var View = Backbone.RelationalModel.extend({ relations: [ { type: Backbone.HasMany, key: 'properties', relatedModel: Properties, reverseRelation: { type: Backbone.HasOne, key: 'view' } } ] }); var props = new Properties( { id: 1, key: 'width', value: '300px', view: 1 } ); var view = new View({ id: 1, properties: [ { id: 1, key: 'width', value: '300px', view: 1 } ] }); ok( props.get( 'view' ) === view ); ok( view.get( 'properties' ).include( props ) ); }); test( "Reverse relations are found for models that have not been instantiated and use .extend()", function() { var View = Backbone.RelationalModel.extend({ }); var Property = Backbone.RelationalModel.extend({ relations: [{ type: Backbone.HasOne, key: 'view', relatedModel: View, reverseRelation: { type: Backbone.HasMany, key: 'properties' } }] }); var view = new View({ id: 1, properties: [ { id: 1, key: 'width', value: '300px' } ] }); ok( view.get( 'properties' ) instanceof Backbone.Collection ); }); test( "Reverse relations found for models that have not been instantiated and run .setup() manually", function() { // Generated from CoffeeScript code: // class View extends Backbone.RelationalModel // // View.setup() // // class Property extends Backbone.RelationalModel // relations: [ // type: Backbone.HasOne // key: 'view' // relatedModel: View // reverseRelation: // type: Backbone.HasMany // key: 'properties' // ] // // Property.setup() var Property, View, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; }; View = ( function( _super ) { __extends(View, _super); View.name = 'View'; function View() { return View.__super__.constructor.apply( this, arguments ); } return View; })( Backbone.RelationalModel ); View.setup(); Property = (function(_super) { __extends(Property, _super); Property.name = 'Property'; function Property() { return Property.__super__.constructor.apply(this, arguments); } Property.prototype.relations = [{ type: Backbone.HasOne, key: 'view', relatedModel: View, reverseRelation: { type: Backbone.HasMany, key: 'properties' } }]; return Property; })(Backbone.RelationalModel); Property.setup(); var view = new View({ id: 1, properties: [ { id: 1, key: 'width', value: '300px' } ] }); ok( view.get( 'properties' ) instanceof Backbone.Collection ); }); test( "ReverseRelations are applied retroactively", function() { // Use brand new Model types, so we can be sure we don't have any reverse relations cached from previous tests var NewUser = Backbone.RelationalModel.extend({}); var NewPerson = Backbone.RelationalModel.extend({ relations: [{ type: Backbone.HasOne, key: 'user', relatedModel: NewUser, reverseRelation: { type: Backbone.HasOne, key: 'person' } }] }); var user = new NewUser( { id: 'newuser-1' } ); //var user2 = new NewUser( { id: 'newuser-2', person: 'newperson-1' } ); var person = new NewPerson( { id: 'newperson-1', user: user } ); ok( person.get('user') === user ); ok( user.get('person') === person ); //console.log( person, user ); }); test( "ReverseRelations are applied retroactively (2)", function() { var models = {}; Backbone.Relational.store.addModelScope( models ); // Use brand new Model types, so we can be sure we don't have any reverse relations cached from previous tests models.NewPerson = Backbone.RelationalModel.extend({ relations: [{ type: Backbone.HasOne, key: 'user', relatedModel: 'NewUser', reverseRelation: { type: Backbone.HasOne, key: 'person' } }] }); models.NewUser = Backbone.RelationalModel.extend({}); var user = new models.NewUser( { id: 'newuser-1', person: { id: 'newperson-1' } } ); equal( user.getRelations().length, 1 ); ok( user.get( 'person' ) instanceof models.NewPerson ); }); test( "Deep reverse relation starting from a collection", function() { var nodes = new NodeList([ { id: 1, children: [ { id: 2, children: [ { id: 3, children: [ 1 ] } ] } ] } ]); var parent = nodes.first(); ok( parent, 'first item accessible after resetting collection' ); ok( parent.collection === nodes, '`parent.collection` is set to `nodes`' ); var child = parent.get( 'children' ).first(); ok( child, '`child` can be retrieved from `parent`' ); ok( child.get( 'parent' ), 'reverse relation from `child` to `parent` works'); var grandchild = child.get( 'children' ).first(); ok( grandchild, '`grandchild` can be retrieved from `child`' ); ok( grandchild.get( 'parent' ), 'reverse relation from `grandchild` to `child` works'); ok( grandchild.get( 'children' ).first() === parent, 'reverse relation from `grandchild` to `parent` works'); ok( parent.get( 'parent' ) === grandchild, 'circular reference from `grandchild` to `parent` works' ); }); test( "Deep reverse relation starting from a collection, with existing model", function() { new Node( { id: 1 } ); var nodes = new NodeList(); nodes.set([ { id: 1, children: [ { id: 2, children: [ { id: 3, children: [ 1 ] } ] } ] } ]); var parent = nodes.first(); ok( parent && parent.id === 1, 'first item accessible after resetting collection' ); var child = parent.get( 'children' ).first(); ok( child, '`child` can be retrieved from `parent`' ); ok( child.get( 'parent' ), 'reverse relation from `child` to `parent` works'); var grandchild = child.get( 'children' ).first(); ok( grandchild, '`grandchild` can be retrieved from `child`' ); ok( grandchild.get( 'parent' ), 'reverse relation from `grandchild` to `child` works'); ok( grandchild.get( 'children' ).first() === parent, 'reverse relation from `grandchild` to `parent` works'); ok( parent.get( 'parent' ) === grandchild, 'circular reference from `grandchild` to `parent` works' ); }); module( "Backbone.Collection", { setup: reset } ); test( "Loading (fetching) multiple times updates the model, and relations's `keyContents`", function() { var collA = new Backbone.Collection(); collA.model = User; var collB = new Backbone.Collection(); collB.model = User; // Similar to what happens when calling 'fetch' on collA, updating it, calling 'fetch' on collB var name = 'User 1'; collA.add( { id: '/user/1/', name: name } ); var user = collA.at( 0 ); equal( user.get( 'name' ), name ); // The 'name' of 'user' is updated when adding a new hash to the collection name = 'New name'; collA.add( { id: '/user/1/', name: name }, { merge: true } ); var updatedUser = collA.at( 0 ); equal( user.get( 'name' ), name ); equal( updatedUser.get( 'name' ), name ); // The 'name' of 'user' is also updated when adding a new hash to another collection name = 'Another new name'; collB.add( { id: '/user/1/', name: name, title: 'Superuser' }, { merge: true } ); var updatedUser2 = collA.at( 0 ); equal( user.get( 'name' ), name ); equal( updatedUser2.get('name'), name ); //console.log( collA.models, collA.get( '/user/1/' ), user, updatedUser, updatedUser2 ); ok( collA.get( '/user/1/' ) === updatedUser ); ok( collA.get( '/user/1/' ) === updatedUser2 ); ok( collB.get( '/user/1/' ) === user ); }); test( "Loading (fetching) a collection multiple times updates related models as well (HasOne)", function() { var coll = new PersonCollection(); coll.add( { id: 'person-10', name: 'Person', user: { id: 'user-10', login: 'User' } } ); var person = coll.at( 0 ); var user = person.get( 'user' ); equal( user.get( 'login' ), 'User' ); coll.add( { id: 'person-10', name: 'New person', user: { id: 'user-10', login: 'New user' } }, { merge: true } ); equal( person.get( 'name' ), 'New person' ); equal( user.get( 'login' ), 'New user' ); }); test( "Loading (fetching) a collection multiple times updates related models as well (HasMany)", function() { var coll = new Backbone.Collection(); coll.model = Zoo; // Create a 'zoo' with 1 animal in it coll.add( { id: 'zoo-1', name: 'Zoo', animals: [ { id: 'lion-1', name: 'Mufasa' } ] } ); var zoo = coll.at( 0 ); var lion = zoo.get( 'animals' ) .at( 0 ); equal( lion.get( 'name' ), 'Mufasa' ); // Update the name of 'zoo' and 'lion' coll.add( { id: 'zoo-1', name: 'Zoo Station', animals: [ { id: 'lion-1', name: 'Simba' } ] }, { merge: true } ); equal( zoo.get( 'name' ), 'Zoo Station' ); equal( lion.get( 'name' ), 'Simba' ); }); test( "reset should use `merge: true` by default", function() { var nodeList = new NodeList(); nodeList.add( [ { id: 1 }, { id: 2, parent: 1 } ] ); var node1 = nodeList.get( 1 ), node2 = nodeList.get( 2 ); ok( node2.get( 'parent' ) === node1 ); ok( !node1.get( 'parent' ) ); nodeList.reset( [ { id: 1, parent: 2 } ] ); ok( node1.get( 'parent' ) === node2 ); }); test( "add/remove/update (with `add`, `remove` and `merge` options)", function() { var coll = new AnimalCollection(); /** * Add */ coll.add( { id: 1, species: 'giraffe' } ); ok( coll.length === 1 ); coll.add( { id: 1, species: 'giraffe' } ); ok( coll.length === 1 ); coll.add([ { id: 1, species: 'giraffe' }, { id: 2, species: 'gorilla' } ]); var giraffe = coll.get( 1 ), gorilla = coll.get( 2 ), dolphin = new Animal( { species: 'dolphin' } ), hippo = new Animal( { id: 4, species: 'hippo' } ); ok( coll.length === 2 ); coll.add( dolphin ); ok( coll.length === 3 ); // Update won't do anything coll.add( { id: 1, species: 'giraffe', name: 'Long John' } ); ok( !coll.get( 1 ).get( 'name' ), 'name=' + coll.get( 1 ).get( 'name' ) ); // Update with `merge: true` will update the animal coll.add( { id: 1, species: 'giraffe', name: 'Long John' }, { merge: true } ); ok( coll.get( 1 ).get( 'name' ) === 'Long John' ); /** * Remove */ coll.remove( 1 ); ok( coll.length === 2 ); ok( !coll.get( 1 ), "`giraffe` removed from coll" ); coll.remove( dolphin ); ok( coll.length === 1 ); ok( coll.get( 2 ) === gorilla, "Only `gorilla` is left in coll" ); /** * Update */ coll.add( giraffe ); // This shouldn't do much at all var options = { add: false, merge: false, remove: false }; coll.set( [ dolphin, { id: 2, name: 'Silverback' } ], options ); ok( coll.length === 2 ); ok( coll.get( 2 ) === gorilla, "`gorilla` is left in coll" ); ok( !coll.get( 2 ).get( 'name' ), "`gorilla` name not updated" ); // This should remove `giraffe`, add `hippo`, leave `dolphin`, and update `gorilla`. options = { add: true, merge: true, remove: true }; coll.set( [ 4, dolphin, { id: 2, name: 'Silverback' } ], options ); ok( coll.length === 3 ); ok( !coll.get( 1 ), "`giraffe` removed from coll" ); equal( coll.get( 2 ), gorilla ); ok( !coll.get( 3 ) ); equal( coll.get( 4 ), hippo ); equal( coll.get( dolphin ), dolphin ); equal( gorilla.get( 'name' ), 'Silverback' ); }); test( "add/remove/update on a relation (with `add`, `remove` and `merge` options)", function() { var zoo = new Zoo(), animals = zoo.get( 'animals' ), a = new Animal( { id: 'a' } ), b = new Animal( { id: 'b' } ), c = new Animal( { id: 'c' } ); // The default is to call `Collection.update` without specifying options explicitly; // the defaults are { add: true, merge: true, remove: true }. zoo.set( 'animals', [ a ] ); ok( animals.length == 1, 'animals.length=' + animals.length + ' == 1?' ); zoo.set( 'animals', [ a, b ], { add: false, merge: true, remove: true } ); ok( animals.length == 1, 'animals.length=' + animals.length + ' == 1?' ); zoo.set( 'animals', [ b ], { add: false, merge: false, remove: true } ); ok( animals.length == 0, 'animals.length=' + animals.length + ' == 0?' ); zoo.set( 'animals', [ { id: 'a', species: 'a' } ], { add: false, merge: true, remove: false } ); ok( animals.length == 0, 'animals.length=' + animals.length + ' == 0?' ); ok( a.get( 'species' ) === 'a', "`a` not added, but attributes did get merged" ); zoo.set( 'animals', [ { id: 'b', species: 'b' } ], { add: true, merge: false, remove: false } ); ok( animals.length == 1, 'animals.length=' + animals.length + ' == 1?' ); ok( !b.get( 'species' ), "`b` added, but attributes did not get merged" ); zoo.set( 'animals', [ { id: 'c', species: 'c' } ], { add: true, merge: false, remove: true } ); ok( animals.length == 1, 'animals.length=' + animals.length + ' == 1?' ); ok( !animals.get( 'b' ), "b removed from animals" ); ok( animals.get( 'c' ) === c, "c added to animals" ); ok( !c.get( 'species' ), "`c` added, but attributes did not get merged" ); zoo.set( 'animals', [ a, { id: 'b', species: 'b' } ] ); ok( animals.length == 2, 'animals.length=' + animals.length + ' == 2?' ); ok( b.get( 'species' ) === 'b', "`b` added, attributes got merged" ); ok( !animals.get( 'c' ), "c removed from animals" ); zoo.set( 'animals', [ { id: 'c', species: 'c' } ], { add: true, merge: true, remove: false } ); ok( animals.length == 3, 'animals.length=' + animals.length + ' == 3?' ); ok( c.get( 'species' ) === 'c', "`c` added, attributes got merged" ); }); test( "`merge` on a nested relation", function() { var zoo = new Zoo( { id: 1, animals: [ { id: 'a' } ] } ), animals = zoo.get( 'animals' ), a = animals.get( 'a' ); ok( a.get( 'livesIn' ) === zoo, "`a` is in `zoo`" ); // Pass a non-default option to a new model, with an existing nested model var zoo2 = new Zoo( { id: 2, animals: [ { id: 'a', species: 'a' } ] }, { merge: false } ); ok( a.get( 'livesIn' ) === zoo2, "`a` is in `zoo2`" ); ok( !a.get( 'species' ), "`a` hasn't gotten merged" ); }); test( "pop", function() { var zoo = new Zoo({ animals: [ { name: 'a' } ] }), animals = zoo.get( 'animals' ); var a = animals.pop(), b = animals.pop(); ok( a && a.get( 'name' ) === 'a' ); ok( typeof b === 'undefined' ); }); module( "Events", { setup: reset } ); test( "`add:`, `remove:` and `change:` events", function() { var zoo = new Zoo(), animal = new Animal(); var addEventsTriggered = 0, removeEventsTriggered = 0, changeEventsTriggered = 0; zoo // .on( 'change:animals', function( model, coll ) { // console.log( 'change:animals; args=%o', arguments ); // }) .on( 'add:animals', function( model, coll ) { //console.log( 'add:animals; args=%o', arguments ); addEventsTriggered++; }) .on( 'remove:animals', function( model, coll ) { //console.log( 'remove:animals; args=%o', arguments ); removeEventsTriggered++; }); animal .on( 'change:livesIn', function( model, coll ) { //console.log( 'change:livesIn; args=%o', arguments ); changeEventsTriggered++; }); // Should trigger `change:livesIn` and `add:animals` animal.set( 'livesIn', zoo ); zoo.set( 'id', 'z1' ); animal.set( 'id', 'a1' ); ok( addEventsTriggered === 1 ); ok( removeEventsTriggered === 0 ); ok( changeEventsTriggered === 1 ); // Doing this shouldn't trigger any `add`/`remove`/`update` events zoo.set( 'animals', [ 'a1' ] ); ok( addEventsTriggered === 1 ); ok( removeEventsTriggered === 0 ); ok( changeEventsTriggered === 1 ); // Doesn't cause an actual state change animal.set( 'livesIn', 'z1' ); ok( addEventsTriggered === 1 ); ok( removeEventsTriggered === 0 ); ok( changeEventsTriggered === 1 ); // Should trigger a `remove` on zoo and an `update` on animal animal.set( 'livesIn', { id: 'z2' } ); ok( addEventsTriggered === 1 ); ok( removeEventsTriggered === 1 ); ok( changeEventsTriggered === 2 ); }); test( "`reset` events", function() { var initialize = AnimalCollection.prototype.initialize; var resetEvents = 0, addEvents = 0, removeEvents = 0; AnimalCollection.prototype.initialize = function() { this .on( 'add', function() { addEvents++; }) .on( 'reset', function() { resetEvents++; }) .on( 'remove', function() { removeEvents++; }); }; var zoo = new Zoo(); // No events triggered when initializing a HasMany ok( zoo.get( 'animals' ) instanceof AnimalCollection ); ok( resetEvents === 0, "No `reset` event fired" ); ok( addEvents === 0 ); ok( removeEvents === 0 ); zoo.set( 'animals', { id: 1 } ); ok( addEvents === 1 ); ok( zoo.get( 'animals' ).length === 1, "animals.length === 1" ); zoo.get( 'animals' ).reset(); ok( resetEvents === 1, "`reset` event fired" ); ok( zoo.get( 'animals' ).length === 0, "animals.length === 0" ); AnimalCollection.prototype.initialize = initialize; }); test( "Firing of `change` and `change:<key>` events", function() { var data = { id: 1, animals: [] }; var zoo = new Zoo( data ); var change = 0; zoo.on( 'change', function() { change++; }); var changeAnimals = 0; zoo.on( 'change:animals', function() { changeAnimals++; }); var animalChange = 0; zoo.get( 'animals' ).on( 'change', function() { animalChange++; }); // Set the same data zoo.set( data ); ok( change === 0, 'no change event should fire' ); ok( changeAnimals === 0, 'no change:animals event should fire' ); ok( animalChange === 0, 'no animals:change event should fire' ); // Add an `animal` change = changeAnimals = animalChange = 0; zoo.set( { animals: [ { id: 'a1' } ] } ); ok( change === 1, 'change event should fire' ); ok( changeAnimals === 1, 'change:animals event should fire' ); ok( animalChange === 1, 'no animals:change event should fire' ); // Change an animal change = changeAnimals = animalChange = 0; zoo.set( { animals: [ { id: 'a1', name: 'a1' } ] } ); ok( change === 0, 'no change event should fire' ); ok( changeAnimals === 0, 'no change:animals event should fire' ); ok( animalChange === 1, 'animals:change event should fire' ); // Only change the `zoo` itself change = changeAnimals = animalChange = 0; zoo.set( { name: 'Artis' } ); ok( change === 1, 'change event should fire' ); ok( changeAnimals === 0, 'no change:animals event should fire' ); ok( animalChange === 0, 'no animals:change event should fire' ); // Replace an `animal` change = changeAnimals = animalChange = 0; zoo.set( { animals: [ { id: 'a2' } ] } ); ok( change === 1, 'change event should fire' ); ok( changeAnimals === 1, 'change:animals event should fire' ); ok( animalChange === 1, 'animals:change event should fire' ); // Remove an `animal` change = changeAnimals = animalChange = 0; zoo.set( { animals: [] } ); ok( change === 1, 'change event should fire' ); ok( changeAnimals === 1, 'change:animals event should fire' ); ok( animalChange === 0, 'no animals:change event should fire' ); // Operate directly on the HasMany collection var animals = zoo.get( 'animals' ), a1 = Animal.findOrCreate( 'a1', { create: false } ), a2 = Animal.findOrCreate( 'a2', { create: false } ); ok( a1 instanceof Animal ); ok( a2 instanceof Animal ); // Add an animal change = changeAnimals = animalChange = 0; animals.add( 'a2' ); ok( change === 0, 'change event not should fire' ); ok( changeAnimals === 0, 'no change:animals event should fire' ); ok( animalChange === 0, 'no animals:change event should fire' ); // Update an animal directly change = changeAnimals = animalChange = 0; a2.set( 'name', 'a2' ); ok( change === 0, 'no change event should fire' ); ok( changeAnimals === 0, 'no change:animals event should fire' ); ok( animalChange === 1, 'animals:change event should fire' ); // Remove an animal directly change = changeAnimals = animalChange = 0; animals.remove( 'a2' ); ok( change === 0, 'no change event should fire' ); ok( changeAnimals === 0, 'no change:animals event should fire' ); ok( animalChange === 0, 'no animals:change event should fire' ); }); test( "Does not trigger add / remove events for existing models on bulk assignment", function() { var house = new House({ id: 'house-100', location: 'in the middle of the street', occupants: [ { id : 'person-5', jobs: [ { id : 'job-22' } ] }, { id : 'person-6' } ] }); var eventsTriggered = 0; house .on( 'add:occupants', function(model) { ok( false, model.id + " should not be added" ); eventsTriggered++; }) .on( 'remove:occupants', function(model) { ok( false, model.id + " should not be removed" ); eventsTriggered++; }); house.get( 'occupants' ).at( 0 ).on( 'add:jobs', function( model ) { ok( false, model.id + " should not be added" ); eventsTriggered++; }); house.set( house.toJSON() ); ok( eventsTriggered === 0, "No add / remove events were triggered" ) }); test( "triggers appropriate add / remove / change events on bulk assignment", function() { var house = new House({ id: 'house-100', location: 'in the middle of the street', occupants: [ { id : 'person-5', nickname : 'Jane' }, { id : 'person-6' }, { id : 'person-8', nickname : 'Jon' } ] }); var addEventsTriggered = 0, removeEventsTriggered = 0, changeEventsTriggered = 0; house // .on( 'all', function(ev, model) { // console.log('all', ev, model); // }) .on( 'add:occupants', function( model ) { ok( model.id === 'person-7', "Only person-7 should be added: " + model.id + " being added" ); addEventsTriggered++; }) .on( 'remove:occupants', function( model ) { ok( model.id === 'person-6', "Only person-6 should be removed: " + model.id + " being removed" ); removeEventsTriggered++; }); house.get( 'occupants' ).on( 'change:nickname', function( model ) { ok( model.id === 'person-8', "Only person-8 should have it's nickname updated: " + model.id + " nickname updated" ); changeEventsTriggered++; }); house.set( { occupants : [ { id : 'person-5', nickname : 'Jane'}, { id : 'person-7' }, { id : 'person-8', nickname : 'Phil' } ] } ); ok( addEventsTriggered == 1, "Exactly one add event was triggered (triggered " + addEventsTriggered + " events)" ); ok( removeEventsTriggered == 1, "Exactly one remove event was triggered (triggered " + removeEventsTriggered + " events)" ); ok( changeEventsTriggered == 1, "Exactly one change event was triggered (triggered " + changeEventsTriggered + " events)" ); }); test( "triggers appropriate change events even when callbacks have triggered set with an unchanging value", function() { var house = new House({ id: 'house-100', location: 'in the middle of the street' }); var changeEventsTriggered = 0; house .on('change:location', function() { house.set({location: 'somewhere else'}); }) .on( 'change', function () { changeEventsTriggered++; }); house.set( { location: 'somewhere else' } ); ok( changeEventsTriggered === 1, 'one change triggered for `house`' ); var person = new Person({ id: 1 }); changeEventsTriggered = 0; person .on('change:livesIn', function() { //console.log( arguments ); house.set({livesIn: house}); }) .on( 'change', function () { //console.log( arguments ); changeEventsTriggered++; }); person.set({livesIn: house}); ok( changeEventsTriggered === 2, 'one change each triggered for `house` and `person`' ); }); module( "Performance", { setup: reset } ); test( "Creation and destruction", 0, function() { var addHasManyCount = 0, addHasOneCount = 0, tryAddRelatedHasMany = Backbone.HasMany.prototype.tryAddRelated, tryAddRelatedHasOne = Backbone.HasOne.prototype.tryAddRelated; Backbone.HasMany.prototype.tryAddRelated = function( model, coll, options ) { addHasManyCount++; return tryAddRelatedHasMany.apply( this, arguments ); }; Backbone.HasOne.prototype.tryAddRelated = function( model, coll, options ) { addHasOneCount++; return tryAddRelatedHasOne.apply( this, arguments ); }; var removeHasManyCount = 0, removeHasOneCount = 0, removeRelatedHasMany = Backbone.HasMany.prototype.removeRelated, removeRelatedHasOne= Backbone.HasOne.prototype.removeRelated; Backbone.HasMany.prototype.removeRelated = function( model, coll, options ) { removeHasManyCount++; return removeRelatedHasMany.apply( this, arguments ); }; Backbone.HasOne.prototype.removeRelated = function( model, coll, options ) { removeHasOneCount++; return removeRelatedHasOne.apply( this, arguments ); }; var Child = Backbone.RelationalModel.extend({ url: '/child/' }); var Parent = Backbone.RelationalModel.extend({ relations: [{ type: Backbone.HasMany, key: 'children', relatedModel: Child, reverseRelation: { key: 'parent' } }] }); var Parents = Backbone.Collection.extend({ model: Parent }); // bootstrap data var data = []; for ( var i = 1; i <= 300; i++ ) { data.push({ name: 'parent-' + i, children: [ {id: 'p-' + i + '-c1', name: 'child-1'}, {id: 'p-' + i + '-c2', name: 'child-2'}, {id: 'p-' + i + '-c3', name: 'child-3'} ] }); } /** * Test 2 */ Backbone.Relational.store.reset(); addHasManyCount = addHasOneCount = 0; console.log('loading test 2...'); var start = new Date(); var preparedData = _.map( data, function( item ) { item = _.clone( item ); item.children = item.children.map( function( child ) { return new Child( child ); }); return item; }); var parents = new Parents(); parents.on('reset', function () { var secs = (new Date() - start) / 1000; console.log( 'data loaded in %s, addHasManyCount=%o, addHasOneCount=%o', secs, addHasManyCount, addHasOneCount ); }); parents.reset( preparedData ); /** * Test 1 */ Backbone.Relational.store.reset(); addHasManyCount = addHasOneCount = 0; console.log('loading test 1...'); var start = new Date(); var parents = new Parents(); parents.on('reset', function () { var secs = (new Date() - start) / 1000; console.log( 'data loaded in %s, addHasManyCount=%o, addHasOneCount=%o', secs, addHasManyCount, addHasOneCount ); }); parents.reset( data ); /** * Test 2 (again) */ Backbone.Relational.store.reset(); addHasManyCount = addHasOneCount = removeHasManyCount = removeHasOneCount = 0; console.log('loading test 2...'); var start = new Date(); var parents = new Parents(); parents.on('reset', function () { var secs = (new Date() - start) / 1000; console.log( 'data loaded in %s, addHasManyCount=%o, addHasOneCount=%o', secs, addHasManyCount, addHasOneCount ); }); parents.reset( preparedData ); start = new Date(); parents.each( function( parent ) { parent.get( 'children' ).each( function( child ) { child.destroy(); }); }); var secs = (new Date() - start) / 1000; console.log( 'data loaded in %s, removeHasManyCount=%o, removeHasOneCount=%o', secs, removeHasManyCount, removeHasOneCount ); /** * Test 1 (again) */ Backbone.Relational.store.reset(); addHasManyCount = addHasOneCount = removeHasManyCount = removeHasOneCount = 0; console.log('loading test 1...'); var start = new Date(); var parents = new Parents(); parents.on('reset', function () { var secs = (new Date() - start) / 1000; console.log( 'data loaded in %s, addHasManyCount=%o, addHasOneCount=%o', secs, addHasManyCount, addHasOneCount ); }); parents.reset(data); start = new Date(); parents.remove( parents.models ); var secs = (new Date() - start) / 1000; console.log( 'data loaded in %s, removeHasManyCount=%o, removeHasOneCount=%o', secs, removeHasManyCount, removeHasOneCount ); }); });
const MongoClient = require('mongodb').MongoClient; var MONGOURL = process.env.MONGOURL || 'mongodb://localhost:27017/dataset'; module.exports = { MONGOURL_EXPORT: MONGOURL, MongoUpsert: function func2(collection, data, callback) { MongoClient.connect(MONGOURL, function (err, db) { if (err) { return callback(err, null); } var col = db.collection(collection); col.remove({}) .then(function () { col.insertMany(data) .then(function (result) { db.close(); return callback(null, result.insertedCount); }) .catch(function (error) { db.close(); console.error(error.stack); return callback(error.stack, null); }); }) .catch(function (error) { db.close(); console.error(error.stack); return callback(error.stack, null); }); }); } };
/* Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang("language","el",{button:"Θέση γλώσσας",remove:"Αφαίρεση γλώσσας"});
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); class UserCardModel { } exports.UserCardModel = UserCardModel; //# sourceMappingURL=user-card.model.js.map
Template.header.rendered = function() { $("[rel=tooltip]").tooltip({ placement: 'bottom'}); } Template.header.helpers({ notificationCount: function() { if (Meteor.user && Notifications) { var notifs = Notifications.find({userId: Meteor.userId(), read: false}, {sort: {timestamp: -1}}).fetch(); Session.set('notifications', notifs); return notifs.length; } } }); Template.header.events({ 'click #gotoNotifications': function(e) { e.preventDefault(); Router.go('notifications'); } })
/* 标签接口 */ var express = require('express'); var router = express.Router(); var TagModel = require('../../models/tag'); var PostModel = require('../../models/post'); var lang = require('../../lib/lang.json'); var checkLogin = require('../checkLogin').checkLogin; var checkVisitor = require('../checkLogin').checkVisitor; router.route('/tag') .get(checkVisitor, function (req, res, next) { var tagCollection; var tagQuery = TagModel.Tag.find({}); tagQuery.exec(function (err, categories) { tagCollection = categories; res.json(200, tagCollection); }); }) .post(checkLogin, function (req, res, next) { var id = req.body.id; var name = req.body.name; if (!name.match(/^[A-z0-9\u4e00-\u9fa5\+\#\.\-]{0,20}$/)) { res.json(200, { status: 0, message: lang.illegalInput }) } else if (id) { var tagQuery = TagModel.Tag.findOne().where('_id', id); tagQuery.exec(function (error, doc) { doc.name = name; doc.save(function (err) { if (err) { res.json(200, { status: 0, message: lang.error }) } else { res.json(200, { status: 1, message: lang.success }) } }) }) } else { var tagQuery = TagModel.Tag.findOne({'name': {$regex: '^' + name + '$', $options: '$i'}}); tagQuery.exec(function (err, repeat) { if (repeat) { res.json(200, { status: 0, message: lang.error + ': 标签已存在' }) } else { var newTag = new TagModel.Tag({ name: name }); newTag.save(function (err) { if (err) { res.json(200, { status: 0, message: lang.error }); } else { res.json(200, { status: 1, message: lang.success }); } }) } }); } }) .delete(checkLogin, function (req, res, next) { var tagQuery = TagModel.Tag.find({'_id': {$in: req.body.id}}); tagQuery.exec(function (err) { if (err) { res.json(200, { status: 0, message: lang.error }) } else { tagQuery.remove(function (err, doc) { if (err) { res.json(200, { status: 0, message: lang.error }) } else { res.json(200, { status: 1, message: lang.success, doc: doc }) } }); } }) }); router.route('/taginfo') .get(checkVisitor, function (req, res, next) { PostModel.Post.aggregate({ $project: { tags: 1 } }).exec(function (err, doc) { if (err) { res.json(200, { status: 0, message: lang.error }) } else { res.json(200, { status: 1, message: lang.success, data: doc }) } }) }); module.exports = router;
$(function() { var $result_list = $('.Results'), $search_bar = $('.Header-input'), $alert = $('.alert'), $spinner = $('.AjaxLoader'), request_id; var display_reverb_crap = function(data) { var result_elements = []; console.log(data); $spinner.hide(); for (var i = 0; i < data.length; i++) { var instrument = data[i]; instrument['listing'] = Mustache.render(Templates['Reverb::Listing'], instrument['listings'][0]); instrument_markup = Mustache.render(Templates['Reverb::Instrument'], instrument); result_elements.push(instrument_markup); } $result_list.append(result_elements.join('\n')); } var request_by_name = function(name, use_similar) { use_similar = use_similar || false; $result_list.empty(); $alert.hide(); $spinner.show(); $spinner.css('display', 'block'); similar = use_similar ? '?similar=true' : ''; $.get('/reverb/artist/' + name + similar, function(data){ if(data.length == 0) { $spinner.hide(); if (use_similar) { $alert.html("Couldn't find instruments for artists similar to " + $search_bar.val() + ". Sorry :("); } else { similar_link = $('<a href="#">similar artists</a>'); similar_link.click(function() { request_by_name($search_bar.val(), true); }); $alert.html("Couldn't find instruments for " + $search_bar.val() + ". Try "); $alert.append(similar_link); } $alert.show(); } else { ajax_pester( '/reverb/request/' + data, 200, display_reverb_crap, function() { $alert.html("No instruments currently on sale for " + $search_bar.val() + "."); $alert.show(); $spinner.hide(); } ); } }); }; var rebuild_instrument_list = function(data) { var $instrument_list = $('.instruments'), instruments = []; $instrument_list.empty(); for(var i = data.length; i > 0; i--) { instruments.push('<ul>' + data[i - 1].name + '</ul>'); } $instrument_list.append(instruments.join('\n')); } $search_bar.keypress(function(e) { var code = (e.keyCode ? e.keyCode : e.which); if(code == 13) { e.preventDefault(); request_by_name($search_bar.val()); } }); });
var express = require('express'); var router = express.Router(); /* GET home page. */ router.get("/", function (req, res) { if (req.session.user) { res.render("welcome", req.session.user); } else { res.render("welcome") } }); module.exports = router;
var MattSpeakman; (function (MattSpeakman) { /** * This is an example of a date picker factory that could be implemented */ var DatePickerFactory = (function () { function DatePickerFactory() { var _this = this; this.datePickerOptions = { dateFormat: 'dd/mm/yy', minDate: '0d', maxDate: '+30d' }; this.directiveCode = function () { return new DatePickerDirective(_this.directiveName(), _this.datePickerOptions); }; } DatePickerFactory.prototype.directiveName = function () { return DatePickerFactory._directiveName; }; return DatePickerFactory; }()); DatePickerFactory._directiveName = "datePicker"; MattSpeakman.DatePickerFactory = DatePickerFactory; /** * This directive adds a JQueryUI datepicker to an element */ var DatePickerDirective = (function () { function DatePickerDirective(directiveName, datePickerOptions) { var _this = this; this.directiveName = directiveName; this.datePickerOptions = datePickerOptions; // restrict this to attribute only this.link = function (_scope, element, attrs) { var handler = function (event, ui) { setScopeValue(ui.item.value); }; // Update the scope with the required value var setScopeValue = function (value) { // Need to wrap this in a try catch so that upon setup no errors are thrown try { var eleScope = element.scope(); // Establish the property name we need to be binding to // Here we are allowing you to set either a ng-model="SomeProperty" or date-picker="SomeProperty" var modelPropertyName = ""; var ngModelName = attrs["ngModel"]; var directiveName = attrs[_this.directiveName]; if (MattSpeakman.StringExtensions.IsNullOrWhitespace(ngModelName)) modelPropertyName = directiveName; else modelPropertyName = ngModelName; // Build the angular expression to be evaluated // This will get the name of the property in the scope so that we are applying in order to evaluate and set the appropriate value var exp = modelPropertyName + "='" + value + "'"; // Code to execute in scope.apply. // If we are not currently in a digest loop then apply the value to the scope if (!eleScope.$$phase) { eleScope.$apply(function (SC) { return SC.$eval(exp); }); } else { // Use current scope eleScope.$eval(exp); } } catch (Exception) { } // Set the element as a date picker element.datepicker(_this.datePickerOptions); // Set the scope to the initial value setScopeValue(element.val()); }; }; } return DatePickerDirective; }()); })(MattSpeakman || (MattSpeakman = {})); //# sourceMappingURL=DatePickerDirective.js.map
game.magic = me.Entity.extend({ init: function(x, y, settings, facing){ this._super(me.Entity, 'init', [x, y, { image: "magic", width: 24, height: 24, spritewidth: "24", spriteheight: "24", getShape: function(){ return (new me.Rect(0, 0, 24, 24)).toPolygon(); } }]); this.alwaysUpdate = true; this.body.setVelocity(8, 0); this.attack = game.data.skill2*10; this.type = "magic"; this.facing = facing; }, update: function(delta){ //changes the spear's direction on where you throw it if(this.facing === "left"){ this.body.vel.x -= this.body.accel.x * me.timer.tick; this.flipX(true); }else{ this.body.vel.x += this.body.accel.x * me.timer.tick; this.flipX(false); } me.collision.check(this, true, this.collideHandler.bind(this), true); this.body.update(delta); this._super(me.Entity, "update", [delta]); return true; }, collideHandler: function(response){ //checks if it collides with either the Enemy base or Enemy Creep. if(response.b.type==='EnemyCreep'){ response.b.loseHealth(this.attack); me.game.world.removeChild(this); } if(response.b.type==='EnemyBaseEntity'){ response.b.loseHealth(this.attack); me.game.world.removeChild(this); } } });
// Dependencies: import { parseOrdinal } from './ordinals'; export function addSelectHelpers () { let { by, ElementFinder } = global.protractor; ElementFinder.prototype.selectOptionByText = function (text) { return this.all(by.cssContainingText('option', text)).first().click(); }; ElementFinder.prototype.selectOptionByIndex = function (index) { index = parseOrdinal(index) - 1 || index; return this.all(by.tagName('option')).then(options => options[index].click()); }; ElementFinder.prototype.getSelectedOptionText = function () { return this.element(by.css('option:checked')).getText(); }; }
/*! * Angular Material Design * https://github.com/angular/material * @license MIT * v1.1.0-rc.5-master-3a0f323 */ (function( window, angular, undefined ){ "use strict"; /** * @ngdoc module * @name material.components.list * @description * List module */ angular.module('material.components.list', [ 'material.core' ]) .controller('MdListController', MdListController) .directive('mdList', mdListDirective) .directive('mdListItem', mdListItemDirective); /** * @ngdoc directive * @name mdList * @module material.components.list * * @restrict E * * @description * The `<md-list>` directive is a list container for 1..n `<md-list-item>` tags. * * @usage * <hljs lang="html"> * <md-list> * <md-list-item class="md-2-line" ng-repeat="item in todos"> * <md-checkbox ng-model="item.done"></md-checkbox> * <div class="md-list-item-text"> * <h3>{{item.title}}</h3> * <p>{{item.description}}</p> * </div> * </md-list-item> * </md-list> * </hljs> */ function mdListDirective($mdTheming) { return { restrict: 'E', compile: function(tEl) { tEl[0].setAttribute('role', 'list'); return $mdTheming; } }; } mdListDirective.$inject = ["$mdTheming"]; /** * @ngdoc directive * @name mdListItem * @module material.components.list * * @restrict E * * @description * A `md-list-item` element can be used to represent some information in a row.<br/> * * @usage * ### Single Row Item * <hljs lang="html"> * <md-list-item> * <span>Single Row Item</span> * </md-list-item> * </hljs> * * ### Multiple Lines * By using the following markup, you will be able to have two lines inside of one `md-list-item`. * * <hljs lang="html"> * <md-list-item class="md-2-line"> * <div class="md-list-item-text" layout="column"> * <p>First Line</p> * <p>Second Line</p> * </div> * </md-list-item> * </hljs> * * It is also possible to have three lines inside of one list item. * * <hljs lang="html"> * <md-list-item class="md-3-line"> * <div class="md-list-item-text" layout="column"> * <p>First Line</p> * <p>Second Line</p> * <p>Third Line</p> * </div> * </md-list-item> * </hljs> * * ### Secondary Items * Secondary items are elements which will be aligned at the end of the `md-list-item`. * * <hljs lang="html"> * <md-list-item> * <span>Single Row Item</span> * <md-button class="md-secondary"> * Secondary Button * </md-button> * </md-list-item> * </hljs> * * It also possible to have multiple secondary items inside of one `md-list-item`. * * <hljs lang="html"> * <md-list-item> * <span>Single Row Item</span> * <md-button class="md-secondary">First Button</md-button> * <md-button class="md-secondary">Second Button</md-button> * </md-list-item> * </hljs> * * ### Proxy Item * Proxies are elements, which will execute their specific action on click<br/> * Currently supported proxy items are * - `md-checkbox` (Toggle) * - `md-switch` (Toggle) * - `md-menu` (Open) * * This means, when using a supported proxy item inside of `md-list-item`, the list item will * become clickable and executes the associated action of the proxy element on click. * * <hljs lang="html"> * <md-list-item> * <span>First Line</span> * <md-checkbox class="md-secondary"></md-checkbox> * </md-list-item> * </hljs> * * The `md-checkbox` element will be automatically detected as a proxy element and will toggle on click. * * <hljs lang="html"> * <md-list-item> * <span>First Line</span> * <md-switch class="md-secondary"></md-switch> * </md-list-item> * </hljs> * * The recognized `md-switch` will toggle its state, when the user clicks on the `md-list-item`. * * It is also possible to have a `md-menu` inside of a `md-list-item`. * <hljs lang="html"> * <md-list-item> * <p>Click anywhere to fire the secondary action</p> * <md-menu class="md-secondary"> * <md-button class="md-icon-button"> * <md-icon md-svg-icon="communication:message"></md-icon> * </md-button> * <md-menu-content width="4"> * <md-menu-item> * <md-button> * Redial * </md-button> * </md-menu-item> * <md-menu-item> * <md-button> * Check voicemail * </md-button> * </md-menu-item> * <md-menu-divider></md-menu-divider> * <md-menu-item> * <md-button> * Notifications * </md-button> * </md-menu-item> * </md-menu-content> * </md-menu> * </md-list-item> * </hljs> * * The menu will automatically open, when the users clicks on the `md-list-item`.<br/> * * If the developer didn't specify any position mode on the menu, the `md-list-item` will automatically detect the * position mode and applies it to the `md-menu`. * * ### Avatars * Sometimes you may want to have some avatars inside of the `md-list-item `.<br/> * You are able to create a optimized icon for the list item, by applying the `.md-avatar` class on the `<img>` element. * * <hljs lang="html"> * <md-list-item> * <img src="my-avatar.png" class="md-avatar"> * <span>Alan Turing</span> * </hljs> * * When using `<md-icon>` for an avater, you have to use the `.md-avatar-icon` class. * <hljs lang="html"> * <md-list-item> * <md-icon class="md-avatar-icon" md-svg-icon="avatars:timothy"></md-icon> * <span>Timothy Kopra</span> * </md-list-item> * </hljs> * * In cases, you have a `md-list-item`, which doesn't have any avatar, * but you want to align it with the other avatar items, you have to use the `.md-offset` class. * * <hljs lang="html"> * <md-list-item class="md-offset"> * <span>Jon Doe</span> * </md-list-item> * </hljs> * * ### DOM modification * The `md-list-item` component automatically detects if the list item should be clickable. * * --- * If the `md-list-item` is clickable, we wrap all content inside of a `<div>` and create * an overlaying button, which will will execute the given actions (like `ng-href`, `ng-click`) * * We create an overlaying button, instead of wrapping all content inside of the button, * because otherwise some elements may not be clickable inside of the button. * * --- * When using a secondary item inside of your list item, the `md-list-item` component will automatically create * a secondary container at the end of the `md-list-item`, which contains all secondary items. * * The secondary item container is not static, because otherwise the overflow will not work properly on the * list item. * */ function mdListItemDirective($mdAria, $mdConstant, $mdUtil, $timeout) { var proxiedTypes = ['md-checkbox', 'md-switch', 'md-menu']; return { restrict: 'E', controller: 'MdListController', compile: function(tEl, tAttrs) { // Check for proxy controls (no ng-click on parent, and a control inside) var secondaryItems = tEl[0].querySelectorAll('.md-secondary'); var hasProxiedElement; var proxyElement; var itemContainer = tEl; tEl[0].setAttribute('role', 'listitem'); if (tAttrs.ngClick || tAttrs.ngDblclick || tAttrs.ngHref || tAttrs.href || tAttrs.uiSref || tAttrs.ngAttrUiSref) { wrapIn('button'); } else { for (var i = 0, type; type = proxiedTypes[i]; ++i) { if (proxyElement = tEl[0].querySelector(type)) { hasProxiedElement = true; break; } } if (hasProxiedElement) { wrapIn('div'); } else if (!tEl[0].querySelector('md-button:not(.md-secondary):not(.md-exclude)')) { tEl.addClass('md-no-proxy'); } } wrapSecondaryItems(); setupToggleAria(); if (hasProxiedElement && proxyElement.nodeName === "MD-MENU") { setupProxiedMenu(); } function setupToggleAria() { var toggleTypes = ['md-switch', 'md-checkbox']; var toggle; for (var i = 0, toggleType; toggleType = toggleTypes[i]; ++i) { if (toggle = tEl.find(toggleType)[0]) { if (!toggle.hasAttribute('aria-label')) { var p = tEl.find('p')[0]; if (!p) return; toggle.setAttribute('aria-label', 'Toggle ' + p.textContent); } } } } function setupProxiedMenu() { var menuEl = angular.element(proxyElement); var isEndAligned = menuEl.parent().hasClass('md-secondary-container') || proxyElement.parentNode.firstElementChild !== proxyElement; var xAxisPosition = 'left'; if (isEndAligned) { // When the proxy item is aligned at the end of the list, we have to set the origin to the end. xAxisPosition = 'right'; } // Set the position mode / origin of the proxied menu. if (!menuEl.attr('md-position-mode')) { menuEl.attr('md-position-mode', xAxisPosition + ' target'); } // Apply menu open binding to menu button var menuOpenButton = menuEl.children().eq(0); if (!hasClickEvent(menuOpenButton[0])) { menuOpenButton.attr('ng-click', '$mdOpenMenu($event)'); } if (!menuOpenButton.attr('aria-label')) { menuOpenButton.attr('aria-label', 'Open List Menu'); } } function wrapIn(type) { if (type == 'div') { itemContainer = angular.element('<div class="md-no-style md-list-item-inner">'); itemContainer.append(tEl.contents()); tEl.addClass('md-proxy-focus'); } else { // Element which holds the default list-item content. itemContainer = angular.element( '<div class="md-button md-no-style">'+ ' <div class="md-list-item-inner"></div>'+ '</div>' ); // Button which shows ripple and executes primary action. var buttonWrap = angular.element( '<md-button class="md-no-style"></md-button>' ); buttonWrap[0].setAttribute('aria-label', tEl[0].textContent); copyAttributes(tEl[0], buttonWrap[0]); // We allow developers to specify the `md-no-focus` class, to disable the focus style // on the button executor. Once more classes should be forwarded, we should probably make the // class forward more generic. if (tEl.hasClass('md-no-focus')) { buttonWrap.addClass('md-no-focus'); } // Append the button wrap before our list-item content, because it will overlay in relative. itemContainer.prepend(buttonWrap); itemContainer.children().eq(1).append(tEl.contents()); tEl.addClass('_md-button-wrap'); } tEl[0].setAttribute('tabindex', '-1'); tEl.append(itemContainer); } function wrapSecondaryItems() { var secondaryItemsWrapper = angular.element('<div class="md-secondary-container">'); angular.forEach(secondaryItems, function(secondaryItem) { wrapSecondaryItem(secondaryItem, secondaryItemsWrapper); }); itemContainer.append(secondaryItemsWrapper); } function wrapSecondaryItem(secondaryItem, container) { // If the current secondary item is not a button, but contains a ng-click attribute, // the secondary item will be automatically wrapped inside of a button. if (secondaryItem && !isButton(secondaryItem) && secondaryItem.hasAttribute('ng-click')) { $mdAria.expect(secondaryItem, 'aria-label'); var buttonWrapper = angular.element('<md-button class="md-secondary md-icon-button">'); // Copy the attributes from the secondary item to the generated button. // We also support some additional attributes from the secondary item, // because some developers may use a ngIf, ngHide, ngShow on their item. copyAttributes(secondaryItem, buttonWrapper[0], ['ng-if', 'ng-hide', 'ng-show']); secondaryItem.setAttribute('tabindex', '-1'); buttonWrapper.append(secondaryItem); secondaryItem = buttonWrapper[0]; } if (secondaryItem && (!hasClickEvent(secondaryItem) || (!tAttrs.ngClick && isProxiedElement(secondaryItem)))) { // In this case we remove the secondary class, so we can identify it later, when we searching for the // proxy items. angular.element(secondaryItem).removeClass('md-secondary'); } tEl.addClass('md-with-secondary'); container.append(secondaryItem); } /** * Copies attributes from a source element to the destination element * By default the function will copy the most necessary attributes, supported * by the button executor for clickable list items. * @param source Element with the specified attributes * @param destination Element which will retrieve the attributes * @param extraAttrs Additional attributes, which will be copied over. */ function copyAttributes(source, destination, extraAttrs) { var copiedAttrs = $mdUtil.prefixer([ 'ng-if', 'ng-click', 'ng-dblclick', 'aria-label', 'ng-disabled', 'ui-sref', 'href', 'ng-href', 'target', 'ng-attr-ui-sref', 'ui-sref-opts' ]); if (extraAttrs) { copiedAttrs = copiedAttrs.concat($mdUtil.prefixer(extraAttrs)); } angular.forEach(copiedAttrs, function(attr) { if (source.hasAttribute(attr)) { destination.setAttribute(attr, source.getAttribute(attr)); source.removeAttribute(attr); } }); } function isProxiedElement(el) { return proxiedTypes.indexOf(el.nodeName.toLowerCase()) != -1; } function isButton(el) { var nodeName = el.nodeName.toUpperCase(); return nodeName == "MD-BUTTON" || nodeName == "BUTTON"; } function hasClickEvent (element) { var attr = element.attributes; for (var i = 0; i < attr.length; i++) { if (tAttrs.$normalize(attr[i].name) === 'ngClick') return true; } return false; } return postLink; function postLink($scope, $element, $attr, ctrl) { $element.addClass('_md'); // private md component indicator for styling var proxies = [], firstElement = $element[0].firstElementChild, isButtonWrap = $element.hasClass('_md-button-wrap'), clickChild = isButtonWrap ? firstElement.firstElementChild : firstElement, hasClick = clickChild && hasClickEvent(clickChild); computeProxies(); computeClickable(); if ($element.hasClass('md-proxy-focus') && proxies.length) { angular.forEach(proxies, function(proxy) { proxy = angular.element(proxy); $scope.mouseActive = false; proxy.on('mousedown', function() { $scope.mouseActive = true; $timeout(function(){ $scope.mouseActive = false; }, 100); }) .on('focus', function() { if ($scope.mouseActive === false) { $element.addClass('md-focused'); } proxy.on('blur', function proxyOnBlur() { $element.removeClass('md-focused'); proxy.off('blur', proxyOnBlur); }); }); }); } function computeProxies() { if (firstElement && firstElement.children && !hasClick) { angular.forEach(proxiedTypes, function(type) { // All elements which are not capable for being used a proxy have the .md-secondary class // applied. These items had been sorted out in the secondary wrap function. angular.forEach(firstElement.querySelectorAll(type + ':not(.md-secondary)'), function(child) { proxies.push(child); }); }); } } function computeClickable() { if (proxies.length == 1 || hasClick) { $element.addClass('md-clickable'); if (!hasClick) { ctrl.attachRipple($scope, angular.element($element[0].querySelector('.md-no-style'))); } } } function isEventFromControl(event) { var forbiddenControls = ['md-slider']; // If there is no path property in the event, then we can assume that the event was not bubbled. if (!event.path) { return forbiddenControls.indexOf(event.target.tagName.toLowerCase()) !== -1; } // We iterate the event path up and check for a possible component. // Our maximum index to search, is the list item root. var maxPath = event.path.indexOf($element.children()[0]); for (var i = 0; i < maxPath; i++) { if (forbiddenControls.indexOf(event.path[i].tagName.toLowerCase()) !== -1) { return true; } } } var clickChildKeypressListener = function(e) { if (e.target.nodeName != 'INPUT' && e.target.nodeName != 'TEXTAREA' && !e.target.isContentEditable) { var keyCode = e.which || e.keyCode; if (keyCode == $mdConstant.KEY_CODE.SPACE) { if (clickChild) { clickChild.click(); e.preventDefault(); e.stopPropagation(); } } } }; if (!hasClick && !proxies.length) { clickChild && clickChild.addEventListener('keypress', clickChildKeypressListener); } $element.off('click'); $element.off('keypress'); if (proxies.length == 1 && clickChild) { $element.children().eq(0).on('click', function(e) { // When the event is coming from an control and it should not trigger the proxied element // then we are skipping. if (isEventFromControl(e)) return; var parentButton = $mdUtil.getClosest(e.target, 'BUTTON'); if (!parentButton && clickChild.contains(e.target)) { angular.forEach(proxies, function(proxy) { if (e.target !== proxy && !proxy.contains(e.target)) { if (proxy.nodeName === 'MD-MENU') { proxy = proxy.children[0]; } angular.element(proxy).triggerHandler('click'); } }); } }); } $scope.$on('$destroy', function () { clickChild && clickChild.removeEventListener('keypress', clickChildKeypressListener); }); } } }; } mdListItemDirective.$inject = ["$mdAria", "$mdConstant", "$mdUtil", "$timeout"]; /* * @private * @ngdoc controller * @name MdListController * @module material.components.list * */ function MdListController($scope, $element, $mdListInkRipple) { var ctrl = this; ctrl.attachRipple = attachRipple; function attachRipple (scope, element) { var options = {}; $mdListInkRipple.attach(scope, element, options); } } MdListController.$inject = ["$scope", "$element", "$mdListInkRipple"]; })(window, window.angular);
const alpha = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTYVWXYZ' const numbers = '0123456789' const symbols = '-_=+/?>,<[]{}\\|!@#$%^&*()_+:' module.exports.alpha = alpha module.exports.numbers = numbers module.exports.symbols = symbols module.exports.alphanum = alpha + numbers module.exports.all = alpha + numbers + symbols
export default config => require('letsencrypt-express').create({ server: config.env === 'production' ? 'https://acme-v01.api.letsencrypt.org/directory' : 'staging', email: 'hallitus@ktto.fi', agreeTos: true, approveDomains: ['varjo.ktto.fi'] })
import { api } from 'sharp'; export function getGlobalFilters() { return api.get(`filters`).then(response => response.data); } export function postGlobalFilters({ filterKey, value }) { return api.post(`filters/${filterKey}`, { value }); }
var mongoose = require('mongoose'); var bcrypt = require('bcrypt'); var Schema = mongoose.Schema; const saltRounds = 10; var UserSchema = new Schema({ username : {type : String, required : true, index : {unique : true }}, password : {type : String, required : true}, quoraUsername : {type : String, required : true}, totalViews : {type : Number} }); UserSchema.pre('save', function(next){ var user = this; //Hash the password only if the password has been modified if(!user.isModified('password')) return next(); //Generate the hash bcrypt.genSalt(saltRounds, function(error, salt){ if(error) return next(error); bcrypt.hash(user.password, salt, function(error, hash){ if(error) return next(error); user.password = hash; next(); }); }); }); UserSchema.methods.comparePassword = function(password){ var user = this; return bcrypt.compareSync(password, user.password); }; module.exports = mongoose.model('User', UserSchema);
export { default } from 'ember-freestyle/modifiers/freestyle-highlight';
'use strict'; /** * Set up Passport if it is available and connect to the application. Passport * will use the user model. * @param {Express} app Express application to add Passport to. */ module.exports = function(app) { // Check if Passport is available try { var passport = require('passport'); } catch(e) { return; } // Get user model and Passport strategies var User = require('../models/user'); var strategies = [ require('./local') ]; // Hook in with user model passport.serializeUser(function(user, done) { done(null, user.id); }); passport.deserializeUser(function(id, done) { User.findById(id, '-password').exec(done); }); // Add any strategies required strategies.forEach(function(strategy) { passport.use(strategy); }); // Connect middleware app.use(passport.initialize()); app.use(passport.session()); };
'use strict'; import { REQUEST_TIMEOUT } from '../lib/constants'; import { default as baseRequest } from 'request'; import cheerio from 'cheerio'; import { flattenDeep, isFinite } from 'lodash'; import { parallel } from 'async'; import { default as moment } from 'moment-timezone'; import { convertUnits } from '../lib/utils'; const request = baseRequest.defaults({timeout: REQUEST_TIMEOUT}); export const name = 'tsag-agaar'; // agaar.mn provides data for these // so skip them to avoid unneeded duplicates export const skippableLocations = ['УБ-2', 'УБ-8']; export function fetchData (source, cb) { request(source.url, (err, res, body) => { if (err || res.statusCode !== 200) { return cb({message: 'Failure to load data url.'}, []); } const $ = cheerio.load(body); const regionTasks = $('#WeatherCity option') .filter((i, el) => { return $(el).attr('value') !== ''; }) .map((i, el) => { return followRegion(source, $(el).attr('value')); }) .get(); parallel(regionTasks, (err, results) => { if (err) { return cb(err, []); } results = flattenDeep(results); results = convertUnits(results); return cb(err, {name: 'unused', measurements: results}); }); }); } const followRegion = function (source, regionID) { return function (done) { const regionURL = `${source.sourceURL}/update_stations/?type=air-data&city=${regionID}`; request(regionURL, (err, res, body) => { if (err || res.statusCode !== 200) { return done(null, []); } const $ = cheerio.load(body); const cityTasks = $('#WeatherSum option') .filter((i, el) => { return $(el).attr('value') !== ''; }) .map((i, el) => { return followCity(source, $(el).attr('value'), $(el).text()); }) .get(); parallel(cityTasks, (err, results) => { if (err) { return done(err, []); } return done(null, results); }); }); }; }; const followCity = function (source, cityID, cityName) { return function (done) { const cityURL = `${source.sourceURL}/get_monitoring_data/?type=air-data&sum=${cityID}`; request(cityURL, (err, res, body) => { if (err || res.statusCode !== 200) { return done(null, []); } formatData(source, body, cityName, (measurements) => { return done(null, measurements); }); }); }; }; const formatData = function (source, body, city, cb) { const $ = cheerio.load(body); let measurements = []; $('#table-data table').each((i, el) => { let parameters = {}; let units = {}; const stationMeta = $(el).find('th').text(); $(el).find('thead tr').last().find('td').each((i, el) => { if (i < 2) { return; } parameters[i] = $(el).text().trim().split(' ')[0].toLowerCase(); units[i] = $(el).text().trim().match(/.* \((.*\/.*)\)/)[1]; }); $(el).find('tbody tr').each((i, el) => { const date = $(el).find('td').first().text(); const hours = $(el).find('td').eq(1).text(); $(el).find('td').each((i, el) => { if (i < 2 || !isFinite(Number($(el).text()))) { return; } const location = stationMeta.split(' (')[0]; if (skippableLocations.indexOf(location) > -1) { return; } if (location.match(/УБ-[0-9]{1,2}/)) { city = 'Ulaanbaatar'; } if (units[i] === 'мг/м3') { units[i] = 'mg/m³'; } let m = { city: city, location: location, parameter: parameters[i], unit: units[i], value: Number($(el).text()), coordinates: coordinates[location], date: getDate(date, hours, source.timezone), description: stationMeta, attribution: [ { name: source.name, url: source.sourceURL }, { name: 'National Agency of Meteorology and Environmental Monitoring', url: 'http://namem.gov.mn' } ], averagingPeriod: { value: 0.3, unit: 'hours' } }; measurements.push(m); }); }); }); return cb(measurements); }; const getDate = function (dateText, hours, timezone) { const date = moment.tz(`${dateText} ${hours}`, 'YYYY.MM.DD HH', timezone); return { utc: date.toDate(), local: date.format() }; }; const coordinates = { 'УБ-1': { latitude: 47.89401111111111, longitude: 106.88265 }, 'УБ-2': { latitude: 47.91540555555555, longitude: 106.89433333333334 }, 'УБ-3': { latitude: 47.91786111111111, longitude: 106.84806111111111 }, 'УБ-4': { latitude: 47.917402777777774, longitude: 106.93749166666667 }, 'УБ-5': { latitude: 47.93290277777778, longitude: 106.92137777777778 }, 'УБ-6': { latitude: 47.91345, longitude: 106.97203055555556 }, 'УБ-7': { latitude: 47.90561666666667, longitude: 106.84249166666666 }, 'УБ-8': { latitude: 47.86595277777778, longitude: 107.11826944444444 }, 'УБ-9': { latitude: 47.98191388888889, longitude: 106.94051111111112 }, 'УБ-10': { latitude: 47.91208888888889, longitude: 106.82301944444444 }, 'УБ-11': { latitude: 47.95143055555556, longitude: 106.90407222222223 }, 'Цэцэрлэг': { latitude: 47.47219444444445, longitude: 101.46244444444444 }, 'Өлгий': { latitude: 48.96919444444445, longitude: 89.96494444444444 }, 'Баянхонгор': { latitude: 46.197111111111106, longitude: 100.72008333333333 }, 'Булган': { latitude: 48.818222222222225, longitude: 103.51866666666666 }, 'Алтай': { latitude: 46.37652777777778, longitude: 96.26233333333333 }, 'Чойр': { latitude: 46.35777777777778, longitude: 108.24611111111112 }, 'Дархан': { latitude: 49.49038888888889, longitude: 105.90650000000001 }, 'Шарын гол': { latitude: 49.26144444444444, longitude: 106.4118888888889 }, 'Мандалговь': { latitude: 45.76711111111111, longitude: 106.27488888888888 }, 'Чойбалсан': { latitude: 48.080555555555556, longitude: 114.53758333333333 }, 'Сайншанд': { latitude: 45.06663888888889, longitude: 110.1463888888889 }, 'Баруун-Урт': { latitude: 46.680305555555556, longitude: 113.28025 }, 'Сүхбаатар': { latitude: 50.239694444444446, longitude: 106.19277777777778 }, 'Зүүнхараа': { latitude: 48.86666666666667, longitude: 106.85 }, 'Улиастай': { latitude: 47.726888888888894, longitude: 96.84738888888889 }, 'Улаангом': { latitude: 49.971944444444446, longitude: 92.0773611111111 }, 'Ховд': { latitude: 47.996, longitude: 91.63391666666668 }, 'Мөрөн': { latitude: 49.63886111111111, longitude: 100.16652777777779 }, 'Өндөрхаан': { latitude: 47.323972222222224, longitude: 110.64866666666667 }, 'Зуунмод': { latitude: 47.71038888888889, longitude: 106.95365277777778 }, 'Арвайхээр': { latitude: 46.258916666666664, longitude: 102.78922222222222 }, 'Даланзадгад': { latitude: 43.56761111111111, longitude: 104.42266666666667 }, 'Эрдэнэт1': { latitude: 49.01938888888889, longitude: 104.04527777777777 }, 'Эрдэнэт2': { latitude: 49.01705555555556, longitude: 104.02813888888889 }, 'Эрдэнэт3': { latitude: 49.01347222222222, longitude: 104.019 } };
'use strict'; /** * Register action */ module.exports = function(req, res) { var scope = require('../../scope')(waterlock.Auth, waterlock.engine); var params = req.params.all(); if (typeof params[scope.type] === 'undefined' || typeof params.password === 'undefined') { waterlock.cycle.registerFailure(req, res, null, { error: 'Invalid ' + scope.type + ' or password' }); } else { scope.registerUserAuthObject(params, req, function(err, user) { if (err) { res.serverError(err); } if (typeof user === 'undefined') { //Registration should be a success waterlock.cycle.registerSuccess(req, res, user); } else { waterlock.cycle.registerFailure(req, res, null, { error: scope.type + ' is already in use' }); } }); } };
function add(n1, n2) { return n1 + n2; } module.exports = { add: add };
import Component from '@ember/component'; import { schedule } from '@ember/runloop'; export default Component.extend({ classNames: ['schema-field-component', 'schema-field-checkbox'], init() { this._super(...arguments); let key = this.get('key'); let jsonDocument = this.get('document'); let defaultValue = this.get('property.default'); schedule('afterRender', () => { let initialValue = null; let documentValue = jsonDocument.get(key); if (typeof defaultValue !== 'undefined') { initialValue = defaultValue; } if (typeof documentValue !== 'undefined') { initialValue = documentValue; } if (initialValue !== null) { this.set('value', initialValue); jsonDocument.set(key, initialValue); } }); }, actions: { update(values) { let { document, key } = this.getProperties('document', 'key'); document.set(key, values); this.set('value', values); this.sendAction('changed', values); // eslint-disable-line ember/closure-actions } } });
var _ = require('lodash'); var extend = require('node.extend'); // turn a buffer into an int intelligently depending on its length module.exports.bufferToInt = function (buffer, signed) { // builds something like 'readUInt8' or 'readInt32' var method = [ 'read', signed ? '' : 'U', 'Int', buffer.length * 8, buffer.length > 1 ? 'BE' : '' ].join(''); return buffer[method](0); }; // return a value as a percentage scaled to the given ranges module.exports.scaleValue = function (rawValue, options) { var defaults = { min_raw: 0, min_actual: 0 }; options = extend(defaults, options); var rangeRaw = options.max_raw - options.min_raw; var rangeActual = options.max_actual - options.min_actual; return (1.0 * rawValue / rangeRaw) * rangeActual; }; // parse the first byte as a boolean and return it module.exports.byteToBool = function (bytes) { return !!(bytes[0]); } // create a byte that's a combination of the given bits, in low to high order. // only the lowest values need to be specified - all others will be assumed 0. module.exports.bitsToByte = function (bits) { // jshint bitwise:false var b = 0; b = b ^ (!!bits[0] << 0); b = b ^ (!!bits[1] << 1); b = b ^ (!!bits[2] << 2); b = b ^ (!!bits[3] << 3); b = b ^ (!!bits[4] << 4); b = b ^ (!!bits[5] << 5); b = b ^ (!!bits[6] << 6); b = b ^ (!!bits[7] << 7); return b; }; // return the bits of a byte as a boolean array module.exports.byteToBits = function (b) { // jshint bitwise:false return [ !!(b & 0x1), !!((b & 0x2) >> 1), !!((b & 0x4) >> 2), !!((b & 0x8) >> 3), !!((b & 0x10) >> 4), !!((b & 0x20) >> 5), !!((b & 0x40) >> 6), !!((b & 0x80) >> 7) ]; }; // given a 'previous' version of an object, the current version of the same // object, and a dot-delimited key string, determine if that key's value has // changed between objects using a deep-equals comparison. if the value has // changed, return it in a 'value' key in the result object. if the values are // the same, returns an empty object. if a callback is specified, it is run with // the current value if that value differs from the previous one. if context is // specified, the callback will be run with it as its 'this' value. module.exports.compare = function (prevObj, curObj, keyString, callback, context) { var keyParts = keyString.trim().split('.'); var i, length, key; // get the previous and current values at our key location var prevVal = prevObj; var curVal = curObj; for (i = 0, length = keyParts.length; key = keyParts[i], i < length; i++) { prevVal = prevVal[key]; curVal = curVal[key]; } // return information about whether the values differed var result = { key: keyString, changed: !_.isEqual(curVal, prevVal), value: curVal }; // run the callback function if the value changed if (result.changed && _.isFunction(callback)) { callback.call(context || null, result.value); } return result; };
var utils = require('../utils'); var _ = require('lodash'); var factory = require('../factory'); var hasValue = utils.hasValue; function parseFloatFromString(value) { if (/^(\-|\+)?([0-9]+(\.[0-9]+)?)$/.test(value)) { return Number(value); } return value; } module.exports = factory({ initialize: function(opts) { this.opts = opts || {}; var hasMinValue = hasValue(this.opts.min); var hasMaxValue = hasValue(this.opts.max); if (hasMinValue && !_.isNumber(this.opts.min)) { throw new Error('Invalid minimum option: ' + this.opts.min); } if (hasMaxValue && !_.isNumber(this.opts.max)) { throw new Error('Invalid maximum option: ' + this.opts.max); } this.min = this.opts.min; this.max = this.opts.max; this.parse = this.opts.parse || false; this.description = this.opts.description; if (this.min != null && this.max != null && this.min > this.max) { throw new Error('Invalid option: ' + this.min + ' > ' + this.max); } }, match: function(path, value) { if (this.parse) { value = parseFloatFromString(value); } if (typeof value !== 'number') { return 'should be a number'; } if (this.min != null && this.max != null && (value < this.min || value > this.max)) { return 'should be a number between ' + this.min + ' and ' + this.max; } if (this.min != null && value < this.min) { return 'should be a number >= ' + this.min; } if (this.max != null && value > this.max) { return 'should be a number <= ' + this.max; } }, toJSONSchema: function() { var schema = { type: 'number' }; if (this.min) { schema.minimum = this.min; } if (this.max) { schema.maximum = this.max; } if (this.description) { schema.description = this.description; } return schema; } });
/** * ${project} < ${FILE} > * * @DATE ${DATE} * @VERSION ${version} * @AUTHOR ${author} * * ---------------------------------------------------------------------------- * * ---------------------------------------------------------------------------- */ Define("jQuery.Easing", Depend("./jQuery"), function(require, JEasing, module) { var jQuery = require("jQuery"); jQuery.easing['jswing'] = jQuery.easing['swing']; module.exports = jQuery.extend( jQuery.easing, { def: 'easeOutQuad', swing: function (x, t, b, c, d) { //alert(jQuery.easing.default); return jQuery.easing[jQuery.easing.def](x, t, b, c, d); }, easeInQuad: function (x, t, b, c, d) { return c*(t/=d)*t + b; }, easeOutQuad: function (x, t, b, c, d) { return -c *(t/=d)*(t-2) + b; }, easeInOutQuad: function (x, t, b, c, d) { if ((t/=d/2) < 1) return c/2*t*t + b; return -c/2 * ((--t)*(t-2) - 1) + b; }, easeInCubic: function (x, t, b, c, d) { return c*(t/=d)*t*t + b; }, easeOutCubic: function (x, t, b, c, d) { return c*((t=t/d-1)*t*t + 1) + b; }, easeInOutCubic: function (x, t, b, c, d) { if ((t/=d/2) < 1) return c/2*t*t*t + b; return c/2*((t-=2)*t*t + 2) + b; }, easeInQuart: function (x, t, b, c, d) { return c*(t/=d)*t*t*t + b; }, easeOutQuart: function (x, t, b, c, d) { return -c * ((t=t/d-1)*t*t*t - 1) + b; }, easeInOutQuart: function (x, t, b, c, d) { if ((t/=d/2) < 1) return c/2*t*t*t*t + b; return -c/2 * ((t-=2)*t*t*t - 2) + b; }, easeInQuint: function (x, t, b, c, d) { return c*(t/=d)*t*t*t*t + b; }, easeOutQuint: function (x, t, b, c, d) { return c*((t=t/d-1)*t*t*t*t + 1) + b; }, easeInOutQuint: function (x, t, b, c, d) { if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b; return c/2*((t-=2)*t*t*t*t + 2) + b; }, easeInSine: function (x, t, b, c, d) { return -c * Math.cos(t/d * (Math.PI/2)) + c + b; }, easeOutSine: function (x, t, b, c, d) { return c * Math.sin(t/d * (Math.PI/2)) + b; }, easeInOutSine: function (x, t, b, c, d) { return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b; }, easeInExpo: function (x, t, b, c, d) { return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b; }, easeOutExpo: function (x, t, b, c, d) { return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b; }, easeInOutExpo: function (x, t, b, c, d) { if (t==0) return b; if (t==d) return b+c; if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b; return c/2 * (-Math.pow(2, -10 * --t) + 2) + b; }, easeInCirc: function (x, t, b, c, d) { return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b; }, easeOutCirc: function (x, t, b, c, d) { return c * Math.sqrt(1 - (t=t/d-1)*t) + b; }, easeInOutCirc: function (x, t, b, c, d) { if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b; return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b; }, easeInElastic: function (x, t, b, c, d) { var s=1.70158;var p=0;var a=c; if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3; if (a < Math.abs(c)) { a=c; var s=p/4; } else var s = p/(2*Math.PI) * Math.asin (c/a); return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; }, easeOutElastic: function (x, t, b, c, d) { var s=1.70158;var p=0;var a=c; if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3; if (a < Math.abs(c)) { a=c; var s=p/4; } else var s = p/(2*Math.PI) * Math.asin (c/a); return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b; }, easeInOutElastic: function (x, t, b, c, d) { var s=1.70158;var p=0;var a=c; if (t==0) return b; if ((t/=d/2)==2) return b+c; if (!p) p=d*(.3*1.5); if (a < Math.abs(c)) { a=c; var s=p/4; } else var s = p/(2*Math.PI) * Math.asin (c/a); if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b; }, easeInBack: function (x, t, b, c, d, s) { if (s == undefined) s = 1.70158; return c*(t/=d)*t*((s+1)*t - s) + b; }, easeOutBack: function (x, t, b, c, d, s) { if (s == undefined) s = 1.70158; return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b; }, easeInOutBack: function (x, t, b, c, d, s) { if (s == undefined) s = 1.70158; if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b; return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b; }, easeInBounce: function (x, t, b, c, d) { return c - jQuery.easing.easeOutBounce (x, d-t, 0, c, d) + b; }, easeOutBounce: function (x, t, b, c, d) { if ((t/=d) < (1/2.75)) { return c*(7.5625*t*t) + b; } else if (t < (2/2.75)) { return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b; } else if (t < (2.5/2.75)) { return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b; } else { return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b; } }, easeInOutBounce: function (x, t, b, c, d) { if (t < d/2) return jQuery.easing.easeInBounce (x, t*2, 0, c, d) * .5 + b; return jQuery.easing.easeOutBounce (x, t*2-d, 0, c, d) * .5 + c*.5 + b; } }); })
work = load("charge-tm.circuit.work"); tagCircuitPathBreakerClearAll(work); tagCircuitPathBreakerAutoAppend(work); insertCircuitTestableGates(work); insertCircuitScan(work); write( "Cycle absence check: " + checkCircuitCycles(work) + "\n" + "Combined check: " + checkCircuitCombined(work) + "\n" + statCircuit(work), "charge-tm.circuit.stat"); exit();
module.exports = function () { return async (ctx, next) => { try { await next(); } catch (err) { ctx.status = 500; ctx.app.emit('error', err); return ctx.render('500'); } }; };
var crypto = require('crypto') var http = require('http'); var HANDLER = process.env._HANDLER var FN_NAME = process.env.AWS_LAMBDA_FUNCTION_NAME var VERSION = process.env.AWS_LAMBDA_FUNCTION_VERSION var MEM_SIZE = process.env.AWS_LAMBDA_FUNCTION_MEMORY_SIZE var TIMEOUT = process.env.AWS_LAMBDA_FUNCTION_TIMEOUT var REGION = process.env.AWS_REGION var ACCOUNT_ID = process.env.AWS_ACCOUNT_ID var ACCESS_KEY_ID = process.env.AWS_ACCESS_KEY_ID var SECRET_ACCESS_KEY = process.env.AWS_SECRET_ACCESS_KEY var SESSION_TOKEN = process.env.AWS_SESSION_TOKEN function consoleLog(str) { process.stderr.write(formatConsole(str)) } function systemLog(str) { process.stderr.write(formatSystem(str) + '\n') } function systemErr(str) { process.stderr.write(formatErr(str) + '\n') } // Don't think this can be done in the Docker image process.umask(2) var OPTIONS = { initInvokeId: uuid(), handler: HANDLER, suppressInit: true, credentials: { key: ACCESS_KEY_ID, secret: SECRET_ACCESS_KEY, session: SESSION_TOKEN, }, contextObjects: { // XXX do we need this here // clientContext: '{}', // cognitoIdentityId: undefined, // cognitoPoolId: undefined, }, } var invoked = false var start = null // InvokeServer implement an http server that listen to a single request at a time // After recieving this single request it close the socket until it is armed again class InvokeServer { // start the server, and listen to a single request start() { if (this.server) { throw Error("InvokeServer already started") } this.cb = null this.err = null this.msg = null this.server = http.createServer((request,response) => this._recieve(request,response)) this.server.listen(8999) } _recieve(request,response) { let body = []; request.on('error', (err) => { systemLog('_recieve error:' + err) this._result(err) }).on('data', (chunk) => { body.push(chunk); }).on('end', () => { var err var msg try { body = Buffer.concat(body).toString(); msg = JSON.parse(body) } catch (e) { response.writeHead(500,'Exception') err = e } response.end() this._result(err, msg) }); } _result(err,msg) { this._close() if (this.cb != null) { this.cb(err, msg) } else { this.err = err this.msg = msg } } _close() { this.server.close((err) => { if (err) { systemLog('closed server error: ' + err) } }) this.server = null } // wait the server to recieve the message, if the message arrived before wait is called, // the call back is called imedatly, otherwise we store the cb to be called when the message arive wait(cb) { if (this.msg != null) { setImmediate(cb, this.err, this.msg) this.msg = null } else { if (!this.server) { throw Error("not listening") } this.cb = cb } } } var invokeServer = new InvokeServer() invokeServer.start() module.exports = { initRuntime: function() { process.stdout.write(JSON.stringify({OK:true})) return OPTIONS }, waitForInvoke: function(fn) { invokeServer.wait( (err,msg,response) => { if (err != null) { systemLog('recived message error: ' + err) process.exit(2) } invoked=true start = process.hrtime() deadline = new Date(msg.deadline) TIMEOUT = 100*(1+Math.floor(module.exports.getRemainingTime()/100)) try { fn({ invokeid: msg.context.aws_request_id, invokeId: msg.context.aws_request_id, credentials: { key: ACCESS_KEY_ID, secret: SECRET_ACCESS_KEY, session: SESSION_TOKEN, }, eventBody: JSON.stringify(msg.event), contextObjects: { // TODO // clientContext: '{}', // cognitoIdentityId: undefined, // cognitoPoolId: undefined, }, invokedFunctionArn: msg.context.invoked_function_arn, }) } catch (err) { systemLog('User handler encountered an error: ' + err) setImmediate(module.exports.reportDone, msg.context.aws_request_id,"exception",JSON.stringify(err.toString())) } }) }, reportRunning: function(invokeId) {}, // eslint-disable-line no-unused-vars reportDone: function(invokeId, errType, resultStr) { if (!invoked) { return } var diffMs = hrTimeMs(process.hrtime(start)) var billedMs = Math.min(100 * (Math.floor(diffMs / 100) + 1), TIMEOUT * 1000) systemLog('END RequestId: ' + invokeId) process.stdout.write(JSON.stringify({ result:JSON.parse(resultStr), errortype:errType, invokeid:invokeId, errors: errType!=null, billing: { duration: diffMs, memory: MEM_SIZE, Used: Math.round(process.memoryUsage().rss / (1024 * 1024)), } })) invokeServer.start() }, reportFault: function(invokeId, msg, errName, errStack) { systemErr(msg + (errName ? ': ' + errName : '')) if (errStack) systemErr(errStack) }, reportUserInitStart: function() {}, reportUserInitEnd: function() {}, reportUserInvokeStart: function() {}, reportUserInvokeEnd: function() {}, reportException: function() {}, getRemainingTime: function() { return deadline.getTime() - (new Date()).getTime() }, sendConsoleLogs: consoleLog, maxLoggerErrorSize: 256 * 1024, } function formatConsole(str) { return str.replace(/^[0-9TZ:\.\-]+\t[0-9a-f\-]+\t/, '\033[34m$&\u001b[0m') } function formatSystem(str) { return '\033[32m' + str + '\033[0m' } function formatErr(str) { return '\033[31m' + str + '\033[0m' } function hrTimeMs(hrtime) { return (hrtime[0] * 1e9 + hrtime[1]) / 1e6 } // Approximates the look of a v1 UUID function uuid() { return crypto.randomBytes(4).toString('hex') + '-' + crypto.randomBytes(2).toString('hex') + '-' + crypto.randomBytes(2).toString('hex').replace(/^./, '1') + '-' + crypto.randomBytes(2).toString('hex') + '-' + crypto.randomBytes(6).toString('hex') }
import { fromJS } from 'immutable'; export const INITIAL_STATE = fromJS({}); export function setEntries(state, entries) { return state.set('entries', fromJS(entries)); } function getWinner(voteState) { if (!voteState) { return []; } const [a, b] = voteState.get('pair'); const aVotes = voteState.getIn(['tally', a], 0); const bVotes = voteState.getIn(['tally', b], 0); if (aVotes > bVotes) { return [a]; } else if (aVotes < bVotes) { return [b]; } return [a, b]; } export function next(state) { const entries = state.get('entries') .concat(getWinner(state.get('vote'))); if (entries.size === 1) { return state.remove('entries') .remove('vote') .set('winner', entries.first()); } return state.merge({ vote: { pair: entries.take(2), }, entries: entries.skip(2), }); } export function vote(voteState, entry) { return voteState.updateIn(['tally', entry], 0, tally => tally + 1); }
const path = require('path'); const webpack = require('webpack'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const CopyWebpackPlugin = require('copy-webpack-plugin'); const CleanWebpackPlugin = require('clean-webpack-plugin'); const helpers = require('./webpack.helpers'); const ROOT = path.resolve(__dirname, '..'); console.log('@@@@@@@@@ USING DEVELOPMENT @@@@@@@@@@@@@@@'); module.exports = { devtool: 'source-map', performance: { hints: false }, entry: { 'polyfills': './angularApp/polyfills.ts', 'vendor': './angularApp/vendor.ts', 'app': './angularApp/main.ts' }, output: { path: ROOT + '/wwwroot/', filename: 'dist/[name].bundle.js', chunkFilename: 'dist/[id].chunk.js', publicPath: '/' }, resolve: { extensions: ['.ts', '.js', '.json'] }, devServer: { historyApiFallback: true, contentBase: path.join(ROOT, '/wwwroot/'), watchOptions: { aggregateTimeout: 300, poll: 1000 } }, module: { rules: [ { test: /\.ts$/, use: [ 'awesome-typescript-loader', 'angular-router-loader', 'angular2-template-loader', 'source-map-loader', 'tslint-loader' ] }, { test: /\.(png|jpg|gif|woff|woff2|ttf|svg|eot)$/, use: 'file-loader?name=assets/[name]-[hash:6].[ext]' }, { test: /favicon.ico$/, use: 'file-loader?name=/[name].[ext]' }, { test: /\.css$/, use: [ 'style-loader', 'css-loader' ] }, { test: /\.scss$/, include: path.join(ROOT, 'angularApp/style'), use: [ 'style-loader', 'css-loader', 'sass-loader' ] }, { test: /\.scss$/, exclude: path.join(ROOT, 'angularApp/style'), use: [ 'raw-loader', 'sass-loader' ] }, { test: /\.html$/, use: 'raw-loader' } ], exprContextCritical: false }, plugins: [ new webpack.optimize.CommonsChunkPlugin({ name: ['vendor', 'polyfills'] }), new CleanWebpackPlugin( [ './wwwroot/dist', './wwwroot/assets' ], { root: ROOT } ), new HtmlWebpackPlugin({ filename: 'index.html', inject: 'body', template: 'angularApp/index.html' }), new CopyWebpackPlugin([ { from: './angularApp/images/*.*', to: 'assets/', flatten: true } ]) ] };
export { default as Login } from './login'; export { default as Home } from './home'; export { default as Account } from './account'; export { default as Article } from './article'; export { default as ArticleDetail } from './article_detail'; export { default as Recommend } from './recommend'; export { default as RecommendDetail } from './recommend_detail';
"use strict"; import React from 'react'; class Timer extends React.Component { constructor(props) { super(props); // 與 ES5 React.createClass({}) 不同的是 component 內自定義的方法需要自行綁定 this context //或是使用 arrow function this.tick = this.tick.bind(this); // 初始 state,等於 ES5 中的 getInitialState this.state = { secondsElapsed: 0, } } // 累加器方法,每一秒被呼叫後就會使用 setState() 更新內部 state,讓 Component 重新 render tick() { this.setState( { secondsElapsed : this.state.secondsElapsed +1 }); } // componentDidMount 為 component 生命週期中階段 component 已插入節點的階段, //通常一些非同步操作都會放置在這個階段。這便是每1秒鐘會去呼叫 tick 方法 componentDidMount() { this.interval = setInterval(this.tick, 1000); } // componentWillUnmount 為 component 生命週期中 component 即將移出插入的節點的階段。 //這邊移除了 setInterval 效力 componentWillUnmount() { clearInterval(this.interval); } // render 為 class Component 中唯一需要定義的方法,其回傳 component 欲顯示的內容 render() { return ( <div>Seconds Elapsed: {this.state.secondsElapsed}</div> ); } } export default Timer;
const path = require("path"); const Utility = require("./util/Utility"); function InitConfiguration(src, build, test, lib, babelOptions) { /** * * @type {{root: (string|*), node_modules: (string|*)}} */ const paths = { root: Utility.projectDir, app: path.join(Utility.projectDir, src), build: path.join(Utility.projectDir, build), test: path.join(Utility.projectDir, test), lib: lib ? path.join(Utility.projectDir, lib) : null, node_modules: path.join(Utility.projectDir, "/node_modules") }; if (!babelOptions) { babelOptions = { presets: [ "react", "es2015", "stage-0" ] }; } const conf = { paths: paths, // reference path variable /** * @link https://webpack.github.io/docs/configuration.html#context * The base path directory for resolving the entry option if output.pathinfo is set the include shortened to this directory. */ context: paths.app, /* add resolve.extensions */ /** * * @link https://webpack.github.io/docs/configuration.html#resolve */ resolve: { /** * @link https://webpack.github.io/docs/configuration.html#resolve-root * The directory (absolute path) that contains your modules. * May also be an array of directories. This setting should be used to add individual directories to the search path. * It must be an absolute path! Don’t pass something like ./app/modules. */ root: [paths.app], /** * @link https://webpack.github.io/docs/configuration.html#resolve-extensions * An array of extensions that should be used to resolve modules. * For example, in order to discover react jsx files, your array should contain the string ".jsx". */ extensions: ["", ".jsx", ".js", ".json"], /** * @link https://webpack.github.io/docs/configuration.html#resolve-modulesdirectories * An array of directory names to be resolved to the current directory as well as its ancestors, and searched for modules. * This functions similarly to how node finds “node_modules” directories. * For example, if the value is ["mydir"], webpack will look in “./mydir”, “../mydir”, “../../mydir”, etc. */ modulesDirectories: [paths.node_modules] }, /** * @link https://webpack.github.io/docs/configuration.html#module */ module: { noParse: [/autoit.js/], /** * @link https://webpack.github.io/docs/configuration.html#module-preloaders-module-postloaders */ preLoaders: [], /** * https://webpack.github.io/docs/configuration.html#loaders */ loaders: [ { /** * @link https://github.com/gaearon/react-hot-loader * npm install react-hot-loader --save-dev */ test: /\.jsx?$/, loader: "babel", loaders: ["babel", "react-hot"], exclude: /(node_modules|bower_components|fonts)/, include: paths.lib ? [paths.app, paths.lib, paths.test] : [paths.app, paths.test], query: babelOptions }, { /** * @link https://github.com/webpack/json-loader * npm install json-loader --save-dev */ test: /\.json$/, loader: "json-loader" }, { /** * @link https://github.com/webpack/file-loader * npm install file-loader --save-dev */ test: /\.(ttf|eot|svg|woff(2)?)(\?[a-z0-9]+)?$/, loader: "file-loader", include: /fonts/ }, { test: /\.s?css$/, loader: "style-loader!css-loader" }, { /** * @link https://github.com/webpack/url-loader * npm install url-loader --save-dev */ test: /\.(eot|woff|woff2|ttf|svg|png|jpe?g|gif)(\?\S*)?$/, loader: "url?limit=100000&name=[name].[ext]" }, { /** * @link https://github.com/webpack/json-loader * npm install json-loader --save-dev */ test: /\.txt$/, loader: "raw-loader" } ] }, /** * @link https://webpack.github.io/docs/configuration.html#plugins * will added by environment mode. */ plugins: [] }; if (paths.lib) { conf.resolve.root.push(paths.lib); } return conf; } module.exports = InitConfiguration;
import $ from 'jquery'; import * as utils from './utilities'; function getPointersCenter(pointers) { let pageX = 0; let pageY = 0; let count = 0; $.each(pointers, (i, { startX, startY }) => { pageX += startX; pageY += startY; count += 1; }); pageX /= count; pageY /= count; return { pageX, pageY, }; } export default { // Show the crop box manually crop() { const self = this; if (!self.ready || self.disabled) { return; } if (!self.cropped) { self.cropped = true; self.limitCropBox(true, true); if (self.options.modal) { self.$dragBox.addClass('cropper-modal'); } self.$cropBox.removeClass('cropper-hidden'); } self.setCropBoxData(self.initialCropBox); }, // Reset the image and crop box to their initial states reset() { const self = this; if (!self.ready || self.disabled) { return; } self.image = $.extend({}, self.initialImage); self.canvas = $.extend({}, self.initialCanvas); self.cropBox = $.extend({}, self.initialCropBox); self.renderCanvas(); if (self.cropped) { self.renderCropBox(); } }, // Clear the crop box clear() { const self = this; if (!self.cropped || self.disabled) { return; } $.extend(self.cropBox, { left: 0, top: 0, width: 0, height: 0 }); self.cropped = false; self.renderCropBox(); self.limitCanvas(true, true); // Render canvas after crop box rendered self.renderCanvas(); self.$dragBox.removeClass('cropper-modal'); self.$cropBox.addClass('cropper-hidden'); }, /** * Replace the image's src and rebuild the cropper * * @param {String} url * @param {Boolean} onlyColorChanged (optional) */ replace(url, onlyColorChanged) { const self = this; if (!self.disabled && url) { if (self.isImg) { self.$element.attr('src', url); } if (onlyColorChanged) { self.url = url; self.$clone.attr('src', url); if (self.ready) { self.$preview.find('img').add(self.$clone2).attr('src', url); } } else { if (self.isImg) { self.replaced = true; } // Clear previous data self.options.data = null; self.load(url); } } }, // Enable (unfreeze) the cropper enable() { const self = this; if (self.ready) { self.disabled = false; self.$cropper.removeClass('cropper-disabled'); } }, // Disable (freeze) the cropper disable() { const self = this; if (self.ready) { self.disabled = true; self.$cropper.addClass('cropper-disabled'); } }, // Destroy the cropper and remove the instance from the image destroy() { const self = this; const $this = self.$element; if (self.loaded) { if (self.isImg && self.replaced) { $this.attr('src', self.originalUrl); } self.unbuild(); $this.removeClass('cropper-hidden'); } else if (self.isImg) { $this.off('load', self.start); } else if (self.$clone) { self.$clone.remove(); } $this.removeData('cropper'); }, /** * Move the canvas with relative offsets * * @param {Number} offsetX * @param {Number} offsetY (optional) */ move(offsetX, offsetY) { const self = this; const canvas = self.canvas; self.moveTo( utils.isUndefined(offsetX) ? offsetX : canvas.left + Number(offsetX), utils.isUndefined(offsetY) ? offsetY : canvas.top + Number(offsetY) ); }, /** * Move the canvas to an absolute point * * @param {Number} x * @param {Number} y (optional) */ moveTo(x, y) { const self = this; const canvas = self.canvas; let changed = false; // If "y" is not present, its default value is "x" if (utils.isUndefined(y)) { y = x; } x = Number(x); y = Number(y); if (self.ready && !self.disabled && self.options.movable) { if (utils.isNumber(x)) { canvas.left = x; changed = true; } if (utils.isNumber(y)) { canvas.top = y; changed = true; } if (changed) { self.renderCanvas(true); } } }, /** * Zoom the canvas with a relative ratio * * @param {Number} ratio * @param {jQuery Event} _event (private) */ zoom(ratio, _event) { const self = this; const canvas = self.canvas; ratio = Number(ratio); if (ratio < 0) { ratio = 1 / (1 - ratio); } else { ratio = 1 + ratio; } self.zoomTo((canvas.width * ratio) / canvas.naturalWidth, _event); }, /** * Zoom the canvas to an absolute ratio * * @param {Number} ratio * @param {jQuery Event} _event (private) */ zoomTo(ratio, _event) { const self = this; const options = self.options; const pointers = self.pointers; const canvas = self.canvas; const width = canvas.width; const height = canvas.height; const naturalWidth = canvas.naturalWidth; const naturalHeight = canvas.naturalHeight; ratio = Number(ratio); if (ratio >= 0 && self.ready && !self.disabled && options.zoomable) { const newWidth = naturalWidth * ratio; const newHeight = naturalHeight * ratio; let originalEvent; if (_event) { originalEvent = _event.originalEvent; } if (self.trigger('zoom', { originalEvent, oldRatio: width / naturalWidth, ratio: newWidth / naturalWidth }).isDefaultPrevented()) { return; } if (originalEvent) { const offset = self.$cropper.offset(); const center = pointers && utils.objectKeys(pointers).length ? getPointersCenter(pointers) : { pageX: _event.pageX || originalEvent.pageX || 0, pageY: _event.pageY || originalEvent.pageY || 0 }; // Zoom from the triggering point of the event canvas.left -= (newWidth - width) * ( ((center.pageX - offset.left) - canvas.left) / width ); canvas.top -= (newHeight - height) * ( ((center.pageY - offset.top) - canvas.top) / height ); } else { // Zoom from the center of the canvas canvas.left -= (newWidth - width) / 2; canvas.top -= (newHeight - height) / 2; } canvas.width = newWidth; canvas.height = newHeight; self.renderCanvas(true); } }, /** * Rotate the canvas with a relative degree * * @param {Number} degree */ rotate(degree) { const self = this; self.rotateTo((self.image.rotate || 0) + Number(degree)); }, /** * Rotate the canvas to an absolute degree * https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function#rotate() * * @param {Number} degree */ rotateTo(degree) { const self = this; degree = Number(degree); if (utils.isNumber(degree) && self.ready && !self.disabled && self.options.rotatable) { self.image.rotate = degree % 360; self.rotated = true; self.renderCanvas(true); } }, /** * Scale the image * https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function#scale() * * @param {Number} scaleX * @param {Number} scaleY (optional) */ scale(scaleX, scaleY) { const self = this; const image = self.image; let changed = false; // If "scaleY" is not present, its default value is "scaleX" if (utils.isUndefined(scaleY)) { scaleY = scaleX; } scaleX = Number(scaleX); scaleY = Number(scaleY); if (self.ready && !self.disabled && self.options.scalable) { if (utils.isNumber(scaleX)) { image.scaleX = scaleX; changed = true; } if (utils.isNumber(scaleY)) { image.scaleY = scaleY; changed = true; } if (changed) { self.renderImage(true); } } }, /** * Scale the abscissa of the image * * @param {Number} scaleX */ scaleX(scaleX) { const self = this; const scaleY = self.image.scaleY; self.scale(scaleX, utils.isNumber(scaleY) ? scaleY : 1); }, /** * Scale the ordinate of the image * * @param {Number} scaleY */ scaleY(scaleY) { const self = this; const scaleX = self.image.scaleX; self.scale(utils.isNumber(scaleX) ? scaleX : 1, scaleY); }, /** * Get the cropped area position and size data (base on the original image) * * @param {Boolean} isRounded (optional) * @return {Object} data */ getData(isRounded) { const self = this; const options = self.options; const image = self.image; const canvas = self.canvas; const cropBox = self.cropBox; let ratio; let data; if (self.ready && self.cropped) { data = { x: cropBox.left - canvas.left, y: cropBox.top - canvas.top, width: cropBox.width, height: cropBox.height }; ratio = image.width / image.naturalWidth; $.each(data, (i, n) => { n /= ratio; data[i] = isRounded ? Math.round(n) : n; }); } else { data = { x: 0, y: 0, width: 0, height: 0 }; } if (options.rotatable) { data.rotate = image.rotate || 0; } if (options.scalable) { data.scaleX = image.scaleX || 1; data.scaleY = image.scaleY || 1; } return data; }, /** * Set the cropped area position and size with new data * * @param {Object} data */ setData(data) { const self = this; const options = self.options; const image = self.image; const canvas = self.canvas; const cropBoxData = {}; let rotated; let isScaled; let ratio; if ($.isFunction(data)) { data = data.call(self.element); } if (self.ready && !self.disabled && $.isPlainObject(data)) { if (options.rotatable) { if (utils.isNumber(data.rotate) && data.rotate !== image.rotate) { image.rotate = data.rotate; self.rotated = rotated = true; } } if (options.scalable) { if (utils.isNumber(data.scaleX) && data.scaleX !== image.scaleX) { image.scaleX = data.scaleX; isScaled = true; } if (utils.isNumber(data.scaleY) && data.scaleY !== image.scaleY) { image.scaleY = data.scaleY; isScaled = true; } } if (rotated) { self.renderCanvas(); } else if (isScaled) { self.renderImage(); } ratio = image.width / image.naturalWidth; if (utils.isNumber(data.x)) { cropBoxData.left = (data.x * ratio) + canvas.left; } if (utils.isNumber(data.y)) { cropBoxData.top = (data.y * ratio) + canvas.top; } if (utils.isNumber(data.width)) { cropBoxData.width = data.width * ratio; } if (utils.isNumber(data.height)) { cropBoxData.height = data.height * ratio; } self.setCropBoxData(cropBoxData); } }, /** * Get the container size data * * @return {Object} data */ getContainerData() { return this.ready ? this.container : {}; }, /** * Get the image position and size data * * @return {Object} data */ getImageData() { return this.loaded ? this.image : {}; }, /** * Get the canvas position and size data * * @return {Object} data */ getCanvasData() { const self = this; const canvas = self.canvas; const data = {}; if (self.ready) { $.each([ 'left', 'top', 'width', 'height', 'naturalWidth', 'naturalHeight' ], (i, n) => { data[n] = canvas[n]; }); } return data; }, /** * Set the canvas position and size with new data * * @param {Object} data */ setCanvasData(data) { const self = this; const canvas = self.canvas; const aspectRatio = canvas.aspectRatio; if ($.isFunction(data)) { data = data.call(self.$element); } if (self.ready && !self.disabled && $.isPlainObject(data)) { if (utils.isNumber(data.left)) { canvas.left = data.left; } if (utils.isNumber(data.top)) { canvas.top = data.top; } if (utils.isNumber(data.width)) { canvas.width = data.width; canvas.height = data.width / aspectRatio; } else if (utils.isNumber(data.height)) { canvas.height = data.height; canvas.width = data.height * aspectRatio; } self.renderCanvas(true); } }, /** * Get the crop box position and size data * * @return {Object} data */ getCropBoxData() { const self = this; const cropBox = self.cropBox; return self.ready && self.cropped ? { left: cropBox.left, top: cropBox.top, width: cropBox.width, height: cropBox.height } : {}; }, /** * Set the crop box position and size with new data * * @param {Object} data */ setCropBoxData(data) { const self = this; const cropBox = self.cropBox; const aspectRatio = self.options.aspectRatio; let widthChanged; let heightChanged; if ($.isFunction(data)) { data = data.call(self.$element); } if (self.ready && self.cropped && !self.disabled && $.isPlainObject(data)) { if (utils.isNumber(data.left)) { cropBox.left = data.left; } if (utils.isNumber(data.top)) { cropBox.top = data.top; } if (utils.isNumber(data.width) && data.width !== cropBox.width) { widthChanged = true; cropBox.width = data.width; } if (utils.isNumber(data.height) && data.height !== cropBox.height) { heightChanged = true; cropBox.height = data.height; } if (aspectRatio) { if (widthChanged) { cropBox.height = cropBox.width / aspectRatio; } else if (heightChanged) { cropBox.width = cropBox.height * aspectRatio; } } self.renderCropBox(); } }, /** * Get a canvas drawn the cropped image * * @param {Object} options (optional) * @return {HTMLCanvasElement} canvas */ getCroppedCanvas(options) { const self = this; if (!self.ready || !window.HTMLCanvasElement) { return null; } if (!self.cropped) { return utils.getSourceCanvas(self.$clone[0], self.image); } if (!$.isPlainObject(options)) { options = {}; } const data = self.getData(); const originalWidth = data.width; const originalHeight = data.height; const aspectRatio = originalWidth / originalHeight; let scaledWidth; let scaledHeight; let scaledRatio; if ($.isPlainObject(options)) { scaledWidth = options.width; scaledHeight = options.height; if (scaledWidth) { scaledHeight = scaledWidth / aspectRatio; scaledRatio = scaledWidth / originalWidth; } else if (scaledHeight) { scaledWidth = scaledHeight * aspectRatio; scaledRatio = scaledHeight / originalHeight; } } // The canvas element will use `Math.Math.floor` on a float number, so Math.floor first const canvasWidth = Math.floor(scaledWidth || originalWidth); const canvasHeight = Math.floor(scaledHeight || originalHeight); const canvas = $('<canvas>')[0]; const context = canvas.getContext('2d'); canvas.width = canvasWidth; canvas.height = canvasHeight; if (options.fillColor) { context.fillStyle = options.fillColor; context.fillRect(0, 0, canvasWidth, canvasHeight); } if ($.isFunction(options.beforeDrawImage)) { options.beforeDrawImage(canvas); } // https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D.drawImage const parameters = (() => { const source = utils.getSourceCanvas(self.$clone[0], self.image); const sourceWidth = source.width; const sourceHeight = source.height; const canvasData = self.canvas; const params = [source]; // Source canvas let srcX = data.x + ((canvasData.naturalWidth * (Math.abs(data.scaleX || 1) - 1)) / 2); let srcY = data.y + ((canvasData.naturalHeight * (Math.abs(data.scaleY || 1) - 1)) / 2); let srcWidth; let srcHeight; // Destination canvas let dstX; let dstY; let dstWidth; let dstHeight; if (srcX <= -originalWidth || srcX > sourceWidth) { srcX = srcWidth = dstX = dstWidth = 0; } else if (srcX <= 0) { dstX = -srcX; srcX = 0; srcWidth = dstWidth = Math.min(sourceWidth, originalWidth + srcX); } else if (srcX <= sourceWidth) { dstX = 0; srcWidth = dstWidth = Math.min(originalWidth, sourceWidth - srcX); } if (srcWidth <= 0 || srcY <= -originalHeight || srcY > sourceHeight) { srcY = srcHeight = dstY = dstHeight = 0; } else if (srcY <= 0) { dstY = -srcY; srcY = 0; srcHeight = dstHeight = Math.min(sourceHeight, originalHeight + srcY); } else if (srcY <= sourceHeight) { dstY = 0; srcHeight = dstHeight = Math.min(originalHeight, sourceHeight - srcY); } // All the numerical parameters should be integer for `drawImage` (#476) params.push(Math.floor(srcX), Math.floor(srcY), Math.floor(srcWidth), Math.floor(srcHeight)); // Scale destination sizes if (scaledRatio) { dstX *= scaledRatio; dstY *= scaledRatio; dstWidth *= scaledRatio; dstHeight *= scaledRatio; } // Avoid "IndexSizeError" in IE and Firefox if (dstWidth > 0 && dstHeight > 0) { params.push( Math.floor(dstX), Math.floor(dstY), Math.floor(dstWidth), Math.floor(dstHeight) ); } return params; })(); context.drawImage(...parameters); return canvas; }, /** * Change the aspect ratio of the crop box * * @param {Number} aspectRatio */ setAspectRatio(aspectRatio) { const self = this; const options = self.options; if (!self.disabled && !utils.isUndefined(aspectRatio)) { // 0 -> NaN options.aspectRatio = Math.max(0, aspectRatio) || NaN; if (self.ready) { self.initCropBox(); if (self.cropped) { self.renderCropBox(); } } } }, /** * Change the drag mode * * @param {String} mode (optional) */ setDragMode(mode) { const self = this; const options = self.options; let croppable; let movable; if (self.loaded && !self.disabled) { croppable = mode === 'crop'; movable = options.movable && mode === 'move'; mode = (croppable || movable) ? mode : 'none'; self.$dragBox .data('action', mode) .toggleClass('cropper-crop', croppable) .toggleClass('cropper-move', movable); if (!options.cropBoxMovable) { // Sync drag mode to crop box when it is not movable(#300) self.$face .data('action', mode) .toggleClass('cropper-crop', croppable) .toggleClass('cropper-move', movable); } } } };
8.0-alpha3:cc857e699d0a71c3df7a89d7151109346c198ad434ca16bc87f0f60dcab93d5b 8.0-alpha4:cc857e699d0a71c3df7a89d7151109346c198ad434ca16bc87f0f60dcab93d5b 8.0-alpha5:cc857e699d0a71c3df7a89d7151109346c198ad434ca16bc87f0f60dcab93d5b 8.0-alpha6:cc857e699d0a71c3df7a89d7151109346c198ad434ca16bc87f0f60dcab93d5b 8.0-alpha7:cc857e699d0a71c3df7a89d7151109346c198ad434ca16bc87f0f60dcab93d5b 8.0-alpha8:cc857e699d0a71c3df7a89d7151109346c198ad434ca16bc87f0f60dcab93d5b 8.0-alpha9:cc857e699d0a71c3df7a89d7151109346c198ad434ca16bc87f0f60dcab93d5b 8.0-alpha10:cc857e699d0a71c3df7a89d7151109346c198ad434ca16bc87f0f60dcab93d5b 8.0-alpha11:cc857e699d0a71c3df7a89d7151109346c198ad434ca16bc87f0f60dcab93d5b 8.0-alpha12:111f76e93f22706c051b90f7f71e8c48127e6b3d3b9f241cdb0384ef5e8727a7 8.0-alpha13:111f76e93f22706c051b90f7f71e8c48127e6b3d3b9f241cdb0384ef5e8727a7 8.0.0-alpha14:111f76e93f22706c051b90f7f71e8c48127e6b3d3b9f241cdb0384ef5e8727a7 8.0.0-alpha15:895ee45dfe3f039dc4ce7538ed701c279c875592e5c2a5def94306a566dfb157 8.0.0-beta1:895ee45dfe3f039dc4ce7538ed701c279c875592e5c2a5def94306a566dfb157 8.0.0-beta2:895ee45dfe3f039dc4ce7538ed701c279c875592e5c2a5def94306a566dfb157 8.0.0-beta3:895ee45dfe3f039dc4ce7538ed701c279c875592e5c2a5def94306a566dfb157 8.0.0-beta4:895ee45dfe3f039dc4ce7538ed701c279c875592e5c2a5def94306a566dfb157 8.0.0-beta6:895ee45dfe3f039dc4ce7538ed701c279c875592e5c2a5def94306a566dfb157 8.0.0-beta7:654ba49194989aec784ea3cc6c239458c9234eeef25c026a54d71e799439b8b4 8.0.0-beta9:654ba49194989aec784ea3cc6c239458c9234eeef25c026a54d71e799439b8b4 8.0.0-beta10:654ba49194989aec784ea3cc6c239458c9234eeef25c026a54d71e799439b8b4 8.0.0-beta11:654ba49194989aec784ea3cc6c239458c9234eeef25c026a54d71e799439b8b4 8.0.0-beta12:654ba49194989aec784ea3cc6c239458c9234eeef25c026a54d71e799439b8b4 8.0.0-beta13:654ba49194989aec784ea3cc6c239458c9234eeef25c026a54d71e799439b8b4 8.0.0-beta14:654ba49194989aec784ea3cc6c239458c9234eeef25c026a54d71e799439b8b4 8.0.0-beta15:654ba49194989aec784ea3cc6c239458c9234eeef25c026a54d71e799439b8b4 8.0.0-beta16:dfead6aafce1bc57e29bfdb4cd7cbf2d569cb3eefcb32975b3829427a3384f41 8.0.0-rc1:dfead6aafce1bc57e29bfdb4cd7cbf2d569cb3eefcb32975b3829427a3384f41 8.0.0-rc2:dfead6aafce1bc57e29bfdb4cd7cbf2d569cb3eefcb32975b3829427a3384f41 8.0.0-rc3:dfead6aafce1bc57e29bfdb4cd7cbf2d569cb3eefcb32975b3829427a3384f41 8.0.0-rc4:dfead6aafce1bc57e29bfdb4cd7cbf2d569cb3eefcb32975b3829427a3384f41 8.0.1:dfead6aafce1bc57e29bfdb4cd7cbf2d569cb3eefcb32975b3829427a3384f41 8.0.2:dfead6aafce1bc57e29bfdb4cd7cbf2d569cb3eefcb32975b3829427a3384f41 8.0.3:dfead6aafce1bc57e29bfdb4cd7cbf2d569cb3eefcb32975b3829427a3384f41 8.0.4:dfead6aafce1bc57e29bfdb4cd7cbf2d569cb3eefcb32975b3829427a3384f41 8.0.5:dfead6aafce1bc57e29bfdb4cd7cbf2d569cb3eefcb32975b3829427a3384f41 8.0.6:dfead6aafce1bc57e29bfdb4cd7cbf2d569cb3eefcb32975b3829427a3384f41 8.1.0-beta1:143615544cf915d282456d21ea680d04e3891883cae05c9c99eda65e00456997 8.1.0-beta2:83a06bbe5f8e06c8561809a2f399423e307645c2a6906bf746795e2d44be6381 8.1.0-rc1:83a06bbe5f8e06c8561809a2f399423e307645c2a6906bf746795e2d44be6381 8.1.1:83a06bbe5f8e06c8561809a2f399423e307645c2a6906bf746795e2d44be6381 8.1.2:83a06bbe5f8e06c8561809a2f399423e307645c2a6906bf746795e2d44be6381 8.1.3:83a06bbe5f8e06c8561809a2f399423e307645c2a6906bf746795e2d44be6381 8.1.4:83a06bbe5f8e06c8561809a2f399423e307645c2a6906bf746795e2d44be6381 8.1.5:83a06bbe5f8e06c8561809a2f399423e307645c2a6906bf746795e2d44be6381 8.1.6:83a06bbe5f8e06c8561809a2f399423e307645c2a6906bf746795e2d44be6381 8.1.7:83a06bbe5f8e06c8561809a2f399423e307645c2a6906bf746795e2d44be6381 8.1.8:45a1adb643a7176062ccaa9462246296a76f466495ea0708a19322fa38123fce 8.1.9:45a1adb643a7176062ccaa9462246296a76f466495ea0708a19322fa38123fce 8.1.10:45a1adb643a7176062ccaa9462246296a76f466495ea0708a19322fa38123fce 8.2.0-beta1:45a1adb643a7176062ccaa9462246296a76f466495ea0708a19322fa38123fce 8.2.0-beta2:45a1adb643a7176062ccaa9462246296a76f466495ea0708a19322fa38123fce 8.2.0-beta3:45a1adb643a7176062ccaa9462246296a76f466495ea0708a19322fa38123fce 8.2.0-rc1:45a1adb643a7176062ccaa9462246296a76f466495ea0708a19322fa38123fce 8.2.0-rc2:45a1adb643a7176062ccaa9462246296a76f466495ea0708a19322fa38123fce 8.2.1:45a1adb643a7176062ccaa9462246296a76f466495ea0708a19322fa38123fce 8.2.2:45a1adb643a7176062ccaa9462246296a76f466495ea0708a19322fa38123fce 8.2.3:45a1adb643a7176062ccaa9462246296a76f466495ea0708a19322fa38123fce 8.2.4:45a1adb643a7176062ccaa9462246296a76f466495ea0708a19322fa38123fce 8.2.5:45a1adb643a7176062ccaa9462246296a76f466495ea0708a19322fa38123fce 8.2.6:45a1adb643a7176062ccaa9462246296a76f466495ea0708a19322fa38123fce 8.3.0-alpha1:7384a55c9a620364cf27a52f03a30b32e38c8a403e1e0f85454fb55487ecc451 8.3.0-beta1:68174fe8fc79d02c6c22dda599902d2fa6e6d89c352ed35a2d8b149fabf0382f 8.3.0-rc1:68174fe8fc79d02c6c22dda599902d2fa6e6d89c352ed35a2d8b149fabf0382f 8.2.7:45a1adb643a7176062ccaa9462246296a76f466495ea0708a19322fa38123fce 8.3.0-rc2:68174fe8fc79d02c6c22dda599902d2fa6e6d89c352ed35a2d8b149fabf0382f 8.0.0:dfead6aafce1bc57e29bfdb4cd7cbf2d569cb3eefcb32975b3829427a3384f41 8.1.0:83a06bbe5f8e06c8561809a2f399423e307645c2a6906bf746795e2d44be6381 8.2.0:45a1adb643a7176062ccaa9462246296a76f466495ea0708a19322fa38123fce 8.3.0:68174fe8fc79d02c6c22dda599902d2fa6e6d89c352ed35a2d8b149fabf0382f
"use strict" var instance; var dataArray; var downloadData = function(){ $.ajax({ url: '/api/list', dataType: 'json', success: function(res) { console.log('_________________'); console.log('Simple List data recieved:'); dataArray = res.data; console.log(dataArray); instance.setState({simpleList: dataArray}); }.bind(instance), error: function(xhr, status, err) { console.log('_________________'); console.log('Data error:'); console.error(instance.props.url, status, err.toString()) }.bind(instance) }); }; var SimpleFilterableList = React.createClass({displayName: "SimpleFilterableList", componentDidMount: function() { instance = this; downloadData(); }, getInitialState: function() { return { userInput: "", simpleList: [ { row: 'cargando ...' } ] }; }, updateUserInput: function(input){ console.log('_________________'); console.log('User search input:'); console.log(input.target.value); this.setState({userInput: input.target.value}); }, favToInput: function(){ console.log('_________________'); console.log('Convertig fav to input'); document.getElementById("newElement").className = ''; document.getElementById("newElement").placeholder = 'Agregar nuevo paso...'; }, sendNewElement: function(key){ if (key.key == "Enter"){ console.log('_________________'); console.log('Sending new element:'); console.log(document.getElementById('newElement').value); document.getElementById('newElement').disabled = true; var newObject = {row:document.getElementById('newElement').value}; dataArray.push(newObject); console.log(dataArray); $.ajax({ url: "/api/update", type: "post", data: {"data":dataArray} }).done(function(response){ // console.log(response.data) downloadData(); document.getElementById('newElement').value = ''; document.getElementById("newElement").className = 'fav'; document.getElementById("newElement").placeholder = "+"; document.getElementById('newElement').disabled = false; document.getElementById("userInput").focus(); console.log('_________________'); }); }; }, render: function(){ return ( React.createElement("div", null, React.createElement("input", { id: "userInput", type: "text", placeholder: "Filtrar...", onChange: this.updateUserInput} ), React.createElement(SimpleList, { simpleList: this.state.simpleList, userInput: this.state.userInput}), React.createElement("input", { id: "newElement", type: "text", placeholder: "+", onKeyPress: this.sendNewElement, onClick: this.favToInput, className: "fav"} ) ) ); } }); var SimpleList = React.createClass({displayName: "SimpleList", render: function() { return ( React.createElement("span", null, React.createElement("p", null, React.createElement("strong", null, "Pasos para dominar un nuevo lenguaje de programación:")), React.createElement(SimpleListRow, { simpleList: this.props.simpleList, userInput: this.props.userInput}) ) ); } }); var SimpleListRow = React.createClass({displayName: "SimpleListRow", render: function() { console.log('_________________'); console.log('simpleList rows props:'); console.log(this.props); var rows = this.props.simpleList; var userInput = this.props.userInput; return ( React.createElement("ol", null, rows.map(function(element){ if (element.row){ if (element.row.toLowerCase().search(userInput.toLowerCase()) > -1){ console.log("userInput found in simpleList row: "+element.row); return ( React.createElement("li", null, element.row) ); } } }) ) ); } }); React.render( React.createElement(SimpleFilterableList, null), document.getElementById('list') )
define(['Backbone', 'bootstrap', 'summernote', 'views/zs_notify_view', 'views/zs_access_control_view'], function(B, b, s, zsNotifyView, zsAccessControlView) { console.log("inside zs_single_question_view") var zsSingleQuestionView = Backbone.View.extend({ el: 'body', events: { "click #question_title_edit a": "question_edit", // "click #question_title_edit.editor_opened a": "question_save", "click #question_text_edit a": "question_edit", // "click #question_text_edit.editor_opened a": "question_save", "click #answer_edit a": "answer_edit", "click #comment_text_edit a": "comment_edit", // "click #question_text_edit.editor_opened a": "question_save", // $('.note-image-input').on("change", this.editor_s3_upload); // "change .note-image-input": "editor_s3_upload", // "click .question-div .zs_question_fav": "zs_question_fav", // "click .question-div .zs_question_upvote": "zs_question_upvote", // "click .question-div .zs_question_downvote": "zs_question_downvote", // "click .question-div .zs_comment_count": "zs_post_toggle_comments", // "click .question-div .zs_comment_count": "zs_toggle_comments", // "click .question-div .zs_question_fav": "zs_post_fav", // "click .question-div .zs_question_upvote": "zs_post_upvote", // "click .question-div .zs_question_downvote": "zs_post_downvote", // "click .post-div .zs_post_fav": "zs_post_fav", // "click .post-div .zs_post_upvote": "zs_post_upvote", // "click .post-div .zs_post_downvote": "zs_post_downvote", // "click .post-div .zs_toggle_comments": "zs_post_toggle_comments", // #TODO remove this event binding after replacing classes // "click .post-div .zs_comment_count": "zs_toggle_comments", }, initialize: function(args) { console.log("zs single question view initialized") zsNotifyView = new zsNotifyView(); zsAccessControlView = new zsAccessControlView(); // this.post_pub_id = args.post_pub_id; this.$(".answer_input_editable").on("focus", function(e){ // this.$(".answer_input_editable").summernote({ $(e.target).summernote({ // height: 120, focus: true, toolbar: [ ['style', ['style']], // no style button ['style', ['bold', 'italic', 'underline']], // ['fontsize', ['fontsize']], // ['color', ['color']], ['para', ['ul', 'ol']], // ['height', ['height']], ['insert', ['picture', 'video', 'link']], // no insert buttons // ['table', ['table']], // no table button // ['help', ['help']] //no help button ], }); }); }, // zs_toggle_comments: function(e) { // // console.log("zs_toggle_comments"); // // console.log($(e.target).closest(".post-div")); // // console.log($(e.target).closest(".post-div").find("#comment-container")); // // console.log($(e.target).closest(".post-div").find(".comment-container-wrap")); // // console.log("zs_toggle_comments"); // // $(e.target).closest(".post-div").find("#comment-container").toggle(); // var comment_element = $(e.target).closest(".post-div").find(".comment-container-wrap"); // // console.log(comment_element); // comment_element.toggle(); // // this.$("#comment-container").toggle(); // return false; // }, // zs_question_upvote: function(e) { // console.log("Inside zs_question_upvote"); // question_id = $(".post-div").attr("id").split("_")[1]; // $.ajax({ // type: 'POST', // url: '/question/'+question_id+'/meta/upvote', // success: function(data, status, jqxhr) { // // console.log(data); // // var uv = $('.zs_question_upvote'); // // var dv = $('.zs_question_downvote'); // // var vc = $('.zs_question_votecount'); // var parent_div = $(e.target).closest(".post-div"); // var uv = $(parent_div.find('.zs_question_upvote')); // var dv = $(parent_div.find('.zs_question_downvote')); // var vc = $(parent_div.find('.zs_question_votecount')); // if (dv.hasClass("vote-down-on")){ // vc.text(parseInt(vc.text()) + 1); // } // if (!uv.hasClass("vote-up-on")){ // vc.text(parseInt(vc.text()) + 1); // } else { // vc.text(parseInt(vc.text()) - 1); // } // uv.toggleClass("vote-up-off").toggleClass("vote-up-on"); // dv.removeClass("vote-down-on").addClass("vote-down-off"); // }, // error: function(jqxhr, status) { // console.log(status); // }, // }); // return false; // }, // zs_question_downvote: function(e) { // // console.log("Inside zs_question_downvote"); // question_id = $(".post-div").attr("id").split("_")[1]; // $.ajax({ // type: 'POST', // url: '/question/'+question_id+'/meta/downvote', // success: function(data, status, jqxhr) { // // console.log(data); // // var dv = $('.zs_question_downvote'); // // var uv = $('.zs_question_upvote'); // // var vc = $('.zs_question_votecount'); // var parent_div = $(e.target).closest(".post-div"); // var uv = $(parent_div.find('.zs_question_upvote')); // var dv = $(parent_div.find('.zs_question_downvote')); // var vc = $(parent_div.find('.zs_question_votecount')); // if (uv.hasClass("vote-up-on")){ // vc.text(parseInt(vc.text()) - 1); // } // if (!dv.hasClass("vote-down-on")){ // vc.text(parseInt(vc.text()) - 1); // } else { // vc.text(parseInt(vc.text()) + 1); // } // dv.toggleClass("vote-down-off").toggleClass("vote-down-on"); // uv.removeClass("vote-up-on").addClass("vote-up-off"); // }, // error: function(jqxhr, status) { // console.log(status); // }, // }); // return false; // }, // zs_question_fav: function() { // // console.log("Inside zs_question_downvote"); // question_id = $(".post-div").attr("id").split("_")[1]; // $.ajax({ // type: 'POST', // url: '/question/'+question_id+'/meta/favourite', // success: function(data, status, jqxhr) { // // console.log(data); // var fa = $('.zs_question_fav'); // var fc = $('.zs_question_favcount'); // if (!fa.hasClass("star-on")){ // fc.text(parseInt(fc.text()) + 1); // } else { // fc.text(parseInt(fc.text()) - 1); // } // fa.toggleClass("star-off").toggleClass("star-on"); // }, // error: function(jqxhr, status) { // console.log(status); // }, // }); // return false; // }, // COMMENT, UPVOTE, DOWNVOTE and FAVOURITE for a generic "Post" // zs_post_toggle_comments: function(e) { // // console.log("inside zs_post_toggle_comments"); // // console.log(e.target); // var parent_div = $(e.target).closest(".post-div"); // var comment_element = parent_div.find(".comment-container-wrap"); // if (comment_element.hasClass("comments-populated")) { // comment_element.toggle(); // } else { // post_id = parent_div.attr("id").split("_")[1]; // post_name = parent_div.attr("post"); // post_title = "dummy_question_title"; // if (post_name.toLowerCase() == "question") // var comment_url = '/'+post_name+'/'+post_id+'/'+post_title+'/comments'; // else // var comment_url = '/'+post_name+'/'+post_id+'/comments'; // console.log(comment_url); // comment_element.load(comment_url, function(res, status, jqxhr){ // comment_element.addClass("comments-populated"); // }); // } // return false; // }, // zs_post_upvote: function(e) { // console.log("Inside zs_post_upvote"); // var parent_div = $(e.target).closest(".post-div"); // post_id = parent_div.attr("id").split("_")[1]; // post_name = parent_div.attr("post"); // $.ajax({ // type: 'POST', // url: '/'+post_name+'/'+post_id+'/meta/upvote', // success: function(data, status, jqxhr) { // // console.log(data); // // var uv = $('.zs_post_upvote'); // // var dv = $('.zs_post_downvote'); // // var vc = $('.zs_post_votecount'); // // var parent_div = $(e.target).closest(".post-div"); // var uv = $(parent_div.find('.zs_post_upvote')); // var dv = $(parent_div.find('.zs_post_downvote')); // var vc = $(parent_div.find('.zs_post_votecount')); // if (dv.hasClass("vote-down-on")){ // vc.text(parseInt(vc.text()) + 1); // } // if (!uv.hasClass("vote-up-on")){ // vc.text(parseInt(vc.text()) + 1); // } else { // vc.text(parseInt(vc.text()) - 1); // } // uv.toggleClass("vote-up-off").toggleClass("vote-up-on"); // dv.removeClass("vote-down-on").addClass("vote-down-off"); // }, // error: function(jqxhr, status) { // console.log(status); // }, // }); // return false; // }, // zs_post_downvote: function(e) { // // console.log("Inside zs_post_downvote"); // var parent_div = $(e.target).closest(".post-div"); // post_id = parent_div.attr("id").split("_")[1]; // post_name = parent_div.attr("post"); // $.ajax({ // type: 'POST', // url: '/'+post_name+'/'+post_id+'/meta/downvote', // success: function(data, status, jqxhr) { // // console.log(data); // // var dv = $('.zs_post_downvote'); // // var uv = $('.zs_post_upvote'); // // var vc = $('.zs_post_votecount'); // // var parent_div = $(e.target).closest(".post-div"); // var uv = $(parent_div.find('.zs_post_upvote')); // var dv = $(parent_div.find('.zs_post_downvote')); // var vc = $(parent_div.find('.zs_post_votecount')); // if (uv.hasClass("vote-up-on")){ // vc.text(parseInt(vc.text()) - 1); // } // if (!dv.hasClass("vote-down-on")){ // vc.text(parseInt(vc.text()) - 1); // } else { // vc.text(parseInt(vc.text()) + 1); // } // dv.toggleClass("vote-down-off").toggleClass("vote-down-on"); // uv.removeClass("vote-up-on").addClass("vote-up-off"); // }, // error: function(jqxhr, status) { // console.log(status); // }, // }); // return false; // }, // zs_post_fav: function(e) { // // console.log("Inside zs_post_downvote"); // var parent_div = $(e.target).closest(".post-div"); // post_id = parent_div.attr("id").split("_")[1]; // post_name = parent_div.attr("post"); // $.ajax({ // type: 'POST', // url: '/'+post_name+'/'+post_id+'/meta/favourite', // success: function(data, status, jqxhr) { // // console.log(data); // // var fa = $('.zs_post_fav'); // // var fc = $('.zs_post_favcount'); // // var parent_div = $(e.target).closest(".post-div"); // var fa = $(parent_div.find('.zs_post_fav')); // var fc = $(parent_div.find('.zs_post_favcount')); // if (!fa.hasClass("star-on")){ // fc.text(parseInt(fc.text()) + 1); // } else { // fc.text(parseInt(fc.text()) - 1); // } // fa.toggleClass("star-off").toggleClass("star-on"); // }, // error: function(jqxhr, status) { // console.log(status); // }, // }); // return false; // }, // editor_s3_upload: function(e){ // e.preventDefault(); // console.log("inside editor_s3_upload function"); // changed_element = $($('.note-image-input').parent()); // changed_status_element = $(changed_element.find("h5")[0]); // var s3upload = new S3Upload({ // // file_dom_selector: '#user_profile_img_edit', // file_dom_selector: '.note-image-input', // s3_sign_put_url: '/sign_s3', // onProgress: function(percent, message) { // console.log("onProgress"); // changed_status_element.html(percent + '% ' + message); // }, // onFinishS3Put: function(public_url) { // console.log("onFinishS3Put", public_url); // // $('#user_profile_img_status').html('Upload completed. Uploaded to: '+ public_url); // // $('#user_profile_img_status').html(''); // // $('#user_profile_img_edit').hide(); // // $('#user_profile_img_submit').show(); // // $('#user_profile_img_cancel').show(); // // $("#user_profile_img_avatar_url").val(public_url); // // $("#user_profile_img_preview").html('<img src="'+public_url+'" style="width:300px;" />'); // // console.log(public_url); // // $("#user_profile_img_preview").attr("src", public_url); // changed_status_element.html(public_url); // return public_url; // }, // onError: function(status, jqxhr) { // console.log("onError", status); // // console.log(jqxhr.status); // // $('#user_profile_img_status').html('Upload error: ' + status); // changed_status_element.html('Upload error: ' + status); // return ""; // } // }); // }, open_editor: function(editable, type) { if (type == 0) { // open editor without a toolbar editable.summernote({ focus: true, toolbar: false, }) return; } else if (type == 1) { // open editor with a small toolbar if (zsAccessControlView.isAdmin() || zsAccessControlView.isStaff()) { editable.summernote({ focus: true, toolbar: [ ['style', ['style']], ['style', ['bold', 'italic', 'underline']], ['para', ['ul', 'ol']], ['insert', ['picture', 'video', 'link']], ['misc', ['codeview', 'fullscreen']], ], }) } else { editable.summernote({ focus: true, toolbar: [ ['style', ['style']], ['style', ['bold', 'italic', 'underline']], ['para', ['ul', 'ol']], ['insert', ['picture', 'video', 'link']], ], }) } return; } else { if (zsAccessControlView.isAdmin() || zsAccessControlView.isStaff()) { editable.summernote({ // height: 300, focus: true, toolbar: [ ['style', ['style']], ['style', ['bold', 'italic', 'underline']], ['fontsize', ['fontsize']], ['color', ['color']], ['para', ['ul', 'ol', 'paragraph']], ['height', ['height']], ['insert', ['picture', 'video', 'link']], // ['table', ['table']], // no table button // ['help', ['help']] //no help button ['misc', ['codeview', 'fullscreen']], ], }); } else { editable.summernote({ // height: 300, focus: true, toolbar: [ ['style', ['style']], ['style', ['bold', 'italic', 'underline']], ['fontsize', ['fontsize']], ['color', ['color']], ['para', ['ul', 'ol', 'paragraph']], ['height', ['height']], ['insert', ['picture', 'video', 'link']], // ['table', ['table']], // no table button // ['help', ['help']] //no help button ], }); } return; } }, question_edit: function(e) { // console.log("inside question_edit"); zsNotifyView.nv_show(1); var clicked_op = $(e.target).text().toLowerCase(); // console.log(clicked_op); var clicked_element = $(e.target).parent(); // console.log(clicked_element); // console.log(clicked_element.attr("id")); var edit_target_class = clicked_element.attr("id")+"_content"; var post_div = clicked_element.closest(".post-div"); var post_type = post_div.attr("id").split("_")[0].toLowerCase() ; var post_id = post_div.attr("id").split("_")[1] ; // console.log(edit_target_class); var edit_target_element = post_div.find("."+edit_target_class); if (clicked_element.hasClass("editor_opened")) { // do save operations // should not destroy it until a update confirmation comes back if (clicked_op == "cancel") { edit_target_element.code(edit_target_element.html()); clicked_element.toggleClass("editor_opened").html("<a>Edit</a>"); edit_target_element.destroy(); zsNotifyView.nv_hide(1); } else { updated_question = this.getQuestionEditObj(edit_target_element); // console.log(updated_question); that = this; $.ajax({ type: 'POST', url: '/'+post_type+'/'+post_id, data: updated_question, success: function(data, status, jqxhr) { // console.log("question edited successfully") clicked_element.toggleClass("editor_opened").html("<a>Edit</a>"); edit_target_element.destroy(); zsNotifyView.nv_hide(1); }, error: function(jqxhr, status) { // console.log(jqxhr.status, status); // #TODO display the html message sent by the server zsNotifyView.nv_show(1, jqxhr.responseText); }, }); } // clicked_element.toggleClass("editor_opened").html("<a>Edit</a>"); } else { // do edit operations // #TODO disallow "html" in "question_title_edit_content" // both in UX and backend. if (edit_target_class == "question_title_edit_content") this.open_editor(edit_target_element, 0); else this.open_editor(edit_target_element, 1); clicked_element.toggleClass("editor_opened").html("<a>Cancel</a> <a>Save</a>"); zsNotifyView.nv_hide(1); } // clicked_element.addClass("editor_opened").html("<a>Save</a>"); }, answer_edit: function(e) { // console.log("inside answer_edit"); zsNotifyView.nv_show(1); var clicked_op = $(e.target).text().toLowerCase(); var clicked_element = $(e.target).parent(); // console.log(clicked_element); // console.log(clicked_element.attr("id")); edit_target_class = clicked_element.attr("id")+"_content"; // console.log(edit_target_class); post_div = clicked_element.closest(".post-div"); post_type = post_div.attr("id").split("_")[0].toLowerCase() ; post_id = post_div.attr("id").split("_")[1] ; // console.log(post_div); var edit_target_element = post_div.find("."+edit_target_class); // console.log(edit_target_element); if (clicked_element.hasClass("editor_opened")) { // #TODO Check for empty post, same while posting new post and show "Post cannot be empty" message in zs_notify // do save operations // should not destroy it until a update confirmation comes back // console.log(edit_target_element); if (clicked_op == "cancel") { edit_target_element.code(edit_target_element.html()); clicked_element.toggleClass("editor_opened").html("<a>Edit</a>"); edit_target_element.destroy(); zsNotifyView.nv_hide(1); } else { updated_answer = this.getAnswerEditObj(edit_target_element); // console.log(updated_answer); that = this; $.ajax({ type: 'POST', url: '/'+post_type+'/'+post_id, data: updated_answer, success: function(data, status, jqxhr) { // console.log("answer edited successfully") clicked_element.toggleClass("editor_opened").html("<a>Edit</a>"); edit_target_element.destroy(); zsNotifyView.nv_hide(1); }, error: function(jqxhr, status) { // console.log(jqxhr.status, status); // #TODO display the html message sent by the server zsNotifyView.nv_show(1, jqxhr.responseText); }, }); } // #TODO remove this // edit_target_element.destroy(); // clicked_element.toggleClass("editor_opened").html("<a>Edit</a>"); } else { // do edit operations this.open_editor(edit_target_element, 1); clicked_element.toggleClass("editor_opened").html("<a>Cancel</a> <a>Save</a>"); zsNotifyView.nv_hide(1); } // clicked_element.addClass("editor_opened").html("<a>Save</a>"); }, comment_edit: function(e) { zsNotifyView.nv_show(1); var clicked_op = $(e.target).text().toLowerCase(); var clicked_element = $(e.target).parent(); edit_target_class = clicked_element.attr("id")+"_content"; post_div = clicked_element.closest(".post-div"); post_type = post_div.attr("id").split("_")[0].toLowerCase() ; post_id = post_div.attr("id").split("_")[1] ; var edit_target_element = post_div.find("."+edit_target_class); if (clicked_element.hasClass("editor_opened")) { updated_comment = this.getCommentEditObj(edit_target_element); // console.log(updated_comment); if (clicked_op == "cancel") { // console.log(edit_target_element.attr("data-orig")); // console.log("--------------------------------------------"); // console.log(edit_target_element.html()); edit_target_element.html(edit_target_element.attr("data-orig")); clicked_element.toggleClass("editor_opened").html("<a>Edit</a>"); edit_target_element.toggleClass("comment-content").toggleClass("full-comment").attr("contenteditable", false); zsNotifyView.nv_hide(1); } else { that = this; $.ajax({ type: 'POST', url: '/'+post_type+'/'+post_id, data: updated_comment, success: function(data, status, jqxhr) { // console.log("comment edited successfully") clicked_element.toggleClass("editor_opened").html("<a>Edit</a>"); // edit_target_element.destroy(); edit_target_element.toggleClass("comment-content").toggleClass("full-comment").attr("contenteditable", false); zsNotifyView.nv_hide(1); }, error: function(jqxhr, status) { zsNotifyView.nv_show(1, jqxhr.responseText); }, }); } } else { // this.open_editor(edit_target_element, 1); var orig = edit_target_element.html(); edit_target_element.attr("data-orig", orig); edit_target_element.toggleClass("comment-content").toggleClass("full-comment").attr("contenteditable", true); clicked_element.toggleClass("editor_opened").html("<a>Cancel</a> <a>Save</a>"); zsNotifyView.nv_hide(1); } }, // question_save: function(e) { // console.log("inside question_save"); // var clicked_element = $(e.target).parent(); // // console.log(clicked_element); // // console.log(clicked_element.attr("id")); // save_target_class = clicked_element.attr("id")+"_content"; // post_div = clicked_element.closest(".post-div"); // post_id = post_div.attr("id"); // e.g.. "Queston_23" // // console.log(save_target_class); // var save_target_element = post_div.find("."+save_target_class); // // should not destroy it until a update confirmation comes back // save_target_element.destroy(); // console.log(save_target_element); // updated_question = this.getQuestionEditObj(save_target_element); // console.log(updated_question); // clicked_element.removeClass("editor_opened").html("<a>Edit</a>"); // }, getQuestionEditObj: function(target_element) { var key = target_element.attr("key"); var uq = {}, val; if (key == "content_title"){ // val = target_element.text().trim(); val = $("<div></div>").html(target_element.code().trim()).text(); } else if (key == "content_text") { val = target_element.code().trim(); // } else if (key == "") { // _seller _pro_cat _ser_cat _pro _ser } else { return; } uq[key] = val; // console.log(uq); return uq; }, getAnswerEditObj: function(target_element) { var key = target_element.attr("key"); var ua = {}, val; if (key == "content_text") { val = target_element.code().trim(); // } else if (key == "") { // do it for _seller _pro_cat _ser_cat _pro _ser tags } else { return; } ua[key] = val; // console.log(ua); return ua; }, getCommentEditObj: function(target_element) { var key = target_element.attr("key"); var ua = {}, val; if (key == "content_text") { val = target_element.code().trim(); // } else if (key == "") { // do it for _seller _pro_cat _ser_cat _pro _ser tags } else { return; } ua[key] = val; // console.log(ua); return ua; }, render: function() { // console.log("in all_question_view render function"); return this; } }); return zsSingleQuestionView; });
import DS from 'ember-data'; import BackboneElement from 'ember-fhir/models/backbone-element'; const { attr, belongsTo } = DS; export default BackboneElement.extend({ type_: attr('string'), value: attr('string'), preferred: attr('boolean', { allowNull: true }), comment: attr('string'), period: belongsTo('period', { async: false }) });
import * as React from 'react'; import TextField from '@material-ui/core/TextField'; import AdapterDateFns from '@material-ui/lab/AdapterDateFns'; import LocalizationProvider from '@material-ui/lab/LocalizationProvider'; import DateTimePicker from '@material-ui/lab/DateTimePicker'; import MobileDateTimePicker from '@material-ui/lab/MobileDateTimePicker'; import DesktopDateTimePicker from '@material-ui/lab/DesktopDateTimePicker'; export default function ResponsiveDateTimePickers() { const [value, setValue] = React.useState(new Date('2018-01-01T00:00:00.000Z')); return ( <LocalizationProvider dateAdapter={AdapterDateFns}> <div style={{ width: 300 }}> <MobileDateTimePicker value={value} onChange={(newValue) => { setValue(newValue); }} renderInput={(params) => ( <TextField {...params} margin="normal" variant="standard" /> )} /> <DesktopDateTimePicker value={value} onChange={(newValue) => { setValue(newValue); }} renderInput={(params) => ( <TextField {...params} margin="normal" variant="standard" /> )} /> <DateTimePicker renderInput={(params) => ( <TextField {...params} margin="normal" variant="standard" /> )} value={value} onChange={(newValue) => { setValue(newValue); }} /> </div> </LocalizationProvider> ); }
import Body from './Body'; import Vector from './Vector'; const temp1 = Vector.create() const temp2 = Vector.create() const temp3 = Vector.create() const temp4 = Vector.create() export default class Solver { constructor() { } solve(collsions) { for (var i = collsions.length - 1; i >= 0; i--) { const collision = collsions[i]; if(!collision.ignore && !collision.shape1.sensor && !collision.shape2.sensor) { const projection = collision.projection; const penetration = collision.penetration; const body1 = collision.body1; const body2 = collision.body2; var amount = 0.5; var amount2 = 0.5; if(body2.type === Body.STATIC) { amount = 1; amount2 = 0; this.bounce(body1, body2, projection) } else if(body1.type === Body.STATIC) { amount = 0; amount2 = 1; this.bounce(body2, body1, Vector.set(temp4, -projection.x, -projection.y)) } var dx = projection.x * penetration; var dy = projection.y * penetration; body1.position.x -= dx * amount; body1.position.y -= dy * amount; body2.position.x += dx * amount2; body2.position.y += dy * amount2; } } } bounce(body1, body2, projection) { var collisionForce = Vector.sub(temp3, body1.velocity, body2.velocity); // this kind works! if(Vector.dot(collisionForce, projection ) > 0) { return; } // convert to 90 degs var perp = new Vector(projection.y, -projection.x); var frictionVector = Vector.project(temp1, collisionForce, perp); var projectionToLine2 = Vector.project(temp2, collisionForce, projection); var bounceVector = new Vector(0, 0); bounceVector.x = projection.x * Vector.len(projectionToLine2); bounceVector.y = projection.y * Vector.len(projectionToLine2); Vector.mul(frictionVector, frictionVector, body1.contactFriction); Vector.mul(bounceVector, bounceVector, body1.bounce); body1.velocity.x = (frictionVector.x + bounceVector.x); body1.velocity.y = (frictionVector.y + bounceVector.y); } }
import React from 'react'; import PropTypes from 'prop-types'; import { Text, TouchableOpacity, View } from 'react-native'; import IconIonic from 'react-native-vector-icons/Ionicons'; import IconFontAwesome from 'react-native-vector-icons/FontAwesome'; import styles from './style'; /* * Component to make the user choose between two * controller types */ const ControllerTypeSelector = props => ( <View> <View style={styles.blockHeading}> <Text style={styles.textHeading}>TYPE</Text> </View> <View style={styles.blockFields}> <TouchableOpacity style={props.type === "switch" ? styles.buttonPressed : styles.button} onPress={() => props.onPress('switch')} > <IconFontAwesome name={'toggle-on'} color={props.type === "switch" ? "white" : "#42275A"} size={40} /> <Text style={props.type === "switch" ? styles.buttonPressedText : styles.buttonText}>Switch</Text> </TouchableOpacity> <TouchableOpacity style={props.type === "dimmer" ? styles.buttonPressed : styles.button} onPress={() => props.onPress('dimmer')} > <IconIonic style={{ bottom: 5 }} name={'ios-git-commit'} color={props.type === "dimmer" ? "white" : "#42275A"} size={50} /> <Text style={props.type === "dimmer" ? styles.buttonPressedText : styles.buttonText}>Dimmer</Text> </TouchableOpacity> </View> </View> ); ControllerTypeSelector.propTypes = { onPress: PropTypes.func.isRequired, type: PropTypes.string.isRequired, }; export default ControllerTypeSelector;
!(function($) { return $.ender({ hash: require('hashchange').hash }); })(ender);
"use strict"; let datafire = require('datafire'); let openapi = require('./openapi.json'); module.exports = datafire.Integration.fromOpenAPI(openapi, "azure_network_usage");
/* */ (function(process) { var fs = require("fs"), connect = require("connect"), colors = require("colors"), WebSocket = require("faye-websocket"), path = require("path"), url = require("url"), http = require("http"), send = require("send"), open = require("open"), es = require("event-stream"), watchr = require("watchr"); var INJECTED_CODE = fs.readFileSync(__dirname + "/injected.html", "utf8"); var LiveServer = {}; function escape(html) { return String(html).replace(/&(?!\w+;)/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;'); } function staticServer(root) { return function(req, res, next) { if ('GET' != req.method && 'HEAD' != req.method) return next(); var reqpath = url.parse(req.url).pathname; var hasNoOrigin = !req.headers.origin; var doInject = false; function directory() { var pathname = url.parse(req.originalUrl).pathname; res.statusCode = 301; res.setHeader('Location', pathname + '/'); res.end('Redirecting to ' + escape(pathname) + '/'); } function file(filepath, stat) { var x = path.extname(filepath); if (hasNoOrigin && (x === "" || x == ".html" || x == ".htm" || x == ".xhtml" || x == ".php")) { var contents = fs.readFileSync(filepath, "utf8"); doInject = contents.indexOf("</body>") > -1; } } function error(err) { if (404 == err.status) return next(); next(err); } function inject(stream) { if (doInject) { var len = INJECTED_CODE.length + res.getHeader('Content-Length'); res.setHeader('Content-Length', len); var originalPipe = stream.pipe; stream.pipe = function(res) { originalPipe.call(stream, es.replace(new RegExp("</body>", "i"), INJECTED_CODE + "</body>")).pipe(res); }; } } send(req, reqpath, {root: root}).on('error', error).on('directory', directory).on('file', file).on('stream', inject).pipe(res); }; } function entryPoint(staticHandler, file) { if (!file) return function(req, res, next) { next(); }; return function(req, res, next) { req.url = "/" + file; staticHandler(req, res, next); }; } LiveServer.start = function(options) { options = options || {}; var host = options.host || '0.0.0.0'; var port = options.port || 8080; var root = options.root || process.cwd(); var logLevel = options.logLevel === undefined ? 2 : options.logLevel; var openPath = (options.open === undefined || options.open === true) ? "" : ((options.open === null || options.open === false) ? null : options.open); if (options.noBrowser) openPath = null; var file = options.file; var staticServerHandler = staticServer(root); var wait = options.wait || 0; var app = connect().use(staticServerHandler).use(entryPoint(staticServerHandler, file)).use(connect.directory(root, {icons: true})); if (logLevel >= 2) app.use(connect.logger('dev')); var server = http.createServer(app); server.addListener('error', function(e) { if (e.code == 'EADDRINUSE') { var serveURL = 'http://' + host + ':' + port; console.log('%s is already in use. Trying another port.'.red, serveURL); setTimeout(function() { server.listen(0, host); }, 1000); } }); server.addListener('listening', function(e) { var address = server.address(); var serveHost = address.address == "0.0.0.0" ? "127.0.0.1" : address.address; var serveURL = 'http://' + serveHost + ':' + address.port; if (logLevel >= 1) { console.log(("Serving \"%s\" at %s").green, root, serveURL); } if (openPath !== null) open(serveURL + openPath); }); server.listen(port, host); var clients = []; server.addListener('upgrade', function(request, socket, head) { var ws = new WebSocket(request, socket, head); ws.onopen = function() { ws.send('connected'); }; if (wait > 0) { (function(ws) { var wssend = ws.send; var waitTimeout; ws.send = function() { var args = arguments; if (waitTimeout) clearTimeout(waitTimeout); waitTimeout = setTimeout(function() { wssend.apply(ws, args); }, wait); }; })(ws); } ws.onclose = function() { clients = clients.filter(function(x) { return x !== ws; }); }; clients.push(ws); }); watchr.watch({ path: root, ignorePaths: options.ignore || false, ignoreCommonPatterns: true, ignoreHiddenFiles: true, preferredMethods: ['watchFile', 'watch'], interval: 1407, listeners: { error: function(err) { console.log("ERROR:".red, err); }, change: function(eventName, filePath, fileCurrentStat, filePreviousStat) { clients.forEach(function(ws) { if (!ws) return; if (path.extname(filePath) == ".css") { ws.send('refreshcss'); if (logLevel >= 1) console.log("CSS change detected".magenta); } else { ws.send('reload'); if (logLevel >= 1) console.log("File change detected".cyan); } }); } } }); }; module.exports = LiveServer; })(require("process"));
export const PlayStates = { IDLE :'IDLE', //从未开始播放的初始状态,播放后不会回到这个状态 PLAYING : 'PLAYING', PAUSED : 'PAUSED', STOP : 'STOP' }; export const SeekStates = { IDLE :'IDLE', //从未seek时的初始状态,seek后不可逆 SEEKING : 'SEEKING', SEEKED : 'SEEKED' }; // default||'' 显示默认控件,none 不显示控件,system 显示系统控件 export const ControlsStates={ 'DEFAULT' : 'default',//显示默认控件,可以样式定制 'NONE' : 'none',// 隐藏控件,pc端除外 'SYSTEM' : '' //显示系统控件, };
var t = require("tcomb-validation"); var Size = t.struct({ height: t.Num, width: t.Num }, "Size", true); //var SizeFuncs = t.struct({ // isSizeZero: t.func(Size, t.Bool) //}); // //Size = Size.extend(SizeFuncs); // //Size.prototype.isSizeZero = function(size) { // return size.height = 0 && size.width == 0; //} module.exports = Size;
var Weight, WeightSet, duration, expect, hydratedWeights, jsonWeights; duration = require('moment').duration; WeightSet = require('../lib/weightSet'); Weight = require('../lib/weight'); ({expect} = require('./spec-helper')); jsonWeights = [ { weight: 155, reps: 10 }, { weight: 145, reps: 10 }, { weight: 135, reps: 10 } ]; hydratedWeights = jsonWeights.map(function(weight) { return new Weight(weight); }); describe('WeightSet', function() { var weightSet; ({weightSet} = {}); describe('unnamed weightSet', function() { beforeEach(function() { return weightSet = new WeightSet(); }); return describe('::toString', function() { return it('outputs nothing without content', function() { return expect(weightSet.toString()).to.eq(''); }); }); }); describe('named weightSet with intervals', function() { beforeEach(function() { return weightSet = new WeightSet({ name: 'weightSet 2', intervals: jsonWeights }); }); it('creates hydrated intervals from given JSON', function() { return expect(weightSet.intervals).to.eql(hydratedWeights); }); it('sets the name', function() { return expect(weightSet.name).to.eq('weightSet 2'); }); describe('::toString', function() { return it('displays correct notation for all intervals', function() { return expect(weightSet.toString()).to.eq('weightSet 2\n- 155 lbs x 10 reps\n- 145 lbs x 10 reps\n- 135 lbs x 10 reps'); }); }); describe('::toJSON', function() { return it('outputs JSON matching original input', function() { return expect(weightSet.toJSON()).to.eql({ name: 'weightSet 2', intervals: jsonWeights }); }); }); return describe('::oneRepMax', function() { return it('takes the maximum value from the intervals', function() { return expect(Math.round(weightSet.oneRepMax())).to.eq(207); }); }); }); return describe('named weightSet', function() { beforeEach(function() { return weightSet = new WeightSet({ name: 'weightSet 1' }); }); it('creates an array of empty intervals', function() { return expect(weightSet.intervals).to.eql([]); }); it('sets the name', function() { return expect(weightSet.name).to.eq('weightSet 1'); }); describe('::current', function() { var interval; ({interval} = {}); beforeEach(function() { return interval = weightSet.current(); }); it('creates a new interval if called when empty', function() { return expect(weightSet.intervals.length).to.eq(1); }); it('creates a valid interval', function() { return expect(interval).to.be.ok; }); return describe('::setWeight(number)', function() { beforeEach(function() { return weightSet.setWeight(155); }); return it('sets the weight', function() { return expect(weightSet.current().weight).to.eq(155); }); }); }); describe('::add', function() { it('calling with null throws', function() { return expect(function() { return weightSet.add(null); }).to.throw('Invalid weight given'); }); return it('calling with no params creates an empty interval', function() { return expect(weightSet.add()).to.be.ok; }); }); return describe('with added intervals', function() { beforeEach(function() { return jsonWeights.forEach(function(weight) { return weightSet.add(weight); }); }); describe('::toString', function() { return it('displays correct notation for all intervals', function() { return expect(weightSet.toString()).to.eq('weightSet 1\n- 155 lbs x 10 reps\n- 145 lbs x 10 reps\n- 135 lbs x 10 reps'); }); }); return describe('::toJSON', function() { return it('outputs correct information', function() { return expect(weightSet.toJSON()).to.eql({ name: 'weightSet 1', intervals: jsonWeights }); }); }); }); }); });
var express = require('express'); var KullaniciModeli = require('../Modeller/KullaniciModeli'); var RolTanimiModeli = require('../Modeller/RolTanimiModeli'); var VersionModeli = require('../Modeller/VersionModel'); function yoneticiOlustur(firmaKodu){ return { firmaKodu : firmaKodu, isim : 'isim', soyisim : 'Soyisim', email : 'yonetici@yonetici.com', sifre : '1234', rol : 'Yönetici', gorev : '', gsm1 : '', gsm2 : '', resimLinki : '', hesapTipi : 'Yönetici', aktif : true, degistiren : 'Sistem' } } function rolOlustur(firmaKodu){ return { rol : "Yönetici", degistiren: 'Sistem', firmaKodu: firmaKodu } } function versionOlustur(firma){ return { mobilVersion : "1", firmaKodu:firma } } function OnyuklmemeRouter(){ var router = express.Router(); router.get('/yoneticiekle', function(req, res){ var firmaKodu = req.param('firmaKodu'); new KullaniciModeli(yoneticiOlustur(firmaKodu)).save(function(dbHatasi, eklenen){ if(dbHatasi) { res.send({state : false, data : dbHatasi}); return; } else { res.send({state : true, data : eklenen}); } }); }); router.get('/rolekle', function(req, res){ var firmaKodu = req.param('firma'); new RolTanimiModeli(rolOlustur(firmaKodu)).save(function(dbHatasi, eklenen){ if(dbHatasi) { res.send({state : false, data : dbHatasi}); return; } else { res.send({state : true, data : eklenen}); } }); }); router.get('/firmaversionekle', function(req, res){ var firma = req.param('firma'); if(firma != ''){ new VersionModeli(versionOlustur(firma)).save(function(dbHatasi, eklenen){ if(dbHatasi) { res.send({state : false, data : dbHatasi}); return; } else { res.send({state : true, data : eklenen}); } }); }else{ res.send("Firma unvani bulunamadi."); } }); return router; } module.exports = OnyuklmemeRouter;
// Javascript UI for surveyor jQuery(document).ready(function(){ // if(jQuery.browser.msie){ // // IE has trouble with the change event for form radio/checkbox elements - bind click instead // jQuery("form#survey_form input[type=radio], form#survey_form [type=checkbox]").bind("click", function(){ // jQuery(this).parents("form").ajaxSubmit({dataType: 'json', success: successfulSave}); // }); // // IE fires the change event for all other (not radio/checkbox) elements of the form // jQuery("form#survey_form *").not("input[type=radio], input[type=checkbox]").bind("change", function(){ // jQuery(this).parents("form").ajaxSubmit({dataType: 'json', success: successfulSave}); // }); // }else{ // // Other browsers just use the change event on the form // // Uncomment the following to use the jQuery Tools Datepicker (http://jquerytools.org/demos/dateinput/index.html) // instead of the default jQuery UI Datepicker (http://jqueryui.com/demos/datepicker/) // // For a date input, i.e. using dateinput from jQuery tools, the value is not updated // before the onChange or change event is fired, so we hang this in before the update is // sent to the server and set the correct value from the dateinput object. // jQuery('li.date input').change(function(){ // if ( $(this).data('dateinput') ) { // var date_obj = $(this).data('dateinput').getValue(); // this.value = date_obj.getFullYear() + "-" + (date_obj.getMonth()+1) + "-" + // date_obj.getDate() + " 00:00:00 UTC"; // } // }); // // $('li input.date').dateinput({ // format: 'dd mmm yyyy' // }); // Default Datepicker uses jQuery UI Datepicker jQuery("input[type='text'].datetime").datetimepicker({ showSecond: true, showMillisec: false, timeFormat: 'HH:mm:ss', dateFormat: 'yy-mm-dd', changeMonth: true, changeYear: true }); jQuery("li.date input").datepicker({ dateFormat: 'yy-mm-dd', changeMonth: true, changeYear: true }); jQuery("input[type='text'].date").datepicker({ dateFormat: 'yy-mm-dd', changeMonth: true, changeYear: true }); jQuery("input[type='text'].datepicker").datepicker({ dateFormat: 'yy-mm-dd', changeMonth: true, changeYear: true }); jQuery("input[type='text'].time").timepicker({}); jQuery('.surveyor_check_boxes input[type=text]').change(function(){ var textValue = $(this).val() if (textValue.length > 0) { $(this).parent().children().has('input[type="checkbox"]')[0].children[0].checked = true; } }); jQuery('.surveyor_radio input[type=text]').change(function(){ var textValue = $(this).val() if (textValue.length > 0) { $(this).parent().children().has('input[type="radio"]')[0].children[0].checked = true; } }); jQuery("form#survey_form input, form#survey_form select, form#survey_form textarea").change(function(){ var elements = [$('[type="submit"]').parent(), $('[name="' + this.name +'"]').closest('li')]; question_data = $(this).parents('fieldset[id^="q_"],tr[id^="q_"]'). find("input, select, textarea"). add($("form#survey_form input[name='authenticity_token']")). serialize(); $.ajax({ type: "PUT", url: $(this).parents('form#survey_form').attr("action"), data: question_data, dataType: 'json', success: function(response) { successfulSave(response); } }); }); // http://www.filamentgroup.com/lab/update_jquery_ui_slider_from_a_select_element_now_with_aria_support/ $('fieldset.q_slider select').each(function(i,e) { $(e).selectToUISlider({"labelSrc": "text"}).hide() }); // If javascript works, we don't need to show dependents from // previous sections at the top of the page. jQuery("#dependents").remove(); function successfulSave(responseText) { // surveyor_controller returns a json object to show/hide elements // e.g. {"hide":["question_12","question_13"],"show":["question_14"]} jQuery.each(responseText.show, function(){ showElement(this) }); jQuery.each(responseText.hide, function(){ hideElement(this) }); console.log(responseText); return false; } function showElement(id){ group = id.match('^g_') ? true : false; if (group) { jQuery('#' + id).removeClass("g_hidden").find('.q_hidden').removeClass('q_hidden'); } else { jQuery('#' + id).removeClass("q_hidden"); } } function hideElement(id){ group = id.match('^g_') ? true : false; if (group) { jQuery('#' + id).addClass("g_hidden"); } else { jQuery('#' + id).addClass("q_hidden"); } } // is_exclusive checkboxes should disble sibling checkboxes $('input.exclusive:checked').parents('fieldset[id^="q_"]'). find(':checkbox'). not(".exclusive"). attr('checked', false). attr('disabled', true); $('input.exclusive:checkbox').click(function(){ var e = $(this); var others = e.parents('fieldset[id^="q_"]').find(':checkbox').not(e); if(e.is(':checked')){ others.attr('checked', false).attr('disabled', 'disabled'); }else{ others.attr('disabled', false); } }); jQuery("input[data-input-mask]").each(function(i,e){ var inputMask = $(e).attr('data-input-mask'); var placeholder = $(e).attr('data-input-mask-placeholder'); var options = { placeholder: placeholder }; $(e).mask(inputMask, options); }); // translations selection $(".surveyor_language_selection").show(); $(".surveyor_language_selection select#locale").change(function(){ this.form.submit(); }); });
'use strict'; exports.validate = function(dependencies, expected) { var ilen = expected.length; var jlen = dependencies.length; var i, j, exp, dep, found; for(i = 0; i < ilen; i++) { found = false; exp = expected[i]; for(j = 0; j < jlen; j++) { dep = dependencies[j]; if(exp in dep) { found = true; break; } } if(!found) { return false; } } return true; }; exports.getNames = function(dependencies) { var ret = []; var len = dependencies.length; var i; for(i = 0; i < len; i++) { ret = ret.concat(Object.keys(dependencies[i])); } return ret; };
var filter = require("reducers/filter") , reductions = require("reducers/reductions") , not = require("not") , summaries = require("../reflex/summaries") fork.todos = todos module.exports = fork function fork(state) { var output = state.output , changes = summaries(output) , todoChanges = filter(changes, function (change) { return isTodo(change.name) }) , counters = reductions(output, intoCounters, {}) return { todoChanges: todoChanges , counters: counters } } function todos(current) { return Object.keys(current) .filter(isTodo) .map(function (name) { return current[name] }) .filter(Boolean) } function isTodo(str) { return str.substr(0, 5) === "todo:" } function intoCounters(_, current) { var values = Object.keys(current) .filter(isTodo) .map(function (key) { return current[key] }) .filter(toBoolean) return { completed: values.filter(isCompleted).length , remaining: values.filter(not(isCompleted)).length } } function toBoolean(value) { return !!value } function isCompleted(item) { return item && item.completed }
module.exports = { "db": { "host": "112.124.23.114" , "port": 27017 , "dbname": "shoteyes" , "pool": 5 }, "testdb": { "host": "112.124.23.114" , "port": 27017 , "dbname": "developer" , "pool": 5 }, "mail": { "service": "Gmail" , "auth": { "user": "smart@gmail.com" , "pass": "smart" } }, "app": { "public":"public" , "port": 3000 , "views": "views" , "cookieSecret": "smartcore" , "sessionSecret": "smartcore" , "sessionKey": "smartcore.sid" , "sessionTimeout": 720 // 24 * 30 一个月 , "tmp": "/tmp" , "hmackey": "smartcore" , "i18n": { "cache": "memory" , "lang": "zh" , "category": "diandian" } , "ignoreAuth": [ "^\/stylesheets" , "^\/javascripts" , "^\/vendor" , "^\/images" , "^\/video" , "^\/$" , "^\/simplelogin.*" , "^\/simplelogout.*" , "^\/login.*" , "^\/register.*" , "^\/archive" , "^\/status.json" ] } , "log": { "fluent": { "enable": "false" , "tag": "node" , "host": "10.2.8.228" , "port": 24224 , "timeout": 3.0 } }, "mq": { "host": "mq" , "port": 5672 , "user": "guest" , "password": "guest" , "queue_join": "smartJoin" , "queue_apn": "smartApn" , "queue_thumb": "smartThumb" , "maxListeners": 0 }, "websocket": { "center_server": { "primary": "http://localhost:3000" ,"secondary": "" } , "log_level": 1 } }
const getData = require('./index') const download = (filename, text) => { var element = document.createElement('a') element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text)) element.setAttribute('download', filename) element.style.display = 'none' document.body.appendChild(element) element.click() document.body.removeChild(element) } document.getElementById('exec').addEventListener('click', (event) => { event.preventDefault() let street_name = document.getElementById('street_name').value.trim() let building_number = document.getElementById('building_number').value.trim() let building_number_addition = document.getElementById('building_number_addition').value.trim() let year = document.getElementById('year').value.trim() let plz = document.getElementById('plz').value.trim() getData(street_name, building_number, year, plz, building_number_addition, (err, data) => { if (err) return document.getElementById('result').value = err document.getElementById('result').value = data document.getElementById('result').style.visibility = 'visible' document.getElementById('download').style.visibility = 'visible' }) }, false) document.getElementById('download').addEventListener('click', (event) => { let street_name = document.getElementById('street_name').value let building_number = document.getElementById('building_number').value let building_number_addition = document.getElementById('building_number_addition').value let year = document.getElementById('year').value download('abfuhrkalender_' + year.trim() + '_' + encodeURIComponent(street_name.trim().replace('.', '')) + '_' + building_number.trim() + '.ics', document.getElementById('result').value) })
var assert = require('chai').assert; var expect = require('chai').expect; var fs = require('fs'); var parser = require('../js/page-html-parser.js'); var articleUtil = require('../js/article-util.js'); var isNan = function(number) { return number !== number; }; describe('Page HTML Parser', function() { describe('#parseArticles()', function () { var articles = parser.parseArticles('Boys', fs.readFileSync('./test/source-base.html', 'utf-8')); it('should return correct number of articles', function () { assert.equal(8, articles.length); }); it('should have a title', function () { assert.notEqual(undefined, articles[0].title); }); it('should have a link', function () { assert.notEqual(undefined, articles[0].link); }); it('should have an id', function () { articles.forEach(function(article) { assert.isFalse(isNan(article.id), "Article " + article.title + " has no ID"); }); }); it('should have a team', function () { assert.equal('Boys', articles[0].teamName); }); }); describe('Integration test which finds new articles', function() { var knownArticles = parser.parseArticles('Boys', fs.readFileSync('./test/source-base.html', 'utf-8')); var freshArticles = parser.parseArticles('Boys', fs.readFileSync('./test/source-change.html', 'utf-8')); it('finds the new articles', function() { var articleDiff = articleUtil.findDiff(freshArticles, knownArticles); expect(articleDiff.created).to.have.length(1); expect(articleDiff.updated).to.have.length(1); }); }); });
/** * Tabs Scenes * * React Native Starter App * https://github.com/mcnamee/react-native-starter-app */ import React from 'react'; import { Scene } from 'react-native-router-flux'; // Consts and Libs import { AppConfig } from '@constants/'; import { AppStyles, AppSizes } from '@theme/'; // Components import { TabIcon } from '@ui/'; import { NavbarMenuButton } from '@containers/ui/NavbarMenuButton/NavbarMenuButtonContainer'; // Scenes import CartView from '@containers/shopping/CartView'; import ItemBrowser from '@containers/shopping/ItemBrowser'; import IBeaconMonitorView from '@containers/beacons/IBeaconMonitorView'; import StyleGuide from '@containers/StyleGuideView'; const navbarPropsTabs = { ...AppConfig.navbarProps, renderLeftButton: () => <NavbarMenuButton />, sceneStyle: { ...AppConfig.navbarProps.sceneStyle, paddingBottom: AppSizes.tabbarHeight, }, }; /* Routes ==================================================================== */ const scenes = ( <Scene key={'tabBar'} tabs tabBarIconContainerStyle={AppStyles.tabbar} pressOpacity={0.95}> <Scene key={'shoppingCart'} {...navbarPropsTabs} title={'Your shopping cart'} component={CartView} icon={props => TabIcon({ ...props, icon: 'shopping-cart' })} analyticsDesc={'ShoppingCart: Shopping Cart'} /> <Scene key={'itemBrowser'} {...navbarPropsTabs} title={'Browse items'} component={ItemBrowser} icon={props => TabIcon({ ...props, icon: 'shopping-bag' })} analyticsDesc={'ItemBrowser: Item Browser'} /> <Scene key={'ibeacon'} {...navbarPropsTabs} title={'Ibeacon Monitoring'} component={IBeaconMonitorView} icon={props => TabIcon({ ...props, icon: 'signal' })} analyticsDesc={'iBeacon: Beacon monitoring'} /> </Scene> ); export default scenes;
define(['wdf/event-emitter', 'wdf/adobe-animate', 'app/views/stage-setup'], function(EventEmitter, AdobeAnimate) { function IndexView(config) { var self = this; var config = config; var adobeAnimate = null; var bindings = []; self.init = function() { adobeAnimate = new AdobeAnimate(config.animateCompositionId, config.stageName); adobeAnimate.on('adobe-animate-initialized', function(event, data) { console.log('Adobe Animate Initialized'); // now the Adobe Animate stage is initialized set the references to the actual controls that are databound for (var i = 0; i < bindings.length; i++) { var binding = bindings[i]; binding.control = adobeAnimate.stage.children[0][binding.controlName]; } self.trigger('view-initialized', null); }); // setup the databinding setupDataBinding(); // init the animation adobeAnimate.init(); } self.update = function(data) { for (var i = 0; i < bindings.length; i++) { var binding = bindings[i]; // find the bound data item var matchedItem = data.find(function(item) { return (item[binding.dataIdProperty] == binding.dataValue) }); if (matchedItem != null) { var value = matchedItem[binding.dataDisplayProperty]; if (binding.formatter != null) value = binding.formatter(value, binding.formatString); binding.control[binding.controlProperty] = value; } } } function setupDataBinding() { // TODO configure the array of data bindings here - it is an array of objects per the example below /* { control: null, controlName: 'THE NAME OF THE CONTROL TO BIND', controlProperty: 'THE NAME OF THE CONTROL PROPERTY TO UPDATE', dataIdProperty: 'THE ID PROPERTY OF THE DATA OBJECT', dataDisplayProperty: 'THE PROPERTY OF THE DATA OBJECT TO BIND TO THE CONTROL', dataValue: 'THE VALUE OF THE ID FIELD OF THE DATA OBJECT TO BE BOUND TO THE CONTROL' } e.g. var binding = { control: null, controlName: 'product1Price', controlProperty: 'text', dataIdProperty: 'id', dataDisplayProperty: 'price', dataValue: '735' }; bindings.push(binding); */ } } IndexView.prototype = Object.create(EventEmitter.prototype); return IndexView; })
var webpack = require('webpack'); var path = require('path'); var pkg = require('./package.json'); var hots = [path.join(__dirname, 'src'), path.join(__dirname, 'demo')]; if (pkg.dependencies) for (var pack in pkg.dependencies) { /^react-/.test(pack) && hots.push(path.join(__dirname, 'node_modules', pack)); } module.exports = { entry: { demo: [ 'webpack-dev-server/client?http://localhost:3000', 'webpack/hot/only-dev-server', './demo/demo' ] }, output: { path: path.join(__dirname, '/'), filename: '[name].entry.js', publicPath: '/' }, resolve: { modulesDirectories: ['node_modules', './src'], extensions: ['', '.js', '.jsx'] }, module: { loaders: [{ test: /\.jsx?$/, loader: 'react-hot!babel', include: hots }, { test: /\.less$/, loader: 'style!css!autoprefixer!less' }, { test: /\.css$/, loader: 'style!css!autoprefixer' }] }, plugins: [ new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin() ] };
var UziBlock = (function () { var blocklyArea, blocklyDiv, workspace; var autorunInterval, autorunNextTime; var lastFileName; var lastProgram = { ast: undefined, bytecodes: undefined }; function init(area, div) { blocklyArea = area; blocklyDiv = div; initButtons(); initBlockly(); } function initButtons() { $("#compile").on("click", function () { Uzi.compile(getGeneratedCodeAsJSON(), "json", function (bytecodes) { console.log(bytecodes); Alert.success("Compilation successful"); }); }); $("#install").on("click", function () { Uzi.install(getGeneratedCodeAsJSON(), "json", function (bytecodes) { console.log(bytecodes); Alert.success("Installation successful"); }); }); $("#run").on("click", function () { var cur = getGeneratedCodeAsJSON(); Uzi.run(cur, "json", function (bytecodes) { lastProgram = { ast: cur, bytecodes: bytecodes }; console.log(bytecodes); }); }); $("#debug").on("click", function() { Alert.danger("Debugger not implemented yet"); }); $("#newButton").on("click", function () { if (confirm("You will lose all your unsaved changes. Are you sure?")) { workspace.clear(); } }); $("#autorunCheckbox").on("change", function () { if (this.checked && autorunInterval === undefined) { autorunInterval = setInterval(autorun, 100); } else { autorunInterval = clearInterval(autorunInterval); } }); $("#openButton").on("change", function () { var file = this.files[0]; this.value = null; if (file === undefined) return; var reader = new FileReader(); reader.onload = function(e) { var xml = e.target.result; var dom = Blockly.Xml.textToDom(xml); workspace.clear(); Blockly.Xml.domToWorkspace(dom, workspace); }; reader.readAsText(file); }); $("#saveButton").on("click", function () { lastFileName = prompt("File name:", lastFileName || "program.uziblock"); if (lastFileName === null) return; if (!lastFileName.endsWith(".uziblock")) { lastFileName += ".uziblock"; } var xml = Blockly.Xml.domToPrettyText(Blockly.Xml.workspaceToDom(workspace)); var blob = new Blob([xml], {type: "text/plain;charset=utf-8"}); saveAs(blob, lastFileName); }); Uzi.onConnectionUpdate(function () { if (Uzi.isConnected) { $("#install").removeAttr("disabled"); $("#run").removeAttr("disabled"); $("#more").removeAttr("disabled"); scheduleAutorun(); } else { $("#install").attr("disabled", "disabled"); $("#run").attr("disabled", "disabled"); $("#more").attr("disabled", "disabled"); } }); Uzi.onProgramUpdate(function () { var prev = JSON.stringify(lastProgram.bytecodes); var next = JSON.stringify(Uzi.program.bytecodes); if (prev !== next && workspace !== undefined) { var xml = ASTToBlocks.generate(Uzi.program.ast); workspace.clear(); Blockly.Xml.domToWorkspace(xml, workspace); workspace.cleanUp(); } }); } function initBlockly() { var counter = 0; ajax.request({ type: 'GET', url: 'toolbox.xml', success: function (xml) { initToolbox(xml); makeResizable(); if (++counter == 2) { restore(); } } }); ajax.request({ type: 'GET', url: 'blocks.json', success: function (json) { initBlocks(JSON.parse(json)); if (++counter == 2) { restore(); } } }); } function initToolbox(toolbox) { workspace = Blockly.inject(blocklyDiv, { toolbox: toolbox }); } function initBlocks(blocks) { Blockly.defineBlocksWithJsonArray(blocks); } function resize() { // Compute the absolute coordinates and dimensions of blocklyArea. var element = blocklyArea; var x = 0; var y = 0; do { x += element.offsetLeft; y += element.offsetTop; element = element.offsetParent; } while (element); // Position blocklyDiv over blocklyArea. blocklyDiv.style.left = x + 'px'; blocklyDiv.style.top = y + 'px'; blocklyDiv.style.width = blocklyArea.offsetWidth + 'px'; blocklyDiv.style.height = blocklyArea.offsetHeight + 'px'; Blockly.svgResize(workspace); } function makeResizable() { var onresize = function (e) { resize(); } window.addEventListener('resize', onresize, false); onresize(); } function getGeneratedCode(){ var xml = Blockly.Xml.workspaceToDom(workspace); return BlocksToAST.generate(xml); } function getGeneratedCodeAsJSON() { var code = getGeneratedCode(); return JSON.stringify(code); } function workspaceChanged() { save(); scheduleAutorun(); } function save() { localStorage["uzi"] = Blockly.Xml.domToText(Blockly.Xml.workspaceToDom(workspace)); } function scheduleAutorun(deltaTime) { var currentTime = +new Date(); autorunNextTime = currentTime + (deltaTime || 200); } function autorun() { if (!Uzi.isConnected) return; if (autorunNextTime === undefined) return; var currentTime = +new Date(); if (currentTime < autorunNextTime) return; var old = Uzi.program; if (old !== undefined && old.compiled === false) return; var cur = getGeneratedCodeAsJSON(); if (cur === lastProgram.ast) return; autorunNextTime = undefined; Uzi.run(cur, "json", function (bytecodes) { lastProgram = { ast: cur, bytecodes: bytecodes }; console.log(bytecodes); }); } function restore() { try { Blockly.Xml.domToWorkspace(Blockly.Xml.textToDom(localStorage["uzi"]), workspace); } catch (err) { console.error(err); } workspace.addChangeListener(workspaceChanged); } return { init: init, resize: resize, getGeneratedCode: getGeneratedCode, getWorkspace: function () { return workspace; } }; })();
'use strict'; exports.__esModule = true; 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 _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } var _node = require('./node'); var _node2 = _interopRequireDefault(_node); var Comment = (function (_Node) { function Comment(defaults) { _classCallCheck(this, Comment); _Node.call(this, defaults); this.type = 'comment'; } _inherits(Comment, _Node); Comment.prototype.stringify = function stringify(builder) { var before = this.style('before'); if (before) builder(before); var left = this.style('left', 'commentLeft'); var right = this.style('right', 'commentRight'); builder('/*' + left + this.text + right + '*/', this); }; return Comment; })(_node2['default']); exports['default'] = Comment; module.exports = exports['default'];
import { expect } from 'chai' import generateActionNames from '../../src/utils/actionNames' describe('Utils::ActionNames', () => { describe('generateActionNames', () => { it('should return generated action names', () => { const expectedResult = { startPre: 'USERS_FETCH_PRE', start: 'USERS_FETCH', startPost: 'USERS_FETCH_POST', successPre: 'USERS_FETCH_SUCCESS_PRE', success: 'USERS_FETCH_SUCCESS', successPost: 'USERS_FETCH_SUCCESS_POST', errorPre: 'USERS_FETCH_ERROR_PRE', error: 'USERS_FETCH_ERROR', errorPost: 'USERS_FETCH_ERROR_POST' } expect(generateActionNames('users', 'fetch')).to.deep.equal(expectedResult) }) }) })
exports = {}; exports.barBeh = function barBeh(customer) { customer("bar"); }; exports.bazBeh = function bazBeh(customer) { customer("baz"); };
define(function() { 'use strict'; var LATIN_US = '\0\u263A\u263B\u2665\u2666\u2663\u2660\u2022\u25D8\u25CB\u25D9\u2642\u2640\u266A\u266B\u263C' + '\u25BA\u25C4\u2195\u203C\u00B6\u00A7\u25AC\u21A8\u2191\u2193\u2192\u2190\u221F\u2194\u25B2\u25BC' + ' |"#$%&\'()&+,-./' + '0123456789:;<=>?' + '@ABCDEFGHIJKLMNO' + 'PQRSTUVWXYZ[\\]^_' + '`abcdefghijklmno' + 'pqrstuvwxyz{|}~\u2302' + '\xC7\xFC\xE9\xE2\xE4\xE0\xE5\xE7\xEA\xEB\xE8\xEF\xEE\xEC\xC4\xC5' + '\xC9\xE6\xC6\xF4\xF6\xF2\xFB\xF9\xFF\xD6\xDC\xA2\xA3\xA5\u20A7\u0192' + '\xE1\xED\xF3\xFA\xF1\xD1\xAA\xBA\xBF\u2310\xAC\xBD\xBC\xA1\xAB\xBB' + '\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255D\u255C\u255B\u2510' + '\u2514\u2534\u252C\u251C\u2500\u253C\u255E\u255F\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u2567' + '\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256B\u256A\u2518\u250C\u2588\u2584\u258C\u2590\u2580' + '\u03B1\u00DF\u0393\u03C0\u03A3\u03C3\u00B5\u03C4\u03A6\u0398\u03A9\u03B4\u221E\u03C6\u03B5\u2229' + '\u2261\u00B1\u2265\u2264\u2320\u2321\u00F7\u2248\u00B0\u2219\u00B7\u221A\u207F\u00B2\u25A0\u00A0'; return { getTimeAndDate: function(dataView, offset) { var d = new Date(); this.assignTimeFromUint16(d, dataView.getUint16(offset, true)); this.assignDateFromUint16(d, dataView.getUint16(offset + 2, true)); return d; }, assignTimeFromUint16: function(d, u16) { d.setSeconds((u16 & 0x1f) << 1); d.setMinutes((u16 >> 5) & 0x3f); d.setHours((u16 >> 11) & 0x1f); }, assignDateFromUint16: function(d, u16) { d.setDate(u16 & 0x1f); d.setMonth((u16 >> 5) & 0xf); d.setFullYear(1980 + (u16 >> 9)); }, decodeLatinUS: function(bytes, offset, length) { if (arguments.length === 3) { bytes = bytes.subarray(offset, offset + length); } else if (arguments.length === 2) { bytes = bytes.subarray(offset); } return String.fromCharCode.apply(null, bytes).replace(/[\x01-\x1F\x7F-\xFF]/g, function(c) { return LATIN_US.charAt(c.charCodeAt(0)); }); }, }; });
module.exports = { SITE_TITLE: "Silder", DEFAULT_PAGE: "pages/page", PORT: process.env.PORT || 1234, CONTENTFUL_ACCESS_TOKEN: process.env.CONTENTFUL_ACCESS_TOKEN, CONTENTFUL_SPACE: process.env.CONTENTFUL_SPACE, PRODUCT_CONTENTTYPE_ID: process.env.PRODUCT_CONTENTTYPE_ID };
const NODE_ENV = process.env.NODE_ENV || 'development' module.exports = { /** The environment to use when building the project */ env: NODE_ENV, /** The port number the server is listening on */ port: process.env.PORT || 3000, /** The full path to the project's root directory */ basePath: __dirname, /** The name of the directory containing the application source code */ srcDir: 'src', /** The file name of the application's entry point */ main: 'main', /** The name of the directory in which to emit compiled assets */ outDir: 'dist', /** The base path for all projects assets (relative to the website root) */ publicPath: '/', /** Whether to generate sourcemaps */ sourcemaps: true, /** A hash map of keys that the compiler should treat as external to the project */ externals: {}, /** A hash map of variables and their values to expose globally */ globals: { GOOGLE_MAP_KEY: JSON.stringify(process.env.GOOGLE_MAP_KEY || 'AIzaSyCqLYkTZRH-u3j9Zc3fPXtbkqfuyLlmWqU'), GOOGLE_MAP_URL: JSON.stringify(process.env.GOOGLE_MAP_URL || 'https://maps.googleapis.com/maps/api/js?v=3&libraries=places,geometry'), // eslint-disable-line max-len }, /** Whether to enable verbose logging */ verbose: false, /** The list of modules to bundle separately from the core application code */ vendors: [ 'react', 'react-dom', 'redux', 'react-redux', 'redux-thunk', 'react-router', ], }
'use strict'; var gulp = require('gulp'); var gutil = require('gulp-util'); var concat = require('gulp-concat'); var gulpif = require('gulp-if'); var cached = require('gulp-cached'); var remember = require('gulp-remember'); var replace = require('gulp-replace-task'); var plumber = require('gulp-plumber'); var beep = require('beepbeep'); var notify = require('gulp-notify'); var del = require('del'); var minimist = require('minimist'); var sass = require('gulp-sass'); var minifyCSS = require('gulp-minify-css'); var sourcemaps = require('gulp-sourcemaps'); var minifyHTML = require('gulp-minify-html'); var browserSync = require('browser-sync'); var reload = browserSync.reload; var ngAnnotate = require('gulp-ng-annotate'); var minifyJS = require('gulp-uglify'); var eslint = require('gulp-eslint'); var fs = require('fs'); var xml2js = require('xml2js'); var parser = new xml2js.Parser({ async: false }); var xmlConfig = fs.readFileSync(__dirname + '/config.xml'); var knownOptions = { string: 'env', default: { env : process.env.NODE_ENV || 'development', turnServer : { username : process.env.TURN_USERNAME || '', password : process.env.TURN_PASSWORD || '', }, rollbar : { token : process.env.ROLLBAR_TOKEN || '', environment : process.env.ROLLBAR_ENV || 'development' } } }; var options = minimist(process.argv.slice(2), knownOptions); parser.parseString(xmlConfig, function (err, results) { if (err) { throw err; } options.version = results.widget.$.version }); var onError = function(err) { notify.onError({ title: "Gulp error in " + err.plugin, message: err.toString() })(err); beep(3); this.emit('end'); }; gulp.task('build', ['scss', 'js', 'html', 'fonts', 'copy-res'], function() { gutil.log('Finished building app to folder www'); }); gulp.task('scss', function() { return gulp.src(['app/scss/*.scss', './app/vendor/intlpnIonic/scss/intlpn.scss']) .pipe(plumber({errorHandler: onError})) .pipe(cached('scss')) .pipe(gulpif(options.env === 'development', sourcemaps.init())) .pipe(sass()) .on('error', sass.logError) .pipe(gulpif(options.env !== 'development', minifyCSS())) .pipe(remember('scss')) .pipe(concat('app.css')) .pipe(gulpif(options.env === 'development', sourcemaps.write())) .pipe(gulp.dest('./www/css/')) .pipe(reload({stream: true})) }); gulp.task('html', function() { return gulp.src(['./app/**/*.html', '!./app/vendor/**/*.html']) .pipe(cached('html')) .pipe(gulpif(options.env !== 'development', minifyHTML())) .pipe(gulp.dest('./www/')) .pipe(reload({stream: true})) }); gulp.task('ioconfig-replace', function () { var start = 'IONIC_SETTINGS_STRING_START: var settings =' ; var config = fs.readFileSync('./.io-config.json', 'utf8') var end = '; return { get: function(setting) { if (settings[setting]) { return settings[setting]; } return null; } };"IONIC_SETTINGS_STRING_END"'; var replaceWith = start + config + end; return gulp.src(['./app/vendor/ionic-platform-web-client/dist/ionic.io.bundle.js'], { base: './app' } ) .pipe(replace({ patterns: [ { match: /"IONIC_SETTINGS_STRING_START.*IONIC_SETTINGS_STRING_END"/, replacement: function () { return replaceWith; } } ] })) .pipe(gulp.dest('./www')) }); gulp.task('vendor-js', ['ioconfig-replace'], function() { return gulp.src( ['./app/vendor/ionic/js/ionic.bundle.js', './app/vendor/ngCordova/dist/*.js', './app/vendor/jquery/dist/jquery.min.js', './app/vendor/peerjs/peer.min.js', './app/vendor/rollbar/dist/rollbar.min.js', './app/vendor/angular-moment/angular-moment.min.js', './app/vendor/moment/moment.js', './app/vendor/moment/locale/fi.js', './app/vendor/lodash/lodash.min.js', './app/vendor/ngstorage/ngStorage.min.js', './app/vendor/angular-translate/angular-translate.min.js', './app/vendor/intlpnIonic/js/intlpnIonic.js', './app/vendor/intlpnIonic/js/data.js', './app/vendor/intlpnIonic/lib/libphonenumber/build/utils.js', './app/vendor/angular-translate-loader-static-files/angular-translate-loader-static-files.min.js', './app/vendor/socket.io-client/socket.io.js', './app/vendor/recordrtc/RecordRTC.js', './app/vendor/recordrtc/libs/screenshot-dev.js', './app/vendor/draggabilly/dist/draggabilly.pkgd.js', './app/vendor/fabric.js/dist/fabric.js'], { base: './app' }) .pipe(ngAnnotate()) .pipe(gulp.dest('./www/')) }); gulp.task('lint', function () { return gulp.src('./app/js/**/*.js') .pipe(eslint()) .pipe(eslint.format()) .pipe(eslint.failAfterError()) }); gulp.task('replace-env', function () { return gulp.src('./app/js/env.js', { base: './app'}) .pipe(replace({ patterns: [ { match: 'ROLLBAR_TOKEN', replacement: options.rollbar.token }, { match: 'ROLLBAR_ENV', replacement: options.rollbar.environment }, { match: 'ENVIRONMENT', replacement: options.env }, { match: 'VERSION', replacement: options.version }, { match: 'TURN_USERNAME', replacement: options.turnServer.username }, { match: 'TURN_PASSWORD', replacement: options.turnServer.password } ] })) .pipe(gulp.dest('./www/')) }) gulp.task('copy-res', ['copy-img'], function() { return gulp.src(['./app/res/**/*'], { base: './app' }) .pipe(cached('res')) .pipe(gulp.dest('./www/')) .pipe(reload({stream: true})) }); gulp.task('copy-img', function() { return gulp.src(['./app/img/*'], { base: './app' }) .pipe(gulp.dest('./www/')) }); gulp.task('fonts', function() { return gulp.src(['./app/vendor/ionic/fonts/*']) .pipe(gulp.dest('./www/fonts')) }); gulp.task('js', ['vendor-js', 'replace-env'], function() { return gulp.src(['./app/js/**/*', '!./app/js/env.js']) .pipe(plumber({errorHandler: onError})) .pipe(ngAnnotate()) .pipe(gulpif(options.env !== 'development', minifyJS())) .pipe(cached('js')) .pipe(gulp.dest('./www/js/')) .pipe(reload({stream: true})) }); gulp.task('watch', ['build'], function() { browserSync({ server: { baseDir: 'www/' }, open: false }); var scss = gulp.watch('./app/scss/*.scss', ['scss'], {cwd: 'www'}, reload); var html = gulp.watch(['./app/**/*.html', '!./app/vendor/**/*.html'], ['html'], {cwd: 'www'}, reload); var js = gulp.watch('./app/js/**/*', ['js'], {cwd: 'www'}, reload); var res = gulp.watch('./app/res/**/*', ['copy-res'], {cwd: 'www'}, reload); /*scss.on('change', function(event) { if (event.type === 'deleted') { gutil.log('Forgetting scss: ' + event.path); delete cached.caches.scss[event.path]; remember.forget('scss', event.path); } }); html.on('change', function(event) { if (event.type === 'deleted') { gutil.log('Forgetting html: ' + event.path); delete cached.caches.html[event.path]; } }); js.on('change', function(event) { if (event.type === 'deleted') { gutil.log('Forgetting js: ' + event.path); delete cached.caches.js[event.path]; } }); res.on('change', function(event) { if (event.type === 'deleted') { gutil.log('Forgetting res: ' + event.path); delete cached.caches.res[event.path]; } });*/ }); gulp.task('clean', function() { return del('www'); });
(function (window, angular, undefined) { angular.module('sdw.viewmodel', []).provider('viewmodel', function () { var self = this; var states = {}; var defaultState; var params = {}; var routes = []; this.state = function (name, options) { states[name] = { route: options.route, action: options.action }; return this; }; this.param = function (name, action) { params[name] = action; }; this.fallback = function (newDefault) { defaultState = newDefault; return this; }; this.$get = [ '$rootScope', '$location', '$routeParams', function ($rootScope, $location, $routeParams) { Object.keys(states).forEach(buildRoute); $rootScope.$on('$locationChangeSuccess', onLocationChange); self.applyState = applyState; function buildRoute(stateName, index) { var fullRoute = ''; var ancestors = getAncestors(states, stateName); ancestors.forEach(addRoute); var regex = regexRoute(fullRoute); routes.push({ string: fullRoute, state: stateName, regex: regex.re, params: regex.params }); function addRoute(ancestor, index) { fullRoute += ancestor.route; } } function onLocationChange() { var match = matchRoute($location.path()); if (match) applyState($rootScope, match.state, match.params); else if (defaultState) applyState($rootScope, defaultState, {}); else applyDefaults(); var search = $location.search(); var newState = {}; for (var key in params) { if (typeof search[key] !== 'undefined') params[key](newState, search[key]); } $rootScope.$broadcast('viewmodel:state', newState); } } ]; function matchRoute(path) { var paramMap = {}; var route, params; for (var i = 0; i < routes.length; i++) { route = routes[i]; paramValues = path.match(route.regex); if (paramValues) { paramValues.slice(1).forEach(mapParam); return { state: route.state, params: paramMap }; } } return undefined; function mapParam(val, index) { var name = route.params[index]; paramMap[name] = val; } } function regexRoute(route) { var regex = ''; var params = []; var dst = {}; var routeString = '^' + route.replace(/[-\/\\^$:*+?.()|[\]{}]/g, '\\$&') + '$'; var re = /\\([:*])(\w+)/g; var lastMatchedIndex = 0; var paramMatch; while ((paramMatch = re.exec(routeString)) !== null) { regex += routeString.slice(lastMatchedIndex, paramMatch.index); if (paramMatch[1] === ':') regex += '([^\\/]*)'; else if (paramMatch[1] === '*') regex += '(.*)'; params.push(paramMatch[2]); lastMatchedIndex = re.lastIndex; } regex += routeString.slice(lastMatchedIndex); return { string: regex, re: new RegExp(regex, 'i'), params: params }; } function applyState(scope, name, params) { var newStateValues = {}; var ancestors = getAncestors(states, name); ancestors.forEach(doAction); scope.$broadcast('viewmodel:state', newStateValues); function doAction(state, index) { var action = state.action; if (!action) return; action(newStateValues, params); } } function getAncestors(object, path) { var chain = path.split('.'); var ancestors = []; var ancestorPath; for (var len = 1; len <= chain.length; len++) { ancestorPath = chain.slice(0, len).join('.'); ancestors.push(object[ancestorPath]); } return ancestors; } }).directive('sdwViewmodel', [ '$rootScope', 'viewmodel', function ($rootScope, viewmodel) { return { restrict: 'EA', link: viewmodelLink }; function viewmodelLink(scope, element, attrs, controller) { var vmName = attrs.model || attrs.sdwViewmodel; scope[vmName] = scope[vmName] || {}; $rootScope.$on('viewmodel:state', onState); function onState(event, newState) { for (var key in newState) { scope[vmName][key] = newState[key]; } } } } ]); angular.module('dtv.demo.routes', ['sdw.viewmodel']).config([ 'viewmodelProvider', function (viewmodelProvider) { viewmodelProvider.otherwise('browse').state('browse', { route: '', action: function (vm, params) { vm.showModal = false; } }).state('browse.movie', { route: '/movie/:movie', action: function (vm, params) { vm.showModal = true; vm.modalView = 'movie'; vm.movieId = +params.movie; } }).state('browse.movie.rent', { route: '/rent', action: function (vm, params) { vm.modalView = 'rent'; } }).state('browse.celebrity', { route: '/celebrity/:celeb', action: function (vm, params) { vm.showModal = true; vm.modalView = 'celebrity'; vm.celebId = +params.celeb; } }); } ]).controller('RouteController', [ '$scope', '$location', 'viewmodel', function ($scope, $location, viewmodel) { $scope.movies = [ { id: 123, title: 'The Shawshank Redemption', celeb: 333 }, { id: 234, title: 'Garden State', celeb: 444 }, { id: 345, title: 'Crouching Tiger, Hidden Dragon', celeb: 555 } ]; $scope.celebs = [ { id: 333, name: 'Morgan Freeman' }, { id: 444, name: 'Zach Braff' }, { id: 555, name: 'Chow Yun Fat' } ]; $scope.movieData = function () { for (var i = 0; i < $scope.movies.length; i++) { if ($scope.movies[i].id === $scope.vm.movieId) return $scope.movies[i]; } }; $scope.celebData = function () { for (var i = 0; i < $scope.celebs.length; i++) { if ($scope.celebs[i].id === $scope.vm.celebId) return $scope.celebs[i]; } }; $scope.onRent = function () { alert('Rented ' + $scope.movieData().title + '!'); $location.path(''); }; } ]); angular.module('examples.simple', ['sdw.viewmodel']).config([ 'viewmodelProvider', function (viewmodelProvider) { viewmodelProvider.fallback('default').state('default', { action: function (vm, params) { vm.showModal = false; vm.article = ''; vm.showPrice = false; } }).state('article', { route: '/article/:article', action: function (vm, params) { vm.showModal = true; vm.article = params.article; } }).state('article.buy', { route: '/buy', action: function (vm, params) { vm.showPrice = true; } }).param('alt', function (vm, param) { console.log('alt'); vm.useAltStyle = param === 'true'; }); } ]); angular.module('templates-app', []); angular.module('templates-component', []); }(window, window.angular));
"use strict"; var assert = require('assert'); var Item = function(desc) { var items = []; this.description = desc; return this; }; var description = function(desc) { return function(x) { return x.description === desc; }; }; var Basket = function() { var items = []; this.add = function(item) { items.push(item); }; this.contents = function() { return items; }; this.itemsMatching = function(x) { return items.filter(x); }; return this; }; var Checkout = function() { this.price = function(basket) { return 0; }; return this; }; var Unit = function(item,price) { this.applies = function(basket) { return true; }; return this; }; describe('shopping basket', function() { describe('item', function() { it('exists', function() { assert(new Item('description')); }); it('has a description', function() { var item = new Item('banana'); assert.equal('banana', item.description); }); }); describe('basket', function() { it('exists', function() { assert(new Basket()); }); it('items can be added', function() { var basket = new Basket(); basket.add(new Item('Shoes')); assert.equal(1, basket.contents().length); }); it('can be queried', function() { var basket = new Basket(); var items = basket.itemsMatching( function(x) { return false; } ); assert.equal(0, items.length); }); it('returns results', function() { var basket = new Basket(); var beans = new Item('beans'); basket.add(beans); assert.deepEqual( [beans], basket.itemsMatching(description('beans')) ); }); }); describe('checkout', function() { it('exists', function() { assert(new Checkout()); }); it('prices an empty basket at zero', function() { var checkout = new Checkout(); assert.equal(0, checkout.price(new Basket())); }); }); describe('offers', function() { it('unit', function() { var beans = new Item('beans'); var basket = new Basket(); var unit = new Unit(beans, 50); basket.add(beans); assert(unit.applies(basket)); }); }); }); // LA Story is on.
/******************************************************************************* * Copyright (c) 2014, 2015 IBM Corporation * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. *******************************************************************************/ var dataUtil = (function() { function onSuccess() { console.log('success'); console.log(arguments); } function onError() { console.log('error'); console.log(arguments); } return { 'getData' : function(options) { $.ajax('data/' + options.type +"?"+(new Date()).getTime(), { 'method' : 'GET', 'data' : options.data || {}, 'dataType' : 'json', 'error' : function() { (options.error || onError).apply(this, arguments); }, 'success' : function() { (options.success || onSuccess).apply(this, arguments); } }); }, 'deleteData' : function(options) { $.ajax('data/' + options.type + '/' + options.id, { 'method' : 'DELETE', 'dataType' : 'json', 'error' : function() { (options.error || onError).apply(this, arguments); }, 'success' : function() { (options.success || onSuccess).apply(this, arguments); } }); }, 'postData' : function(options) { $.ajax('data/' + options.type, { 'method' : 'POST', 'data' : options.data, 'dataType' : 'json', 'error' : function() { (options.error || onError).apply(this, arguments); }, 'success' : function() { (options.success || onSuccess).apply(this, arguments); } }); }, 'postFormData' : function(options) { // note: data/type url rewrite does not work with multipart $.ajax('data?type=' + options.type + (options.id?"&id="+options.id:"") , { 'method' : 'POST', 'contentType' : false, 'processData' : false, 'data' : options.data, 'dataType' : 'json', 'error' : function() { (options.error || onError).apply(this, arguments); }, 'success' : function() { (options.success || onSuccess).apply(this, arguments); } }); } }; })();
'use strict'; var any = require('../').any; var tape = require('tape'); var Handlebars = require('handlebars'); Handlebars.registerHelper(any.name, any); tape('any', function (test) { var expected = '✔︎'; var template; var actual; test.plan(7); template = Handlebars.compile('{{#any a b c}}✔︎{{/any}}'); actual = template({ a: true, b: true, c: true }); test.equal(actual, expected, 'Resolves to true when all values are true'); template = Handlebars.compile('{{#any a b c d e f g}}✔︎{{/any}}'); actual = template({ a: true, b: 14, c: 'false', d: {}, e: [], f: '0', g: -42 }); test.equal(actual, expected, 'Resolves to true when all values are truthy'); template = Handlebars.compile('{{#any a b c}}✔︎{{/any}}'); actual = template({ a: false, b: true, c: false }); test.equal(actual, expected, 'Resolves to true when any value is true'); template = Handlebars.compile('{{#any a b c}}✔︎{{/any}}'); actual = template({ a: false, b: 14, c: false }); test.equal(actual, expected, 'Resolves to true when any value is truthy'); template = Handlebars.compile('{{#any a b c}}{{else}}✔︎{{/any}}'); actual = template({ a: false, b: false, c: false }); test.equal(actual, expected, 'Resolves to false when no value is true'); template = Handlebars.compile('{{#any a b c}}{{else}}✔︎{{/any}}'); actual = template({ a: false, b: undefined, c: false }); test.equal(actual, expected, 'Resolves to false when no value is truthy'); template = Handlebars.compile('{{#if (any a b c)}}✔︎{{/if}}'); actual = template({ a: false, b: true, c: false }); test.equal(actual, expected, 'Works as an inline helper'); });
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var AbstractEvent = /** @class */ (function () { function AbstractEvent(type, payload) { this.type = type; this.payload = payload; } return AbstractEvent; }()); exports.AbstractEvent = AbstractEvent; //# sourceMappingURL=AbstractEvent.js.map
git://github.com/BBC-News/Imager.js.git
const stopLang = require('../../umd/stop.js'); describe('The POP instruction', () => { const getResult = dataString => { const program = new stopLang([`POP ${dataString}`]); program.go(); return program.currentResult; }; it('can be empty', () => { const instructions = [ 'NOOP 1', 'NOOP 2', 'POP', 'NOOP $0' ]; const program = new stopLang(instructions); program.go(); expect(program.currentResult).toBe(2); }); it('must be empty', () => { expect(() => getResult('1')).toThrowError(SyntaxError); }); it('can remove itself', () => { expect(getResult('')).not.toBeDefined(); }); it('can update the value instruction pointer', () => { const instructions = [ 'GOTO "TEST"', 'POP', '(TEST) NOOP $ip $ci $1 $ip $ci' ]; const program = new stopLang(instructions); program.go(); expect(program.currentResult).toEqual([2, 2, undefined, 1, 1]); }); });
/** * third() * ---------- * Method that return the third item in an array. * * @param {array} array - An array. * @return {any} - The third element. */ const third = array => array[2] export default third
import React from 'react'; import PropTypes from 'prop-types'; import { Alert, Button } from 'react-bootstrap'; import { RefreshIcon } from '../../icons'; import './Alert.css'; const ErrorAlert = ({ error, onDismiss }) => <Alert bsStyle="danger" className="Alert-container" onDismiss={onDismiss}> <h4>You got an error!</h4> <p> {error.message} </p> {error.refresh && <Button onClick={error.refresh}> <RefreshIcon /> Refresh </Button>} </Alert>; ErrorAlert.propTypes = { error: PropTypes.shape({ message: PropTypes.string.isRequired, refresh: PropTypes.func }), onDismiss: PropTypes.func.isRequired }; export default ErrorAlert;
import { componentName, stripLeadingUnderscore, capitalize } from './normalize-inputs'; describe('componentName', () => { test('should return the default value', () => { expect(componentName('value', 'previousValue', { label: 'label' })).toEqual( 'value' ); }); test('should return the created value', () => { expect(componentName('', '', { label: 'label' })).toEqual('LABEL'); }); }); describe('stripLeadingUnderscore', () => { test('should remove leading underscore', () => { expect(stripLeadingUnderscore('_this is a string')).toEqual('this'); }); }); describe('capitalize', () => { test('should return a capitalized version of a string', () => { expect(capitalize('this is a string')).toEqual('This is a string'); }); });
/* * React.js Starter Kit * Copyright (c) 2014 Konstantin Tarkus (@koistya), KriaSoft LLC. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ /* global jest, describe, it, expect, beforeEach */ 'use strict'; jest.dontMock('../LanguageList'); describe('LanguageList', function() { var React, TestUtils, LanguageList, Component; beforeEach(function() { React = require('react/addons'); TestUtils = React.addons.TestUtils; LanguageList = require('../LanguageList'); Component = TestUtils.renderIntoDocument(React.createElement(LanguageList, { gitHubRepoLanguages: require.requireActual('../../../models/__mocks__/fakeGitHubRepoLanguages.js') })); }); it('has class language-list', function() { var element = TestUtils.findRenderedDOMComponentWithClass(Component, 'language-list'); expect(element).toBeDefined(); }); it('displays the languages of the repo, and the respective percentages', function() { var languageElements = TestUtils.scryRenderedDOMComponentsWithClass(Component, 'language'); expect(languageElements.length).toBeGreaterThan(0); var languageNameElements = TestUtils.scryRenderedDOMComponentsWithClass(Component, 'language-name'); expect(languageNameElements.length).toBeGreaterThan(0); var percentageElements = TestUtils.scryRenderedDOMComponentsWithClass(Component, 'language-percentage'); expect(percentageElements.length).toBeGreaterThan(0); }); });
'use strict'; let express = require('express'); let router = express.Router(); /* GET: Generate OTP */ router.get('/', (req, res, next) => { let data = [{ "id": 1, "first_name": "Daniel", "last_name": "Ramos", "email": "dramos0@trellian.com", "gender": "Male", "ip_address": "188.70.152.200" }, { "id": 2, "first_name": "Nicole", "last_name": "Morales", "email": "nmorales1@behance.net", "gender": "Female", "ip_address": "239.88.129.115" }, { "id": 3, "first_name": "Stephen", "last_name": "Price", "email": "sprice2@posterous.com", "gender": "Male", "ip_address": "47.250.52.230" }, { "id": 4, "first_name": "Robin", "last_name": "Russell", "email": "rrussell3@netvibes.com", "gender": "Female", "ip_address": "111.35.255.240" }, { "id": 5, "first_name": "William", "last_name": "Hansen", "email": "whansen4@about.me", "gender": "Male", "ip_address": "75.187.161.245" }, { "id": 6, "first_name": "Carlos", "last_name": "Lynch", "email": "clynch5@netlog.com", "gender": "Male", "ip_address": "59.74.97.207" }, { "id": 7, "first_name": "Theresa", "last_name": "Hudson", "email": "thudson6@walmart.com", "gender": "Female", "ip_address": "37.90.208.192" }, { "id": 8, "first_name": "Martha", "last_name": "Moore", "email": "mmoore7@t.co", "gender": "Female", "ip_address": "5.116.77.255" }, { "id": 9, "first_name": "Anthony", "last_name": "Dixon", "email": "adixon8@linkedin.com", "gender": "Male", "ip_address": "120.233.236.10" }, { "id": 10, "first_name": "Martin", "last_name": "Little", "email": "mlittle9@usgs.gov", "gender": "Male", "ip_address": "219.201.238.178" }, { "id": 11, "first_name": "Todd", "last_name": "Ramos", "email": "tramosa@1688.com", "gender": "Male", "ip_address": "88.141.123.142" }, { "id": 12, "first_name": "Jason", "last_name": "Ramos", "email": "jramosb@skype.com", "gender": "Male", "ip_address": "221.64.96.122" }, { "id": 13, "first_name": "Carlos", "last_name": "Barnes", "email": "cbarnesc@nytimes.com", "gender": "Male", "ip_address": "142.82.59.105" }, { "id": 14, "first_name": "Diane", "last_name": "Montgomery", "email": "dmontgomeryd@globo.com", "gender": "Female", "ip_address": "15.47.215.178" }, { "id": 15, "first_name": "Frances", "last_name": "Rivera", "email": "friverae@etsy.com", "gender": "Female", "ip_address": "240.20.209.34" }, { "id": 16, "first_name": "Jessica", "last_name": "Hicks", "email": "jhicksf@scribd.com", "gender": "Female", "ip_address": "101.98.140.132" }, { "id": 17, "first_name": "Sara", "last_name": "Gordon", "email": "sgordong@mapquest.com", "gender": "Female", "ip_address": "23.212.231.100" }, { "id": 18, "first_name": "Nicole", "last_name": "Ruiz", "email": "nruizh@fotki.com", "gender": "Female", "ip_address": "188.157.132.76" }, { "id": 19, "first_name": "Jeremy", "last_name": "Wilson", "email": "jwilsoni@jalbum.net", "gender": "Male", "ip_address": "248.86.210.184" }, { "id": 20, "first_name": "Frances", "last_name": "Warren", "email": "fwarrenj@google.de", "gender": "Female", "ip_address": "214.131.180.20" }, { "id": 21, "first_name": "Helen", "last_name": "Mills", "email": "hmillsk@acquirethisname.com", "gender": "Female", "ip_address": "143.245.54.58" }, { "id": 22, "first_name": "Joshua", "last_name": "Moreno", "email": "jmorenol@github.com", "gender": "Male", "ip_address": "150.112.127.35" }, { "id": 23, "first_name": "Philip", "last_name": "Moreno", "email": "pmorenom@wix.com", "gender": "Male", "ip_address": "171.175.127.118" }, { "id": 24, "first_name": "Anne", "last_name": "Alexander", "email": "aalexandern@buzzfeed.com", "gender": "Female", "ip_address": "83.239.116.81" }, { "id": 25, "first_name": "Judith", "last_name": "Lawson", "email": "jlawsono@telegraph.co.uk", "gender": "Female", "ip_address": "225.210.165.50" }, { "id": 26, "first_name": "Timothy", "last_name": "Diaz", "email": "tdiazp@ca.gov", "gender": "Male", "ip_address": "47.153.3.169" }, { "id": 27, "first_name": "Anthony", "last_name": "Hansen", "email": "ahansenq@moonfruit.com", "gender": "Male", "ip_address": "104.242.33.95" }, { "id": 28, "first_name": "Clarence", "last_name": "Ferguson", "email": "cfergusonr@comcast.net", "gender": "Male", "ip_address": "216.23.64.92" }, { "id": 29, "first_name": "Andrew", "last_name": "Reid", "email": "areids@51.la", "gender": "Male", "ip_address": "71.204.55.173" }, { "id": 30, "first_name": "Craig", "last_name": "Scott", "email": "cscottt@blogger.com", "gender": "Male", "ip_address": "30.243.9.119" }, { "id": 31, "first_name": "Anthony", "last_name": "Young", "email": "ayoungu@mysql.com", "gender": "Male", "ip_address": "4.29.27.222" }, { "id": 32, "first_name": "Melissa", "last_name": "Stephens", "email": "mstephensv@mtv.com", "gender": "Female", "ip_address": "202.117.205.176" }, { "id": 33, "first_name": "Adam", "last_name": "Cox", "email": "acoxw@disqus.com", "gender": "Male", "ip_address": "95.60.189.47" }, { "id": 34, "first_name": "Daniel", "last_name": "Kelly", "email": "dkellyx@joomla.org", "gender": "Male", "ip_address": "157.205.140.178" }, { "id": 35, "first_name": "Steven", "last_name": "Johnston", "email": "sjohnstony@noaa.gov", "gender": "Male", "ip_address": "202.228.239.230" }, { "id": 36, "first_name": "Julia", "last_name": "Morris", "email": "jmorrisz@blogger.com", "gender": "Female", "ip_address": "102.230.216.123" }, { "id": 37, "first_name": "Arthur", "last_name": "Welch", "email": "awelch10@nbcnews.com", "gender": "Male", "ip_address": "179.141.198.73" }, { "id": 38, "first_name": "Carolyn", "last_name": "Foster", "email": "cfoster11@symantec.com", "gender": "Female", "ip_address": "127.75.49.245" }, { "id": 39, "first_name": "Bonnie", "last_name": "Vasquez", "email": "bvasquez12@hostgator.com", "gender": "Female", "ip_address": "37.74.104.58" }, { "id": 40, "first_name": "Douglas", "last_name": "Lopez", "email": "dlopez13@goodreads.com", "gender": "Male", "ip_address": "22.105.160.157" }, { "id": 41, "first_name": "Michelle", "last_name": "Dunn", "email": "mdunn14@liveinternet.ru", "gender": "Female", "ip_address": "126.121.66.199" }, { "id": 42, "first_name": "Kathy", "last_name": "Cunningham", "email": "kcunningham15@state.tx.us", "gender": "Female", "ip_address": "48.113.103.133" }, { "id": 43, "first_name": "Kathryn", "last_name": "Simmons", "email": "ksimmons16@scientificamerican.com", "gender": "Female", "ip_address": "92.219.227.138" }, { "id": 44, "first_name": "Richard", "last_name": "Ferguson", "email": "rferguson17@com.com", "gender": "Male", "ip_address": "79.207.55.55" }, { "id": 45, "first_name": "Diana", "last_name": "Baker", "email": "dbaker18@time.com", "gender": "Female", "ip_address": "53.128.150.108" }, { "id": 46, "first_name": "Jacqueline", "last_name": "Warren", "email": "jwarren19@usa.gov", "gender": "Female", "ip_address": "29.129.180.79" }, { "id": 47, "first_name": "Anne", "last_name": "Ortiz", "email": "aortiz1a@mlb.com", "gender": "Female", "ip_address": "233.14.151.253" }, { "id": 48, "first_name": "Dorothy", "last_name": "Bradley", "email": "dbradley1b@bing.com", "gender": "Female", "ip_address": "133.102.5.129" }, { "id": 49, "first_name": "Chris", "last_name": "Montgomery", "email": "cmontgomery1c@berkeley.edu", "gender": "Male", "ip_address": "80.131.249.14" }, { "id": 50, "first_name": "Henry", "last_name": "Perez", "email": "hperez1d@webeden.co.uk", "gender": "Male", "ip_address": "68.179.214.74" }, { "id": 51, "first_name": "Antonio", "last_name": "Morrison", "email": "amorrison1e@paginegialle.it", "gender": "Male", "ip_address": "125.231.23.158" }, { "id": 52, "first_name": "Eugene", "last_name": "Jackson", "email": "ejackson1f@fotki.com", "gender": "Male", "ip_address": "47.240.20.246" }, { "id": 53, "first_name": "Sharon", "last_name": "Lopez", "email": "slopez1g@topsy.com", "gender": "Female", "ip_address": "92.38.86.196" }, { "id": 54, "first_name": "Deborah", "last_name": "Duncan", "email": "dduncan1h@webeden.co.uk", "gender": "Female", "ip_address": "34.86.146.56" }, { "id": 55, "first_name": "Denise", "last_name": "Hanson", "email": "dhanson1i@wisc.edu", "gender": "Female", "ip_address": "51.58.243.51" }, { "id": 56, "first_name": "Mark", "last_name": "Cruz", "email": "mcruz1j@google.es", "gender": "Male", "ip_address": "234.182.255.66" }, { "id": 57, "first_name": "Phillip", "last_name": "Davis", "email": "pdavis1k@netvibes.com", "gender": "Male", "ip_address": "184.158.117.26" }, { "id": 58, "first_name": "Debra", "last_name": "Coleman", "email": "dcoleman1l@goo.gl", "gender": "Female", "ip_address": "117.230.184.19" }, { "id": 59, "first_name": "Alan", "last_name": "Rodriguez", "email": "arodriguez1m@skyrock.com", "gender": "Male", "ip_address": "127.47.242.26" }, { "id": 60, "first_name": "Stephanie", "last_name": "Gutierrez", "email": "sgutierrez1n@zimbio.com", "gender": "Female", "ip_address": "35.171.40.193" }, { "id": 61, "first_name": "Christopher", "last_name": "Medina", "email": "cmedina1o@wunderground.com", "gender": "Male", "ip_address": "135.88.84.201" }, { "id": 62, "first_name": "Jeffrey", "last_name": "Price", "email": "jprice1p@hhs.gov", "gender": "Male", "ip_address": "254.116.87.139" }, { "id": 63, "first_name": "James", "last_name": "Woods", "email": "jwoods1q@omniture.com", "gender": "Male", "ip_address": "55.85.94.50" }, { "id": 64, "first_name": "Kevin", "last_name": "Montgomery", "email": "kmontgomery1r@ehow.com", "gender": "Male", "ip_address": "36.62.231.23" }, { "id": 65, "first_name": "Cheryl", "last_name": "Nichols", "email": "cnichols1s@pinterest.com", "gender": "Female", "ip_address": "60.220.197.91" }, { "id": 66, "first_name": "Sarah", "last_name": "Garza", "email": "sgarza1t@example.com", "gender": "Female", "ip_address": "101.180.123.83" }, { "id": 67, "first_name": "Arthur", "last_name": "Willis", "email": "awillis1u@ezinearticles.com", "gender": "Male", "ip_address": "150.106.225.244" }, { "id": 68, "first_name": "George", "last_name": "Hughes", "email": "ghughes1v@hud.gov", "gender": "Male", "ip_address": "105.198.54.176" }, { "id": 69, "first_name": "Christine", "last_name": "Wallace", "email": "cwallace1w@weather.com", "gender": "Female", "ip_address": "240.164.179.183" }, { "id": 70, "first_name": "Benjamin", "last_name": "Miller", "email": "bmiller1x@ucoz.ru", "gender": "Male", "ip_address": "229.200.9.192" }, { "id": 71, "first_name": "Andrea", "last_name": "Hanson", "email": "ahanson1y@surveymonkey.com", "gender": "Female", "ip_address": "55.204.65.74" }, { "id": 72, "first_name": "Justin", "last_name": "Meyer", "email": "jmeyer1z@java.com", "gender": "Male", "ip_address": "79.88.7.251" }, { "id": 73, "first_name": "Ryan", "last_name": "Williamson", "email": "rwilliamson20@themeforest.net", "gender": "Male", "ip_address": "147.29.159.185" }, { "id": 74, "first_name": "Timothy", "last_name": "Cunningham", "email": "tcunningham21@squidoo.com", "gender": "Male", "ip_address": "201.41.90.199" }, { "id": 75, "first_name": "Sara", "last_name": "Rodriguez", "email": "srodriguez22@angelfire.com", "gender": "Female", "ip_address": "107.250.85.26" }, { "id": 76, "first_name": "Carl", "last_name": "Jones", "email": "cjones23@pinterest.com", "gender": "Male", "ip_address": "114.190.63.95" }, { "id": 77, "first_name": "Julia", "last_name": "Rodriguez", "email": "jrodriguez24@jiathis.com", "gender": "Female", "ip_address": "166.52.208.174" }, { "id": 78, "first_name": "Irene", "last_name": "Ward", "email": "iward25@drupal.org", "gender": "Female", "ip_address": "71.13.44.248" }, { "id": 79, "first_name": "David", "last_name": "Gutierrez", "email": "dgutierrez26@nytimes.com", "gender": "Male", "ip_address": "98.200.111.183" }, { "id": 80, "first_name": "Randy", "last_name": "Martinez", "email": "rmartinez27@ycombinator.com", "gender": "Male", "ip_address": "18.101.178.236" }, { "id": 81, "first_name": "Carl", "last_name": "Cunningham", "email": "ccunningham28@uol.com.br", "gender": "Male", "ip_address": "41.89.137.155" }, { "id": 82, "first_name": "Karen", "last_name": "Palmer", "email": "kpalmer29@youtu.be", "gender": "Female", "ip_address": "102.137.88.214" }, { "id": 83, "first_name": "Helen", "last_name": "Bradley", "email": "hbradley2a@google.fr", "gender": "Female", "ip_address": "246.209.88.230" }, { "id": 84, "first_name": "Aaron", "last_name": "Reyes", "email": "areyes2b@indiegogo.com", "gender": "Male", "ip_address": "39.15.17.15" }, { "id": 85, "first_name": "Jessica", "last_name": "Hunter", "email": "jhunter2c@thetimes.co.uk", "gender": "Female", "ip_address": "25.0.118.160" }, { "id": 86, "first_name": "Harold", "last_name": "Holmes", "email": "hholmes2d@g.co", "gender": "Male", "ip_address": "108.168.254.11" }, { "id": 87, "first_name": "Edward", "last_name": "Miller", "email": "emiller2e@reference.com", "gender": "Male", "ip_address": "175.212.149.241" }, { "id": 88, "first_name": "Donald", "last_name": "Morales", "email": "dmorales2f@jigsy.com", "gender": "Male", "ip_address": "43.75.8.134" }, { "id": 89, "first_name": "Cheryl", "last_name": "Harrison", "email": "charrison2g@ucoz.ru", "gender": "Female", "ip_address": "214.130.239.7" }, { "id": 90, "first_name": "Nicole", "last_name": "Banks", "email": "nbanks2h@nymag.com", "gender": "Female", "ip_address": "10.195.231.94" }, { "id": 91, "first_name": "Joshua", "last_name": "Weaver", "email": "jweaver2i@reverbnation.com", "gender": "Male", "ip_address": "190.69.212.112" }, { "id": 92, "first_name": "John", "last_name": "Williamson", "email": "jwilliamson2j@yelp.com", "gender": "Male", "ip_address": "54.81.69.43" }, { "id": 93, "first_name": "Sean", "last_name": "Robinson", "email": "srobinson2k@fda.gov", "gender": "Male", "ip_address": "159.173.76.2" }, { "id": 94, "first_name": "Eric", "last_name": "Perez", "email": "eperez2l@nasa.gov", "gender": "Male", "ip_address": "100.158.159.51" }, { "id": 95, "first_name": "Nicholas", "last_name": "Moreno", "email": "nmoreno2m@storify.com", "gender": "Male", "ip_address": "56.78.97.168" }, { "id": 96, "first_name": "Paula", "last_name": "Hayes", "email": "phayes2n@webs.com", "gender": "Female", "ip_address": "106.42.11.168" }, { "id": 97, "first_name": "Dennis", "last_name": "Sims", "email": "dsims2o@blog.com", "gender": "Male", "ip_address": "41.86.90.185" }, { "id": 98, "first_name": "Rebecca", "last_name": "Harris", "email": "rharris2p@economist.com", "gender": "Female", "ip_address": "40.117.132.229" }, { "id": 99, "first_name": "Ernest", "last_name": "Hanson", "email": "ehanson2q@artisteer.com", "gender": "Male", "ip_address": "22.95.47.102" }, { "id": 100, "first_name": "Sara", "last_name": "Stevens", "email": "sstevens2r@redcross.org", "gender": "Female", "ip_address": "8.36.132.152" }]; res.status(200).send(data); }); module.exports = router;
"use strict"; if (process.env.CI_TEACHER_ACCOUNT) { const { ipcRenderer } = require("electron"); const logger = {}; Object.keys(console).forEach(fnName => { logger[fnName] = function () { const args = Array.from(arguments); ipcRenderer.send("logger." + fnName, args); return console[fnName].apply(console, args); }; }); module.exports = logger; } else { module.exports = console; }
$('#asistencia').click(function () { var pro = $('#txtpro').val(); var lista = []; $('.listainst:checked').each(function () { lista.push(this.value); }); if (lista.length > 0) { $.ajax({ url: 'ControllerAsistenciaprogramacion/insertDetalleAsistencia', type: "POST", data:{programacion:pro,instruc:lista}, dataType:"JSON", }).done(function(data) { if (data.funciono) { swal( 'Exitoso!', 'Los instructores seleccionados asistieron a la programación! '+ " " + pro, 'success' ) setTimeout(function(){location.reload()}, 1300); } }).fail(function (jqXHR, textStatus, errorThrown) { swal("Seleccione Programación"); }); } else { swal("seleccione instructor"); } }); $(document).ready(function() { $("#txtpro").select2(); });
var pump0, pump1, pump2, pump3, pump4, awake = false; var five = require('johnny-five'); try { if (process.env.BAR !== 'NO') { console.log("Bartender Waking Up".green); var boardPort = process.env.BOARD_PORT || 'COM5'; var board; if (boardPort !== undefined && boardPort !== null && boardPort.length > 0) { board = new five.Board({port:boardPort, repl: false}); } else { board = new five.Board({repl: false}); } board.on('ready', function() { pump0 = new five.Led(3); pump1 = new five.Led(4); pump2 = new five.Led(5); pump3 = new five.Led(6); pump4 = new five.Led(7); console.log('Bartender Ready'.green); awake = true; }); board.on("fail", function(event) { /* Event { type: "info"|"warn"|"fail", timestamp: Time of event in milliseconds, class: name of relevant component class, message: message [+ ...detail] } */ console.log("%s sent a 'fail' message: %s", event.class, event.message); }); board.on('error', function(err) { console.log("Ooops", err); return; }); } } catch(err) { console.log('Bartender not initialised. Is it plugged in?', err); } exports.clean = function(time) { var t = time || 5000; setTimeout(function () { pumpMilliseconds('pump0', time); }, 50); setTimeout(function () { pumpMilliseconds('pump1', time); }, 50); setTimeout(function () { pumpMilliseconds('pump2', time); }, 50); setTimeout(function () { pumpMilliseconds('pump3', time); }, 50); setTimeout(function () { pumpMilliseconds('pump4', time); }, 50); }; exports.pump = function(ingredients) { if (awake === false) { console.log("Go away, I'm sleeping!"); return; } console.log('Making drink...'.blue); for (var i in ingredients) { (function(i) { setTimeout(function () { pumpMilliseconds(ingredients[i].pump, ingredients[i].amount); }, ingredients[i].delay); })(i); } }; function pumpMilliseconds(pump, time) { exports.startPump(pump); setTimeout(function () { exports.stopPump(pump); }, time); } exports.startPump = function (pump) { console.log(new Date()) console.log(("Starting " + pump).blue); var p = exports.usePump(pump); p.on(); }; exports.stopPump = function (pump) { console.log(new Date()) console.log(("Stopping " + pump).blue); var p = exports.usePump(pump); p.off(); }; exports.usePump = function (pump) { var using; switch(pump) { case 'pump0': using = pump0; break; case 'pump1': using = pump1; break; case 'pump2': using = pump2; break; case 'pump3': using = pump3; break; case 'pump4': using = pump4; break; default: using = null; break; } return using; };
// ## Grunt configuration configureGrunt = function (grunt) { // load all grunt tasks require('matchdep').filterDev(['grunt-*', '!grunt-cli']).forEach(grunt.loadNpmTasks); var cfg = { // ### Config for grunt-contrib-watch // Watch files and livereload in the browser during development watch: { 'handlebars-ember': { files: ['core/client/**/*.hbs'], tasks: ['emberTemplates:dev'] }, ember: { files: ['core/client/**/*.js'], tasks: ['transpile', 'concat_sourcemap'] }, express: { // Restart any time clientold or server js files change files: ['core/server.js', 'core/server/**/*.js', 'core/client/*.js', 'core/client/**/*.js'], tasks: ['express:dev'], options: { //Without this option specified express won't be reloaded nospawn: true } } }, // ### Config for grunt-express-server // Start our server in development express: { options: { script: 'app.js', output: 'Ghost is running' }, dev: { options: { //output: 'Express server listening on address:.*$' } }, test: { options: { node_env: 'testing' } } }, // ### Config for grunt-ember-templates // Compiles handlebar templates for ember emberTemplates: { dev: { options: { templateBasePath: /core\/client\//, templateFileExtensions: /\.hbs/, templateRegistration: function (name, template) { return grunt.config.process("define('expressboiler/") + name + "', ['exports'], function(__exports__){ __exports__['default'] = " + template + "; });"; } }, files: { "core/built/scripts/templates-ember.js": "core/client/templates/**/*.hbs" } } }, // ### Config for grunt-es6-module-transpiler // Compiles Ember es6 modules transpile: { client: { type: 'amd', moduleName: function (path) { return 'expressboiler/' + path; }, files: [{ expand: true, cwd: 'core/client/', src: ['**/*.js'], dest: '.tmp/ember-transpiled/' }] } }, // ### Config for grunt-contrib-concat-sourcemap // Compiles Ember es6 modules concat_sourcemap: { client: { src: ['.tmp/ember-transpiled/**/*.js'], dest: 'core/built/scripts/expressboiler-ember.js', options: { sourcesContent: true } } }, // ### Config for grunt-contrib-concat // Compiles Ember es6 modules concat: { client: { src: ['.tmp/ember-transpiled/**/*.js'], dest: 'core/built/scripts/expressboiler-ember.js' } }, // ### Config for grunt-contrib-copy // Copies necessary files to public copy: { main: { files: [ { src: 'core/built/scripts/expressboiler-ember.js.map', dest: 'public/scripts/expressboiler-ember.js.map' } ] } } }; grunt.initConfig(cfg); // All tasks related to building the Ember client code grunt.registerTask('emberBuild', 'Build Ember JS & templates for development', ['emberTemplates:dev', 'transpile', 'concat', 'copy']); grunt.registerTask('dev', 'Build JS & templates for development', [ 'emberBuild', 'express:dev', 'watch' ]); grunt.registerTask('default', 'Build JS & templates for development', [ 'emberBuild' ]); } module.exports = configureGrunt;
/*! * jQuery UI 1.8.5 * * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * http://docs.jquery.com/UI */ (function(c,j){function k(a){return!c(a).parents().andSelf().filter(function(){return c.curCSS(this,"visibility")==="hidden"||c.expr.filters.hidden(this)}).length}c.ui=c.ui||{};if(!c.ui.version){c.extend(c.ui,{version:"1.8.5",keyCode:{ALT:18,BACKSPACE:8,CAPS_LOCK:20,COMMA:188,COMMAND:91,COMMAND_LEFT:91,COMMAND_RIGHT:93,CONTROL:17,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,INSERT:45,LEFT:37,MENU:93,NUMPAD_ADD:107,NUMPAD_DECIMAL:110,NUMPAD_DIVIDE:111,NUMPAD_ENTER:108,NUMPAD_MULTIPLY:106, NUMPAD_SUBTRACT:109,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SHIFT:16,SPACE:32,TAB:9,UP:38,WINDOWS:91}});c.fn.extend({_focus:c.fn.focus,focus:function(a,b){return typeof a==="number"?this.each(function(){var d=this;setTimeout(function(){c(d).focus();b&&b.call(d)},a)}):this._focus.apply(this,arguments)},scrollParent:function(){var a;a=c.browser.msie&&/(static|relative)/.test(this.css("position"))||/absolute/.test(this.css("position"))?this.parents().filter(function(){return/(relative|absolute|fixed)/.test(c.curCSS(this, "position",1))&&/(auto|scroll)/.test(c.curCSS(this,"overflow",1)+c.curCSS(this,"overflow-y",1)+c.curCSS(this,"overflow-x",1))}).eq(0):this.parents().filter(function(){return/(auto|scroll)/.test(c.curCSS(this,"overflow",1)+c.curCSS(this,"overflow-y",1)+c.curCSS(this,"overflow-x",1))}).eq(0);return/fixed/.test(this.css("position"))||!a.length?c(document):a},zIndex:function(a){if(a!==j)return this.css("zIndex",a);if(this.length){a=c(this[0]);for(var b;a.length&&a[0]!==document;){b=a.css("position"); if(b==="absolute"||b==="relative"||b==="fixed"){b=parseInt(a.css("zIndex"));if(!isNaN(b)&&b!=0)return b}a=a.parent()}}return 0},disableSelection:function(){return this.bind("mousedown.ui-disableSelection selectstart.ui-disableSelection",function(a){a.preventDefault()})},enableSelection:function(){return this.unbind(".ui-disableSelection")}});c.each(["Width","Height"],function(a,b){function d(f,g,l,m){c.each(e,function(){g-=parseFloat(c.curCSS(f,"padding"+this,true))||0;if(l)g-=parseFloat(c.curCSS(f, "border"+this+"Width",true))||0;if(m)g-=parseFloat(c.curCSS(f,"margin"+this,true))||0});return g}var e=b==="Width"?["Left","Right"]:["Top","Bottom"],h=b.toLowerCase(),i={innerWidth:c.fn.innerWidth,innerHeight:c.fn.innerHeight,outerWidth:c.fn.outerWidth,outerHeight:c.fn.outerHeight};c.fn["inner"+b]=function(f){if(f===j)return i["inner"+b].call(this);return this.each(function(){c.style(this,h,d(this,f)+"px")})};c.fn["outer"+b]=function(f,g){if(typeof f!=="number")return i["outer"+b].call(this,f);return this.each(function(){c.style(this, h,d(this,f,true,g)+"px")})}});c.extend(c.expr[":"],{data:function(a,b,d){return!!c.data(a,d[3])},focusable:function(a){var b=a.nodeName.toLowerCase(),d=c.attr(a,"tabindex");if("area"===b){b=a.parentNode;d=b.name;if(!a.href||!d||b.nodeName.toLowerCase()!=="map")return false;a=c("img[usemap=#"+d+"]")[0];return!!a&&k(a)}return(/input|select|textarea|button|object/.test(b)?!a.disabled:"a"==b?a.href||!isNaN(d):!isNaN(d))&&k(a)},tabbable:function(a){var b=c.attr(a,"tabindex");return(isNaN(b)||b>=0)&&c(a).is(":focusable")}}); c(function(){var a=document.createElement("div"),b=document.body;c.extend(a.style,{minHeight:"100px",height:"auto",padding:0,borderWidth:0});c.support.minHeight=b.appendChild(a).offsetHeight===100;b.removeChild(a).style.display="none"});c.extend(c.ui,{plugin:{add:function(a,b,d){a=c.ui[a].prototype;for(var e in d){a.plugins[e]=a.plugins[e]||[];a.plugins[e].push([b,d[e]])}},call:function(a,b,d){if((b=a.plugins[b])&&a.element[0].parentNode)for(var e=0;e<b.length;e++)a.options[b[e][0]]&&b[e][1].apply(a.element, d)}},contains:function(a,b){return document.compareDocumentPosition?a.compareDocumentPosition(b)&16:a!==b&&a.contains(b)},hasScroll:function(a,b){if(c(a).css("overflow")==="hidden")return false;b=b&&b==="left"?"scrollLeft":"scrollTop";var d=false;if(a[b]>0)return true;a[b]=1;d=a[b]>0;a[b]=0;return d},isOverAxis:function(a,b,d){return a>b&&a<b+d},isOver:function(a,b,d,e,h,i){return c.ui.isOverAxis(a,d,h)&&c.ui.isOverAxis(b,e,i)}})}})(jQuery); ;/*! * jQuery UI Widget 1.8.5 * * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * http://docs.jquery.com/UI/Widget */ (function(b,j){if(b.cleanData){var k=b.cleanData;b.cleanData=function(a){for(var c=0,d;(d=a[c])!=null;c++)b(d).triggerHandler("remove");k(a)}}else{var l=b.fn.remove;b.fn.remove=function(a,c){return this.each(function(){if(!c)if(!a||b.filter(a,[this]).length)b("*",this).add([this]).each(function(){b(this).triggerHandler("remove")});return l.call(b(this),a,c)})}}b.widget=function(a,c,d){var e=a.split(".")[0],f;a=a.split(".")[1];f=e+"-"+a;if(!d){d=c;c=b.Widget}b.expr[":"][f]=function(h){return!!b.data(h, a)};b[e]=b[e]||{};b[e][a]=function(h,g){arguments.length&&this._createWidget(h,g)};c=new c;c.options=b.extend(true,{},c.options);b[e][a].prototype=b.extend(true,c,{namespace:e,widgetName:a,widgetEventPrefix:b[e][a].prototype.widgetEventPrefix||a,widgetBaseClass:f},d);b.widget.bridge(a,b[e][a])};b.widget.bridge=function(a,c){b.fn[a]=function(d){var e=typeof d==="string",f=Array.prototype.slice.call(arguments,1),h=this;d=!e&&f.length?b.extend.apply(null,[true,d].concat(f)):d;if(e&&d.substring(0,1)=== "_")return h;e?this.each(function(){var g=b.data(this,a);if(!g)throw"cannot call methods on "+a+" prior to initialization; attempted to call method '"+d+"'";if(!b.isFunction(g[d]))throw"no such method '"+d+"' for "+a+" widget instance";var i=g[d].apply(g,f);if(i!==g&&i!==j){h=i;return false}}):this.each(function(){var g=b.data(this,a);g?g.option(d||{})._init():b.data(this,a,new c(d,this))});return h}};b.Widget=function(a,c){arguments.length&&this._createWidget(a,c)};b.Widget.prototype={widgetName:"widget", widgetEventPrefix:"",options:{disabled:false},_createWidget:function(a,c){b.data(c,this.widgetName,this);this.element=b(c);this.options=b.extend(true,{},this.options,b.metadata&&b.metadata.get(c)[this.widgetName],a);var d=this;this.element.bind("remove."+this.widgetName,function(){d.destroy()});this._create();this._init()},_create:function(){},_init:function(){},destroy:function(){this.element.unbind("."+this.widgetName).removeData(this.widgetName);this.widget().unbind("."+this.widgetName).removeAttr("aria-disabled").removeClass(this.widgetBaseClass+ "-disabled ui-state-disabled")},widget:function(){return this.element},option:function(a,c){var d=a,e=this;if(arguments.length===0)return b.extend({},e.options);if(typeof a==="string"){if(c===j)return this.options[a];d={};d[a]=c}b.each(d,function(f,h){e._setOption(f,h)});return e},_setOption:function(a,c){this.options[a]=c;if(a==="disabled")this.widget()[c?"addClass":"removeClass"](this.widgetBaseClass+"-disabled ui-state-disabled").attr("aria-disabled",c);return this},enable:function(){return this._setOption("disabled", false)},disable:function(){return this._setOption("disabled",true)},_trigger:function(a,c,d){var e=this.options[a];c=b.Event(c);c.type=(a===this.widgetEventPrefix?a:this.widgetEventPrefix+a).toLowerCase();d=d||{};if(c.originalEvent){a=b.event.props.length;for(var f;a;){f=b.event.props[--a];c[f]=c.originalEvent[f]}}this.element.trigger(c,d);return!(b.isFunction(e)&&e.call(this.element[0],c,d)===false||c.isDefaultPrevented())}}})(jQuery); ;/*! * jQuery UI Mouse 1.8.5 * * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * http://docs.jquery.com/UI/Mouse * * Depends: * jquery.ui.widget.js */ (function(c){c.widget("ui.mouse",{options:{cancel:":input,option",distance:1,delay:0},_mouseInit:function(){var a=this;this.element.bind("mousedown."+this.widgetName,function(b){return a._mouseDown(b)}).bind("click."+this.widgetName,function(b){if(a._preventClickEvent){a._preventClickEvent=false;b.stopImmediatePropagation();return false}});this.started=false},_mouseDestroy:function(){this.element.unbind("."+this.widgetName)},_mouseDown:function(a){a.originalEvent=a.originalEvent||{};if(!a.originalEvent.mouseHandled){this._mouseStarted&& this._mouseUp(a);this._mouseDownEvent=a;var b=this,e=a.which==1,f=typeof this.options.cancel=="string"?c(a.target).parents().add(a.target).filter(this.options.cancel).length:false;if(!e||f||!this._mouseCapture(a))return true;this.mouseDelayMet=!this.options.delay;if(!this.mouseDelayMet)this._mouseDelayTimer=setTimeout(function(){b.mouseDelayMet=true},this.options.delay);if(this._mouseDistanceMet(a)&&this._mouseDelayMet(a)){this._mouseStarted=this._mouseStart(a)!==false;if(!this._mouseStarted){a.preventDefault(); return true}}this._mouseMoveDelegate=function(d){return b._mouseMove(d)};this._mouseUpDelegate=function(d){return b._mouseUp(d)};c(document).bind("mousemove."+this.widgetName,this._mouseMoveDelegate).bind("mouseup."+this.widgetName,this._mouseUpDelegate);c.browser.safari||a.preventDefault();return a.originalEvent.mouseHandled=true}},_mouseMove:function(a){if(c.browser.msie&&!a.button)return this._mouseUp(a);if(this._mouseStarted){this._mouseDrag(a);return a.preventDefault()}if(this._mouseDistanceMet(a)&& this._mouseDelayMet(a))(this._mouseStarted=this._mouseStart(this._mouseDownEvent,a)!==false)?this._mouseDrag(a):this._mouseUp(a);return!this._mouseStarted},_mouseUp:function(a){c(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate);if(this._mouseStarted){this._mouseStarted=false;this._preventClickEvent=a.target==this._mouseDownEvent.target;this._mouseStop(a)}return false},_mouseDistanceMet:function(a){return Math.max(Math.abs(this._mouseDownEvent.pageX- a.pageX),Math.abs(this._mouseDownEvent.pageY-a.pageY))>=this.options.distance},_mouseDelayMet:function(){return this.mouseDelayMet},_mouseStart:function(){},_mouseDrag:function(){},_mouseStop:function(){},_mouseCapture:function(){return true}})})(jQuery); ;/* * jQuery UI Draggable 1.8.5 * * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * http://docs.jquery.com/UI/Draggables * * Depends: * jquery.ui.core.js * jquery.ui.mouse.js * jquery.ui.widget.js */ (function(d){d.widget("ui.draggable",d.ui.mouse,{widgetEventPrefix:"drag",options:{addClasses:true,appendTo:"parent",axis:false,connectToSortable:false,containment:false,cursor:"auto",cursorAt:false,grid:false,handle:false,helper:"original",iframeFix:false,opacity:false,refreshPositions:false,revert:false,revertDuration:500,scope:"default",scroll:true,scrollSensitivity:20,scrollSpeed:20,snap:false,snapMode:"both",snapTolerance:20,stack:false,zIndex:false},_create:function(){if(this.options.helper== "original"&&!/^(?:r|a|f)/.test(this.element.css("position")))this.element[0].style.position="relative";this.options.addClasses&&this.element.addClass("ui-draggable");this.options.disabled&&this.element.addClass("ui-draggable-disabled");this._mouseInit()},destroy:function(){if(this.element.data("draggable")){this.element.removeData("draggable").unbind(".draggable").removeClass("ui-draggable ui-draggable-dragging ui-draggable-disabled");this._mouseDestroy();return this}},_mouseCapture:function(a){var b= this.options;if(this.helper||b.disabled||d(a.target).is(".ui-resizable-handle"))return false;this.handle=this._getHandle(a);if(!this.handle)return false;return true},_mouseStart:function(a){var b=this.options;this.helper=this._createHelper(a);this._cacheHelperProportions();if(d.ui.ddmanager)d.ui.ddmanager.current=this;this._cacheMargins();this.cssPosition=this.helper.css("position");this.scrollParent=this.helper.scrollParent();this.offset=this.positionAbs=this.element.offset();this.offset={top:this.offset.top- this.margins.top,left:this.offset.left-this.margins.left};d.extend(this.offset,{click:{left:a.pageX-this.offset.left,top:a.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()});this.originalPosition=this.position=this._generatePosition(a);this.originalPageX=a.pageX;this.originalPageY=a.pageY;b.cursorAt&&this._adjustOffsetFromHelper(b.cursorAt);b.containment&&this._setContainment();if(this._trigger("start",a)===false){this._clear();return false}this._cacheHelperProportions(); d.ui.ddmanager&&!b.dropBehaviour&&d.ui.ddmanager.prepareOffsets(this,a);this.helper.addClass("ui-draggable-dragging");this._mouseDrag(a,true);return true},_mouseDrag:function(a,b){this.position=this._generatePosition(a);this.positionAbs=this._convertPositionTo("absolute");if(!b){b=this._uiHash();if(this._trigger("drag",a,b)===false){this._mouseUp({});return false}this.position=b.position}if(!this.options.axis||this.options.axis!="y")this.helper[0].style.left=this.position.left+"px";if(!this.options.axis|| this.options.axis!="x")this.helper[0].style.top=this.position.top+"px";d.ui.ddmanager&&d.ui.ddmanager.drag(this,a);return false},_mouseStop:function(a){var b=false;if(d.ui.ddmanager&&!this.options.dropBehaviour)b=d.ui.ddmanager.drop(this,a);if(this.dropped){b=this.dropped;this.dropped=false}if(!this.element[0]||!this.element[0].parentNode)return false;if(this.options.revert=="invalid"&&!b||this.options.revert=="valid"&&b||this.options.revert===true||d.isFunction(this.options.revert)&&this.options.revert.call(this.element, b)){var c=this;d(this.helper).animate(this.originalPosition,parseInt(this.options.revertDuration,10),function(){c._trigger("stop",a)!==false&&c._clear()})}else this._trigger("stop",a)!==false&&this._clear();return false},cancel:function(){this.helper.is(".ui-draggable-dragging")?this._mouseUp({}):this._clear();return this},_getHandle:function(a){var b=!this.options.handle||!d(this.options.handle,this.element).length?true:false;d(this.options.handle,this.element).find("*").andSelf().each(function(){if(this== a.target)b=true});return b},_createHelper:function(a){var b=this.options;a=d.isFunction(b.helper)?d(b.helper.apply(this.element[0],[a])):b.helper=="clone"?this.element.clone():this.element;a.parents("body").length||a.appendTo(b.appendTo=="parent"?this.element[0].parentNode:b.appendTo);a[0]!=this.element[0]&&!/(fixed|absolute)/.test(a.css("position"))&&a.css("position","absolute");return a},_adjustOffsetFromHelper:function(a){if(typeof a=="string")a=a.split(" ");if(d.isArray(a))a={left:+a[0],top:+a[1]|| 0};if("left"in a)this.offset.click.left=a.left+this.margins.left;if("right"in a)this.offset.click.left=this.helperProportions.width-a.right+this.margins.left;if("top"in a)this.offset.click.top=a.top+this.margins.top;if("bottom"in a)this.offset.click.top=this.helperProportions.height-a.bottom+this.margins.top},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var a=this.offsetParent.offset();if(this.cssPosition=="absolute"&&this.scrollParent[0]!=document&&d.ui.contains(this.scrollParent[0], this.offsetParent[0])){a.left+=this.scrollParent.scrollLeft();a.top+=this.scrollParent.scrollTop()}if(this.offsetParent[0]==document.body||this.offsetParent[0].tagName&&this.offsetParent[0].tagName.toLowerCase()=="html"&&d.browser.msie)a={top:0,left:0};return{top:a.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:a.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if(this.cssPosition=="relative"){var a=this.element.position();return{top:a.top- (parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:a.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}else return{top:0,left:0}},_cacheMargins:function(){this.margins={left:parseInt(this.element.css("marginLeft"),10)||0,top:parseInt(this.element.css("marginTop"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var a=this.options;if(a.containment== "parent")a.containment=this.helper[0].parentNode;if(a.containment=="document"||a.containment=="window")this.containment=[0-this.offset.relative.left-this.offset.parent.left,0-this.offset.relative.top-this.offset.parent.top,d(a.containment=="document"?document:window).width()-this.helperProportions.width-this.margins.left,(d(a.containment=="document"?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top];if(!/^(document|window|parent)$/.test(a.containment)&& a.containment.constructor!=Array){var b=d(a.containment)[0];if(b){a=d(a.containment).offset();var c=d(b).css("overflow")!="hidden";this.containment=[a.left+(parseInt(d(b).css("borderLeftWidth"),10)||0)+(parseInt(d(b).css("paddingLeft"),10)||0)-this.margins.left,a.top+(parseInt(d(b).css("borderTopWidth"),10)||0)+(parseInt(d(b).css("paddingTop"),10)||0)-this.margins.top,a.left+(c?Math.max(b.scrollWidth,b.offsetWidth):b.offsetWidth)-(parseInt(d(b).css("borderLeftWidth"),10)||0)-(parseInt(d(b).css("paddingRight"), 10)||0)-this.helperProportions.width-this.margins.left,a.top+(c?Math.max(b.scrollHeight,b.offsetHeight):b.offsetHeight)-(parseInt(d(b).css("borderTopWidth"),10)||0)-(parseInt(d(b).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top]}}else if(a.containment.constructor==Array)this.containment=a.containment},_convertPositionTo:function(a,b){if(!b)b=this.position;a=a=="absolute"?1:-1;var c=this.cssPosition=="absolute"&&!(this.scrollParent[0]!=document&&d.ui.contains(this.scrollParent[0], this.offsetParent[0]))?this.offsetParent:this.scrollParent,f=/(html|body)/i.test(c[0].tagName);return{top:b.top+this.offset.relative.top*a+this.offset.parent.top*a-(d.browser.safari&&d.browser.version<526&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():f?0:c.scrollTop())*a),left:b.left+this.offset.relative.left*a+this.offset.parent.left*a-(d.browser.safari&&d.browser.version<526&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft(): f?0:c.scrollLeft())*a)}},_generatePosition:function(a){var b=this.options,c=this.cssPosition=="absolute"&&!(this.scrollParent[0]!=document&&d.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,f=/(html|body)/i.test(c[0].tagName),e=a.pageX,g=a.pageY;if(this.originalPosition){if(this.containment){if(a.pageX-this.offset.click.left<this.containment[0])e=this.containment[0]+this.offset.click.left;if(a.pageY-this.offset.click.top<this.containment[1])g=this.containment[1]+ this.offset.click.top;if(a.pageX-this.offset.click.left>this.containment[2])e=this.containment[2]+this.offset.click.left;if(a.pageY-this.offset.click.top>this.containment[3])g=this.containment[3]+this.offset.click.top}if(b.grid){g=this.originalPageY+Math.round((g-this.originalPageY)/b.grid[1])*b.grid[1];g=this.containment?!(g-this.offset.click.top<this.containment[1]||g-this.offset.click.top>this.containment[3])?g:!(g-this.offset.click.top<this.containment[1])?g-b.grid[1]:g+b.grid[1]:g;e=this.originalPageX+ Math.round((e-this.originalPageX)/b.grid[0])*b.grid[0];e=this.containment?!(e-this.offset.click.left<this.containment[0]||e-this.offset.click.left>this.containment[2])?e:!(e-this.offset.click.left<this.containment[0])?e-b.grid[0]:e+b.grid[0]:e}}return{top:g-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+(d.browser.safari&&d.browser.version<526&&this.cssPosition=="fixed"?0:this.cssPosition=="fixed"?-this.scrollParent.scrollTop():f?0:c.scrollTop()),left:e-this.offset.click.left- this.offset.relative.left-this.offset.parent.left+(d.browser.safari&&d.browser.version<526&&this.cssPosition=="fixed"?0:this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():f?0:c.scrollLeft())}},_clear:function(){this.helper.removeClass("ui-draggable-dragging");this.helper[0]!=this.element[0]&&!this.cancelHelperRemoval&&this.helper.remove();this.helper=null;this.cancelHelperRemoval=false},_trigger:function(a,b,c){c=c||this._uiHash();d.ui.plugin.call(this,a,[b,c]);if(a=="drag")this.positionAbs= this._convertPositionTo("absolute");return d.Widget.prototype._trigger.call(this,a,b,c)},plugins:{},_uiHash:function(){return{helper:this.helper,position:this.position,originalPosition:this.originalPosition,offset:this.positionAbs}}});d.extend(d.ui.draggable,{version:"1.8.5"});d.ui.plugin.add("draggable","connectToSortable",{start:function(a,b){var c=d(this).data("draggable"),f=c.options,e=d.extend({},b,{item:c.element});c.sortables=[];d(f.connectToSortable).each(function(){var g=d.data(this,"sortable"); if(g&&!g.options.disabled){c.sortables.push({instance:g,shouldRevert:g.options.revert});g._refreshItems();g._trigger("activate",a,e)}})},stop:function(a,b){var c=d(this).data("draggable"),f=d.extend({},b,{item:c.element});d.each(c.sortables,function(){if(this.instance.isOver){this.instance.isOver=0;c.cancelHelperRemoval=true;this.instance.cancelHelperRemoval=false;if(this.shouldRevert)this.instance.options.revert=true;this.instance._mouseStop(a);this.instance.options.helper=this.instance.options._helper; c.options.helper=="original"&&this.instance.currentItem.css({top:"auto",left:"auto"})}else{this.instance.cancelHelperRemoval=false;this.instance._trigger("deactivate",a,f)}})},drag:function(a,b){var c=d(this).data("draggable"),f=this;d.each(c.sortables,function(){this.instance.positionAbs=c.positionAbs;this.instance.helperProportions=c.helperProportions;this.instance.offset.click=c.offset.click;if(this.instance._intersectsWith(this.instance.containerCache)){if(!this.instance.isOver){this.instance.isOver= 1;this.instance.currentItem=d(f).clone().appendTo(this.instance.element).data("sortable-item",true);this.instance.options._helper=this.instance.options.helper;this.instance.options.helper=function(){return b.helper[0]};a.target=this.instance.currentItem[0];this.instance._mouseCapture(a,true);this.instance._mouseStart(a,true,true);this.instance.offset.click.top=c.offset.click.top;this.instance.offset.click.left=c.offset.click.left;this.instance.offset.parent.left-=c.offset.parent.left-this.instance.offset.parent.left; this.instance.offset.parent.top-=c.offset.parent.top-this.instance.offset.parent.top;c._trigger("toSortable",a);c.dropped=this.instance.element;c.currentItem=c.element;this.instance.fromOutside=c}this.instance.currentItem&&this.instance._mouseDrag(a)}else if(this.instance.isOver){this.instance.isOver=0;this.instance.cancelHelperRemoval=true;this.instance.options.revert=false;this.instance._trigger("out",a,this.instance._uiHash(this.instance));this.instance._mouseStop(a,true);this.instance.options.helper= this.instance.options._helper;this.instance.currentItem.remove();this.instance.placeholder&&this.instance.placeholder.remove();c._trigger("fromSortable",a);c.dropped=false}})}});d.ui.plugin.add("draggable","cursor",{start:function(){var a=d("body"),b=d(this).data("draggable").options;if(a.css("cursor"))b._cursor=a.css("cursor");a.css("cursor",b.cursor)},stop:function(){var a=d(this).data("draggable").options;a._cursor&&d("body").css("cursor",a._cursor)}});d.ui.plugin.add("draggable","iframeFix",{start:function(){var a= d(this).data("draggable").options;d(a.iframeFix===true?"iframe":a.iframeFix).each(function(){d('<div class="ui-draggable-iframeFix" style="background: #fff;"></div>').css({width:this.offsetWidth+"px",height:this.offsetHeight+"px",position:"absolute",opacity:"0.001",zIndex:1E3}).css(d(this).offset()).appendTo("body")})},stop:function(){d("div.ui-draggable-iframeFix").each(function(){this.parentNode.removeChild(this)})}});d.ui.plugin.add("draggable","opacity",{start:function(a,b){a=d(b.helper);b=d(this).data("draggable").options; if(a.css("opacity"))b._opacity=a.css("opacity");a.css("opacity",b.opacity)},stop:function(a,b){a=d(this).data("draggable").options;a._opacity&&d(b.helper).css("opacity",a._opacity)}});d.ui.plugin.add("draggable","scroll",{start:function(){var a=d(this).data("draggable");if(a.scrollParent[0]!=document&&a.scrollParent[0].tagName!="HTML")a.overflowOffset=a.scrollParent.offset()},drag:function(a){var b=d(this).data("draggable"),c=b.options,f=false;if(b.scrollParent[0]!=document&&b.scrollParent[0].tagName!= "HTML"){if(!c.axis||c.axis!="x")if(b.overflowOffset.top+b.scrollParent[0].offsetHeight-a.pageY<c.scrollSensitivity)b.scrollParent[0].scrollTop=f=b.scrollParent[0].scrollTop+c.scrollSpeed;else if(a.pageY-b.overflowOffset.top<c.scrollSensitivity)b.scrollParent[0].scrollTop=f=b.scrollParent[0].scrollTop-c.scrollSpeed;if(!c.axis||c.axis!="y")if(b.overflowOffset.left+b.scrollParent[0].offsetWidth-a.pageX<c.scrollSensitivity)b.scrollParent[0].scrollLeft=f=b.scrollParent[0].scrollLeft+c.scrollSpeed;else if(a.pageX- b.overflowOffset.left<c.scrollSensitivity)b.scrollParent[0].scrollLeft=f=b.scrollParent[0].scrollLeft-c.scrollSpeed}else{if(!c.axis||c.axis!="x")if(a.pageY-d(document).scrollTop()<c.scrollSensitivity)f=d(document).scrollTop(d(document).scrollTop()-c.scrollSpeed);else if(d(window).height()-(a.pageY-d(document).scrollTop())<c.scrollSensitivity)f=d(document).scrollTop(d(document).scrollTop()+c.scrollSpeed);if(!c.axis||c.axis!="y")if(a.pageX-d(document).scrollLeft()<c.scrollSensitivity)f=d(document).scrollLeft(d(document).scrollLeft()- c.scrollSpeed);else if(d(window).width()-(a.pageX-d(document).scrollLeft())<c.scrollSensitivity)f=d(document).scrollLeft(d(document).scrollLeft()+c.scrollSpeed)}f!==false&&d.ui.ddmanager&&!c.dropBehaviour&&d.ui.ddmanager.prepareOffsets(b,a)}});d.ui.plugin.add("draggable","snap",{start:function(){var a=d(this).data("draggable"),b=a.options;a.snapElements=[];d(b.snap.constructor!=String?b.snap.items||":data(draggable)":b.snap).each(function(){var c=d(this),f=c.offset();this!=a.element[0]&&a.snapElements.push({item:this, width:c.outerWidth(),height:c.outerHeight(),top:f.top,left:f.left})})},drag:function(a,b){for(var c=d(this).data("draggable"),f=c.options,e=f.snapTolerance,g=b.offset.left,n=g+c.helperProportions.width,m=b.offset.top,o=m+c.helperProportions.height,h=c.snapElements.length-1;h>=0;h--){var i=c.snapElements[h].left,k=i+c.snapElements[h].width,j=c.snapElements[h].top,l=j+c.snapElements[h].height;if(i-e<g&&g<k+e&&j-e<m&&m<l+e||i-e<g&&g<k+e&&j-e<o&&o<l+e||i-e<n&&n<k+e&&j-e<m&&m<l+e||i-e<n&&n<k+e&&j-e<o&& o<l+e){if(f.snapMode!="inner"){var p=Math.abs(j-o)<=e,q=Math.abs(l-m)<=e,r=Math.abs(i-n)<=e,s=Math.abs(k-g)<=e;if(p)b.position.top=c._convertPositionTo("relative",{top:j-c.helperProportions.height,left:0}).top-c.margins.top;if(q)b.position.top=c._convertPositionTo("relative",{top:l,left:0}).top-c.margins.top;if(r)b.position.left=c._convertPositionTo("relative",{top:0,left:i-c.helperProportions.width}).left-c.margins.left;if(s)b.position.left=c._convertPositionTo("relative",{top:0,left:k}).left-c.margins.left}var t= p||q||r||s;if(f.snapMode!="outer"){p=Math.abs(j-m)<=e;q=Math.abs(l-o)<=e;r=Math.abs(i-g)<=e;s=Math.abs(k-n)<=e;if(p)b.position.top=c._convertPositionTo("relative",{top:j,left:0}).top-c.margins.top;if(q)b.position.top=c._convertPositionTo("relative",{top:l-c.helperProportions.height,left:0}).top-c.margins.top;if(r)b.position.left=c._convertPositionTo("relative",{top:0,left:i}).left-c.margins.left;if(s)b.position.left=c._convertPositionTo("relative",{top:0,left:k-c.helperProportions.width}).left-c.margins.left}if(!c.snapElements[h].snapping&& (p||q||r||s||t))c.options.snap.snap&&c.options.snap.snap.call(c.element,a,d.extend(c._uiHash(),{snapItem:c.snapElements[h].item}));c.snapElements[h].snapping=p||q||r||s||t}else{c.snapElements[h].snapping&&c.options.snap.release&&c.options.snap.release.call(c.element,a,d.extend(c._uiHash(),{snapItem:c.snapElements[h].item}));c.snapElements[h].snapping=false}}}});d.ui.plugin.add("draggable","stack",{start:function(){var a=d(this).data("draggable").options;a=d.makeArray(d(a.stack)).sort(function(c,f){return(parseInt(d(c).css("zIndex"), 10)||0)-(parseInt(d(f).css("zIndex"),10)||0)});if(a.length){var b=parseInt(a[0].style.zIndex)||0;d(a).each(function(c){this.style.zIndex=b+c});this[0].style.zIndex=b+a.length}}});d.ui.plugin.add("draggable","zIndex",{start:function(a,b){a=d(b.helper);b=d(this).data("draggable").options;if(a.css("zIndex"))b._zIndex=a.css("zIndex");a.css("zIndex",b.zIndex)},stop:function(a,b){a=d(this).data("draggable").options;a._zIndex&&d(b.helper).css("zIndex",a._zIndex)}})})(jQuery); ;/* * jQuery UI Droppable 1.8.5 * * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * http://docs.jquery.com/UI/Droppables * * Depends: * jquery.ui.core.js * jquery.ui.widget.js * jquery.ui.mouse.js * jquery.ui.draggable.js */ (function(d){d.widget("ui.droppable",{widgetEventPrefix:"drop",options:{accept:"*",activeClass:false,addClasses:true,greedy:false,hoverClass:false,scope:"default",tolerance:"intersect"},_create:function(){var a=this.options,b=a.accept;this.isover=0;this.isout=1;this.accept=d.isFunction(b)?b:function(c){return c.is(b)};this.proportions={width:this.element[0].offsetWidth,height:this.element[0].offsetHeight};d.ui.ddmanager.droppables[a.scope]=d.ui.ddmanager.droppables[a.scope]||[];d.ui.ddmanager.droppables[a.scope].push(this); a.addClasses&&this.element.addClass("ui-droppable")},destroy:function(){for(var a=d.ui.ddmanager.droppables[this.options.scope],b=0;b<a.length;b++)a[b]==this&&a.splice(b,1);this.element.removeClass("ui-droppable ui-droppable-disabled").removeData("droppable").unbind(".droppable");return this},_setOption:function(a,b){if(a=="accept")this.accept=d.isFunction(b)?b:function(c){return c.is(b)};d.Widget.prototype._setOption.apply(this,arguments)},_activate:function(a){var b=d.ui.ddmanager.current;this.options.activeClass&& this.element.addClass(this.options.activeClass);b&&this._trigger("activate",a,this.ui(b))},_deactivate:function(a){var b=d.ui.ddmanager.current;this.options.activeClass&&this.element.removeClass(this.options.activeClass);b&&this._trigger("deactivate",a,this.ui(b))},_over:function(a){var b=d.ui.ddmanager.current;if(!(!b||(b.currentItem||b.element)[0]==this.element[0]))if(this.accept.call(this.element[0],b.currentItem||b.element)){this.options.hoverClass&&this.element.addClass(this.options.hoverClass); this._trigger("over",a,this.ui(b))}},_out:function(a){var b=d.ui.ddmanager.current;if(!(!b||(b.currentItem||b.element)[0]==this.element[0]))if(this.accept.call(this.element[0],b.currentItem||b.element)){this.options.hoverClass&&this.element.removeClass(this.options.hoverClass);this._trigger("out",a,this.ui(b))}},_drop:function(a,b){var c=b||d.ui.ddmanager.current;if(!c||(c.currentItem||c.element)[0]==this.element[0])return false;var e=false;this.element.find(":data(droppable)").not(".ui-draggable-dragging").each(function(){var g= d.data(this,"droppable");if(g.options.greedy&&!g.options.disabled&&g.options.scope==c.options.scope&&g.accept.call(g.element[0],c.currentItem||c.element)&&d.ui.intersect(c,d.extend(g,{offset:g.element.offset()}),g.options.tolerance)){e=true;return false}});if(e)return false;if(this.accept.call(this.element[0],c.currentItem||c.element)){this.options.activeClass&&this.element.removeClass(this.options.activeClass);this.options.hoverClass&&this.element.removeClass(this.options.hoverClass);this._trigger("drop", a,this.ui(c));return this.element}return false},ui:function(a){return{draggable:a.currentItem||a.element,helper:a.helper,position:a.position,offset:a.positionAbs}}});d.extend(d.ui.droppable,{version:"1.8.5"});d.ui.intersect=function(a,b,c){if(!b.offset)return false;var e=(a.positionAbs||a.position.absolute).left,g=e+a.helperProportions.width,f=(a.positionAbs||a.position.absolute).top,h=f+a.helperProportions.height,i=b.offset.left,k=i+b.proportions.width,j=b.offset.top,l=j+b.proportions.height; switch(c){case "fit":return i<=e&&g<=k&&j<=f&&h<=l;case "intersect":return i<e+a.helperProportions.width/2&&g-a.helperProportions.width/2<k&&j<f+a.helperProportions.height/2&&h-a.helperProportions.height/2<l;case "pointer":return d.ui.isOver((a.positionAbs||a.position.absolute).top+(a.clickOffset||a.offset.click).top,(a.positionAbs||a.position.absolute).left+(a.clickOffset||a.offset.click).left,j,i,b.proportions.height,b.proportions.width);case "touch":return(f>=j&&f<=l||h>=j&&h<=l||f<j&&h>l)&&(e>= i&&e<=k||g>=i&&g<=k||e<i&&g>k);default:return false}};d.ui.ddmanager={current:null,droppables:{"default":[]},prepareOffsets:function(a,b){var c=d.ui.ddmanager.droppables[a.options.scope]||[],e=b?b.type:null,g=(a.currentItem||a.element).find(":data(droppable)").andSelf(),f=0;a:for(;f<c.length;f++)if(!(c[f].options.disabled||a&&!c[f].accept.call(c[f].element[0],a.currentItem||a.element))){for(var h=0;h<g.length;h++)if(g[h]==c[f].element[0]){c[f].proportions.height=0;continue a}c[f].visible=c[f].element.css("display")!= "none";if(c[f].visible){c[f].offset=c[f].element.offset();c[f].proportions={width:c[f].element[0].offsetWidth,height:c[f].element[0].offsetHeight};e=="mousedown"&&c[f]._activate.call(c[f],b)}}},drop:function(a,b){var c=false;d.each(d.ui.ddmanager.droppables[a.options.scope]||[],function(){if(this.options){if(!this.options.disabled&&this.visible&&d.ui.intersect(a,this,this.options.tolerance))c=c||this._drop.call(this,b);if(!this.options.disabled&&this.visible&&this.accept.call(this.element[0],a.currentItem|| a.element)){this.isout=1;this.isover=0;this._deactivate.call(this,b)}}});return c},drag:function(a,b){a.options.refreshPositions&&d.ui.ddmanager.prepareOffsets(a,b);d.each(d.ui.ddmanager.droppables[a.options.scope]||[],function(){if(!(this.options.disabled||this.greedyChild||!this.visible)){var c=d.ui.intersect(a,this,this.options.tolerance);if(c=!c&&this.isover==1?"isout":c&&this.isover==0?"isover":null){var e;if(this.options.greedy){var g=this.element.parents(":data(droppable):eq(0)");if(g.length){e= d.data(g[0],"droppable");e.greedyChild=c=="isover"?1:0}}if(e&&c=="isover"){e.isover=0;e.isout=1;e._out.call(e,b)}this[c]=1;this[c=="isout"?"isover":"isout"]=0;this[c=="isover"?"_over":"_out"].call(this,b);if(e&&c=="isout"){e.isout=0;e.isover=1;e._over.call(e,b)}}}})}}})(jQuery); ;/* * jQuery UI Effects 1.8.5 * * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * http://docs.jquery.com/UI/Effects/ */ jQuery.effects||function(f,j){function l(c){var a;if(c&&c.constructor==Array&&c.length==3)return c;if(a=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(c))return[parseInt(a[1],10),parseInt(a[2],10),parseInt(a[3],10)];if(a=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(c))return[parseFloat(a[1])*2.55,parseFloat(a[2])*2.55,parseFloat(a[3])*2.55];if(a=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(c))return[parseInt(a[1], 16),parseInt(a[2],16),parseInt(a[3],16)];if(a=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(c))return[parseInt(a[1]+a[1],16),parseInt(a[2]+a[2],16),parseInt(a[3]+a[3],16)];if(/rgba\(0, 0, 0, 0\)/.exec(c))return m.transparent;return m[f.trim(c).toLowerCase()]}function r(c,a){var b;do{b=f.curCSS(c,a);if(b!=""&&b!="transparent"||f.nodeName(c,"body"))break;a="backgroundColor"}while(c=c.parentNode);return l(b)}function n(){var c=document.defaultView?document.defaultView.getComputedStyle(this,null):this.currentStyle, a={},b,d;if(c&&c.length&&c[0]&&c[c[0]])for(var e=c.length;e--;){b=c[e];if(typeof c[b]=="string"){d=b.replace(/\-(\w)/g,function(g,h){return h.toUpperCase()});a[d]=c[b]}}else for(b in c)if(typeof c[b]==="string")a[b]=c[b];return a}function o(c){var a,b;for(a in c){b=c[a];if(b==null||f.isFunction(b)||a in s||/scrollbar/.test(a)||!/color/i.test(a)&&isNaN(parseFloat(b)))delete c[a]}return c}function t(c,a){var b={_:0},d;for(d in a)if(c[d]!=a[d])b[d]=a[d];return b}function k(c,a,b,d){if(typeof c=="object"){d= a;b=null;a=c;c=a.effect}if(f.isFunction(a)){d=a;b=null;a={}}if(typeof a=="number"||f.fx.speeds[a]){d=b;b=a;a={}}if(f.isFunction(b)){d=b;b=null}a=a||{};b=b||a.duration;b=f.fx.off?0:typeof b=="number"?b:f.fx.speeds[b]||f.fx.speeds._default;d=d||a.complete;return[c,a,b,d]}f.effects={};f.each(["backgroundColor","borderBottomColor","borderLeftColor","borderRightColor","borderTopColor","color","outlineColor"],function(c,a){f.fx.step[a]=function(b){if(!b.colorInit){b.start=r(b.elem,a);b.end=l(b.end);b.colorInit= true}b.elem.style[a]="rgb("+Math.max(Math.min(parseInt(b.pos*(b.end[0]-b.start[0])+b.start[0],10),255),0)+","+Math.max(Math.min(parseInt(b.pos*(b.end[1]-b.start[1])+b.start[1],10),255),0)+","+Math.max(Math.min(parseInt(b.pos*(b.end[2]-b.start[2])+b.start[2],10),255),0)+")"}});var m={aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],darkgreen:[0,100,0],darkkhaki:[189, 183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255, 165,0],pink:[255,192,203],purple:[128,0,128],violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0],transparent:[255,255,255]},p=["add","remove","toggle"],s={border:1,borderBottom:1,borderColor:1,borderLeft:1,borderRight:1,borderTop:1,borderWidth:1,margin:1,padding:1};f.effects.animateClass=function(c,a,b,d){if(f.isFunction(b)){d=b;b=null}return this.each(function(){var e=f(this),g=e.attr("style")||" ",h=o(n.call(this)),q,u=e.attr("className");f.each(p,function(v, i){c[i]&&e[i+"Class"](c[i])});q=o(n.call(this));e.attr("className",u);e.animate(t(h,q),a,b,function(){f.each(p,function(v,i){c[i]&&e[i+"Class"](c[i])});if(typeof e.attr("style")=="object"){e.attr("style").cssText="";e.attr("style").cssText=g}else e.attr("style",g);d&&d.apply(this,arguments)})})};f.fn.extend({_addClass:f.fn.addClass,addClass:function(c,a,b,d){return a?f.effects.animateClass.apply(this,[{add:c},a,b,d]):this._addClass(c)},_removeClass:f.fn.removeClass,removeClass:function(c,a,b,d){return a? f.effects.animateClass.apply(this,[{remove:c},a,b,d]):this._removeClass(c)},_toggleClass:f.fn.toggleClass,toggleClass:function(c,a,b,d,e){return typeof a=="boolean"||a===j?b?f.effects.animateClass.apply(this,[a?{add:c}:{remove:c},b,d,e]):this._toggleClass(c,a):f.effects.animateClass.apply(this,[{toggle:c},a,b,d])},switchClass:function(c,a,b,d,e){return f.effects.animateClass.apply(this,[{add:a,remove:c},b,d,e])}});f.extend(f.effects,{version:"1.8.5",save:function(c,a){for(var b=0;b<a.length;b++)a[b]!== null&&c.data("ec.storage."+a[b],c[0].style[a[b]])},restore:function(c,a){for(var b=0;b<a.length;b++)a[b]!==null&&c.css(a[b],c.data("ec.storage."+a[b]))},setMode:function(c,a){if(a=="toggle")a=c.is(":hidden")?"show":"hide";return a},getBaseline:function(c,a){var b;switch(c[0]){case "top":b=0;break;case "middle":b=0.5;break;case "bottom":b=1;break;default:b=c[0]/a.height}switch(c[1]){case "left":c=0;break;case "center":c=0.5;break;case "right":c=1;break;default:c=c[1]/a.width}return{x:c,y:b}},createWrapper:function(c){if(c.parent().is(".ui-effects-wrapper"))return c.parent(); var a={width:c.outerWidth(true),height:c.outerHeight(true),"float":c.css("float")},b=f("<div></div>").addClass("ui-effects-wrapper").css({fontSize:"100%",background:"transparent",border:"none",margin:0,padding:0});c.wrap(b);b=c.parent();if(c.css("position")=="static"){b.css({position:"relative"});c.css({position:"relative"})}else{f.extend(a,{position:c.css("position"),zIndex:c.css("z-index")});f.each(["top","left","bottom","right"],function(d,e){a[e]=c.css(e);if(isNaN(parseInt(a[e],10)))a[e]="auto"}); c.css({position:"relative",top:0,left:0})}return b.css(a).show()},removeWrapper:function(c){if(c.parent().is(".ui-effects-wrapper"))return c.parent().replaceWith(c);return c},setTransition:function(c,a,b,d){d=d||{};f.each(a,function(e,g){unit=c.cssUnit(g);if(unit[0]>0)d[g]=unit[0]*b+unit[1]});return d}});f.fn.extend({effect:function(c){var a=k.apply(this,arguments);a={options:a[1],duration:a[2],callback:a[3]};var b=f.effects[c];return b&&!f.fx.off?b.call(this,a):this},_show:f.fn.show,show:function(c){if(!c|| typeof c=="number"||f.fx.speeds[c]||!f.effects[c])return this._show.apply(this,arguments);else{var a=k.apply(this,arguments);a[1].mode="show";return this.effect.apply(this,a)}},_hide:f.fn.hide,hide:function(c){if(!c||typeof c=="number"||f.fx.speeds[c]||!f.effects[c])return this._hide.apply(this,arguments);else{var a=k.apply(this,arguments);a[1].mode="hide";return this.effect.apply(this,a)}},__toggle:f.fn.toggle,toggle:function(c){if(!c||typeof c=="number"||f.fx.speeds[c]||!f.effects[c]||typeof c== "boolean"||f.isFunction(c))return this.__toggle.apply(this,arguments);else{var a=k.apply(this,arguments);a[1].mode="toggle";return this.effect.apply(this,a)}},cssUnit:function(c){var a=this.css(c),b=[];f.each(["em","px","%","pt"],function(d,e){if(a.indexOf(e)>0)b=[parseFloat(a),e]});return b}});f.easing.jswing=f.easing.swing;f.extend(f.easing,{def:"easeOutQuad",swing:function(c,a,b,d,e){return f.easing[f.easing.def](c,a,b,d,e)},easeInQuad:function(c,a,b,d,e){return d*(a/=e)*a+b},easeOutQuad:function(c, a,b,d,e){return-d*(a/=e)*(a-2)+b},easeInOutQuad:function(c,a,b,d,e){if((a/=e/2)<1)return d/2*a*a+b;return-d/2*(--a*(a-2)-1)+b},easeInCubic:function(c,a,b,d,e){return d*(a/=e)*a*a+b},easeOutCubic:function(c,a,b,d,e){return d*((a=a/e-1)*a*a+1)+b},easeInOutCubic:function(c,a,b,d,e){if((a/=e/2)<1)return d/2*a*a*a+b;return d/2*((a-=2)*a*a+2)+b},easeInQuart:function(c,a,b,d,e){return d*(a/=e)*a*a*a+b},easeOutQuart:function(c,a,b,d,e){return-d*((a=a/e-1)*a*a*a-1)+b},easeInOutQuart:function(c,a,b,d,e){if((a/= e/2)<1)return d/2*a*a*a*a+b;return-d/2*((a-=2)*a*a*a-2)+b},easeInQuint:function(c,a,b,d,e){return d*(a/=e)*a*a*a*a+b},easeOutQuint:function(c,a,b,d,e){return d*((a=a/e-1)*a*a*a*a+1)+b},easeInOutQuint:function(c,a,b,d,e){if((a/=e/2)<1)return d/2*a*a*a*a*a+b;return d/2*((a-=2)*a*a*a*a+2)+b},easeInSine:function(c,a,b,d,e){return-d*Math.cos(a/e*(Math.PI/2))+d+b},easeOutSine:function(c,a,b,d,e){return d*Math.sin(a/e*(Math.PI/2))+b},easeInOutSine:function(c,a,b,d,e){return-d/2*(Math.cos(Math.PI*a/e)-1)+ b},easeInExpo:function(c,a,b,d,e){return a==0?b:d*Math.pow(2,10*(a/e-1))+b},easeOutExpo:function(c,a,b,d,e){return a==e?b+d:d*(-Math.pow(2,-10*a/e)+1)+b},easeInOutExpo:function(c,a,b,d,e){if(a==0)return b;if(a==e)return b+d;if((a/=e/2)<1)return d/2*Math.pow(2,10*(a-1))+b;return d/2*(-Math.pow(2,-10*--a)+2)+b},easeInCirc:function(c,a,b,d,e){return-d*(Math.sqrt(1-(a/=e)*a)-1)+b},easeOutCirc:function(c,a,b,d,e){return d*Math.sqrt(1-(a=a/e-1)*a)+b},easeInOutCirc:function(c,a,b,d,e){if((a/=e/2)<1)return-d/ 2*(Math.sqrt(1-a*a)-1)+b;return d/2*(Math.sqrt(1-(a-=2)*a)+1)+b},easeInElastic:function(c,a,b,d,e){c=1.70158;var g=0,h=d;if(a==0)return b;if((a/=e)==1)return b+d;g||(g=e*0.3);if(h<Math.abs(d)){h=d;c=g/4}else c=g/(2*Math.PI)*Math.asin(d/h);return-(h*Math.pow(2,10*(a-=1))*Math.sin((a*e-c)*2*Math.PI/g))+b},easeOutElastic:function(c,a,b,d,e){c=1.70158;var g=0,h=d;if(a==0)return b;if((a/=e)==1)return b+d;g||(g=e*0.3);if(h<Math.abs(d)){h=d;c=g/4}else c=g/(2*Math.PI)*Math.asin(d/h);return h*Math.pow(2,-10* a)*Math.sin((a*e-c)*2*Math.PI/g)+d+b},easeInOutElastic:function(c,a,b,d,e){c=1.70158;var g=0,h=d;if(a==0)return b;if((a/=e/2)==2)return b+d;g||(g=e*0.3*1.5);if(h<Math.abs(d)){h=d;c=g/4}else c=g/(2*Math.PI)*Math.asin(d/h);if(a<1)return-0.5*h*Math.pow(2,10*(a-=1))*Math.sin((a*e-c)*2*Math.PI/g)+b;return h*Math.pow(2,-10*(a-=1))*Math.sin((a*e-c)*2*Math.PI/g)*0.5+d+b},easeInBack:function(c,a,b,d,e,g){if(g==j)g=1.70158;return d*(a/=e)*a*((g+1)*a-g)+b},easeOutBack:function(c,a,b,d,e,g){if(g==j)g=1.70158; return d*((a=a/e-1)*a*((g+1)*a+g)+1)+b},easeInOutBack:function(c,a,b,d,e,g){if(g==j)g=1.70158;if((a/=e/2)<1)return d/2*a*a*(((g*=1.525)+1)*a-g)+b;return d/2*((a-=2)*a*(((g*=1.525)+1)*a+g)+2)+b},easeInBounce:function(c,a,b,d,e){return d-f.easing.easeOutBounce(c,e-a,0,d,e)+b},easeOutBounce:function(c,a,b,d,e){return(a/=e)<1/2.75?d*7.5625*a*a+b:a<2/2.75?d*(7.5625*(a-=1.5/2.75)*a+0.75)+b:a<2.5/2.75?d*(7.5625*(a-=2.25/2.75)*a+0.9375)+b:d*(7.5625*(a-=2.625/2.75)*a+0.984375)+b},easeInOutBounce:function(c, a,b,d,e){if(a<e/2)return f.easing.easeInBounce(c,a*2,0,d,e)*0.5+b;return f.easing.easeOutBounce(c,a*2-e,0,d,e)*0.5+d*0.5+b}})}(jQuery); ;/* * jQuery UI Effects Blind 1.8.5 * * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * http://docs.jquery.com/UI/Effects/Blind * * Depends: * jquery.effects.core.js */ (function(b){b.effects.blind=function(c){return this.queue(function(){var a=b(this),g=["position","top","left"],f=b.effects.setMode(a,c.options.mode||"hide"),d=c.options.direction||"vertical";b.effects.save(a,g);a.show();var e=b.effects.createWrapper(a).css({overflow:"hidden"}),h=d=="vertical"?"height":"width";d=d=="vertical"?e.height():e.width();f=="show"&&e.css(h,0);var i={};i[h]=f=="show"?d:0;e.animate(i,c.duration,c.options.easing,function(){f=="hide"&&a.hide();b.effects.restore(a,g);b.effects.removeWrapper(a); c.callback&&c.callback.apply(a[0],arguments);a.dequeue()})})}})(jQuery); ;/* * jQuery UI Effects Bounce 1.8.5 * * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * http://docs.jquery.com/UI/Effects/Bounce * * Depends: * jquery.effects.core.js */ (function(e){e.effects.bounce=function(b){return this.queue(function(){var a=e(this),l=["position","top","left"],h=e.effects.setMode(a,b.options.mode||"effect"),d=b.options.direction||"up",c=b.options.distance||20,m=b.options.times||5,i=b.duration||250;/show|hide/.test(h)&&l.push("opacity");e.effects.save(a,l);a.show();e.effects.createWrapper(a);var f=d=="up"||d=="down"?"top":"left";d=d=="up"||d=="left"?"pos":"neg";c=b.options.distance||(f=="top"?a.outerHeight({margin:true})/3:a.outerWidth({margin:true})/ 3);if(h=="show")a.css("opacity",0).css(f,d=="pos"?-c:c);if(h=="hide")c/=m*2;h!="hide"&&m--;if(h=="show"){var g={opacity:1};g[f]=(d=="pos"?"+=":"-=")+c;a.animate(g,i/2,b.options.easing);c/=2;m--}for(g=0;g<m;g++){var j={},k={};j[f]=(d=="pos"?"-=":"+=")+c;k[f]=(d=="pos"?"+=":"-=")+c;a.animate(j,i/2,b.options.easing).animate(k,i/2,b.options.easing);c=h=="hide"?c*2:c/2}if(h=="hide"){g={opacity:0};g[f]=(d=="pos"?"-=":"+=")+c;a.animate(g,i/2,b.options.easing,function(){a.hide();e.effects.restore(a,l);e.effects.removeWrapper(a); b.callback&&b.callback.apply(this,arguments)})}else{j={};k={};j[f]=(d=="pos"?"-=":"+=")+c;k[f]=(d=="pos"?"+=":"-=")+c;a.animate(j,i/2,b.options.easing).animate(k,i/2,b.options.easing,function(){e.effects.restore(a,l);e.effects.removeWrapper(a);b.callback&&b.callback.apply(this,arguments)})}a.queue("fx",function(){a.dequeue()});a.dequeue()})}})(jQuery); ;/* * jQuery UI Effects Clip 1.8.5 * * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * http://docs.jquery.com/UI/Effects/Clip * * Depends: * jquery.effects.core.js */ (function(b){b.effects.clip=function(e){return this.queue(function(){var a=b(this),i=["position","top","left","height","width"],f=b.effects.setMode(a,e.options.mode||"hide"),c=e.options.direction||"vertical";b.effects.save(a,i);a.show();var d=b.effects.createWrapper(a).css({overflow:"hidden"});d=a[0].tagName=="IMG"?d:a;var g={size:c=="vertical"?"height":"width",position:c=="vertical"?"top":"left"};c=c=="vertical"?d.height():d.width();if(f=="show"){d.css(g.size,0);d.css(g.position,c/2)}var h={};h[g.size]= f=="show"?c:0;h[g.position]=f=="show"?0:c/2;d.animate(h,{queue:false,duration:e.duration,easing:e.options.easing,complete:function(){f=="hide"&&a.hide();b.effects.restore(a,i);b.effects.removeWrapper(a);e.callback&&e.callback.apply(a[0],arguments);a.dequeue()}})})}})(jQuery); ;/* * jQuery UI Effects Drop 1.8.5 * * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * http://docs.jquery.com/UI/Effects/Drop * * Depends: * jquery.effects.core.js */ (function(c){c.effects.drop=function(d){return this.queue(function(){var a=c(this),h=["position","top","left","opacity"],e=c.effects.setMode(a,d.options.mode||"hide"),b=d.options.direction||"left";c.effects.save(a,h);a.show();c.effects.createWrapper(a);var f=b=="up"||b=="down"?"top":"left";b=b=="up"||b=="left"?"pos":"neg";var g=d.options.distance||(f=="top"?a.outerHeight({margin:true})/2:a.outerWidth({margin:true})/2);if(e=="show")a.css("opacity",0).css(f,b=="pos"?-g:g);var i={opacity:e=="show"?1: 0};i[f]=(e=="show"?b=="pos"?"+=":"-=":b=="pos"?"-=":"+=")+g;a.animate(i,{queue:false,duration:d.duration,easing:d.options.easing,complete:function(){e=="hide"&&a.hide();c.effects.restore(a,h);c.effects.removeWrapper(a);d.callback&&d.callback.apply(this,arguments);a.dequeue()}})})}})(jQuery); ;/* * jQuery UI Effects Explode 1.8.5 * * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * http://docs.jquery.com/UI/Effects/Explode * * Depends: * jquery.effects.core.js */ (function(j){j.effects.explode=function(a){return this.queue(function(){var c=a.options.pieces?Math.round(Math.sqrt(a.options.pieces)):3,d=a.options.pieces?Math.round(Math.sqrt(a.options.pieces)):3;a.options.mode=a.options.mode=="toggle"?j(this).is(":visible")?"hide":"show":a.options.mode;var b=j(this).show().css("visibility","hidden"),g=b.offset();g.top-=parseInt(b.css("marginTop"),10)||0;g.left-=parseInt(b.css("marginLeft"),10)||0;for(var h=b.outerWidth(true),i=b.outerHeight(true),e=0;e<c;e++)for(var f= 0;f<d;f++)b.clone().appendTo("body").wrap("<div></div>").css({position:"absolute",visibility:"visible",left:-f*(h/d),top:-e*(i/c)}).parent().addClass("ui-effects-explode").css({position:"absolute",overflow:"hidden",width:h/d,height:i/c,left:g.left+f*(h/d)+(a.options.mode=="show"?(f-Math.floor(d/2))*(h/d):0),top:g.top+e*(i/c)+(a.options.mode=="show"?(e-Math.floor(c/2))*(i/c):0),opacity:a.options.mode=="show"?0:1}).animate({left:g.left+f*(h/d)+(a.options.mode=="show"?0:(f-Math.floor(d/2))*(h/d)),top:g.top+ e*(i/c)+(a.options.mode=="show"?0:(e-Math.floor(c/2))*(i/c)),opacity:a.options.mode=="show"?1:0},a.duration||500);setTimeout(function(){a.options.mode=="show"?b.css({visibility:"visible"}):b.css({visibility:"visible"}).hide();a.callback&&a.callback.apply(b[0]);b.dequeue();j("div.ui-effects-explode").remove()},a.duration||500)})}})(jQuery); ;/* * jQuery UI Effects Fade 1.8.5 * * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * http://docs.jquery.com/UI/Effects/Fade * * Depends: * jquery.effects.core.js */ (function(b){b.effects.fade=function(a){return this.queue(function(){var c=b(this),d=b.effects.setMode(c,a.options.mode||"hide");c.animate({opacity:d},{queue:false,duration:a.duration,easing:a.options.easing,complete:function(){a.callback&&a.callback.apply(this,arguments);c.dequeue()}})})}})(jQuery); ;/* * jQuery UI Effects Fold 1.8.5 * * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * http://docs.jquery.com/UI/Effects/Fold * * Depends: * jquery.effects.core.js */ (function(c){c.effects.fold=function(a){return this.queue(function(){var b=c(this),j=["position","top","left"],d=c.effects.setMode(b,a.options.mode||"hide"),g=a.options.size||15,h=!!a.options.horizFirst,k=a.duration?a.duration/2:c.fx.speeds._default/2;c.effects.save(b,j);b.show();var e=c.effects.createWrapper(b).css({overflow:"hidden"}),f=d=="show"!=h,l=f?["width","height"]:["height","width"];f=f?[e.width(),e.height()]:[e.height(),e.width()];var i=/([0-9]+)%/.exec(g);if(i)g=parseInt(i[1],10)/100* f[d=="hide"?0:1];if(d=="show")e.css(h?{height:0,width:g}:{height:g,width:0});h={};i={};h[l[0]]=d=="show"?f[0]:g;i[l[1]]=d=="show"?f[1]:0;e.animate(h,k,a.options.easing).animate(i,k,a.options.easing,function(){d=="hide"&&b.hide();c.effects.restore(b,j);c.effects.removeWrapper(b);a.callback&&a.callback.apply(b[0],arguments);b.dequeue()})})}})(jQuery); ;/* * jQuery UI Effects Highlight 1.8.5 * * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * http://docs.jquery.com/UI/Effects/Highlight * * Depends: * jquery.effects.core.js */ (function(b){b.effects.highlight=function(c){return this.queue(function(){var a=b(this),e=["backgroundImage","backgroundColor","opacity"],d=b.effects.setMode(a,c.options.mode||"show"),f={backgroundColor:a.css("backgroundColor")};if(d=="hide")f.opacity=0;b.effects.save(a,e);a.show().css({backgroundImage:"none",backgroundColor:c.options.color||"#ffff99"}).animate(f,{queue:false,duration:c.duration,easing:c.options.easing,complete:function(){d=="hide"&&a.hide();b.effects.restore(a,e);d=="show"&&!b.support.opacity&& this.style.removeAttribute("filter");c.callback&&c.callback.apply(this,arguments);a.dequeue()}})})}})(jQuery); ;/* * jQuery UI Effects Pulsate 1.8.5 * * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * http://docs.jquery.com/UI/Effects/Pulsate * * Depends: * jquery.effects.core.js */ (function(d){d.effects.pulsate=function(a){return this.queue(function(){var b=d(this),c=d.effects.setMode(b,a.options.mode||"show");times=(a.options.times||5)*2-1;duration=a.duration?a.duration/2:d.fx.speeds._default/2;isVisible=b.is(":visible");animateTo=0;if(!isVisible){b.css("opacity",0).show();animateTo=1}if(c=="hide"&&isVisible||c=="show"&&!isVisible)times--;for(c=0;c<times;c++){b.animate({opacity:animateTo},duration,a.options.easing);animateTo=(animateTo+1)%2}b.animate({opacity:animateTo},duration, a.options.easing,function(){animateTo==0&&b.hide();a.callback&&a.callback.apply(this,arguments)});b.queue("fx",function(){b.dequeue()}).dequeue()})}})(jQuery); ;/* * jQuery UI Effects Scale 1.8.5 * * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * http://docs.jquery.com/UI/Effects/Scale * * Depends: * jquery.effects.core.js */ (function(c){c.effects.puff=function(b){return this.queue(function(){var a=c(this),e=c.effects.setMode(a,b.options.mode||"hide"),g=parseInt(b.options.percent,10)||150,h=g/100,i={height:a.height(),width:a.width()};c.extend(b.options,{fade:true,mode:e,percent:e=="hide"?g:100,from:e=="hide"?i:{height:i.height*h,width:i.width*h}});a.effect("scale",b.options,b.duration,b.callback);a.dequeue()})};c.effects.scale=function(b){return this.queue(function(){var a=c(this),e=c.extend(true,{},b.options),g=c.effects.setMode(a, b.options.mode||"effect"),h=parseInt(b.options.percent,10)||(parseInt(b.options.percent,10)==0?0:g=="hide"?0:100),i=b.options.direction||"both",f=b.options.origin;if(g!="effect"){e.origin=f||["middle","center"];e.restore=true}f={height:a.height(),width:a.width()};a.from=b.options.from||(g=="show"?{height:0,width:0}:f);h={y:i!="horizontal"?h/100:1,x:i!="vertical"?h/100:1};a.to={height:f.height*h.y,width:f.width*h.x};if(b.options.fade){if(g=="show"){a.from.opacity=0;a.to.opacity=1}if(g=="hide"){a.from.opacity= 1;a.to.opacity=0}}e.from=a.from;e.to=a.to;e.mode=g;a.effect("size",e,b.duration,b.callback);a.dequeue()})};c.effects.size=function(b){return this.queue(function(){var a=c(this),e=["position","top","left","width","height","overflow","opacity"],g=["position","top","left","overflow","opacity"],h=["width","height","overflow"],i=["fontSize"],f=["borderTopWidth","borderBottomWidth","paddingTop","paddingBottom"],k=["borderLeftWidth","borderRightWidth","paddingLeft","paddingRight"],p=c.effects.setMode(a, b.options.mode||"effect"),n=b.options.restore||false,m=b.options.scale||"both",l=b.options.origin,j={height:a.height(),width:a.width()};a.from=b.options.from||j;a.to=b.options.to||j;if(l){l=c.effects.getBaseline(l,j);a.from.top=(j.height-a.from.height)*l.y;a.from.left=(j.width-a.from.width)*l.x;a.to.top=(j.height-a.to.height)*l.y;a.to.left=(j.width-a.to.width)*l.x}var d={from:{y:a.from.height/j.height,x:a.from.width/j.width},to:{y:a.to.height/j.height,x:a.to.width/j.width}};if(m=="box"||m=="both"){if(d.from.y!= d.to.y){e=e.concat(f);a.from=c.effects.setTransition(a,f,d.from.y,a.from);a.to=c.effects.setTransition(a,f,d.to.y,a.to)}if(d.from.x!=d.to.x){e=e.concat(k);a.from=c.effects.setTransition(a,k,d.from.x,a.from);a.to=c.effects.setTransition(a,k,d.to.x,a.to)}}if(m=="content"||m=="both")if(d.from.y!=d.to.y){e=e.concat(i);a.from=c.effects.setTransition(a,i,d.from.y,a.from);a.to=c.effects.setTransition(a,i,d.to.y,a.to)}c.effects.save(a,n?e:g);a.show();c.effects.createWrapper(a);a.css("overflow","hidden").css(a.from); if(m=="content"||m=="both"){f=f.concat(["marginTop","marginBottom"]).concat(i);k=k.concat(["marginLeft","marginRight"]);h=e.concat(f).concat(k);a.find("*[width]").each(function(){child=c(this);n&&c.effects.save(child,h);var o={height:child.height(),width:child.width()};child.from={height:o.height*d.from.y,width:o.width*d.from.x};child.to={height:o.height*d.to.y,width:o.width*d.to.x};if(d.from.y!=d.to.y){child.from=c.effects.setTransition(child,f,d.from.y,child.from);child.to=c.effects.setTransition(child, f,d.to.y,child.to)}if(d.from.x!=d.to.x){child.from=c.effects.setTransition(child,k,d.from.x,child.from);child.to=c.effects.setTransition(child,k,d.to.x,child.to)}child.css(child.from);child.animate(child.to,b.duration,b.options.easing,function(){n&&c.effects.restore(child,h)})})}a.animate(a.to,{queue:false,duration:b.duration,easing:b.options.easing,complete:function(){a.to.opacity===0&&a.css("opacity",a.from.opacity);p=="hide"&&a.hide();c.effects.restore(a,n?e:g);c.effects.removeWrapper(a);b.callback&& b.callback.apply(this,arguments);a.dequeue()}})})}})(jQuery); ;/* * jQuery UI Effects Shake 1.8.5 * * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * http://docs.jquery.com/UI/Effects/Shake * * Depends: * jquery.effects.core.js */ (function(d){d.effects.shake=function(a){return this.queue(function(){var b=d(this),j=["position","top","left"];d.effects.setMode(b,a.options.mode||"effect");var c=a.options.direction||"left",e=a.options.distance||20,l=a.options.times||3,f=a.duration||a.options.duration||140;d.effects.save(b,j);b.show();d.effects.createWrapper(b);var g=c=="up"||c=="down"?"top":"left",h=c=="up"||c=="left"?"pos":"neg";c={};var i={},k={};c[g]=(h=="pos"?"-=":"+=")+e;i[g]=(h=="pos"?"+=":"-=")+e*2;k[g]=(h=="pos"?"-=":"+=")+ e*2;b.animate(c,f,a.options.easing);for(e=1;e<l;e++)b.animate(i,f,a.options.easing).animate(k,f,a.options.easing);b.animate(i,f,a.options.easing).animate(c,f/2,a.options.easing,function(){d.effects.restore(b,j);d.effects.removeWrapper(b);a.callback&&a.callback.apply(this,arguments)});b.queue("fx",function(){b.dequeue()});b.dequeue()})}})(jQuery); ;/* * jQuery UI Effects Slide 1.8.5 * * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * http://docs.jquery.com/UI/Effects/Slide * * Depends: * jquery.effects.core.js */ (function(c){c.effects.slide=function(d){return this.queue(function(){var a=c(this),h=["position","top","left"],e=c.effects.setMode(a,d.options.mode||"show"),b=d.options.direction||"left";c.effects.save(a,h);a.show();c.effects.createWrapper(a).css({overflow:"hidden"});var f=b=="up"||b=="down"?"top":"left";b=b=="up"||b=="left"?"pos":"neg";var g=d.options.distance||(f=="top"?a.outerHeight({margin:true}):a.outerWidth({margin:true}));if(e=="show")a.css(f,b=="pos"?-g:g);var i={};i[f]=(e=="show"?b=="pos"? "+=":"-=":b=="pos"?"-=":"+=")+g;a.animate(i,{queue:false,duration:d.duration,easing:d.options.easing,complete:function(){e=="hide"&&a.hide();c.effects.restore(a,h);c.effects.removeWrapper(a);d.callback&&d.callback.apply(this,arguments);a.dequeue()}})})}})(jQuery); ;/* * jQuery UI Effects Transfer 1.8.5 * * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * http://docs.jquery.com/UI/Effects/Transfer * * Depends: * jquery.effects.core.js */ (function(e){e.effects.transfer=function(a){return this.queue(function(){var b=e(this),c=e(a.options.to),d=c.offset();c={top:d.top,left:d.left,height:c.innerHeight(),width:c.innerWidth()};d=b.offset();var f=e('<div class="ui-effects-transfer"></div>').appendTo(document.body).addClass(a.options.className).css({top:d.top,left:d.left,height:b.innerHeight(),width:b.innerWidth(),position:"absolute"}).animate(c,a.duration,a.options.easing,function(){f.remove();a.callback&&a.callback.apply(b[0],arguments); b.dequeue()})})}})(jQuery); ;
generate docs...
import Boot from './states/Boot'; import Preload from './states/Preload'; import GameTitle from './states/GameTitle'; import Main from './states/Main'; import GameOver from './states/GameOver'; import GameWon from './states/GameWon'; class Game extends Phaser.Game { constructor() { super(800, 600, Phaser.AUTO, 'game') this.state.add('Boot', Boot, false); this.state.add('Preload', Preload, false); this.state.add('GameTitle', GameTitle, false); this.state.add('Main', Main, false); this.state.add('GameOver', GameOver, false); this.state.add('GameWon', GameWon, false); this.state.start('Boot'); } } new Game();
'use strict'; // -------------------------------------------------------------------- // Private stuff // -------------------------------------------------------------------- function PosInfo() { this.applicationMemoKeyStack = []; // active applications at this position this.memo = {}; this.maxExaminedLength = 0; this.maxRightmostFailureOffset = -1; this.currentLeftRecursion = undefined; } PosInfo.prototype = { isActive(application) { return this.applicationMemoKeyStack.indexOf(application.toMemoKey()) >= 0; }, enter(application) { this.applicationMemoKeyStack.push(application.toMemoKey()); }, exit() { this.applicationMemoKeyStack.pop(); }, startLeftRecursion(headApplication, memoRec) { memoRec.isLeftRecursion = true; memoRec.headApplication = headApplication; memoRec.nextLeftRecursion = this.currentLeftRecursion; this.currentLeftRecursion = memoRec; const applicationMemoKeyStack = this.applicationMemoKeyStack; const indexOfFirstInvolvedRule = applicationMemoKeyStack.indexOf(headApplication.toMemoKey()) + 1; const involvedApplicationMemoKeys = applicationMemoKeyStack.slice( indexOfFirstInvolvedRule ); memoRec.isInvolved = function(applicationMemoKey) { return involvedApplicationMemoKeys.indexOf(applicationMemoKey) >= 0; }; memoRec.updateInvolvedApplicationMemoKeys = function() { for (let idx = indexOfFirstInvolvedRule; idx < applicationMemoKeyStack.length; idx++) { const applicationMemoKey = applicationMemoKeyStack[idx]; if (!this.isInvolved(applicationMemoKey)) { involvedApplicationMemoKeys.push(applicationMemoKey); } } }; }, endLeftRecursion() { this.currentLeftRecursion = this.currentLeftRecursion.nextLeftRecursion; }, // Note: this method doesn't get called for the "head" of a left recursion -- for LR heads, // the memoized result (which starts out being a failure) is always used. shouldUseMemoizedResult(memoRec) { if (!memoRec.isLeftRecursion) { return true; } const applicationMemoKeyStack = this.applicationMemoKeyStack; for (let idx = 0; idx < applicationMemoKeyStack.length; idx++) { const applicationMemoKey = applicationMemoKeyStack[idx]; if (memoRec.isInvolved(applicationMemoKey)) { return false; } } return true; }, memoize(memoKey, memoRec) { this.memo[memoKey] = memoRec; this.maxExaminedLength = Math.max(this.maxExaminedLength, memoRec.examinedLength); this.maxRightmostFailureOffset = Math.max( this.maxRightmostFailureOffset, memoRec.rightmostFailureOffset ); return memoRec; }, clearObsoleteEntries(pos, invalidatedIdx) { if (pos + this.maxExaminedLength <= invalidatedIdx) { // Optimization: none of the rule applications that were memoized here examined the // interval of the input that changed, so nothing has to be invalidated. return; } const memo = this.memo; this.maxExaminedLength = 0; this.maxRightmostFailureOffset = -1; Object.keys(memo).forEach(k => { const memoRec = memo[k]; if (pos + memoRec.examinedLength > invalidatedIdx) { delete memo[k]; } else { this.maxExaminedLength = Math.max(this.maxExaminedLength, memoRec.examinedLength); this.maxRightmostFailureOffset = Math.max( this.maxRightmostFailureOffset, memoRec.rightmostFailureOffset ); } }); } }; // -------------------------------------------------------------------- // Exports // -------------------------------------------------------------------- module.exports = PosInfo;
// # Ghost Configuration // Setup your Ghost install for various [environments](http://support.ghost.org/config/#about-environments). // Ghost runs in `development` mode by default. Full documentation can be found at http://support.ghost.org/config/ var path = require('path'), config; config = { // ### Production // When running Ghost in the wild, use the production environment. // Configure your URL and mail settings here production: { url: 'http://www.afanweb.com', mail: {}, database: { client: 'mysql', connection: { host: 'tcp://10.10.26.58:3306', user: 'uJIiwyOm0RUlnYpr', password: 'p6y852qgWrRBDUkJm', database: 'ghost', charset: 'utf8', }, debug: false }, server: { host: '127.0.0.1', port: '2368' } }, // ### Development **(default)** development: { // The url to use when providing links to the site, E.g. in RSS and email. // Change this to your Ghost blog's published URL. url: 'http://localhost:2368', // Example refferer policy // Visit https://www.w3.org/TR/referrer-policy/ for instructions // default 'origin-when-cross-origin', // referrerPolicy: 'origin-when-cross-origin', // Example mail config // Visit http://support.ghost.org/mail for instructions // ``` // mail: { // transport: 'SMTP', // options: { // service: 'Mailgun', // auth: { // user: '', // mailgun username // pass: '' // mailgun password // } // } // }, // ``` // #### Database // Ghost supports sqlite3 (default), MySQL & PostgreSQL database: { client: 'sqlite3', connection: { filename: path.join(__dirname, '/content/data/ghost-dev.db') }, debug: false }, // #### Server // Can be host & port (default), or socket server: { // Host to be passed to node's `net.Server#listen()` host: '127.0.0.1', // Port to be passed to node's `net.Server#listen()`, for iisnode set this to `process.env.PORT` port: '2368' }, // #### Paths // Specify where your content directory lives paths: { contentPath: path.join(__dirname, '/content/') } }, // **Developers only need to edit below here** // ### Testing // Used when developing Ghost to run tests and check the health of Ghost // Uses a different port number testing: { url: 'http://127.0.0.1:2369', database: { client: 'sqlite3', connection: { filename: path.join(__dirname, '/content/data/ghost-test.db') }, pool: { afterCreate: function (conn, done) { conn.run('PRAGMA synchronous=OFF;' + 'PRAGMA journal_mode=MEMORY;' + 'PRAGMA locking_mode=EXCLUSIVE;' + 'BEGIN EXCLUSIVE; COMMIT;', done); } }, useNullAsDefault: true }, server: { host: '127.0.0.1', port: '2369' }, logging: false }, // ### Testing MySQL // Used by Travis - Automated testing run through GitHub 'testing-mysql': { url: 'http://127.0.0.1:2369', database: { client: 'mysql', connection: { host : '127.0.0.1', user : 'root', password : '', database : 'ghost_testing', charset : 'utf8' } }, server: { host: '127.0.0.1', port: '2369' }, logging: false }, // ### Testing pg // Used by Travis - Automated testing run through GitHub 'testing-pg': { url: 'http://127.0.0.1:2369', database: { client: 'pg', connection: { host : '127.0.0.1', user : 'postgres', password : '', database : 'ghost_testing', charset : 'utf8' } }, server: { host: '127.0.0.1', port: '2369' }, logging: false } }; module.exports = config;
// @flow import React, { Component } from 'react'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import { Icon, Menu } from 'semantic-ui-react'; import { Link } from 'react-router-dom'; import * as AccountActions from '../actions/account'; import * as HiveActions from '../actions/hive'; const src = require('../img/hive.png'); class MenuBar extends Component { state = { intervalId: 0 }; componentDidMount() { this.interval = setInterval(this.timer.bind(this), 10000); this.timer(); // this.props.actions.getTransactions(this.props.keys.names); } componentWillUnmount() { // console.log('unmounting'); clearInterval(this.interval); } interval = 0; timer = () => { // console.log('tick'); this.props.actions.refreshAccountData(this.props.keys.names); this.props.actions.refreshGlobalProps(); // this.props.actions.getTransactions(this.props.account.names); } render() { let height = 'Loading' if (this.props.hive.props) { height = this.props.hive.props.head_block_number; } return ( <Menu vertical fixed="left" color="black" inverted icon="labeled"> <Menu.Item header> <img alt="Vessel" className="ui tiny image" src={src} style={{ width: '50px', height: '50px', margin: '0 auto 1em', }} /> Vessel </Menu.Item> <Link className="link item" to="/transactions"> <Icon name="dashboard" /> Overview </Link> <Link className="link item" to="/send"> <Icon name="send" /> Send </Link> <Link className="link item" to="/vesting"> <Icon name="lightning" /> Vesting </Link> <Link className="link item" to="/accounts"> <Icon name="users" /> Accounts </Link> <Link className="link item" to="/settings"> <Icon name="settings" /> Settings </Link> <Link className="link item" to="/advanced"> <Icon name="lab" /> Advanced </Link> <Menu.Item className="link" style={{ position: 'absolute', bottom: 0 }} > <p> Height </p> {height} </Menu.Item> </Menu> ); } } function mapStateToProps(state) { return { keys: state.keys, hive: state.hive }; } function mapDispatchToProps(dispatch) { return { actions: bindActionCreators({ ...AccountActions, ...HiveActions }, dispatch) }; } export default connect(mapStateToProps, mapDispatchToProps)(MenuBar);
import { Vector3 } from './Vector3.js'; var _v0 = new Vector3(); var _v1 = new Vector3(); var _v2 = new Vector3(); var _v3 = new Vector3(); /** * @constructor * @memberof zen3d * @param {zen3d.Vector3} [a=] * @param {zen3d.Vector3} [b=] * @param {zen3d.Vector3} [c=] */ function Triangle(a, b, c) { this.a = (a !== undefined) ? a : new Vector3(); this.b = (b !== undefined) ? b : new Vector3(); this.c = (c !== undefined) ? c : new Vector3(); } Object.assign(Triangle.prototype, /** @lends zen3d.Triangle.prototype */{ /** * */ set: function(a, b, c) { this.a.copy(a); this.b.copy(b); this.c.copy(c); return this; } }); /** * @method */ Triangle.normal = function(a, b, c, optionalTarget) { var result = optionalTarget || new Vector3(); result.subVectors(c, b); _v0.subVectors(a, b); result.cross(_v0); var resultLengthSq = result.getLengthSquared(); if (resultLengthSq > 0) { return result.multiplyScalar(1 / Math.sqrt(resultLengthSq)); } return result.set(0, 0, 0); }; /** * static/instance method to calculate barycentric coordinates. * based on: http://www.blackpawn.com/texts/pointinpoly/default.html * @method */ Triangle.barycoordFromPoint = function(point, a, b, c, optionalTarget) { _v0.subVectors(c, a); _v1.subVectors(b, a); _v2.subVectors(point, a); var dot00 = _v0.dot(_v0); var dot01 = _v0.dot(_v1); var dot02 = _v0.dot(_v2); var dot11 = _v1.dot(_v1); var dot12 = _v1.dot(_v2); var denom = (dot00 * dot11 - dot01 * dot01); var result = optionalTarget || new Vector3(); // collinear or singular triangle if (denom === 0) { // arbitrary location outside of triangle? // not sure if this is the best idea, maybe should be returning undefined return result.set(-2, -1, -1); } var invDenom = 1 / denom; var u = (dot11 * dot02 - dot01 * dot12) * invDenom; var v = (dot00 * dot12 - dot01 * dot02) * invDenom; // barycentric coordinates must always sum to 1 return result.set(1 - u - v, v, u); }; /** * @method */ Triangle.containsPoint = function(point, a, b, c) { Triangle.barycoordFromPoint(point, a, b, c, _v3); return (_v3.x >= 0) && (_v3.y >= 0) && ((_v3.x + _v3.y) <= 1); }; export { Triangle };
var blog = require('../models/blog'); var util = require('./widget/util'); function _context_ids(id, arr){ var prev_id = next_id = 0; if (arr.length <= 1) { return {pid: 0, nid: 0}; } for (var i = 0; i < arr.length; i++){ if(arr[i]._id == id){ if(i > 0 && i < arr.length-1){ prev_id = arr[i-1]._id; next_id = arr[i+1]._id; } else if(i == 0){ prev_id = arr[arr.length-1]._id; next_id = arr[i+1]._id; } else if(i == arr.length-1){ prev_id = arr[i-1]._id; next_id = arr[0]._id; } return {pid: prev_id, nid: next_id}; } } } exports.showlist = function(req, res) { var session_user = req.session.user; var _uid = session_user && session_user._id; if (!session_user) { res.redirect('/'); } else { blog.get(null, function(status, message) { //过滤热度并返回当前用户所有喜欢的博文 var love_blogs = util.filter_loveAndRecommend(message, _uid); //过滤标签并返回当前用户所有博文 var self_blogs = util.filter_static(message, _uid); //压缩文章内容 util.compress_code(message); res.render('bowen', { title: '个人文章|NodeJs学习站', type: 'bowen', loginer: session_user, blog: self_blogs, love_blog_count: love_blogs.length }); }); } }; exports.detail = function(req, res) { var session_user = req.session.user; var _id = req.params._id; blog.get({_id: _id}, function(status, message) { if (status==1 && message.length>0) { var only_message = message[0]; var title = (only_message.title || '详细文字') + only_message.author_name; //过滤标签 util.filter_static(message); //过滤热度 util.filter_loveAndRecommend(message); //获取文章时间中的月份和天数 only_message.month = util.getNowTime().month; only_message.date = util.getNowTime().date; //找出所有文章 blog.get({author_id: only_message.author_id}, function(estate, all) { //读取上篇、下篇文章的_id var ids = _context_ids(_id, all); only_message.pid = ids.pid; only_message.nid = ids.nid; //记录未登录前最后访问页面 // req.session.last_visit_url = 'bowen/detail/'+_id; //模板渲染 res.render('detail', { title: title+'|NodeJs学习站', type: 'detail', loginer: session_user, blog: only_message }); }); } else { res.render('error', { title: '出错啦|NodeJs学习站', type: 'error', loginer: session_user }); } }); }
import request from 'request'; import { isArray } from 'lodash'; import EnvConfig from '../env.config.json'; import Logger from './Logger'; const logger = Logger('lib:Facebook.js'); const postMessage = (target, message) => { if (isArray(message)) { message.forEach(singleMessage => postMessage(target, singleMessage)); return; } const messageData = { recipient: { id: target, }, message: { text: message, }, }; request({ uri: 'https://graph.facebook.com/v2.6/me/messages', qs: { access_token: EnvConfig.Facebook.pageToken }, method: 'POST', json: messageData, }, (error, response, body) => { if (!error && response.statusCode === 200) { logger.info('Successfully sent generic message', body); } else { logger.error('Unable to send message.', error, response); } }); }; export default postMessage;
var Graph = function() { var self = this; self.init = function() { self.data = DATA; self.all_projects = self.data.projects; self.institute_projects = []; self.filtered_projects = []; self.institutes = self.data.institutes; self.resetFilters(); self.w = 680; self.h = 680; self.svg_h = 900; self.padding = 150; self.stroke = 6; self.svg = d3.select("#graph") .append("svg") .attr("width", self.w) .attr("height", self.svg_h); self.svg.append("g").attr("class", "graph"); self.svg.append("g").attr("class", "legend"); self.updateInstitutes(); self.units = []; self.createScales(); self.createAxes(); self.drawAxes(); self.drawLegend(); $('select[class=select-institute]').on('change', self.instituteChanged); $('select[class=select-reporting-period]').on('change', self.reportingPeriodChanged); $('select[class=select-org-level]').on('change', self.orgLevelChanged); $('select[class=select-status]').on('change', self.statusChanged); $('select[class=select-duration]').on('change', self.durationChanged); $('.show-all-units').on('click', self.showAllUnits) $('.print-graph').on('click', function(e) { e.preventDefault(); window.print(); }) // Default to logged in user's institute. if (self.data.user_institute in self.institutes) { $('select[class=select-institute]').val(self.data.user_institute.id).change(); } }; self.resetFilters = function () { self.filters = { institute: null, reporting_period: null, org_level: "1", status: null, duration: null, units: {} }; // Set status option to the default $('select[class=select-status]').val(""); }; self.getLevelUnits = function () { // Return a set of unique unit names, // which exist for the current chosen level, // for the current instutute. var org_level = 'org_level_' + self.filters.org_level; return _.uniq( _.map( _.filter( self.institute_projects, function(project) { return project[org_level]; }), function(p) { return p[org_level]; })); }; self.updateInstitutes = function() { $.each(self.institutes, function(i, institute) { $('.select-institute').append($('<option>', { value: institute.id, text: institute.name })); }); }; self.updateReportingPeriods = function() { var select = $('.select-reporting-period'); select.find('option').remove(); $.each(self.filters.institute.reporting_periods, function(i, reporting_period) { select.append($('<option>', { value: reporting_period.id, text: reporting_period.name })) }); }; self.updateOrgLevels = function() { var select = $('.select-org-level'); select.find('option').remove(); $.each([1,2,3], function(i, level) { var level_key = 'org_level_' + level + '_name' if (self.filters.institute[level_key]) { select.append($('<option>', { value: level, text: self.filters.institute[level_key] })); } }); }; self.updateUnits = function () { $('#unit-legend-meta').css('display', 'block'); self.units = self.getLevelUnits(); self.filters.units = {}; _.each(self.units, function(u) { self.filters.units[u] = true; }); }; self.updateDownloadForm = function () { $('.user-actions').css('display', 'block'); $('.close-date').val(self.filters.institute['close_date']) $('input[name=institute_id]').val(self.filters.institute['id']); }; self.instituteChanged = function() { var institute_id = $(this).val(); self.resetFilters(); self.filters.institute = _.find(self.institutes, function(institute) { return institute.id == institute_id; }); self.filters.reporting_period = self.filters.institute.reporting_periods[0].id self.institute_projects = _.filter(self.all_projects, function(project) { return project.institute.id == self.filters.institute.id; }); self.updateReportingPeriods(); self.updateOrgLevels(); self.updateUnits(); self.drawUnitLegend(); self.filterAndDrawProjects(); self.updateDownloadForm(); }; self.reportingPeriodChanged = function() { self.filters.reporting_period = $(this).val() || null; self.filterAndDrawProjects(); } self.orgLevelChanged = function() { self.filters.org_level = $(this).val() || null; self.updateUnits(); self.drawUnitLegend(); self.filterAndDrawProjects(); }; self.statusChanged = function() { self.filters.status = $(this).val() || null; self.filterAndDrawProjects(); }; self.durationChanged = function() { self.filters.duration = $(this).val() || null; self.filterAndDrawProjects(); }; self.unitChanged = function(d) { self.filters.units[d] = !self.filters.units[d]; self.filterAndDrawProjects(); }; self.showAllUnits = function(d) { self.updateUnits() self.drawUnitLegend(); self.filterAndDrawProjects(); } self.filterAndDrawProjects = function() { var filters = self.filters; // All unfiltered projects for currrent institute var projects = self.institute_projects; // reporting period if (self.filters.reporting_period) { projects = _.filter(projects, function(project) { return project.reporting_period.id == self.filters.reporting_period; }); } // org level if (self.filters.org_level) { projects = _.filter(projects, function(project) { return project['org_level_' + self.filters.org_level]; }); } // status if (self.filters.status) { projects = _.filter(projects, function(project) { return project.status == self.filters.status; }); } // duration if (self.filters.duration) { projects = _.filter(projects, function(project) { return project.duration == self.filters.duration; }); } // units projects = _.filter(projects, function(p) { var org = p['org_level_' + self.filters.org_level]; return org && self.filters.units[org]; }); self.filtered_projects = _.sortBy(projects, 'duration').reverse(); self.drawResults(); }; self.createScales = function() { var h = self.h, w = self.w, padding = self.padding; var hyp_length = function(x, y) { // Given the length of two side, // return the length of the hypotenuse // of a Right triangle. return Math.sqrt((x * x) + (y * y)); }; self.xScale = d3.scale.linear() .domain([0, 9]) .range([padding, w-padding]); self.yScale = d3.scale.linear() .domain([0, 9]) .range([h-padding, padding]); self.zScale = d3.scale.linear() .domain([0, 9]) .range([0, hyp_length(self.xScale(9) - padding, self.yScale(0) - padding)]); self.rScale = d3.scale.linear() .domain([0, 4]) .range([5, 25]); self.colorScale = d3.scale.category20() .domain(self.units); self.discScale = d3.scale.linear() .domain([0, 4]) .range([5, 15]); }; self.createAxes = function () { self.xAxis = d3.svg.axis() .scale(self.xScale) .orient("bottom") .tickPadding(-4) .innerTickSize(0) .outerTickSize(0); self.yAxis = d3.svg.axis() .scale(self.yScale) .orient("left") .tickPadding(-4) .innerTickSize(0) .outerTickSize(0); self.zAxis = d3.svg.axis() .scale(self.zScale) .orient("bottom") .tickPadding(-4) .innerTickSize(0) .outerTickSize(0); }; self.drawAxes = function () { var h = self.h, w = self.w, padding = self.padding, svg = self.svg.select(".graph"); svg.append("g") .attr("class", "axis") .attr("transform", "translate(0," + (h - self.yScale(4.5)) + ")") .call(self.xAxis) .selectAll("text") .attr("transform", "rotate(45)"); svg.append("g") .attr("class", "axis") .attr("transform", "translate(" + self.xScale(4.5) + ",0)") .call(self.yAxis) .selectAll("text") .attr("transform", "rotate(45)"); // Draw gridlines svg.selectAll("line.horizontalGrid").data(self.yScale.ticks(9)).enter() .append("line") .attr({ "class":"horizontalGrid grid", "x1" : padding, "x2" : w - padding, "y1" : function(d){ return self.yScale(d);}, "y2" : function(d){ return self.yScale(d);}, }); svg.selectAll("line.verticalGrid").data(self.xScale.ticks(9)).enter() .append("line") .attr({ "class":"verticalGrid grid", "y1" : padding, "y2" : h - padding, "x1" : function(d){ return self.xScale(d);}, "x2" : function(d){ return self.xScale(d);}, }); var z_x = padding, z_y = h - padding; svg.append("g") .attr("class", "axis z-axis") .attr("transform", "translate(" + z_x + "," + z_y +") rotate(-45 0 0)") .call(self.zAxis) .selectAll("text") .attr("transform", "rotate(90)"); // Draw the labels svg.append("text") .attr("class", "x label") .attr("x", w - (padding - 20)) .attr("y", h - self.yScale(4.5)) .attr("transform", "rotate(45,"+ (w - (padding - 20)) + "," + (h - self.yScale(4.5)) + ")") .text("Strengthening the") .append("tspan") .text("academic core") .attr("dx", -85) .attr("dy", 12); svg.append("text") .attr("class", "x label") .attr("text-anchor", "end") .attr("x", padding - 20) .attr("y", h - self.yScale(4.5)) .attr("transform", "rotate(45,"+ ((padding - 20)) + "," + (h - self.yScale(4.5)) + ")") .text("Weaking the") .append("tspan") .text("academic core") .attr("dx", -75) .attr("dy", 12); svg.append("text") .attr("class", "y label") .attr("text-anchor", "end") .attr("x", w - self.xScale(4.5)) .attr("y", padding - 25) .attr("transform", "rotate(45,"+ ((w - self.xScale(4.5))) + "," + (padding - 20) + ")") .text("Strong articulation"); svg.append("text") .attr("class", "y label") .attr("x", w - self.xScale(4.5)) .attr("y", h - (padding - 20)) .attr("transform", "rotate(45,"+ ((w - self.xScale(4.5))) + "," + (h - (padding - 20)) + ")") .text("Weak articulation"); svg.append("text") .attr("class", "z label") .attr("text-anchor", "middle") .attr("x", w - (padding - 20)) .attr("y", padding - 20) .text("Interconnected") .attr("transform", "rotate(45,"+ (w - (padding - 20)) + "," + (padding - 20) + ")"); svg.append("text") .attr("class", "z label") .attr("text-anchor", "middle") .attr("x", padding - 20) .attr("y", h - (padding - 20)) .text("Disconnected") .attr("transform", "rotate(45,"+ (padding - 20) + "," + (h - (padding - 20)) + ")"); // Rotate the graph svg.attr("transform", "rotate(-45, " + self.w/2 + ", " + self.h/2 + ")"); }; self.drawLegend = function() { var svg = self.svg.select(".legend"), legendHeight = 260, legendWidth = 150, ongoing_x = 40, complete_x = 100, label_x = 140; svg.attr("transform", "translate(0, " + (self.svg_h - legendHeight - 75) + ")"); svg.append("rect") .attr({ x: 0, y: 0, width: legendWidth, height: legendHeight, }); // titles var txt = svg.append("text") .attr("class", "label legend") .attr("text-anchor", "middle") .attr("x", legendWidth / 2) .attr("y", 10) .attr("text-ancher", "middle") .text("Duration of project (years)"); svg.append("text") .attr("text-anchor", "middle") .attr("dy", legendHeight - 2) .attr("dx", ongoing_x) .text("Ongoing"); svg.append("text") .attr("text-anchor", "middle") .attr("dy", legendHeight - 2) .attr("dx", complete_x) .text("Complete"); // year labels var labels = ['0-1.99', '2-2.99', '3-3.99', '4-4.99', '5+'], years = []; for (var i = 0; i < labels.length; i++) { var y = i === 0 ? legendHeight - 10 : years[years.length-1].y; years.push({ i: i, y: y - self.rScale(i) * 2 - 8, label: labels[i], }); } // Ongoing circles svg.selectAll("circle.ongoing").data(years).enter() .append("circle") .attr({ class: "ongoing", cx: ongoing_x, cy: function(d) { return d.y; }, r: function(d) { return self.rScale(d.i) - self.stroke / 2; }, fill: 'none', stroke: '#ccc', 'stroke-width': self.stroke, }); // Complete circles svg.selectAll("circle.complete").data(years).enter() .append("circle") .attr({ class: "complete", cx: complete_x, cy: function(d) { return d.y; }, r: function(d) { return self.rScale(d.i); }, fill: '#ccc', }); // year labels svg.selectAll(".years").data(years).enter() .append("text") .attr("class", "label") .attr("text-ancher", "middle") .attr("x", label_x) .attr("y", function(d) { return d.y + 5; }) .text(function(d) { return d.label; }); }; self.drawUnitLegend = function () { // Set scale to current units self.colorScale = d3.scale.category20() .domain(self.units); $('#unit-legend').children().remove(); var svg = d3.select("#unit-legend") .append("svg") .attr('class', 'unit-legend') .append("g") .attr("transform", "translate(10, 10)"); var colorLegend = d3.legend.color() .scale(self.colorScale) .shape('circle') .on('cellclick', function(d) { self.unitChanged(d); }); svg.call(colorLegend); // Change opacity of clicked element $('.cell').on('click', function(e) { if ($(this).css('opacity') === '1') { $(this).css('opacity', '0.5'); } else { $(this).css('opacity', '1'); } }); }; self.drawResults = function () { var svg = self.svg.select(".graph"), point = svg.selectAll("circle").data(self.filtered_projects, function(d) { return d.id; }).order(); point.exit() .transition().attr("r", 0).remove(); point.enter() .append("circle") .attr("cx", function(d) { return self.xScale(d.score['x']); }) .attr("cy", function(d) { return self.yScale(d.score['y']); }) .attr("r", 0) .transition() .attr("r", function(d) { var r = self.rScale(d.duration); // ensure outer edge of stroke is at where the edge of a filled circle would be // status: 1 = complete, 2 = ongoing if (d.status == '2') r -= self.stroke / 2; return r; }) .attr("fill", function(d) { // no fill for ongoing // status: 1 = complete, 2 = ongoing return d.status == '2' ? 'none' : self.colorScale(d['org_level_' + self.filters.org_level]); }) .attr("stroke", function(d) { // stroke only for ongoing // status: 1 = complete, 2 = ongoing return d.status == '2' ? self.colorScale(d['org_level_' + self.filters.org_level]) : 'none'; }) .attr("stroke-width", self.stroke); point.on("mouseover", self.showTooltip); point.on("mouseout", self.removeTooltip); }; self.showTooltip = function (d) { buildTooltip = function(d) { return "\ <table>\ <tr>\ <th colspan='2'>Articulation</th>\ <th colspan='2'>Academic core</th>\ </tr>\ <tr>\ <td>Alignment of objectives</td>\ <td>" + d.score['a_1'] + "</td>\ <td>Generates new knowledge or product</td>\ <td>" + d.score['c_1'] + "</td>\ </tr>\ <tr>\ <td>Initiation/agenda-setting</td>\ <td>" + d.score['a_2'] + "</td>\ <td>Dissemination</td>\ <td>" + d.score['c_2'] + "</td>\ </tr>\ <tr>\ <td>External stakeholders</td>\ <td>" + d.score['a_3'] + "</td>\ <td>Teaching/curriculum development</td>\ <td>" + d.score['c_3_a'] + "</td>\ </tr>\ <tr>\ <td>Funding</td>\ <td>" + d.score['a_4'] + "</td>\ <td>Formal teaching/learning of students</td>\ <td>" + d.score['c_3_b'] + "</td>\ </tr>\ <tr>\ <tr>\ <td colspan='2'>\ <td>Links to academic network</td>\ <td>" + d.score['c_4'] + "</td>\ </tr>\ <tr>\ <td>Total</td>\ <td>" + d.score['y'] + "</td>\ <td>Total</td>\ <td>" + d.score['x'] + "</td>\ </tr>\ </table>" } $(this).popover({ placement: 'auto top', container: '#graph', trigger: 'manual', html : true, content: function() { return buildTooltip(d) } }); $(this).popover('show'); }; self.removeTooltip = function () { $('.popover').each(function() { $(this).remove(); }); }; }; var graph = new Graph(); graph.init();