code stringlengths 2 1.05M | repo_name stringlengths 5 114 | path stringlengths 4 991 | language stringclasses 1 value | license stringclasses 15 values | size int32 2 1.05M |
|---|---|---|---|---|---|
/*! @license pzprv3-ui.js v<%= pkg.version %> (c) 2009-<%= grunt.template.today('yyyy') %> <%= pkg.author %>, MIT license
* https://bitbucket.org/sabo2/pzprv3 */
| sabo2/pzprv3 | src/js/common/banner_min.js | JavaScript | mit | 165 |
const test = require('tape')
const nlp = require('../_lib')
test('number-tag:', function (t) {
let arr = [
['16.125', 'Cardinal'],
['+160.125', 'Cardinal'],
['-0.1', 'Cardinal'],
['.13', 'Cardinal'],
['(127.54)', 'Cardinal'],
['16.125th', 'Ordinal'],
['161,253th', 'Ordinal'],
['+160.125th', 'Ordinal'],
['-0.2nd', 'Ordinal'],
['(127.54th)', 'Ordinal'],
// ['(127.54)', 'Money'],
['-0.1%', 'Percent'],
['.1%', 'Percent'],
['+2,340.91%', 'Percent'],
['-2340%', 'Percent'],
['$-2340.01', 'Money'],
['-$2340', 'Money'],
['+$2340.01', 'Money'],
['$2340.01', 'Money'],
['£1,000,000', 'Money'],
['$19', 'Money'],
['($127.54)', 'Money'],
['2,000₽', 'Money'],
['2000₱', 'Money'],
['2000௹', 'Money'],
['₼2000', 'Money'],
['2.23₽', 'Money'],
['₺50', 'Money'],
['$47.5m', 'Money'],
['$47.5bn', 'Money'],
// ['1,000,000p', 'Cardinal'],
]
arr.forEach(function (a) {
let doc = nlp(a[0])
t.equal(doc.has('#' + a[1]), true, a[0] + ' is #' + a[1])
})
t.end()
})
| nlp-compromise/nlp_compromise | tests/tagger/number.test.js | JavaScript | mit | 1,105 |
(function($) {
module("autocomplete: options");
test('setAttributes', function() {
var source = $('#autocomplete').autocomplete("option", "source");
equals(source.join(','), ['ActionScript','AppleScript','Asp','BASIC','C','C++','Clojure','COBOL','ColdFusion','Erlang','Fortran','Groovy','Haskell','Java','JavaScript','Lisp','Perl','PHP','Python','Ruby','Scala','Scheme'].join(','), 'Array property');
var autoFocus = $('#autocomplete').autocomplete("option", "autoFocus");
equals(autoFocus, true, 'Boolean property');
var appendTo = $('#autocomplete').autocomplete("option", "appendTo");
equals(appendTo, '#destination', 'String property');
var minLength = $('#autocomplete').autocomplete("option", "minLength");
equals(minLength, 2, 'Number property');
});
})(jQuery); | davecowart/jquery-ui-unobtrusive | tests/unit/autocomplete/autocomplete_attributes.js | JavaScript | mit | 795 |
'use strict'
const t = require('tap')
const test = t.test
const FindMyWay = require('../')
test('case insensitive static routes of level 1', t => {
t.plan(1)
const findMyWay = FindMyWay({
caseSensitive: false,
defaultRoute: (req, res) => {
t.fail('Should not be defaultRoute')
}
})
findMyWay.on('GET', '/woo', (req, res, params) => {
t.pass('we should be here')
})
findMyWay.lookup({ method: 'GET', url: '/WOO', headers: {} }, null)
})
test('case insensitive static routes of level 2', t => {
t.plan(1)
const findMyWay = FindMyWay({
caseSensitive: false,
defaultRoute: (req, res) => {
t.fail('Should not be defaultRoute')
}
})
findMyWay.on('GET', '/foo/woo', (req, res, params) => {
t.pass('we should be here')
})
findMyWay.lookup({ method: 'GET', url: '/FoO/WOO', headers: {} }, null)
})
test('case insensitive static routes of level 3', t => {
t.plan(1)
const findMyWay = FindMyWay({
caseSensitive: false,
defaultRoute: (req, res) => {
t.fail('Should not be defaultRoute')
}
})
findMyWay.on('GET', '/foo/bar/woo', (req, res, params) => {
t.pass('we should be here')
})
findMyWay.lookup({ method: 'GET', url: '/Foo/bAR/WoO', headers: {} }, null)
})
test('parametric case insensitive', t => {
t.plan(1)
const findMyWay = FindMyWay({
caseSensitive: false,
defaultRoute: (req, res) => {
t.fail('Should not be defaultRoute')
}
})
findMyWay.on('GET', '/foo/:param', (req, res, params) => {
t.equal(params.param, 'bAR')
})
findMyWay.lookup({ method: 'GET', url: '/Foo/bAR', headers: {} }, null)
})
test('parametric case insensitive with a static part', t => {
t.plan(1)
const findMyWay = FindMyWay({
caseSensitive: false,
defaultRoute: (req, res) => {
t.fail('Should not be defaultRoute')
}
})
findMyWay.on('GET', '/foo/my-:param', (req, res, params) => {
t.equal(params.param, 'bAR')
})
findMyWay.lookup({ method: 'GET', url: '/Foo/MY-bAR', headers: {} }, null)
})
test('parametric case insensitive with capital letter', t => {
t.plan(1)
const findMyWay = FindMyWay({
caseSensitive: false,
defaultRoute: (req, res) => {
t.fail('Should not be defaultRoute')
}
})
findMyWay.on('GET', '/foo/:Param', (req, res, params) => {
t.equal(params.Param, 'bAR')
})
findMyWay.lookup({ method: 'GET', url: '/Foo/bAR', headers: {} }, null)
})
test('case insensitive with capital letter in static path with param', t => {
t.plan(1)
const findMyWay = FindMyWay({
caseSensitive: false,
defaultRoute: (req, res) => {
t.fail('Should not be defaultRoute')
}
})
findMyWay.on('GET', '/Foo/bar/:param', (req, res, params) => {
t.equal(params.param, 'baZ')
})
findMyWay.lookup({ method: 'GET', url: '/foo/bar/baZ', headers: {} }, null)
})
test('case insensitive with multiple paths containing capital letter in static path with param', t => {
/*
* This is a reproduction of the issue documented at
* https://github.com/delvedor/find-my-way/issues/96.
*/
t.plan(2)
const findMyWay = FindMyWay({
caseSensitive: false,
defaultRoute: (req, res) => {
t.fail('Should not be defaultRoute')
}
})
findMyWay.on('GET', '/Foo/bar/:param', (req, res, params) => {
t.equal(params.param, 'baZ')
})
findMyWay.on('GET', '/Foo/baz/:param', (req, res, params) => {
t.equal(params.param, 'baR')
})
findMyWay.lookup({ method: 'GET', url: '/foo/bar/baZ', headers: {} }, null)
findMyWay.lookup({ method: 'GET', url: '/foo/baz/baR', headers: {} }, null)
})
test('case insensitive with multiple mixed-case params within same slash couple', t => {
t.plan(2)
const findMyWay = FindMyWay({
caseSensitive: false,
defaultRoute: (req, res) => {
t.fail('Should not be defaultRoute')
}
})
findMyWay.on('GET', '/foo/:param1-:param2', (req, res, params) => {
t.equal(params.param1, 'My')
t.equal(params.param2, 'bAR')
})
findMyWay.lookup({ method: 'GET', url: '/FOO/My-bAR', headers: {} }, null)
})
test('case insensitive with multiple mixed-case params', t => {
t.plan(2)
const findMyWay = FindMyWay({
caseSensitive: false,
defaultRoute: (req, res) => {
t.fail('Should not be defaultRoute')
}
})
findMyWay.on('GET', '/foo/:param1/:param2', (req, res, params) => {
t.equal(params.param1, 'My')
t.equal(params.param2, 'bAR')
})
findMyWay.lookup({ method: 'GET', url: '/FOO/My/bAR', headers: {} }, null)
})
test('case insensitive with wildcard', t => {
t.plan(1)
const findMyWay = FindMyWay({
caseSensitive: false,
defaultRoute: (req, res) => {
t.fail('Should not be defaultRoute')
}
})
findMyWay.on('GET', '/foo/*', (req, res, params) => {
t.equal(params['*'], 'baR')
})
findMyWay.lookup({ method: 'GET', url: '/FOO/baR', headers: {} }, null)
})
test('parametric case insensitive with multiple routes', t => {
t.plan(6)
const findMyWay = FindMyWay({
caseSensitive: false,
defaultRoute: (req, res) => {
t.fail('Should not be defaultRoute')
}
})
findMyWay.on('POST', '/foo/:param/Static/:userId/Save', (req, res, params) => {
t.equal(params.param, 'bAR')
t.equal(params.userId, 'one')
})
findMyWay.on('POST', '/foo/:param/Static/:userId/Update', (req, res, params) => {
t.equal(params.param, 'Bar')
t.equal(params.userId, 'two')
})
findMyWay.on('POST', '/foo/:param/Static/:userId/CANCEL', (req, res, params) => {
t.equal(params.param, 'bAR')
t.equal(params.userId, 'THREE')
})
findMyWay.lookup({ method: 'POST', url: '/foo/bAR/static/one/SAVE', headers: {} }, null)
findMyWay.lookup({ method: 'POST', url: '/fOO/Bar/Static/two/update', headers: {} }, null)
findMyWay.lookup({ method: 'POST', url: '/Foo/bAR/STATIC/THREE/cAnCeL', headers: {} }, null)
})
| delvedor/find-my-way | test/case-insensitive.test.js | JavaScript | mit | 5,906 |
var entityMap = {
"&": "&",
"<": "<",
">": ">",
'"': '"',
"'": ''',
"/": '/'
};
function escapeHTML(string) {
return String(string).replace(/[&<>"'\/]/g, function (s) {
return entityMap[s];
});
}
function escapeCodeBlocks() {
var sections = document.querySelectorAll('.page-section');
[].forEach.call(sections, function (section) {
var sectionCodeBlocks = section.querySelectorAll('.section-code');
if (sectionCodeBlocks.length) {
[].forEach.call(sectionCodeBlocks, function (codeBlock) {
codeBlock.innerHTML = escapeHTML(codeBlock.innerHTML);
})
}
});
}
function formatCodeBlocks() {
[].forEach.call(document.querySelectorAll('code'), function($code) {
var lines = $code.textContent.split('\n');
if (lines[0] === '') {
lines.shift()
}
var matches;
var indentation = (matches = /^[\s\t]+/.exec(lines[0])) !== null ? matches[0] : null;
if (!!indentation) {
lines = lines.map(function(line) {
line = line.replace(indentation, '')
return line.replace(/\t/g, ' ')
});
$code.textContent = lines.join('\n').trim();
}
});
}
function toggleMenu() {
}
function createMenu() {
var menuList = document.querySelector('.menu-list'),
menuItems = document.querySelectorAll('a[name]'),
menuToggle = document.querySelector('.menu-toggle');
menuToggle.addEventListener('click', function () {
var menu = document.querySelector('.menu');
if (menu.classList.contains('menu-open')) {
menu.classList.remove('menu-open');
this.classList.remove('menu-toggle-open');
} else {
menu.classList.add('menu-open');
this.classList.add('menu-toggle-open');
}
});
[].forEach.call(menuItems, function (menuItem) {
var menuText = menuItem.name.charAt(0).toUpperCase() + menuItem.name.slice(1);
var anchor = document.createElement('a');
anchor.href = '#' + menuText.toLowerCase();
var listItemEl = document.createElement('li');
listItemEl.classList.add('menu-list-item');
listItemEl.innerHTML = '<a class="menu-list-link" href="#' + menuText.toLowerCase() + '""><a>' + menuText;
menuList.appendChild(listItemEl)
});
}
(function init() {
createMenu();
escapeCodeBlocks();
formatCodeBlocks();
hljs.initHighlightingOnLoad();
})();
| kylealwyn/flexxed | example/index.js | JavaScript | mit | 2,396 |
'use es6';
const dotenv = require('dotenv');
const Lyft = require('./build/index');
dotenv.load();
const lyft = new Lyft(process.env.LYFT_CLIENT_ID, process.env.LYFT_CLIENT_SECRET);
const query = {
start: {
latitude: 37.7833,
longitude: -122.4167,
},
end: {
latitude: 37.7922,
longitude: -122.4012,
},
rideType: 'lyft_line',
};
lyft.getRideEstimates(query)
.then((result) => {
console.log(result);
})
.catch((error) => {
console.log(error);
});
| djchie/lyft-node | sandbox.js | JavaScript | mit | 494 |
;(function () {
'use strict';
angular.module('angularGAPI')
.factory('User', ['GAPI', userFact]);
function userFact(GAPI) {
var User = new GAPI('plus', 'v1', {});
User.getUserInfo = function(params) {
return User.get('people', 'me', undefined, params);
};
return User;
}
})();
| Quivr/angular-GAPI | lib/plugin/gapi.user.factory.js | JavaScript | mit | 314 |
import {
GET_POSTS,
GET_POST,
GET_POST_SLUG,
GET_TAGS,
GET_TAG,
GET_TAG_SLUG,
GET_USERS,
GET_USER,
GET_USER_SLUG,
RESET,
} from './action-types';
const initialData = { data: null, error: null, loading: false, meta: null };
const initialState = {
posts: initialData,
post: initialData,
tags: initialData,
tag: initialData,
users: initialData,
user: initialData,
};
const createStateHandler = (state, action) => (key) => {
const isSingle = !(key.substr(key.length - 1) === 's');
const statusHandlers = {
error: () => ({
...state,
[key]: {
...state[key],
data: null,
error: action.error || 'Unknown Error',
loading: false,
},
}),
loading: () => ({
...state,
[key]: {
...state[key],
loading: true,
error: null,
},
}),
success: () => ({
...state,
[key]: {
...state[key],
data: isSingle ? action.data[isSingle ? `${key}s` : key][0] : action.data[isSingle ? `${key}s` : key],
meta: action.data.meta || null,
error: null,
loading: false,
},
}),
};
return statusHandlers[action.status] ? statusHandlers[action.status]() : state;
};
const reducer = (state, action) => {
if (typeof state === 'undefined') {
return initialState;
}
const updateKey = createStateHandler(state, action);
const reducers = {
[GET_POSTS]: () => updateKey('posts'),
[GET_POST]: () => updateKey('post'),
[GET_POST_SLUG]: () => updateKey('post'),
[GET_TAGS]: () => updateKey('tags'),
[GET_TAG]: () => updateKey('tag'),
[GET_TAG_SLUG]: () => updateKey('tag'),
[GET_USERS]: () => updateKey('users'),
[GET_USER]: () => updateKey('user'),
[GET_USER_SLUG]: () => updateKey('user'),
[RESET]: () => ({
...initialState,
}),
};
return reducers[action.type] ? reducers[action.type]() : state;
};
export default reducer;
| oliverbenns/redux-ghost | src/reducer.js | JavaScript | mit | 1,962 |
// COPYRIGHT © 2017 Esri
//
// All rights reserved under the copyright laws of the United States
// and applicable international laws, treaties, and conventions.
//
// This material is licensed for use under the Esri Master License
// Agreement (MLA), and is bound by the terms of that agreement.
// You may redistribute and use this code without modification,
// provided you adhere to the terms of the MLA and include this
// copyright notice.
//
// See use restrictions at http://www.esri.com/legal/pdfs/mla_e204_e300/english
//
// For additional information, contact:
// Environmental Systems Research Institute, Inc.
// Attn: Contracts and Legal Services Department
// 380 New York Street
// Redlands, California, USA 92373
// USA
//
// email: contracts@esri.com
//
// See http://js.arcgis.com/4.4/esri/copyright.txt for details.
define(["require","exports","../../core/Warning","../PointCloudClassBreaksRenderer","../PointCloudRGBRenderer","../PointCloudStretchRenderer","../PointCloudUniqueValueRenderer"],function(e,r,n,o,t,u,d){function i(e){return e?a[e.type]||null:null}function l(e,r,o){var t=i(e);if(t){var u=new t;return u.read(e,o),u}return o&&o.messages&&e&&o.messages.push(new n("renderer:unsupported","Renderers of type '"+(e.type||"unknown")+"' are not supported",{definition:e,context:o})),null}function s(e){var r=i(e);return r?r.fromJSON(e):null}Object.defineProperty(r,"__esModule",{value:!0});var a={pointCloudClassBreaksRenderer:o,pointCloudRGBRenderer:t,pointCloudStretchRenderer:u,pointCloudUniqueValueRenderer:d};r.read=l,r.fromJSON=s}); | spencerhan/dojostudy | js/libs/arcgis-js-api/renderers/support/pointCloudJsonUtils.js | JavaScript | mit | 1,567 |
/**
* Created by gbaldeck on 4/17/2017.
*/
var prototype = Object.create(HTMLElement.prototype)
console.log("prototype: ", prototype) | PropaFramework/Propa | src/test/js/test.js | JavaScript | mit | 135 |
var fs = require('fs'),
path = require('path'),
cleanCSS = require('clean-css'),
rjs = require('requirejs');
module.exports = function(grunt) {
// **css* task works pretty much the same as grunt's min task. The task
// target is the destination, data is an array of glob patterns. These
// files are concataned and run through requirejs optimizer to handle
// @import inlines in CSS files.
grunt.task.registerMultiTask('css', 'Concats, replaces @imports and minifies the CSS files', function() {
this.requiresConfig('staging');
// if defined, files get prepended by the output config value
var files = this.data;
// subtarget name is the output destination
var target = this.target;
// async task
var cb = this.async();
// concat prior to rjs optimize css, and before min max info
grunt.log.write('Writing css files to ' + target + '...');
var out = grunt.helper('mincss', files);
// only go through if their's file to process
if(!out) {
return cb();
}
// write minified file before going through rjs:optimize to possibly inline
// @imports (that are not handled by compass within .scss or .sass files)
grunt.file.write(target, out);
// replace @import statements
//
// XXX no error handling in this helper so far..
// Check that rjs returns an error when something wrong (if it throws...)
// if it is bubble the error back here
grunt.helper('rjs:optimize:css', target, function() {
// do the minification once inline imports are done
grunt.log.ok();
cb();
});
});
//
// **mincss** basic utility to concat CSS files and run them through
// [cleanCSS](https://github.com/GoalSmashers/clean-css), might opt to use
// [https://github.com/jzaefferer/grunt-css] plugin.
//
grunt.registerHelper('mincss', function(files, o) {
o = o || {};
files = grunt.file.expandFiles(files);
return files.map(function(filepath) {
var content = grunt.file.read(filepath);
return o.nocompress ? content : cleanCSS.process(content);
}).join('');
});
// **rjs:optimize:css** is an helper using rjs to optimize a single file,
// mainly to properly import multi-level of @import statements, which can be
// tricky with all the url rewrites.
//
// file - Path to the css file to optimize
// options - (optional) rjs configuration
// cb - callback function to call on completion
grunt.registerHelper('rjs:optimize:css', function(file, options, cb) {
if(!cb) { cb = options; options = {}; }
options.cssIn = file;
options.out = options.out || file;
options.optimizeCss = 'standard.keepComments.keepLines';
var before = grunt.file.read(file);
rjs.optimize(options, function() {
grunt.helper('min_max_info', grunt.file.read(file), before);
cb();
});
});
};
| josephgvariam/jems | jems/node_modules/yeoman/tasks/css.js | JavaScript | mit | 2,885 |
// Place all the behaviors and hooks related to the matching controller here.
// All this logic will automatically be available in application.js.
/* fix vertical when not overflow
call fullscreenFix() if .fullscreen content changes */
function fullscreenFix(){
var h = $('body').height();
// set .fullscreen height
$(".content-b").each(function(i){
if($(this).innerHeight() <= h){
$(this).closest(".fullscreen").addClass("not-overflow");
}
});
}
$(window).resize(fullscreenFix);
fullscreenFix();
/* resize background images */
function backgroundResize(){
var windowH = $(window).height();
$(".background").each(function(i){
var path = $(this);
// variables
var contW = path.width();
var contH = path.height();
var imgW = path.attr("data-img-width");
var imgH = path.attr("data-img-height");
var ratio = imgW / imgH;
// overflowing difference
var diff = parseFloat(path.attr("data-diff"));
diff = diff ? diff : 0;
// remaining height to have fullscreen image only on parallax
var remainingH = 0;
if(path.hasClass("parallax")){
var maxH = contH > windowH ? contH : windowH;
remainingH = windowH - contH;
}
// set img values depending on cont
imgH = contH + remainingH + diff;
imgW = imgH * ratio;
// fix when too large
if(contW > imgW){
imgW = contW;
imgH = imgW / ratio;
}
//
path.data("resized-imgW", imgW);
path.data("resized-imgH", imgH);
path.css("background-size", imgW + "px " + imgH + "px");
});
}
$(window).resize(backgroundResize);
$(window).focus(backgroundResize);
backgroundResize(); | mynock/playlister | app/assets/javascripts/welcome.js | JavaScript | mit | 1,794 |
// PYRAMID
// Constants
const path = require("path");
const DATA_ROOT = path.join(__dirname, "..", "data");
module.exports = {
DEBUG: false,
FILE_ENCODING: "utf8",
PROJECT_ROOT: path.join(__dirname, ".."),
DATA_ROOT,
LOG_ROOT: path.join(__dirname, "..", "public", "data", "logs"),
DB_FILENAME: path.join(DATA_ROOT, "pyramid.db"),
RELATIONSHIP_NONE: 0,
RELATIONSHIP_FRIEND: 1,
RELATIONSHIP_BEST_FRIEND: 2,
CACHE_LINES: 150,
CONTEXT_CACHE_LINES: 40,
CONTEXT_CACHE_MINUTES: 60,
LAST_SEEN_UPDATE_RATE: 500,
LOG_PAGE_SIZE: 300,
BUNCHED_EVENT_SIZE: 50,
USER_MODIFYING_EVENT_TYPES:
["join", "part", "quit", "kick", "kill", "mode"],
PART_EVENT_TYPES:
["part", "quit", "kick", "kill"],
BUNCHABLE_EVENT_TYPES:
["join", "part", "quit", "kill", "mode"],
SUPPORTED_CATEGORY_NAMES: ["highlights", "allfriends", "system"],
TOKEN_COOKIE_NAME: "token",
TOKEN_COOKIE_SECONDS: 86400 * 365,
PAGE_TYPES: {
CATEGORY: "category",
CHANNEL: "channel",
USER: "user"
},
CONNECTION_STATUS: {
ABORTED: "aborted",
CONNECTED: "connected",
DISCONNECTED: "disconnected",
FAILED: "failed",
REJECTED: "rejected"
},
CHANNEL_TYPES: {
PUBLIC: 0,
PRIVATE: 1
},
USER_EVENT_VISIBILITY: {
OFF: 0,
COLLAPSE_PRESENCE: 1,
COLLAPSE_MESSAGES: 2,
SHOW_ALL: 3
},
RETAIN_DB_TYPES: {
LINES: 0,
DAYS: 1
}
};
| graulund/pyramid | server/constants.js | JavaScript | mit | 1,340 |
document.addEventListener('DOMContentLoaded', function() {
photoKeys = Object.keys(TRAVEL_PHOTOS);
function injectRandomPhotos() {
figures = document.getElementsByClassName('figure-placeholder');
[].forEach.call(figures, function(fig) {
var randomPhotoKey = photoKeys[Math.floor(Math.random() * photoKeys.length)];
var randomPhoto = TRAVEL_PHOTOS[randomPhotoKey];
var page = TRAVEL_PAGES[randomPhoto.pageKey];
fig.innerHTML = (
'<a href="' + page + '#' + randomPhoto.hash + '">' +
'<i style="background-image:url(\'/img/res/400/' + randomPhotoKey + '\')"></i>' +
'</a>');
});
}
shuffleButton = document.getElementById('shuffle-button');
shuffleButton.addEventListener('click', injectRandomPhotos);
injectRandomPhotos();
});
| schlosser/schlosser.io | _js/random-image.js | JavaScript | mit | 800 |
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* The Input Handler is bound to a specific Sprite and is responsible for managing all Input events on that Sprite.
* @class Phaser.InputHandler
* @constructor
* @param {Phaser.Sprite} sprite - The Sprite object to which this Input Handler belongs.
*/
Phaser.InputHandler = function (sprite) {
/**
* @property {Phaser.Sprite} sprite - The Sprite object to which this Input Handler belongs.
*/
this.sprite = sprite;
/**
* @property {Phaser.Game} game - A reference to the currently running game.
*/
this.game = sprite.game;
/**
* @property {boolean} enabled - If enabled the Input Handler will process input requests and monitor pointer activity.
* @default
*/
this.enabled = false;
/**
* The priorityID is used to determine which game objects should get priority when input events occur. For example if you have
* several Sprites that overlap, by default the one at the top of the display list is given priority for input events. You can
* stop this from happening by controlling the priorityID value. The higher the value, the more important they are considered to the Input events.
* @property {number} priorityID
* @default
*/
this.priorityID = 0;
/**
* @property {boolean} useHandCursor - On a desktop browser you can set the 'hand' cursor to appear when moving over the Sprite.
* @default
*/
this.useHandCursor = false;
/**
* @property {boolean} _setHandCursor - Did this Sprite trigger the hand cursor?
* @private
*/
this._setHandCursor = false;
/**
* @property {boolean} isDragged - true if the Sprite is being currently dragged.
* @default
*/
this.isDragged = false;
/**
* @property {boolean} allowHorizontalDrag - Controls if the Sprite is allowed to be dragged horizontally.
* @default
*/
this.allowHorizontalDrag = true;
/**
* @property {boolean} allowVerticalDrag - Controls if the Sprite is allowed to be dragged vertically.
* @default
*/
this.allowVerticalDrag = true;
/**
* @property {boolean} bringToTop - If true when this Sprite is clicked or dragged it will automatically be bought to the top of the Group it is within.
* @default
*/
this.bringToTop = false;
/**
* @property {Phaser.Point} snapOffset - A Point object that contains by how far the Sprite snap is offset.
* @default
*/
this.snapOffset = null;
/**
* @property {boolean} snapOnDrag - When the Sprite is dragged this controls if the center of the Sprite will snap to the pointer on drag or not.
* @default
*/
this.snapOnDrag = false;
/**
* @property {boolean} snapOnRelease - When the Sprite is dragged this controls if the Sprite will be snapped on release.
* @default
*/
this.snapOnRelease = false;
/**
* @property {number} snapX - When a Sprite has snapping enabled this holds the width of the snap grid.
* @default
*/
this.snapX = 0;
/**
* @property {number} snapY - When a Sprite has snapping enabled this holds the height of the snap grid.
* @default
*/
this.snapY = 0;
/**
* @property {number} snapOffsetX - This defines the top-left X coordinate of the snap grid.
* @default
*/
this.snapOffsetX = 0;
/**
* @property {number} snapOffsetY - This defines the top-left Y coordinate of the snap grid..
* @default
*/
this.snapOffsetY = 0;
/**
* Set to true to use pixel perfect hit detection when checking if the pointer is over this Sprite.
* The x/y coordinates of the pointer are tested against the image in combination with the InputHandler.pixelPerfectAlpha value.
* Warning: This is expensive, especially on mobile (where it's not even needed!) so only enable if required. Also see the less-expensive InputHandler.pixelPerfectClick.
* @property {number} pixelPerfectOver - Use a pixel perfect check when testing for pointer over.
* @default
*/
this.pixelPerfectOver = false;
/**
* Set to true to use pixel perfect hit detection when checking if the pointer is over this Sprite when it's clicked or touched.
* The x/y coordinates of the pointer are tested against the image in combination with the InputHandler.pixelPerfectAlpha value.
* Warning: This is expensive so only enable if you really need it.
* @property {number} pixelPerfectClick - Use a pixel perfect check when testing for clicks or touches on the Sprite.
* @default
*/
this.pixelPerfectClick = false;
/**
* @property {number} pixelPerfectAlpha - The alpha tolerance threshold. If the alpha value of the pixel matches or is above this value, it's considered a hit.
* @default
*/
this.pixelPerfectAlpha = 255;
/**
* @property {boolean} draggable - Is this sprite allowed to be dragged by the mouse? true = yes, false = no
* @default
*/
this.draggable = false;
/**
* @property {Phaser.Rectangle} boundsRect - A region of the game world within which the sprite is restricted during drag.
* @default
*/
this.boundsRect = null;
/**
* @property {Phaser.Sprite} boundsSprite - A Sprite the bounds of which this sprite is restricted during drag.
* @default
*/
this.boundsSprite = null;
/**
* If this object is set to consume the pointer event then it will stop all propogation from this object on.
* For example if you had a stack of 6 sprites with the same priority IDs and one consumed the event, none of the others would receive it.
* @property {boolean} consumePointerEvent
* @default
*/
this.consumePointerEvent = false;
/**
* @property {boolean} _wasEnabled - Internal cache var.
* @private
*/
this._wasEnabled = false;
/**
* @property {Phaser.Point} _tempPoint - Internal cache var.
* @private
*/
this._tempPoint = new Phaser.Point();
/**
* @property {array} _pointerData - Internal cache var.
* @private
*/
this._pointerData = [];
this._pointerData.push({
id: 0,
x: 0,
y: 0,
isDown: false,
isUp: false,
isOver: false,
isOut: false,
timeOver: 0,
timeOut: 0,
timeDown: 0,
timeUp: 0,
downDuration: 0,
isDragged: false
});
};
Phaser.InputHandler.prototype = {
/**
* Starts the Input Handler running. This is called automatically when you enable input on a Sprite, or can be called directly if you need to set a specific priority.
* @method Phaser.InputHandler#start
* @param {number} priority - Higher priority sprites take click priority over low-priority sprites when they are stacked on-top of each other.
* @param {boolean} useHandCursor - If true the Sprite will show the hand cursor on mouse-over (doesn't apply to mobile browsers)
* @return {Phaser.Sprite} The Sprite object to which the Input Handler is bound.
*/
start: function (priority, useHandCursor) {
priority = priority || 0;
if (typeof useHandCursor === 'undefined') { useHandCursor = false; }
// Turning on
if (this.enabled === false)
{
// Register, etc
this.game.input.interactiveItems.add(this);
this.useHandCursor = useHandCursor;
this.priorityID = priority;
for (var i = 0; i < 10; i++)
{
this._pointerData[i] = {
id: i,
x: 0,
y: 0,
isDown: false,
isUp: false,
isOver: false,
isOut: false,
timeOver: 0,
timeOut: 0,
timeDown: 0,
timeUp: 0,
downDuration: 0,
isDragged: false
};
}
this.snapOffset = new Phaser.Point();
this.enabled = true;
this._wasEnabled = true;
// Create the signals the Input component will emit
if (this.sprite.events && this.sprite.events.onInputOver === null)
{
this.sprite.events.onInputOver = new Phaser.Signal();
this.sprite.events.onInputOut = new Phaser.Signal();
this.sprite.events.onInputDown = new Phaser.Signal();
this.sprite.events.onInputUp = new Phaser.Signal();
this.sprite.events.onDragStart = new Phaser.Signal();
this.sprite.events.onDragStop = new Phaser.Signal();
}
}
this.sprite.events.onAddedToGroup.add(this.addedToGroup, this);
this.sprite.events.onRemovedFromGroup.add(this.removedFromGroup, this);
return this.sprite;
},
/**
* Handles when the parent Sprite is added to a new Group.
*
* @method Phaser.InputHandler#addedToGroup
* @private
*/
addedToGroup: function () {
if (this._wasEnabled && !this.enabled)
{
this.start();
}
},
/**
* Handles when the parent Sprite is removed from a Group.
*
* @method Phaser.InputHandler#removedFromGroup
* @private
*/
removedFromGroup: function () {
if (this.enabled)
{
this._wasEnabled = true;
this.stop();
}
else
{
this._wasEnabled = false;
}
},
/**
* Resets the Input Handler and disables it.
* @method Phaser.InputHandler#reset
*/
reset: function () {
this.enabled = false;
for (var i = 0; i < 10; i++)
{
this._pointerData[i] = {
id: i,
x: 0,
y: 0,
isDown: false,
isUp: false,
isOver: false,
isOut: false,
timeOver: 0,
timeOut: 0,
timeDown: 0,
timeUp: 0,
downDuration: 0,
isDragged: false
};
}
},
/**
* Stops the Input Handler from running.
* @method Phaser.InputHandler#stop
*/
stop: function () {
// Turning off
if (this.enabled === false)
{
return;
}
else
{
// De-register, etc
this.enabled = false;
this.game.input.interactiveItems.remove(this);
}
},
/**
* Clean up memory.
* @method Phaser.InputHandler#destroy
*/
destroy: function () {
if (this.sprite)
{
if (this._setHandCursor)
{
this.game.canvas.style.cursor = "default";
this._setHandCursor = false;
}
this.enabled = false;
this.game.input.interactiveItems.remove(this);
this._pointerData.length = 0;
this.boundsRect = null;
this.boundsSprite = null;
this.sprite = null;
}
},
/**
* Checks if the object this InputHandler is bound to is valid for consideration in the Pointer move event.
* This is called by Phaser.Pointer and shouldn't typically be called directly.
*
* @method Phaser.InputHandler#validForInput
* @protected
* @param {number} highestID - The highest ID currently processed by the Pointer.
* @param {number} highestRenderID - The highest Render Order ID currently processed by the Pointer.
* @return {boolean} True if the object this InputHandler is bound to should be considered as valid for input detection.
*/
validForInput: function (highestID, highestRenderID) {
if (this.sprite.scale.x === 0 || this.sprite.scale.y === 0)
{
return false;
}
if (this.pixelPerfectClick || this.pixelPerfectOver)
{
return true;
}
if (this.priorityID > highestID || (this.priorityID === highestID && this.sprite._cache[3] < highestRenderID))
{
return true;
}
return false;
},
/**
* The x coordinate of the Input pointer, relative to the top-left of the parent Sprite.
* This value is only set when the pointer is over this Sprite.
* @method Phaser.InputHandler#pointerX
* @param {Phaser.Pointer} pointer
* @return {number} The x coordinate of the Input pointer.
*/
pointerX: function (pointer) {
pointer = pointer || 0;
return this._pointerData[pointer].x;
},
/**
* The y coordinate of the Input pointer, relative to the top-left of the parent Sprite
* This value is only set when the pointer is over this Sprite.
* @method Phaser.InputHandler#pointerY
* @param {Phaser.Pointer} pointer
* @return {number} The y coordinate of the Input pointer.
*/
pointerY: function (pointer) {
pointer = pointer || 0;
return this._pointerData[pointer].y;
},
/**
* If the Pointer is touching the touchscreen, or the mouse button is held down, isDown is set to true.
* @method Phaser.InputHandler#pointerDown
* @param {Phaser.Pointer} pointer
* @return {boolean}
*/
pointerDown: function (pointer) {
pointer = pointer || 0;
return this._pointerData[pointer].isDown;
},
/**
* If the Pointer is not touching the touchscreen, or the mouse button is up, isUp is set to true
* @method Phaser.InputHandler#pointerUp
* @param {Phaser.Pointer} pointer
* @return {boolean}
*/
pointerUp: function (pointer) {
pointer = pointer || 0;
return this._pointerData[pointer].isUp;
},
/**
* A timestamp representing when the Pointer first touched the touchscreen.
* @method Phaser.InputHandler#pointerTimeDown
* @param {Phaser.Pointer} pointer
* @return {number}
*/
pointerTimeDown: function (pointer) {
pointer = pointer || 0;
return this._pointerData[pointer].timeDown;
},
/**
* A timestamp representing when the Pointer left the touchscreen.
* @method Phaser.InputHandler#pointerTimeUp
* @param {Phaser.Pointer} pointer
* @return {number}
*/
pointerTimeUp: function (pointer) {
pointer = pointer || 0;
return this._pointerData[pointer].timeUp;
},
/**
* Is the Pointer over this Sprite?
* @method Phaser.InputHandler#pointerOver
* @param {number} [index] - The ID number of a Pointer to check. If you don't provide a number it will check all Pointers.
* @return {boolean} True if the given pointer (if a index was given, or any pointer if not) is over this object.
*/
pointerOver: function (index) {
if (this.enabled)
{
if (typeof index === 'undefined')
{
for (var i = 0; i < 10; i++)
{
if (this._pointerData[i].isOver)
{
return true;
}
}
}
else
{
return this._pointerData[index].isOver;
}
}
return false;
},
/**
* Is the Pointer outside of this Sprite?
* @method Phaser.InputHandler#pointerOut
* @param {number} [index] - The ID number of a Pointer to check. If you don't provide a number it will check all Pointers.
* @return {boolean} True if the given pointer (if a index was given, or any pointer if not) is out of this object.
*/
pointerOut: function (index) {
if (this.enabled)
{
if (typeof index === 'undefined')
{
for (var i = 0; i < 10; i++)
{
if (this._pointerData[i].isOut)
{
return true;
}
}
}
else
{
return this._pointerData[index].isOut;
}
}
return false;
},
/**
* A timestamp representing when the Pointer first touched the touchscreen.
* @method Phaser.InputHandler#pointerTimeOver
* @param {Phaser.Pointer} pointer
* @return {number}
*/
pointerTimeOver: function (pointer) {
pointer = pointer || 0;
return this._pointerData[pointer].timeOver;
},
/**
* A timestamp representing when the Pointer left the touchscreen.
* @method Phaser.InputHandler#pointerTimeOut
* @param {Phaser.Pointer} pointer
* @return {number}
*/
pointerTimeOut: function (pointer) {
pointer = pointer || 0;
return this._pointerData[pointer].timeOut;
},
/**
* Is this sprite being dragged by the mouse or not?
* @method Phaser.InputHandler#pointerDragged
* @param {Phaser.Pointer} pointer
* @return {boolean} True if the pointer is dragging an object, otherwise false.
*/
pointerDragged: function (pointer) {
pointer = pointer || 0;
return this._pointerData[pointer].isDragged;
},
/**
* Checks if the given pointer is over this Sprite and can click it.
* @method Phaser.InputHandler#checkPointerDown
* @param {Phaser.Pointer} pointer
* @return {boolean} True if the pointer is down, otherwise false.
*/
checkPointerDown: function (pointer) {
if (!this.enabled || !this.sprite || !this.sprite.parent || !this.sprite.visible || !this.sprite.parent.visible)
{
return false;
}
// Need to pass it a temp point, in case we need it again for the pixel check
if (this.game.input.hitTest(this.sprite, pointer, this._tempPoint))
{
if (this.pixelPerfectClick)
{
return this.checkPixel(this._tempPoint.x, this._tempPoint.y);
}
else
{
return true;
}
}
return false;
},
/**
* Checks if the given pointer is over this Sprite.
* @method Phaser.InputHandler#checkPointerOver
* @param {Phaser.Pointer} pointer
* @return {boolean}
*/
checkPointerOver: function (pointer) {
if (!this.enabled || !this.sprite || !this.sprite.parent || !this.sprite.visible || !this.sprite.parent.visible)
{
return false;
}
// Need to pass it a temp point, in case we need it again for the pixel check
if (this.game.input.hitTest(this.sprite, pointer, this._tempPoint))
{
if (this.pixelPerfectOver)
{
return this.checkPixel(this._tempPoint.x, this._tempPoint.y);
}
else
{
return true;
}
}
return false;
},
/**
* Runs a pixel perfect check against the given x/y coordinates of the Sprite this InputHandler is bound to.
* It compares the alpha value of the pixel and if >= InputHandler.pixelPerfectAlpha it returns true.
* @method Phaser.InputHandler#checkPixel
* @param {number} x - The x coordinate to check.
* @param {number} y - The y coordinate to check.
* @param {Phaser.Pointer} [pointer] - The pointer to get the x/y coordinate from if not passed as the first two parameters.
* @return {boolean} true if there is the alpha of the pixel is >= InputHandler.pixelPerfectAlpha
*/
checkPixel: function (x, y, pointer) {
// Grab a pixel from our image into the hitCanvas and then test it
if (this.sprite.texture.baseTexture.source)
{
this.game.input.hitContext.clearRect(0, 0, 1, 1);
if (x === null && y === null)
{
// Use the pointer parameter
this.game.input.getLocalPosition(this.sprite, pointer, this._tempPoint);
var x = this._tempPoint.x;
var y = this._tempPoint.y;
}
if (this.sprite.anchor.x !== 0)
{
x -= -this.sprite.texture.frame.width * this.sprite.anchor.x;
}
if (this.sprite.anchor.y !== 0)
{
y -= -this.sprite.texture.frame.height * this.sprite.anchor.y;
}
x += this.sprite.texture.frame.x;
y += this.sprite.texture.frame.y;
this.game.input.hitContext.drawImage(this.sprite.texture.baseTexture.source, x, y, 1, 1, 0, 0, 1, 1);
var rgb = this.game.input.hitContext.getImageData(0, 0, 1, 1);
if (rgb.data[3] >= this.pixelPerfectAlpha)
{
return true;
}
}
return false;
},
/**
* Update.
* @method Phaser.InputHandler#update
* @protected
* @param {Phaser.Pointer} pointer
*/
update: function (pointer) {
if (this.sprite === null || this.sprite.parent === undefined)
{
// Abort. We've been destroyed.
return;
}
if (!this.enabled || !this.sprite.visible || !this.sprite.parent.visible)
{
this._pointerOutHandler(pointer);
return false;
}
if (this.draggable && this._draggedPointerID == pointer.id)
{
return this.updateDrag(pointer);
}
else if (this._pointerData[pointer.id].isOver === true)
{
if (this.checkPointerOver(pointer))
{
this._pointerData[pointer.id].x = pointer.x - this.sprite.x;
this._pointerData[pointer.id].y = pointer.y - this.sprite.y;
return true;
}
else
{
this._pointerOutHandler(pointer);
return false;
}
}
},
/**
* Internal method handling the pointer over event.
* @method Phaser.InputHandler#_pointerOverHandler
* @private
* @param {Phaser.Pointer} pointer
*/
_pointerOverHandler: function (pointer) {
if (this.sprite === null)
{
// Abort. We've been destroyed.
return;
}
if (this._pointerData[pointer.id].isOver === false)
{
this._pointerData[pointer.id].isOver = true;
this._pointerData[pointer.id].isOut = false;
this._pointerData[pointer.id].timeOver = this.game.time.now;
this._pointerData[pointer.id].x = pointer.x - this.sprite.x;
this._pointerData[pointer.id].y = pointer.y - this.sprite.y;
if (this.useHandCursor && this._pointerData[pointer.id].isDragged === false)
{
this.game.canvas.style.cursor = "pointer";
this._setHandCursor = true;
}
if (this.sprite && this.sprite.events)
{
this.sprite.events.onInputOver.dispatch(this.sprite, pointer);
}
}
},
/**
* Internal method handling the pointer out event.
* @method Phaser.InputHandler#_pointerOutHandler
* @private
* @param {Phaser.Pointer} pointer
*/
_pointerOutHandler: function (pointer) {
if (this.sprite === null)
{
// Abort. We've been destroyed.
return;
}
this._pointerData[pointer.id].isOver = false;
this._pointerData[pointer.id].isOut = true;
this._pointerData[pointer.id].timeOut = this.game.time.now;
if (this.useHandCursor && this._pointerData[pointer.id].isDragged === false)
{
this.game.canvas.style.cursor = "default";
this._setHandCursor = false;
}
if (this.sprite && this.sprite.events)
{
this.sprite.events.onInputOut.dispatch(this.sprite, pointer);
}
},
/**
* Internal method handling the touched event.
* @method Phaser.InputHandler#_touchedHandler
* @private
* @param {Phaser.Pointer} pointer
*/
_touchedHandler: function (pointer) {
if (this.sprite === null)
{
// Abort. We've been destroyed.
return;
}
if (this._pointerData[pointer.id].isDown === false && this._pointerData[pointer.id].isOver === true)
{
if (this.pixelPerfectClick && !this.checkPixel(null, null, pointer))
{
return;
}
this._pointerData[pointer.id].isDown = true;
this._pointerData[pointer.id].isUp = false;
this._pointerData[pointer.id].timeDown = this.game.time.now;
if (this.sprite && this.sprite.events)
{
this.sprite.events.onInputDown.dispatch(this.sprite, pointer);
}
// Start drag
if (this.draggable && this.isDragged === false)
{
this.startDrag(pointer);
}
if (this.bringToTop)
{
this.sprite.bringToTop();
}
}
// Consume the event?
return this.consumePointerEvent;
},
/**
* Internal method handling the pointer released event.
* @method Phaser.InputHandler#_releasedHandler
* @private
* @param {Phaser.Pointer} pointer
*/
_releasedHandler: function (pointer) {
if (this.sprite === null)
{
// Abort. We've been destroyed.
return;
}
// If was previously touched by this Pointer, check if still is AND still over this item
if (this._pointerData[pointer.id].isDown && pointer.isUp)
{
this._pointerData[pointer.id].isDown = false;
this._pointerData[pointer.id].isUp = true;
this._pointerData[pointer.id].timeUp = this.game.time.now;
this._pointerData[pointer.id].downDuration = this._pointerData[pointer.id].timeUp - this._pointerData[pointer.id].timeDown;
// Only release the InputUp signal if the pointer is still over this sprite
if (this.checkPointerOver(pointer))
{
// Release the inputUp signal and provide optional parameter if pointer is still over the sprite or not
if (this.sprite && this.sprite.events)
{
this.sprite.events.onInputUp.dispatch(this.sprite, pointer, true);
}
}
else
{
// Release the inputUp signal and provide optional parameter if pointer is still over the sprite or not
if (this.sprite && this.sprite.events)
{
this.sprite.events.onInputUp.dispatch(this.sprite, pointer, false);
}
// Pointer outside the sprite? Reset the cursor
if (this.useHandCursor)
{
this.game.canvas.style.cursor = "default";
this._setHandCursor = false;
}
}
// Stop drag
if (this.draggable && this.isDragged && this._draggedPointerID == pointer.id)
{
this.stopDrag(pointer);
}
}
},
/**
* Updates the Pointer drag on this Sprite.
* @method Phaser.InputHandler#updateDrag
* @param {Phaser.Pointer} pointer
* @return {boolean}
*/
updateDrag: function (pointer) {
if (pointer.isUp)
{
this.stopDrag(pointer);
return false;
}
if (this.sprite.fixedToCamera)
{
if (this.allowHorizontalDrag)
{
this.sprite.cameraOffset.x = pointer.x + this._dragPoint.x + this.dragOffset.x;
}
if (this.allowVerticalDrag)
{
this.sprite.cameraOffset.y = pointer.y + this._dragPoint.y + this.dragOffset.y;
}
if (this.boundsRect)
{
this.checkBoundsRect();
}
if (this.boundsSprite)
{
this.checkBoundsSprite();
}
if (this.snapOnDrag)
{
this.sprite.cameraOffset.x = Math.round((this.sprite.cameraOffset.x - (this.snapOffsetX % this.snapX)) / this.snapX) * this.snapX + (this.snapOffsetX % this.snapX);
this.sprite.cameraOffset.y = Math.round((this.sprite.cameraOffset.y - (this.snapOffsetY % this.snapY)) / this.snapY) * this.snapY + (this.snapOffsetY % this.snapY);
}
}
else
{
if (this.allowHorizontalDrag)
{
this.sprite.x = pointer.x + this._dragPoint.x + this.dragOffset.x;
}
if (this.allowVerticalDrag)
{
this.sprite.y = pointer.y + this._dragPoint.y + this.dragOffset.y;
}
if (this.boundsRect)
{
this.checkBoundsRect();
}
if (this.boundsSprite)
{
this.checkBoundsSprite();
}
if (this.snapOnDrag)
{
this.sprite.x = Math.round((this.sprite.x - (this.snapOffsetX % this.snapX)) / this.snapX) * this.snapX + (this.snapOffsetX % this.snapX);
this.sprite.y = Math.round((this.sprite.y - (this.snapOffsetY % this.snapY)) / this.snapY) * this.snapY + (this.snapOffsetY % this.snapY);
}
}
return true;
},
/**
* Returns true if the pointer has entered the Sprite within the specified delay time (defaults to 500ms, half a second)
* @method Phaser.InputHandler#justOver
* @param {Phaser.Pointer} pointer
* @param {number} delay - The time below which the pointer is considered as just over.
* @return {boolean}
*/
justOver: function (pointer, delay) {
pointer = pointer || 0;
delay = delay || 500;
return (this._pointerData[pointer].isOver && this.overDuration(pointer) < delay);
},
/**
* Returns true if the pointer has left the Sprite within the specified delay time (defaults to 500ms, half a second)
* @method Phaser.InputHandler#justOut
* @param {Phaser.Pointer} pointer
* @param {number} delay - The time below which the pointer is considered as just out.
* @return {boolean}
*/
justOut: function (pointer, delay) {
pointer = pointer || 0;
delay = delay || 500;
return (this._pointerData[pointer].isOut && (this.game.time.now - this._pointerData[pointer].timeOut < delay));
},
/**
* Returns true if the pointer has touched or clicked on the Sprite within the specified delay time (defaults to 500ms, half a second)
* @method Phaser.InputHandler#justPressed
* @param {Phaser.Pointer} pointer
* @param {number} delay - The time below which the pointer is considered as just over.
* @return {boolean}
*/
justPressed: function (pointer, delay) {
pointer = pointer || 0;
delay = delay || 500;
return (this._pointerData[pointer].isDown && this.downDuration(pointer) < delay);
},
/**
* Returns true if the pointer was touching this Sprite, but has been released within the specified delay time (defaults to 500ms, half a second)
* @method Phaser.InputHandler#justReleased
* @param {Phaser.Pointer} pointer
* @param {number} delay - The time below which the pointer is considered as just out.
* @return {boolean}
*/
justReleased: function (pointer, delay) {
pointer = pointer || 0;
delay = delay || 500;
return (this._pointerData[pointer].isUp && (this.game.time.now - this._pointerData[pointer].timeUp < delay));
},
/**
* If the pointer is currently over this Sprite this returns how long it has been there for in milliseconds.
* @method Phaser.InputHandler#overDuration
* @param {Phaser.Pointer} pointer
* @return {number} The number of milliseconds the pointer has been over the Sprite, or -1 if not over.
*/
overDuration: function (pointer) {
pointer = pointer || 0;
if (this._pointerData[pointer].isOver)
{
return this.game.time.now - this._pointerData[pointer].timeOver;
}
return -1;
},
/**
* If the pointer is currently over this Sprite this returns how long it has been there for in milliseconds.
* @method Phaser.InputHandler#downDuration
* @param {Phaser.Pointer} pointer
* @return {number} The number of milliseconds the pointer has been pressed down on the Sprite, or -1 if not over.
*/
downDuration: function (pointer) {
pointer = pointer || 0;
if (this._pointerData[pointer].isDown)
{
return this.game.time.now - this._pointerData[pointer].timeDown;
}
return -1;
},
/**
* Make this Sprite draggable by the mouse. You can also optionally set mouseStartDragCallback and mouseStopDragCallback
* @method Phaser.InputHandler#enableDrag
* @param {boolean} [lockCenter=false] - If false the Sprite will drag from where you click it minus the dragOffset. If true it will center itself to the tip of the mouse pointer.
* @param {boolean} [bringToTop=false] - If true the Sprite will be bought to the top of the rendering list in its current Group.
* @param {boolean} [pixelPerfect=false] - If true it will use a pixel perfect test to see if you clicked the Sprite. False uses the bounding box.
* @param {boolean} [alphaThreshold=255] - If using pixel perfect collision this specifies the alpha level from 0 to 255 above which a collision is processed.
* @param {Phaser.Rectangle} [boundsRect=null] - If you want to restrict the drag of this sprite to a specific Rectangle, pass the Phaser.Rectangle here, otherwise it's free to drag anywhere.
* @param {Phaser.Sprite} [boundsSprite=null] - If you want to restrict the drag of this sprite to within the bounding box of another sprite, pass it here.
*/
enableDrag: function (lockCenter, bringToTop, pixelPerfect, alphaThreshold, boundsRect, boundsSprite) {
if (typeof lockCenter == 'undefined') { lockCenter = false; }
if (typeof bringToTop == 'undefined') { bringToTop = false; }
if (typeof pixelPerfect == 'undefined') { pixelPerfect = false; }
if (typeof alphaThreshold == 'undefined') { alphaThreshold = 255; }
if (typeof boundsRect == 'undefined') { boundsRect = null; }
if (typeof boundsSprite == 'undefined') { boundsSprite = null; }
this._dragPoint = new Phaser.Point();
this.draggable = true;
this.bringToTop = bringToTop;
this.dragOffset = new Phaser.Point();
this.dragFromCenter = lockCenter;
this.pixelPerfect = pixelPerfect;
this.pixelPerfectAlpha = alphaThreshold;
if (boundsRect)
{
this.boundsRect = boundsRect;
}
if (boundsSprite)
{
this.boundsSprite = boundsSprite;
}
},
/**
* Stops this sprite from being able to be dragged. If it is currently the target of an active drag it will be stopped immediately. Also disables any set callbacks.
* @method Phaser.InputHandler#disableDrag
*/
disableDrag: function () {
if (this._pointerData)
{
for (var i = 0; i < 10; i++)
{
this._pointerData[i].isDragged = false;
}
}
this.draggable = false;
this.isDragged = false;
this._draggedPointerID = -1;
},
/**
* Called by Pointer when drag starts on this Sprite. Should not usually be called directly.
* @method Phaser.InputHandler#startDrag
* @param {Phaser.Pointer} pointer
*/
startDrag: function (pointer) {
this.isDragged = true;
this._draggedPointerID = pointer.id;
this._pointerData[pointer.id].isDragged = true;
if (this.sprite.fixedToCamera)
{
if (this.dragFromCenter)
{
this.sprite.centerOn(pointer.x, pointer.y);
this._dragPoint.setTo(this.sprite.cameraOffset.x - pointer.x, this.sprite.cameraOffset.y - pointer.y);
}
else
{
this._dragPoint.setTo(this.sprite.cameraOffset.x - pointer.x, this.sprite.cameraOffset.y - pointer.y);
}
}
else
{
if (this.dragFromCenter)
{
var bounds = this.sprite.getBounds();
this.sprite.x = pointer.x + (this.sprite.x - bounds.centerX);
this.sprite.y = pointer.y + (this.sprite.y - bounds.centerY);
this._dragPoint.setTo(this.sprite.x - pointer.x, this.sprite.y - pointer.y);
}
else
{
this._dragPoint.setTo(this.sprite.x - pointer.x, this.sprite.y - pointer.y);
}
}
this.updateDrag(pointer);
if (this.bringToTop)
{
this.sprite.bringToTop();
}
this.sprite.events.onDragStart.dispatch(this.sprite, pointer);
},
/**
* Called by Pointer when drag is stopped on this Sprite. Should not usually be called directly.
* @method Phaser.InputHandler#stopDrag
* @param {Phaser.Pointer} pointer
*/
stopDrag: function (pointer) {
this.isDragged = false;
this._draggedPointerID = -1;
this._pointerData[pointer.id].isDragged = false;
if (this.snapOnRelease)
{
if (this.sprite.fixedToCamera)
{
this.sprite.cameraOffset.x = Math.round((this.sprite.cameraOffset.x - (this.snapOffsetX % this.snapX)) / this.snapX) * this.snapX + (this.snapOffsetX % this.snapX);
this.sprite.cameraOffset.y = Math.round((this.sprite.cameraOffset.y - (this.snapOffsetY % this.snapY)) / this.snapY) * this.snapY + (this.snapOffsetY % this.snapY);
}
else
{
this.sprite.x = Math.round((this.sprite.x - (this.snapOffsetX % this.snapX)) / this.snapX) * this.snapX + (this.snapOffsetX % this.snapX);
this.sprite.y = Math.round((this.sprite.y - (this.snapOffsetY % this.snapY)) / this.snapY) * this.snapY + (this.snapOffsetY % this.snapY);
}
}
this.sprite.events.onDragStop.dispatch(this.sprite, pointer);
if (this.checkPointerOver(pointer) === false)
{
this._pointerOutHandler(pointer);
}
},
/**
* Restricts this sprite to drag movement only on the given axis. Note: If both are set to false the sprite will never move!
* @method Phaser.InputHandler#setDragLock
* @param {boolean} [allowHorizontal=true] - To enable the sprite to be dragged horizontally set to true, otherwise false.
* @param {boolean} [allowVertical=true] - To enable the sprite to be dragged vertically set to true, otherwise false.
*/
setDragLock: function (allowHorizontal, allowVertical) {
if (typeof allowHorizontal == 'undefined') { allowHorizontal = true; }
if (typeof allowVertical == 'undefined') { allowVertical = true; }
this.allowHorizontalDrag = allowHorizontal;
this.allowVerticalDrag = allowVertical;
},
/**
* Make this Sprite snap to the given grid either during drag or when it's released.
* For example 16x16 as the snapX and snapY would make the sprite snap to every 16 pixels.
* @method Phaser.InputHandler#enableSnap
* @param {number} snapX - The width of the grid cell to snap to.
* @param {number} snapY - The height of the grid cell to snap to.
* @param {boolean} [onDrag=true] - If true the sprite will snap to the grid while being dragged.
* @param {boolean} [onRelease=false] - If true the sprite will snap to the grid when released.
* @param {number} [snapOffsetX=0] - Used to offset the top-left starting point of the snap grid.
* @param {number} [snapOffsetX=0] - Used to offset the top-left starting point of the snap grid.
*/
enableSnap: function (snapX, snapY, onDrag, onRelease, snapOffsetX, snapOffsetY) {
if (typeof onDrag == 'undefined') { onDrag = true; }
if (typeof onRelease == 'undefined') { onRelease = false; }
if (typeof snapOffsetX == 'undefined') { snapOffsetX = 0; }
if (typeof snapOffsetY == 'undefined') { snapOffsetY = 0; }
this.snapX = snapX;
this.snapY = snapY;
this.snapOffsetX = snapOffsetX;
this.snapOffsetY = snapOffsetY;
this.snapOnDrag = onDrag;
this.snapOnRelease = onRelease;
},
/**
* Stops the sprite from snapping to a grid during drag or release.
* @method Phaser.InputHandler#disableSnap
*/
disableSnap: function () {
this.snapOnDrag = false;
this.snapOnRelease = false;
},
/**
* Bounds Rect check for the sprite drag
* @method Phaser.InputHandler#checkBoundsRect
*/
checkBoundsRect: function () {
if (this.sprite.fixedToCamera)
{
if (this.sprite.cameraOffset.x < this.boundsRect.left)
{
this.sprite.cameraOffset.x = this.boundsRect.cameraOffset.x;
}
else if ((this.sprite.cameraOffset.x + this.sprite.width) > this.boundsRect.right)
{
this.sprite.cameraOffset.x = this.boundsRect.right - this.sprite.width;
}
if (this.sprite.cameraOffset.y < this.boundsRect.top)
{
this.sprite.cameraOffset.y = this.boundsRect.top;
}
else if ((this.sprite.cameraOffset.y + this.sprite.height) > this.boundsRect.bottom)
{
this.sprite.cameraOffset.y = this.boundsRect.bottom - this.sprite.height;
}
}
else
{
if (this.sprite.x < this.boundsRect.left)
{
this.sprite.x = this.boundsRect.x;
}
else if ((this.sprite.x + this.sprite.width) > this.boundsRect.right)
{
this.sprite.x = this.boundsRect.right - this.sprite.width;
}
if (this.sprite.y < this.boundsRect.top)
{
this.sprite.y = this.boundsRect.top;
}
else if ((this.sprite.y + this.sprite.height) > this.boundsRect.bottom)
{
this.sprite.y = this.boundsRect.bottom - this.sprite.height;
}
}
},
/**
* Parent Sprite Bounds check for the sprite drag.
* @method Phaser.InputHandler#checkBoundsSprite
*/
checkBoundsSprite: function () {
if (this.sprite.fixedToCamera && this.boundsSprite.fixedToCamera)
{
if (this.sprite.cameraOffset.x < this.boundsSprite.camerOffset.x)
{
this.sprite.cameraOffset.x = this.boundsSprite.camerOffset.x;
}
else if ((this.sprite.cameraOffset.x + this.sprite.width) > (this.boundsSprite.camerOffset.x + this.boundsSprite.width))
{
this.sprite.cameraOffset.x = (this.boundsSprite.camerOffset.x + this.boundsSprite.width) - this.sprite.width;
}
if (this.sprite.cameraOffset.y < this.boundsSprite.camerOffset.y)
{
this.sprite.cameraOffset.y = this.boundsSprite.camerOffset.y;
}
else if ((this.sprite.cameraOffset.y + this.sprite.height) > (this.boundsSprite.camerOffset.y + this.boundsSprite.height))
{
this.sprite.cameraOffset.y = (this.boundsSprite.camerOffset.y + this.boundsSprite.height) - this.sprite.height;
}
}
else
{
if (this.sprite.x < this.boundsSprite.x)
{
this.sprite.x = this.boundsSprite.x;
}
else if ((this.sprite.x + this.sprite.width) > (this.boundsSprite.x + this.boundsSprite.width))
{
this.sprite.x = (this.boundsSprite.x + this.boundsSprite.width) - this.sprite.width;
}
if (this.sprite.y < this.boundsSprite.y)
{
this.sprite.y = this.boundsSprite.y;
}
else if ((this.sprite.y + this.sprite.height) > (this.boundsSprite.y + this.boundsSprite.height))
{
this.sprite.y = (this.boundsSprite.y + this.boundsSprite.height) - this.sprite.height;
}
}
}
};
Phaser.InputHandler.prototype.constructor = Phaser.InputHandler;
| BoldBigflank/attbee | src/input/InputHandler.js | JavaScript | mit | 45,014 |
var WorldClocks = {};
(function(w) {
function empty() {};
function msg(key, args) {
if (typeof(chrome) != "undefined" && typeof(chrome.i18n) != "undefined") {
return chrome.i18n.getMessage(key, args);
}
return key;
}
function setPref(key, value) {
try {
if (window.localStorage) {
localStorage[key] = value;
}
} catch (e) {
}
}
function getPref(key, defaultValue) {
var value = defaultValue;
try {
if (window.localStorage) {
value = localStorage[key] || defaultValue;
}
} catch (e) {
}
return value;
}
function log() {
console.log.apply(console, arguments);
}
w.msg = msg;
w.pref = {get:getPref, set:setPref};
w.log = (typeof(console) != "undefined" && typeof(console.log) != "undefined") ? log : empty;
})(WorldClocks);
| makotokw/world-clocks | src/worldclocks.safariextension/worldclocks.js | JavaScript | mit | 958 |
Cypress.Commands.add('fetchQuery', (query, variables) => {
cy.request({
url: '/graphql',
method: 'POST',
body: JSON.stringify({ query, variables }),
headers: {
'Content-Type': 'application/json'
}
});
});
| nomkhonwaan/nomkhonwaan.com | cypress/support/graphql.js | JavaScript | mit | 235 |
// This is the wrapper for custom tests, called upon web components ready state
function runCustomTests() {
// Place any setup steps like variable declaration and initialization here
// This is the placeholder suite to place custom tests in
// Use testCase(options) for a more convenient setup of the test cases
suite('Custom Automation Tests for px-validation', function() {
var px_validation = document.getElementById('px_validation_1');
suiteSetup(function(done){
flush(function(){
done();
});
});
test('Check there is a single px-validator child defined on test fixture', function(){
assert.lengthOf(Polymer.dom(px_validation).children, 1);
});
test('Integer isNumber validation returns true', function() {
assert.isTrue(px_validation.validate(2).passedValidation);
});
test('String representation of number via isNumber validation returns true', function() {
assert.isTrue(px_validation.validate('2').passedValidation);
});
});
}
| cityofsandiego/seaboard | src/assets/bower_components/px-validation/test/px-validation-custom-tests.js | JavaScript | mit | 1,022 |
import React from 'react';
class MyPropertiesExample extends React.Component {
render() {
return (
<div>
<h1>Properties</h1>
My favourite dish is {this.props.dish}.
</div>
);
}
}
MyPropertiesExample.defaultProps = {
dish: 'shrimp with pasta'
};
MyPropertiesExample.propTypes = {
dish: React.PropTypes.string.isRequired
};
class MyVodooComponent extends React.Component {
render() {
return (
<MyPropertiesExample dish="chicken"/>
);
}
}
export default MyPropertiesExample;
| sericaia/react-msf-demos | src/02-Properties.js | JavaScript | mit | 539 |
export App from './App'
export Home from './Home'
export List from './List'
export Login from './Login'
export Chats from './Chats'
| phoenixbox/react-redux-router-webpackhot | src/components/index.js | JavaScript | mit | 132 |
//Form JS File
function frmHome_stopWatch_onClick_seq0() {
alert("You clicked on stop watch");
};
function frmHome_button214149106640_onClick_seq0(eventobject) {
var a = frmHome.stopWatch.stopWatch();
alert(a);
};
function frmHome_button214149106641_onClick_seq0(eventobject) {
frmHome.stopWatch.startWatch();
};
function addWidgetsfrmHome() {
var stopWatch = new CustomStopWatch.StopWatch({
"id": "stopWatch",
"image": null,
"isVisible": true,
"hExpand": true,
"vExpand": false,
"textSize": 35,
"bgTransparancy": 0,
"onClick": frmHome_stopWatch_onClick_seq0
}, {
"widgetAlign": 5,
"containerWeight": 6,
"margin": [5, 5, 5, 5],
"marginInPixel": false,
"padding": [15, 15, 15, 15],
"paddingInPixel": false
}, {
"widgetName": "StopWatch"
});
var button214149106640 = new kony.ui.Button({
"id": "button214149106640",
"isVisible": true,
"text": "Stop Watch",
"skin": "sknBtnKonyThemeNormal",
"focusSkin": "sknBtnKonyThemeFocus",
"onClick": frmHome_button214149106640_onClick_seq0
}, {
"widgetAlignment": constants.WIDGET_ALIGN_CENTER,
"vExpand": false,
"hExpand": true,
"margin": [3, 2, 3, 2],
"padding": [2, 3, 2, 3],
"contentAlignment": constants.CONTENT_ALIGN_CENTER,
"displayText": true,
"marginInPixel": false,
"paddingInPixel": false,
"containerWeight": 6
}, {
"glowEffect": false,
"showProgressIndicator": true
});
var button214149106641 = new kony.ui.Button({
"id": "button214149106641",
"isVisible": true,
"text": "Start Watch",
"skin": "sknBtnKonyThemeNormal",
"focusSkin": "sknBtnKonyThemeFocus",
"onClick": frmHome_button214149106641_onClick_seq0
}, {
"widgetAlignment": constants.WIDGET_ALIGN_CENTER,
"vExpand": false,
"hExpand": true,
"margin": [3, 2, 3, 2],
"padding": [2, 3, 2, 3],
"contentAlignment": constants.CONTENT_ALIGN_CENTER,
"displayText": true,
"marginInPixel": false,
"paddingInPixel": false,
"containerWeight": 6
}, {
"glowEffect": false,
"showProgressIndicator": true
});
frmHome.add(
stopWatch, button214149106640, button214149106641);
};
function frmHomeGlobals() {
var MenuId = [];
frmHome = new kony.ui.Form2({
"id": "frmHome",
"needAppMenu": true,
"title": "StopWatch",
"enabledForIdleTimeout": false,
"skin": "frm",
"addWidgets": addWidgetsfrmHome
}, {
"padding": [0, 0, 0, 0],
"displayOrientation": constants.FORM_DISPLAY_ORIENTATION_PORTRAIT,
"paddingInPixel": false,
"layoutType": constants.CONTAINER_LAYOUT_BOX
}, {
"retainScrollPosition": false,
"needsIndicatorDuringPostShow": true,
"formTransparencyDuringPostShow": "100",
"inputAccessoryViewType": constants.FORM_INPUTACCESSORYVIEW_DEFAULT,
"bounces": true,
"configureExtendTop": false,
"configureExtendBottom": false,
"configureStatusBarStyle": false,
"titleBar": true,
"titleBarSkin": "titleBar",
"titleBarConfig": {
"renderTitleText": true,
"titleBarRightSideView": "title",
"titleBarLeftSideView": "none",
"closureRightSideView": navigateToSettings,
"labelRightSideView": "Settings"
},
"footerOverlap": false,
"headerOverlap": false,
"inTransitionConfig": {
"transitionDirection": "none",
"transitionEffect": "none"
},
"outTransitionConfig": {
"transitionDirection": "none",
"transitionEffect": "none"
},
"deprecated": {
"titleBarBackGroundImage": "blue_pixel.png"
}
});
}; | kony/Custom-stopwatch-widget | StopWatchApp/jssrc/iphone/generated/frmHome.js | JavaScript | mit | 4,030 |
// Generated by CoffeeScript 1.4.0
/* 2D Vector
*/
var Vector;
Vector = (function() {
/* Adds two vectors and returns the product.
*/
Vector.add = function(v1, v2) {
return new Vector(v1.x + v2.x, v1.y + v2.y);
};
/* Subtracts v2 from v1 and returns the product.
*/
Vector.sub = function(v1, v2) {
return new Vector(v1.x - v2.x, v1.y - v2.y);
};
/* Projects one vector (v1) onto another (v2)
*/
Vector.project = function(v1, v2) {
return v1.clone().scale((v1.dot(v2)) / v1.magSq());
};
/* Creates a new Vector instance.
*/
function Vector(x, y) {
this.x = x != null ? x : 0.0;
this.y = y != null ? y : 0.0;
}
/* Sets the components of this vector.
*/
Vector.prototype.set = function(x, y) {
this.x = x;
this.y = y;
return this;
};
/* Add a vector to this one.
*/
Vector.prototype.add = function(v) {
this.x += v.x;
this.y += v.y;
return this;
};
/* Subtracts a vector from this one.
*/
Vector.prototype.sub = function(v) {
this.x -= v.x;
this.y -= v.y;
return this;
};
/* Scales this vector by a value.
*/
Vector.prototype.scale = function(f) {
this.x *= f;
this.y *= f;
return this;
};
/* Computes the dot product between vectors.
*/
Vector.prototype.dot = function(v) {
return this.x * v.x + this.y * v.y;
};
/* Computes the cross product between vectors.
*/
Vector.prototype.cross = function(v) {
return (this.x * v.y) - (this.y * v.x);
};
/* Computes the magnitude (length).
*/
Vector.prototype.mag = function() {
return Math.sqrt(this.x * this.x + this.y * this.y);
};
/* Computes the squared magnitude (length).
*/
Vector.prototype.magSq = function() {
return this.x * this.x + this.y * this.y;
};
/* Computes the distance to another vector.
*/
Vector.prototype.dist = function(v) {
var dx, dy;
dx = v.x - this.x;
dy = v.y - this.y;
return Math.sqrt(dx * dx + dy * dy);
};
/* Computes the squared distance to another vector.
*/
Vector.prototype.distSq = function(v) {
var dx, dy;
dx = v.x - this.x;
dy = v.y - this.y;
return dx * dx + dy * dy;
};
/* Normalises the vector, making it a unit vector (of length 1).
*/
Vector.prototype.norm = function() {
var m;
m = Math.sqrt(this.x * this.x + this.y * this.y);
this.x /= m;
this.y /= m;
return this;
};
/* Limits the vector length to a given amount.
*/
Vector.prototype.limit = function(l) {
var m, mSq;
mSq = this.x * this.x + this.y * this.y;
if (mSq > l * l) {
m = Math.sqrt(mSq);
this.x /= m;
this.y /= m;
this.x *= l;
this.y *= l;
return this;
}
};
/* Copies components from another vector.
*/
Vector.prototype.copy = function(v) {
this.x = v.x;
this.y = v.y;
return this;
};
/* Clones this vector to a new itentical one.
*/
Vector.prototype.clone = function() {
return new Vector(this.x, this.y);
};
/* Resets the vector to zero.
*/
Vector.prototype.clear = function() {
this.x = 0.0;
this.y = 0.0;
return this;
};
return Vector;
})();
| hems/-labs | compiled/math/Vector.js | JavaScript | mit | 3,225 |
'use strict';
const Utils = require('./utils');
const _ = require('lodash');
const DataTypes = require('./data-types');
const SQLiteQueryInterface = require('./dialects/sqlite/query-interface');
const MSSSQLQueryInterface = require('./dialects/mssql/query-interface');
const MySQLQueryInterface = require('./dialects/mysql/query-interface');
const Transaction = require('./transaction');
const Promise = require('./promise');
const QueryTypes = require('./query-types');
/**
* The interface that Sequelize uses to talk to all databases
* @class QueryInterface
* @private
*/
class QueryInterface {
constructor(sequelize) {
this.sequelize = sequelize;
this.QueryGenerator = this.sequelize.dialect.QueryGenerator;
}
createSchema(schema, options) {
options = options || {};
const sql = this.QueryGenerator.createSchema(schema);
return this.sequelize.query(sql, options);
}
dropSchema(schema, options) {
options = options || {};
const sql = this.QueryGenerator.dropSchema(schema);
return this.sequelize.query(sql, options);
}
dropAllSchemas(options) {
options = options || {};
if (!this.QueryGenerator._dialect.supports.schemas) {
return this.sequelize.drop(options);
} else {
return this.showAllSchemas(options).map(schemaName => this.dropSchema(schemaName, options));
}
}
showAllSchemas(options) {
options = _.assign({}, options, {
raw: true,
type: this.sequelize.QueryTypes.SELECT
});
const showSchemasSql = this.QueryGenerator.showSchemasQuery();
return this.sequelize.query(showSchemasSql, options).then(schemaNames => Utils._.flatten(
Utils._.map(schemaNames, value => (!!value.schema_name ? value.schema_name : value))
));
}
databaseVersion(options) {
return this.sequelize.query(
this.QueryGenerator.versionQuery(),
_.assign({}, options, { type: QueryTypes.VERSION })
);
}
createTable(tableName, attributes, options, model) {
const keys = Object.keys(attributes);
const keyLen = keys.length;
let sql = '';
let i = 0;
options = _.clone(options) || {};
attributes = Utils._.mapValues(attributes, attribute => {
if (!Utils._.isPlainObject(attribute)) {
attribute = { type: attribute, allowNull: true };
}
attribute = this.sequelize.normalizeAttribute(attribute);
return attribute;
});
// Postgres requires a special SQL command for enums
if (this.sequelize.options.dialect === 'postgres') {
const promises = [];
for (i = 0; i < keyLen; i++) {
if (attributes[keys[i]].type instanceof DataTypes.ENUM) {
sql = this.QueryGenerator.pgListEnums(tableName, attributes[keys[i]].field || keys[i], options);
promises.push(this.sequelize.query(
sql,
_.assign({}, options, { plain: true, raw: true, type: QueryTypes.SELECT })
));
}
}
return Promise.all(promises).then(results => {
const promises = [];
let enumIdx = 0;
for (i = 0; i < keyLen; i++) {
if (attributes[keys[i]].type instanceof DataTypes.ENUM) {
// If the enum type doesn't exist then create it
if (!results[enumIdx]) {
sql = this.QueryGenerator.pgEnum(tableName, attributes[keys[i]].field || keys[i], attributes[keys[i]], options);
promises.push(this.sequelize.query(
sql,
_.assign({}, options, { raw: true })
));
} else if (!!results[enumIdx] && !!model) {
const enumVals = this.QueryGenerator.fromArray(results[enumIdx].enum_value);
const vals = model.rawAttributes[keys[i]].values;
vals.forEach((value, idx) => {
// reset out after/before options since it's for every enum value
const valueOptions = _.clone(options);
valueOptions.before = null;
valueOptions.after = null;
if (enumVals.indexOf(value) === -1) {
if (!!vals[idx + 1]) {
valueOptions.before = vals[idx + 1];
}
else if (!!vals[idx - 1]) {
valueOptions.after = vals[idx - 1];
}
valueOptions.supportsSearchPath = false;
promises.push(this.sequelize.query(this.QueryGenerator.pgEnumAdd(tableName, keys[i], value, valueOptions), valueOptions));
}
});
enumIdx++;
}
}
}
if (!tableName.schema &&
(options.schema || (!!model && model._schema))) {
tableName = this.QueryGenerator.addSchema({
tableName,
_schema: (!!model && model._schema) || options.schema
});
}
attributes = this.QueryGenerator.attributesToSQL(attributes, {
context: 'createTable'
});
sql = this.QueryGenerator.createTableQuery(tableName, attributes, options);
return Promise.all(promises).then(() => {
return this.sequelize.query(sql, options);
});
});
} else {
if (!tableName.schema &&
(options.schema || (!!model && model._schema))) {
tableName = this.QueryGenerator.addSchema({
tableName,
_schema: (!!model && model._schema) || options.schema
});
}
attributes = this.QueryGenerator.attributesToSQL(attributes, {
context: 'createTable'
});
sql = this.QueryGenerator.createTableQuery(tableName, attributes, options);
return this.sequelize.query(sql, options);
}
}
dropTable(tableName, options) {
// if we're forcing we should be cascading unless explicitly stated otherwise
options = _.clone(options) || {};
options.cascade = options.cascade || options.force || false;
let sql = this.QueryGenerator.dropTableQuery(tableName, options);
return this.sequelize.query(sql, options).then(() => {
const promises = [];
// Since postgres has a special case for enums, we should drop the related
// enum type within the table and attribute
if (this.sequelize.options.dialect === 'postgres') {
const instanceTable = this.sequelize.modelManager.getModel(tableName, { attribute: 'tableName' });
if (!!instanceTable) {
const getTableName = (!options || !options.schema || options.schema === 'public' ? '' : options.schema + '_') + tableName;
const keys = Object.keys(instanceTable.rawAttributes);
const keyLen = keys.length;
for (let i = 0; i < keyLen; i++) {
if (instanceTable.rawAttributes[keys[i]].type instanceof DataTypes.ENUM) {
sql = this.QueryGenerator.pgEnumDrop(getTableName, keys[i]);
options.supportsSearchPath = false;
promises.push(this.sequelize.query(sql, _.assign({}, options, { raw: true })));
}
}
}
}
return Promise.all(promises).get(0);
});
}
dropAllTables(options) {
options = options || {};
const skip = options.skip || [];
const dropAllTables = tableNames => Promise.each(tableNames, tableName => {
// if tableName is not in the Array of tables names then dont drop it
if (skip.indexOf(tableName.tableName || tableName) === -1) {
return this.dropTable(tableName, _.assign({}, options, { cascade: true }) );
}
});
return this.showAllTables(options).then(tableNames => {
if (this.sequelize.options.dialect === 'sqlite') {
return this.sequelize.query('PRAGMA foreign_keys;', options).then(result => {
const foreignKeysAreEnabled = result.foreign_keys === 1;
if (foreignKeysAreEnabled) {
return this.sequelize.query('PRAGMA foreign_keys = OFF', options)
.then(() => dropAllTables(tableNames))
.then(() => this.sequelize.query('PRAGMA foreign_keys = ON', options));
} else {
return dropAllTables(tableNames);
}
});
} else {
return this.getForeignKeysForTables(tableNames, options).then(foreignKeys => {
const promises = [];
tableNames.forEach(tableName => {
let normalizedTableName = tableName;
if (Utils._.isObject(tableName)) {
normalizedTableName = tableName.schema + '.' + tableName.tableName;
}
foreignKeys[normalizedTableName].forEach(foreignKey => {
const sql = this.QueryGenerator.dropForeignKeyQuery(tableName, foreignKey);
promises.push(this.sequelize.query(sql, options));
});
});
return Promise.all(promises).then(() => dropAllTables(tableNames));
});
}
});
}
dropAllEnums(options) {
if (this.sequelize.getDialect() !== 'postgres') {
return Promise.resolve();
}
options = options || {};
return this.pgListEnums(null, options).map(result => this.sequelize.query(
this.QueryGenerator.pgEnumDrop(null, null, this.QueryGenerator.pgEscapeAndQuote(result.enum_name)),
_.assign({}, options, { raw: true })
));
}
pgListEnums(tableName, options) {
options = options || {};
const sql = this.QueryGenerator.pgListEnums(tableName);
return this.sequelize.query(sql, _.assign({}, options, { plain: false, raw: true, type: QueryTypes.SELECT }));
}
renameTable(before, after, options) {
options = options || {};
const sql = this.QueryGenerator.renameTableQuery(before, after);
return this.sequelize.query(sql, options);
}
showAllTables(options) {
options = _.assign({}, options, {
raw: true,
type: QueryTypes.SHOWTABLES
});
let showTablesSql = null;
if (options.schema)
showTablesSql = this.QueryGenerator.showTablesQuery(options.schema);
else
showTablesSql = this.QueryGenerator.showTablesQuery();
return this.sequelize.query(showTablesSql, options).then(tableNames => Utils._.flatten(tableNames));
}
describeTable(tableName, options) {
let schema = null;
let schemaDelimiter = null;
if (typeof options === 'string') {
schema = options;
} else if (typeof options === 'object' && options !== null) {
schema = options.schema || null;
schemaDelimiter = options.schemaDelimiter || null;
}
if (typeof tableName === 'object' && tableName !== null) {
schema = tableName.schema;
tableName = tableName.tableName;
}
const sql = this.QueryGenerator.describeTableQuery(tableName, schema, schemaDelimiter);
return this.sequelize.query(
sql,
_.assign({}, options, { type: QueryTypes.DESCRIBE })
).then(data => {
// If no data is returned from the query, then the table name may be wrong.
// Query generators that use information_schema for retrieving table info will just return an empty result set,
// it will not throw an error like built-ins do (e.g. DESCRIBE on MySql).
if (Utils._.isEmpty(data)) {
return Promise.reject('No description found for "' + tableName + '" table. Check the table name and schema; remember, they _are_ case sensitive.');
} else {
return Promise.resolve(data);
}
});
}
addColumn(table, key, attribute, options) {
if (!table || !key || !attribute) {
throw new Error('addColumn takes atleast 3 arguments (table, attribute name, attribute definition)');
}
options = options || {};
attribute = this.sequelize.normalizeAttribute(attribute);
return this.sequelize.query(this.QueryGenerator.addColumnQuery(table, key, attribute), options);
}
removeColumn(tableName, attributeName, options) {
options = options || {};
switch (this.sequelize.options.dialect) {
case 'sqlite':
// sqlite needs some special treatment as it cannot drop a column
return SQLiteQueryInterface.removeColumn.call(this, tableName, attributeName, options);
case 'mssql':
// mssql needs special treatment as it cannot drop a column with a default or foreign key constraint
return MSSSQLQueryInterface.removeColumn.call(this, tableName, attributeName, options);
case 'mysql':
// mysql needs special treatment as it cannot drop a column with a foreign key constraint
return MySQLQueryInterface.removeColumn.call(this, tableName, attributeName, options);
default:
return this.sequelize.query(this.QueryGenerator.removeColumnQuery(tableName, attributeName), options);
}
}
changeColumn(tableName, attributeName, dataTypeOrOptions, options) {
const attributes = {};
options = options || {};
if (Utils._.values(DataTypes).indexOf(dataTypeOrOptions) > -1) {
attributes[attributeName] = { type: dataTypeOrOptions, allowNull: true };
} else {
attributes[attributeName] = dataTypeOrOptions;
}
attributes[attributeName].type = this.sequelize.normalizeDataType(attributes[attributeName].type);
if (this.sequelize.options.dialect === 'sqlite') {
// sqlite needs some special treatment as it cannot change a column
return SQLiteQueryInterface.changeColumn.call(this, tableName, attributes, options);
} else {
const query = this.QueryGenerator.attributesToSQL(attributes);
const sql = this.QueryGenerator.changeColumnQuery(tableName, query);
return this.sequelize.query(sql, options);
}
}
renameColumn(tableName, attrNameBefore, attrNameAfter, options) {
options = options || {};
return this.describeTable(tableName, options).then(data => {
data = data[attrNameBefore] || {};
const _options = {};
_options[attrNameAfter] = {
attribute: attrNameAfter,
type: data.type,
allowNull: data.allowNull,
defaultValue: data.defaultValue
};
// fix: a not-null column cannot have null as default value
if (data.defaultValue === null && !data.allowNull) {
delete _options[attrNameAfter].defaultValue;
}
if (this.sequelize.options.dialect === 'sqlite') {
// sqlite needs some special treatment as it cannot rename a column
return SQLiteQueryInterface.renameColumn.call(this, tableName, attrNameBefore, attrNameAfter, options);
} else {
const sql = this.QueryGenerator.renameColumnQuery(
tableName,
attrNameBefore,
this.QueryGenerator.attributesToSQL(_options)
);
return this.sequelize.query(sql, options);
}
});
}
addIndex(tableName, attributes, options, rawTablename) {
// Support for passing tableName, attributes, options or tableName, options (with a fields param which is the attributes)
if (!Array.isArray(attributes)) {
rawTablename = options;
options = attributes;
attributes = options.fields;
}
// testhint argsConform.end
if (!rawTablename) {
// Map for backwards compat
rawTablename = tableName;
}
options = Utils.cloneDeep(options);
options.fields = attributes;
const sql = this.QueryGenerator.addIndexQuery(tableName, options, rawTablename);
return this.sequelize.query(sql, _.assign({}, options, { supportsSearchPath: false }));
}
showIndex(tableName, options) {
const sql = this.QueryGenerator.showIndexesQuery(tableName, options);
return this.sequelize.query(sql, _.assign({}, options, { type: QueryTypes.SHOWINDEXES }));
}
nameIndexes(indexes, rawTablename) {
return this.QueryGenerator.nameIndexes(indexes, rawTablename);
}
getForeignKeysForTables(tableNames, options) {
options = options || {};
if (tableNames.length === 0) {
return Promise.resolve({});
}
return Promise.map(tableNames, tableName =>
this.sequelize.query(this.QueryGenerator.getForeignKeysQuery(tableName, this.sequelize.config.database), options).get(0)
).then(results => {
const result = {};
tableNames.forEach((tableName, i) => {
if (Utils._.isObject(tableName)) {
tableName = tableName.schema + '.' + tableName.tableName;
}
result[tableName] = Utils._.compact(results[i]).map(r => r.constraint_name);
});
return result;
});
}
removeIndex(tableName, indexNameOrAttributes, options) {
options = options || {};
const sql = this.QueryGenerator.removeIndexQuery(tableName, indexNameOrAttributes);
return this.sequelize.query(sql, options);
}
insert(instance, tableName, values, options) {
options = Utils.cloneDeep(options);
options.hasTrigger = instance && instance.constructor.options.hasTrigger;
const sql = this.QueryGenerator.insertQuery(tableName, values, instance && instance.constructor.rawAttributes, options);
options.type = QueryTypes.INSERT;
options.instance = instance;
return this.sequelize.query(sql, options).then(results => {
if (instance) results[0].isNewRecord = false;
return results;
});
}
upsert(tableName, valuesByField, updateValues, where, model, options) {
const wheres = [];
const attributes = Object.keys(valuesByField);
let indexes = [];
let indexFields;
options = _.clone(options);
if (!Utils._.isEmpty(where)) {
wheres.push(where);
}
// Lets combine uniquekeys and indexes into one
indexes = Utils._.map(model.options.uniqueKeys, value => {
return value.fields;
});
Utils._.each(model.options.indexes, value => {
if (value.unique === true) {
// fields in the index may both the strings or objects with an attribute property - lets sanitize that
indexFields = Utils._.map(value.fields, field => {
if (Utils._.isPlainObject(field)) {
return field.attribute;
}
return field;
});
indexes.push(indexFields);
}
});
for (const index of indexes) {
if (Utils._.intersection(attributes, index).length === index.length) {
where = {};
for (const field of index) {
where[field] = valuesByField[field];
}
wheres.push(where);
}
}
where = { $or: wheres };
options.type = QueryTypes.UPSERT;
options.raw = true;
const sql = this.QueryGenerator.upsertQuery(tableName, valuesByField, updateValues, where, model.rawAttributes, options);
return this.sequelize.query(sql, options).then(rowCount => {
if (rowCount === undefined) {
return rowCount;
}
// MySQL returns 1 for inserted, 2 for updated http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html. Postgres has been modded to do the same
return rowCount === 1;
});
}
bulkInsert(tableName, records, options, attributes) {
options = _.clone(options) || {};
options.type = QueryTypes.INSERT;
const sql = this.QueryGenerator.bulkInsertQuery(tableName, records, options, attributes);
return this.sequelize.query(sql, options).then(results => results[0]);
}
update(instance, tableName, values, identifier, options) {
options = _.clone(options || {});
options.hasTrigger = !!(instance && instance._modelOptions && instance._modelOptions.hasTrigger);
const sql = this.QueryGenerator.updateQuery(tableName, values, identifier, options, instance.constructor.rawAttributes);
let restrict = false;
options.type = QueryTypes.UPDATE;
// Check for a restrict field
if (instance.constructor && instance.constructor.associations) {
const keys = Object.keys(instance.constructor.associations);
const length = keys.length;
for (let i = 0; i < length; i++) {
if (instance.constructor.associations[keys[i]].options && instance.constructor.associations[keys[i]].options.onUpdate && instance.constructor.associations[keys[i]].options.onUpdate === 'restrict') {
restrict = true;
}
}
}
options.instance = instance;
return this.sequelize.query(sql, options);
}
bulkUpdate(tableName, values, identifier, options, attributes) {
options = Utils.cloneDeep(options);
if (typeof identifier === 'object') identifier = Utils.cloneDeep(identifier);
const sql = this.QueryGenerator.updateQuery(tableName, values, identifier, options, attributes);
const table = Utils._.isObject(tableName) ? tableName : { tableName };
const model = Utils._.find(this.sequelize.modelManager.models, { tableName: table.tableName });
options.model = model;
return this.sequelize.query(sql, options);
}
delete(instance, tableName, identifier, options) {
const cascades = [];
const sql = this.QueryGenerator.deleteQuery(tableName, identifier, null, instance.constructor);
options = _.clone(options) || {};
// Check for a restrict field
if (!!instance.constructor && !!instance.constructor.associations) {
const keys = Object.keys(instance.constructor.associations);
const length = keys.length;
let association;
for (let i = 0; i < length; i++) {
association = instance.constructor.associations[keys[i]];
if (association.options && association.options.onDelete &&
association.options.onDelete.toLowerCase() === 'cascade' &&
association.options.useHooks === true) {
cascades.push(association.accessors.get);
}
}
}
return Promise.each(cascades, cascade => {
return instance[cascade](options).then(instances => {
// Check for hasOne relationship with non-existing associate ("has zero")
if (!instances) {
return Promise.resolve();
}
if (!Array.isArray(instances)) instances = [instances];
return Promise.each(instances, instance => instance.destroy(options));
});
}).then(() => {
options.instance = instance;
return this.sequelize.query(sql, options);
});
}
bulkDelete(tableName, identifier, options, model) {
options = Utils.cloneDeep(options);
options = _.defaults(options, {limit: null});
if (typeof identifier === 'object') identifier = Utils.cloneDeep(identifier);
const sql = this.QueryGenerator.deleteQuery(tableName, identifier, options, model);
return this.sequelize.query(sql, options);
}
select(model, tableName, options) {
options = Utils.cloneDeep(options);
options.type = QueryTypes.SELECT;
options.model = model;
return this.sequelize.query(
this.QueryGenerator.selectQuery(tableName, options, model),
options
);
}
increment(instance, tableName, values, identifier, options) {
const sql = this.QueryGenerator.arithmeticQuery('+', tableName, values, identifier, options.attributes);
options = _.clone(options) || {};
options.type = QueryTypes.UPDATE;
options.instance = instance;
return this.sequelize.query(sql, options);
}
decrement(instance, tableName, values, identifier, options) {
const sql = this.QueryGenerator.arithmeticQuery('-', tableName, values, identifier, options.attributes);
options = _.clone(options) || {};
options.type = QueryTypes.UPDATE;
options.instance = instance;
return this.sequelize.query(sql, options);
}
rawSelect(tableName, options, attributeSelector, Model) {
if (options.schema) {
tableName = this.QueryGenerator.addSchema({
tableName,
_schema: options.schema
});
}
options = Utils.cloneDeep(options);
options = _.defaults(options, {
raw: true,
plain: true,
type: QueryTypes.SELECT
});
const sql = this.QueryGenerator.selectQuery(tableName, options, Model);
if (attributeSelector === undefined) {
throw new Error('Please pass an attribute selector!');
}
return this.sequelize.query(sql, options).then(data => {
if (!options.plain) {
return data;
}
let result = data ? data[attributeSelector] : null;
if (options && options.dataType) {
const dataType = options.dataType;
if (dataType instanceof DataTypes.DECIMAL || dataType instanceof DataTypes.FLOAT) {
result = parseFloat(result);
} else if (dataType instanceof DataTypes.INTEGER || dataType instanceof DataTypes.BIGINT) {
result = parseInt(result, 10);
} else if (dataType instanceof DataTypes.DATE) {
if (!Utils._.isNull(result) && !Utils._.isDate(result)) {
result = new Date(result);
}
} else if (dataType instanceof DataTypes.STRING) {
// Nothing to do, result is already a string.
}
}
return result;
});
}
createTrigger(tableName, triggerName, timingType, fireOnArray, functionName, functionParams, optionsArray, options) {
const sql = this.QueryGenerator.createTrigger(tableName, triggerName, timingType, fireOnArray, functionName, functionParams, optionsArray);
options = options || {};
if (sql) {
return this.sequelize.query(sql, options);
} else {
return Promise.resolve();
}
}
dropTrigger(tableName, triggerName, options) {
const sql = this.QueryGenerator.dropTrigger(tableName, triggerName);
options = options || {};
if (sql) {
return this.sequelize.query(sql, options);
} else {
return Promise.resolve();
}
}
renameTrigger(tableName, oldTriggerName, newTriggerName, options) {
const sql = this.QueryGenerator.renameTrigger(tableName, oldTriggerName, newTriggerName);
options = options || {};
if (sql) {
return this.sequelize.query(sql, options);
} else {
return Promise.resolve();
}
}
createFunction(functionName, params, returnType, language, body, options) {
const sql = this.QueryGenerator.createFunction(functionName, params, returnType, language, body, options);
options = options || {};
if (sql) {
return this.sequelize.query(sql, options);
} else {
return Promise.resolve();
}
}
dropFunction(functionName, params, options) {
const sql = this.QueryGenerator.dropFunction(functionName, params);
options = options || {};
if (sql) {
return this.sequelize.query(sql, options);
} else {
return Promise.resolve();
}
}
renameFunction(oldFunctionName, params, newFunctionName, options) {
const sql = this.QueryGenerator.renameFunction(oldFunctionName, params, newFunctionName);
options = options || {};
if (sql) {
return this.sequelize.query(sql, options);
} else {
return Promise.resolve();
}
}
// Helper methods useful for querying
/**
* Escape an identifier (e.g. a table or attribute name). If force is true,
* the identifier will be quoted even if the `quoteIdentifiers` option is
* false.
* @private
*/
quoteIdentifier(identifier, force) {
return this.QueryGenerator.quoteIdentifier(identifier, force);
}
quoteTable(identifier) {
return this.QueryGenerator.quoteTable(identifier);
}
/**
* Split an identifier into .-separated tokens and quote each part.
* If force is true, the identifier will be quoted even if the
* `quoteIdentifiers` option is false.
* @private
*/
quoteIdentifiers(identifiers, force) {
return this.QueryGenerator.quoteIdentifiers(identifiers, force);
}
/**
* Escape a value (e.g. a string, number or date)
* @private
*/
escape(value) {
return this.QueryGenerator.escape(value);
}
setAutocommit(transaction, value, options) {
if (!transaction || !(transaction instanceof Transaction)) {
throw new Error('Unable to set autocommit for a transaction without transaction object!');
}
if (transaction.parent) {
// Not possible to set a seperate isolation level for savepoints
return Promise.resolve();
}
options = _.assign({}, options, {
transaction: transaction.parent || transaction
});
const sql = this.QueryGenerator.setAutocommitQuery(value, {
parent: transaction.parent
});
if (!sql) return Promise.resolve();
return this.sequelize.query(sql, options);
}
setIsolationLevel(transaction, value, options) {
if (!transaction || !(transaction instanceof Transaction)) {
throw new Error('Unable to set isolation level for a transaction without transaction object!');
}
if (transaction.parent || !value) {
// Not possible to set a seperate isolation level for savepoints
return Promise.resolve();
}
options = _.assign({}, options, {
transaction: transaction.parent || transaction
});
const sql = this.QueryGenerator.setIsolationLevelQuery(value, {
parent: transaction.parent
});
if (!sql) return Promise.resolve();
return this.sequelize.query(sql, options);
}
startTransaction(transaction, options) {
if (!transaction || !(transaction instanceof Transaction)) {
throw new Error('Unable to start a transaction without transaction object!');
}
options = _.assign({}, options, {
transaction: transaction.parent || transaction
});
options.transaction.name = transaction.parent ? transaction.name : undefined;
const sql = this.QueryGenerator.startTransactionQuery(transaction);
return this.sequelize.query(sql, options);
}
deferConstraints(transaction, options) {
options = _.assign({}, options, {
transaction: transaction.parent || transaction
});
const sql = this.QueryGenerator.deferConstraintsQuery(options);
if (sql) {
return this.sequelize.query(sql, options);
}
return Promise.resolve();
}
commitTransaction(transaction, options) {
if (!transaction || !(transaction instanceof Transaction)) {
throw new Error('Unable to commit a transaction without transaction object!');
}
if (transaction.parent) {
// Savepoints cannot be committed
return Promise.resolve();
}
options = _.assign({}, options, {
transaction: transaction.parent || transaction,
supportsSearchPath: false
});
const sql = this.QueryGenerator.commitTransactionQuery(transaction);
const promise = this.sequelize.query(sql, options);
transaction.finished = 'commit';
return promise;
}
rollbackTransaction(transaction, options) {
if (!transaction || !(transaction instanceof Transaction)) {
throw new Error('Unable to rollback a transaction without transaction object!');
}
options = _.assign({}, options, {
transaction: transaction.parent || transaction,
supportsSearchPath: false
});
options.transaction.name = transaction.parent ? transaction.name : undefined;
const sql = this.QueryGenerator.rollbackTransactionQuery(transaction);
const promise = this.sequelize.query(sql, options);
transaction.finished = 'rollback';
return promise;
}
}
module.exports = QueryInterface;
module.exports.QueryInterface = QueryInterface;
module.exports.default = QueryInterface;
| darwinserrano/sequelize | lib/query-interface.js | JavaScript | mit | 31,070 |
'use strict'
const t = require('tcomb')
const fetch = require('node-fetch')
const { requestProperties, validateResponse, parseJSON } = require('../utils')
const PATH = '/designs'
module.exports = function getDesign(id) {
t.String(id)
return new Promise((resolve, reject) => {
const { href, headers } = requestProperties(
this.token, this.version, [PATH, id].join('/')
)
fetch(href, { headers })
.then(validateResponse)
.then(parseJSON)
.then(resolve)
.catch(reject)
})
}
| auttoio/typeform-node | lib/designs/read.js | JavaScript | mit | 524 |
'use strict';
const appErrorsFactory = require('../../app-errors/app-errors-factory');
/**
*
*/
function setup(req, res, next) {
if (!req.currentUser) {
next(appErrorsFactory.createAppError({ statusCode: 401 }));
}
else {
next();
}
}
module.exports = setup;
| pmajoras/pgp-logs | api/middlewares/general-middlewares/must-authorize.js | JavaScript | mit | 278 |
/*global $, google, InfoBox */
var simulation_manager = (function(){
google.maps.visualRefresh = true;
var ua_is_mobile = navigator.userAgent.indexOf('iPhone') !== -1 || navigator.userAgent.indexOf('Android') !== -1;
var config = (function(){
var params = {};
return {
init: function() {
$.ajax({
url: 'static/js/config.js',
dataType: 'json',
async: false,
success: function(config_params) {
params = config_params;
// Override config with the QS params
var url_parts = window.location.href.split('?');
if (url_parts.length === 2) {
var qs_groups = url_parts[1].split('&');
$.each(qs_groups, function(index, qs_group){
var qs_parts = qs_group.split('=');
var key = qs_parts[0];
// Backwards compatibility
switch (key) {
case 'zoom':
key = 'zoom.start';
break;
case 'x':
key = 'center.x';
break;
case 'y':
key = 'center.y';
break;
}
var param_value = decodeURIComponent(qs_parts[1]);
params[key] = param_value;
});
}
},
error: function(a) {
alert('Broken JSON in static/js/config.js');
}
});
},
getParam: function(key) {
return (typeof params[key] === 'undefined') ? null : params[key];
}
};
})();
var map = null;
var simulation_vehicles = {};
var listener_helpers = (function(){
var listeners = {};
function notify(type) {
if (typeof listeners[type] === 'undefined') {
return;
}
$.each(listeners[type], function(i, fn){
fn();
});
}
function subscribe(type, fn) {
if (typeof listeners[type] === 'undefined') {
listeners[type] = [];
}
listeners[type].push(fn);
}
return {
notify: notify,
subscribe: subscribe
};
})();
var stationsPool = (function(){
var stations = {};
function get(id) {
return (typeof stations[id]) === 'undefined' ? '' : stations[id].get('name');
}
function location_get(id) {
return (typeof stations[id]) === 'undefined' ? '' : stations[id].get('location');
}
function addFeatures(features) {
$.each(features, function(index, feature) {
var station_id, station_name;
if (typeof(feature.properties.stop_id) === 'undefined') {
// Custom GeoJSON support
station_id = feature.properties.station_id;
station_name = feature.properties.name;
} else {
// GTFS support
station_id = feature.properties.stop_id;
station_name = feature.properties.stop_name;
}
var station = new google.maps.MVCObject();
station.set('name', station_name);
var station_x = parseFloat(feature.geometry.coordinates[0]);
var station_y = parseFloat(feature.geometry.coordinates[1]);
station.set('location', new google.maps.LatLng(station_y, station_x));
stations[station_id] = station;
});
}
return {
get: get,
addFeatures: addFeatures,
location_get: location_get
};
})();
// Routes manager.
// Roles:
// - keep a reference for the routes between stations
// i.e. (Zürich HB-Bern, Zürich HB-Olten, Olten-Bern)
// Note: one route can contain one or more edges (the low-level entity in the simulation graph)
// - interpolate position at given percent along a route
var linesPool = (function() {
var network_lines = {};
var routes = {};
var route_highlight = new google.maps.Polyline({
path: [],
strokeColor: "white",
strokeOpacity: 0.8,
strokeWeight: 3,
map: null,
icons: [{
icon: {
path: 'M 0,-2 0,2',
strokeColor: 'black',
strokeOpacity: 1.0
},
repeat: '40px'
}],
timer: null
});
// TODO - that can be a nice feature request for google.maps.geometry lib
function positionOnRouteAtPercentGet(ab_edges, percent) {
function routeIsDetailedAtPercent() {
for (var k=0; k<route.detailed_parts.length; k++) {
if ((percent >= route.detailed_parts[k].start) && (percent < route.detailed_parts[k].end)) {
return true;
}
}
return false;
}
var route = routes[ab_edges];
var dAC = route.length*percent;
var is_detailed = map_helpers.isDetailView() ? routeIsDetailedAtPercent() : false;
var position_data = positionDataGet(route, dAC, is_detailed);
if (position_data !== null) {
position_data.is_detailed = is_detailed;
}
return position_data;
}
function routeAdd(ab_edges) {
if (typeof routes[ab_edges] !== 'undefined') {
return;
}
var edges = ab_edges.split(',');
var routePoints = [];
var dAB = 0;
$.each(edges, function(k, edgeID) {
if (edgeID.substr(0, 1) === '-') {
edgeID = edgeID.substr(1);
var points = network_lines[edgeID]?network_lines[edgeID].points.slice().reverse():[];
} else {
var points = network_lines[edgeID]?network_lines[edgeID].points: [];
}
routePoints = routePoints.concat(points);
dAB += network_lines[edgeID]? network_lines[edgeID].length: 0;
});
var routeDetailedParts = [];
var routeDetailedParts_i = 0;
var is_detailed_prev = false;
var dAC = 0;
$.each(edges, function(k, edgeID) {
if (edgeID.substr(0, 1) === '-') {
edgeID = edgeID.substr(1);
}
var is_detailed = network_lines[edgeID] && network_lines[edgeID].is_detailed;
if (is_detailed) {
if (is_detailed_prev === false) {
routeDetailedParts[routeDetailedParts_i] = {
start: dAC / dAB,
end: 1
};
}
} else {
if (is_detailed_prev) {
routeDetailedParts[routeDetailedParts_i].end = dAC / dAB;
routeDetailedParts_i += 1;
}
}
is_detailed_prev = is_detailed;
dAC += network_lines[edgeID] ? network_lines[edgeID].length :0;
});
var route = {
points: routePoints,
length: dAB,
detailed_parts: routeDetailedParts
};
routes[ab_edges] = route;
}
function lengthGet(ab_edges) {
return routes[ab_edges].length;
}
function routeHighlight(vehicle) {
var points = [];
if (vehicle.source === 'gtfs') {
points = routes[vehicle.shape_id].points;
} else {
$.each(vehicle.edges, function(k, ab_edges){
if (k === 0) { return; }
points = points.concat(routes[ab_edges].points);
});
}
route_highlight.setPath(points);
route_highlight.setMap(map);
var icon_offset = 0;
route_highlight.set('timer', setInterval(function(){
if (icon_offset > 39) {
icon_offset = 0;
} else {
icon_offset += 2;
}
var icons = route_highlight.get('icons');
icons[0].offset = icon_offset + 'px';
route_highlight.set('icons', icons);
}, 20));
}
function routeHighlightRemove() {
route_highlight.setMap(null);
clearInterval(route_highlight.get('timer'));
}
function loadEncodedEdges(edges) {
$.each(edges, function(edge_id, encoded_edge) {
network_lines[edge_id] = {
points: google.maps.geometry.encoding.decodePath(encoded_edge),
is_detailed: false
};
});
}
function loadGeoJSONEdges(features) {
$.each(features, function(index, feature) {
var edge_coords = [];
$.each(feature.geometry.coordinates, function(i2, feature_coord){
edge_coords.push(new google.maps.LatLng(feature_coord[1], feature_coord[0]));
});
var edge_id = feature.properties.edge_id || feature.properties.shape_id;
network_lines[edge_id] = {
points: edge_coords,
is_detailed: feature.properties.detailed === 'yes',
length: parseFloat(google.maps.geometry.spherical.computeLength(edge_coords).toFixed(3))
};
});
}
function loadGeoJSONShapes(features) {
$.each(features, function(index, feature) {
var shape_id = feature.properties.shape_id;
var points = [];
$.each(feature.geometry.coordinates, function(i2, feature_coord){
points.push(new google.maps.LatLng(feature_coord[1], feature_coord[0]));
});
var dAB = parseFloat(google.maps.geometry.spherical.computeLength(points).toFixed(3));
var route = {
points: points,
length: dAB,
detailed_parts: []
};
routes[shape_id] = route;
});
}
function positionDataGet(route, dAC, is_detailed) {
var dC = 0;
for (var i=1; i<route.points.length; i++) {
var pA = route.points[i-1];
var pB = route.points[i];
var d12 = google.maps.geometry.spherical.computeDistanceBetween(pA, pB);
if ((dC + d12) > dAC) {
var data = {
position: google.maps.geometry.spherical.interpolate(pA, pB, (dAC - dC)/d12)
};
if (is_detailed) {
data.heading = google.maps.geometry.spherical.computeHeading(pA, pB);
}
return data;
}
dC += d12;
}
return null;
}
function projectDistanceAlongRoute(ab_edges, dAC) {
var route = routes[ab_edges];
return positionDataGet(route, dAC, true);
}
return {
positionGet: positionOnRouteAtPercentGet,
routeAdd: routeAdd,
lengthGet: lengthGet,
routeHighlight: routeHighlight,
routeHighlightRemove: routeHighlightRemove,
loadEncodedEdges: loadEncodedEdges,
loadGeoJSONEdges: loadGeoJSONEdges,
loadGeoJSONShapes: loadGeoJSONShapes,
projectDistanceAlongRoute: projectDistanceAlongRoute
};
})();
// Time manager
// Roles:
// - manages the current number of seconds that passed since midnight
var timer = (function(){
var timer_refresh = 100;
var ts_midnight = null;
var ts_now = null;
var ts_minute = null;
var seconds_multiply = null;
function init() {
(function(){
var d = new Date();
var hms = config.getParam('hms');
// Demo data is set for 9 AM
if (config.getParam('api_paths.trips') === 'api/demo/trips.json') {
hms = '09:00:00';
}
if (hms !== null) {
var hms_matches = hms.match(/^([0-9]{2}):([0-9]{2}):([0-9]{2})$/);
if (hms_matches) {
d.setHours(parseInt(hms_matches[1], 10));
d.setMinutes(parseInt(hms_matches[2], 10));
d.setSeconds(parseInt(hms_matches[3], 10));
}
}
ts_now = d.getTime() / 1000;
d.setHours(0);
d.setMinutes(0);
d.setSeconds(0);
d.setMilliseconds(0);
ts_midnight = d.getTime() / 1000;
})();
seconds_multiply = parseFloat($('#time_multiply').val());
$('#time_multiply').change(function(){
seconds_multiply = parseInt($(this).val(), 10);
});
var timeContainer = $('#day_time');
function timeIncrement() {
var d_now = new Date(ts_now * 1000);
var ts_minute_new = d_now.getMinutes();
if (ts_minute !== ts_minute_new) {
if (ts_minute !== null) {
listener_helpers.notify('minute_changed');
}
ts_minute = ts_minute_new;
}
timeContainer.text(getHMS());
ts_now += (timer_refresh / 1000) * seconds_multiply;
setTimeout(timeIncrement, timer_refresh);
}
timeIncrement();
}
function pad2Dec(what) {
return (what < 10 ? '0' + what : what);
}
function getHMS(ts) {
ts = ts || ts_now;
var d = new Date(ts * 1000);
var hours = pad2Dec(d.getHours());
var minutes = pad2Dec(d.getMinutes());
var seconds = pad2Dec(d.getSeconds());
return hours + ':' + minutes + ':' + seconds;
}
return {
init: init,
getTS: function(ts) {
return ts_now;
},
getHM: function(ts) {
var hms = getHMS(ts);
return hms.substring(0, 2) + ':' + hms.substring(3, 5);
},
getTSMidnight: function() {
return ts_midnight;
},
getRefreshValue: function() {
return timer_refresh;
},
getHMS2TS: function(hms) {
var hms_parts = hms.split(':');
var hours = parseInt(hms_parts[0], 10);
var minutes = parseInt(hms_parts[1], 10);
var seconds = parseInt(hms_parts[2], 10);
return ts_midnight + hours * 3600 + minutes * 60 + seconds;
}
};
})();
var simulation_panel = (function(){
var selected_vehicle = null;
function Toggler(el_id) {
var el = $(el_id);
el.attr('data-value-original', el.val());
var subscriber_types = {
'enable': [function(){
el.addClass('toggled');
el.val(el.attr('data-value-toggle'));
}],
'disable': [function(){
el.removeClass('toggled');
el.val(el.attr('data-value-original'));
}]
};
this.subscriber_types = subscriber_types;
el.click(function(){
var subscribers = el.hasClass('toggled') ? subscriber_types.disable : subscriber_types.enable;
$.each(subscribers, function(index, fn){
fn();
});
});
}
Toggler.prototype.subscribe = function(type, fn) {
this.subscriber_types[type].push(fn);
};
Toggler.prototype.trigger = function(type) {
$.each(this.subscriber_types[type], function(index, fn){
fn();
});
};
var vehicle_follow = (function(){
listener_helpers.subscribe('map_init', function(){
function stop_following() {
if (selected_vehicle === null) {
return;
}
stop();
}
google.maps.event.addListener(map, 'dragstart', stop_following);
google.maps.event.addListener(map, 'click', stop_following);
google.maps.event.addListener(map, 'dblclick', stop_following);
});
var toggler;
function init() {
toggler = new Toggler('#follow_trigger');
toggler.subscribe('enable', function(){
selected_vehicle.marker.set('follow', 'yes-init');
});
toggler.subscribe('disable', function(){
if (selected_vehicle) {
selected_vehicle.marker.set('follow', 'no');
}
map.unbind('center');
});
}
function start(vehicle) {
selected_vehicle = vehicle;
toggler.trigger('enable');
}
function stop() {
toggler.trigger('disable');
}
return {
init: init,
start: start,
stop: stop
};
})();
var vehicle_route = (function(){
var toggler;
function init() {
toggler = new Toggler('#route_show_trigger');
toggler.subscribe('enable', function(){
linesPool.routeHighlight(selected_vehicle);
});
toggler.subscribe('disable', function(){
linesPool.routeHighlightRemove();
});
}
function hide() {
toggler.trigger('disable');
}
return {
init: init,
hide: hide
};
})();
function station_info_hide() {
$('#station_info').addClass('hidden');
}
function vehicle_info_display(vehicle) {
if ((selected_vehicle !== null) && (selected_vehicle.id === vehicle.id)) {
if (selected_vehicle.marker.get('follow') === 'no') {
vehicle_follow.start(selected_vehicle);
}
if (selected_vehicle.marker.get('follow') === 'yes') {
vehicle_follow.stop();
}
return;
}
selected_vehicle = vehicle;
vehicle_follow.stop();
station_info_hide();
vehicle_route.hide();
$('.vehicle_name', $('#vehicle_info')).text(vehicle.name + ' (' + vehicle.id + ')');
var route_config = config.getParam('routes')[vehicle.route_icon];
if (route_config) {
$('.vehicle_name', $('#vehicle_info')).css('background-color', route_config.route_color);
$('.vehicle_name', $('#vehicle_info')).css('color', route_config.route_text_color);
}
var ts = timer.getTS();
var html_rows = [];
$.each(vehicle.stations, function(index, stop_id) {
var s_dep = (typeof vehicle.depS[index] === 'undefined') ? "n/a" : vehicle.depS[index];
var html_row = '<tr data-dep-sec="' + s_dep + '"><td>' + (index + 1) + '.</td>';
var station_location = stationsPool.location_get(stop_id);
if (station_location === null) {
html_row += '<td>' + stationsPool.get(stop_id) + '</td>';
} else {
html_row += '<td><a href="#station_id=' + stop_id + '" data-station-id="' + stop_id + '">' + stationsPool.get(stop_id) + '</a></td>';
}
var hm_arr = (typeof vehicle.arrS[index - 1] === 'undefined') ? '' : timer.getHM(vehicle.arrS[index - 1]);
html_row += '<td>' + hm_arr + '</td>';
var hm_dep = (typeof vehicle.depS[index] === 'undefined') ? '' : timer.getHM(vehicle.depS[index]);
html_row += '<td>' + hm_dep + '</td></tr>';
html_rows.push(html_row);
});
$('#vehicle_timetable > tbody').html(html_rows.join(''));
$('#vehicle_timetable tbody tr').each(function(){
var row_dep_sec = $(this).attr('data-dep-sec');
if (row_dep_sec === "n/a") {
return;
}
if (row_dep_sec < ts) {
$(this).addClass('passed');
}
});
$('#vehicle_info').removeClass('hidden');
}
function vehicle_info_hide() {
vehicle_follow.stop();
vehicle_route.hide();
selected_vehicle = null;
$('#vehicle_info').addClass('hidden');
}
function station_info_display(station_id) {
var hm = timer.getHM();
var url = config.getParam('api_paths.departures');
if (url === null) {
return;
}
url = url.replace(/\[station_id\]/, station_id);
url = url.replace(/\[hhmm\]/, hm.replace(':', ''));
$.ajax({
url: url,
dataType: 'json',
success: function(vehicles) {
vehicle_info_hide();
var html_rows = [];
$.each(vehicles, function(index, vehicle) {
var html_row = '<tr><td>' + (index + 1) + '.</td>';
if (typeof simulation_vehicles[vehicle.id] === 'undefined') {
html_row += '<td>' + vehicle.name + '</td>';
} else {
html_row += '<td><a href="#vehicle_id=' + vehicle.id + '" data-vehicle-id="' + vehicle.id + '">' + vehicle.name + '</a></td>';
}
html_row += '<td>' + stationsPool.get(vehicle.st_b) + '</td>';
html_row += '<td>' + timer.getHM(vehicle.dep) + '</td>';
html_rows.push(html_row);
});
$('#station_departures > tbody').html(html_rows.join(''));
$('#station_info').removeClass('hidden');
$('.station_name', $('#station_info')).text(stationsPool.get(station_id));
}
});
}
function init() {
vehicle_follow.init();
vehicle_route.init();
$(document).on("click", '#station_departures tbody tr a', function(){
var vehicle_id = $(this).attr('data-vehicle-id');
var vehicle = simulation_vehicles[vehicle_id];
simulation_panel.displayVehicle(vehicle);
simulation_panel.followVehicle(vehicle);
return false;
});
$(document).on("click", '#vehicle_timetable tbody tr a', function(){
var station_id = $(this).attr('data-station-id');
var station_location = stationsPool.location_get(station_id);
if (station_location === null) {
return false;
}
map.setCenter(station_location);
if (map.getZoom() < config.getParam('zoom.to_stops')) {
map.setZoom(config.getParam('zoom.to_stops'));
}
vehicle_info_hide();
station_info_display(station_id);
return false;
});
(function(){
var location_el = $('#user_location');
var geolocation_marker = new google.maps.Marker({
icon: {
url: 'static/images/geolocation-bluedot.png',
size: new google.maps.Size(17, 17),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(8, 8)
},
map: null,
position: new google.maps.LatLng(0, 0)
});
var geocoder = new google.maps.Geocoder();
function zoom_to_geometry(geometry) {
if (geometry.viewport) {
map.fitBounds(geometry.viewport);
} else {
map.setCenter(geometry.location);
map.setZoom(15);
}
}
$('#geolocation_click').click(function(){
if (navigator.geolocation) {
location_el.val('...getting location');
navigator.geolocation.getCurrentPosition(function (position) {
var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
zoom_to_geometry({location: latlng});
geolocation_marker.setPosition(latlng);
if (geolocation_marker.getMap() === null) {
geolocation_marker.setMap(map);
}
geocoder.geocode({latLng: latlng}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
location_el.val(results[0].formatted_address);
}
});
});
}
});
var autocomplete = new google.maps.places.Autocomplete($('#user_location')[0], {
types: ['geocode']
});
autocomplete.bindTo('bounds', map);
google.maps.event.addListener(autocomplete, 'place_changed', function(){
var place = autocomplete.getPlace();
if (place.geometry) {
zoom_to_geometry(place.geometry);
} else {
geocoder.geocode({address: place.name}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
zoom_to_geometry(results[0].geometry);
location_el.val(results[0].formatted_address);
}
});
}
});
})();
$('input.panel_collapsible').click(function() {
var panel_content = $(this).closest('div[data-type="panel"]').children('div.panel_content');
if ($(this).hasClass('expanded')) {
$(this).removeClass('expanded');
panel_content.addClass('hidden');
} else {
$(this).addClass('expanded');
panel_content.removeClass('hidden');
}
});
}
return {
init: init,
displayVehicle: vehicle_info_display,
followVehicle: vehicle_follow.start,
displayStation: station_info_display
};
})();
var map_helpers = (function(){
var has_detail_view = false;
var extended_bounds = null;
function init(){
var mapStyles = [
{
featureType: "poi.business",
stylers: [
{ visibility: "off" }
]
},{
featureType: "road",
elementType: "labels",
stylers: [
{ visibility: "off" }
]
},{
featureType: "road",
elementType: "labels",
stylers: [
{ visibility: "off" }
]
},{
featureType: "road",
elementType: "geometry",
stylers: [
{ visibility: "simplified" },
{ lightness: 70 }
]
},{
featureType: "transit.line",
stylers: [
{ visibility: "off" }
]
},{
featureType: "transit.station.bus",
stylers: [
{ visibility: "off" }
]
}
];
var map_inited = false;
var map_options = {
zoom: parseInt(config.getParam('zoom.start'), 10),
center: new google.maps.LatLng(parseFloat(config.getParam('center.y')), parseFloat(config.getParam('center.x'))),
mapTypeId: config.getParam('map_type_id'),
styles: mapStyles,
disableDefaultUI: true,
zoomControl: true,
scaleControl: true,
streetViewControl: true,
overviewMapControl: true,
rotateControl: true,
mapTypeControl: true,
mapTypeControlOptions: {
position: google.maps.ControlPosition.TOP_LEFT,
mapTypeIds: [google.maps.MapTypeId.ROADMAP, google.maps.MapTypeId.TERRAIN, google.maps.MapTypeId.SATELLITE, 'stamen']
}
};
if (config.getParam('tilt') !== null) {
map_options.tilt = parseInt(config.getParam('tilt'), 10);
}
if (config.getParam('zoom.min') !== null) {
map_options.minZoom = parseInt(config.getParam('zoom.min'), 10);
}
if (config.getParam('zoom.max') !== null) {
map_options.maxZoom = parseInt(config.getParam('zoom.max'), 10);
}
map = new google.maps.Map(document.getElementById("map_canvas"), map_options);
/*
var kmlLayer = new google.maps.KmlLayer();
var kmlUrl = 'http://beta.ctweb.inweb.org.br/publico/stops.kml';
var kmlOptions = {
//suppressInfoWindows: true,
//preserveViewport: false,
map: map,
url: kmlUrl
};
var kmlLayer = new google.maps.KmlLayer(kmlOptions);
*/
var stamen_map = new google.maps.StamenMapType('watercolor');
stamen_map.set('name', 'Stamen watercolor');
map.mapTypes.set('stamen', stamen_map);
function map_layers_add(){
var edges_layer;
var stations_layer;
var ft_id;
// Graph topology layers - EDGES
ft_id = config.getParam('ft_layer_ids.topology_edges');
if (ft_id !== null) {
edges_layer = new google.maps.FusionTablesLayer({
query: {
select: 'geometry',
from: ft_id
},
clickable: false,
map: map,
styles: [
{
polylineOptions: {
strokeColor: "#FF0000",
strokeWeight: 2
}
},{
where: "type = 'tunnel'",
polylineOptions: {
strokeColor: "#FAAFBE",
strokeWeight: 1.5
}
}
]
});
}
// Graph topology layers - STATIONS
ft_id = config.getParam('ft_layer_ids.topology_stations');
if (ft_id !== null) {
stations_layer = new google.maps.FusionTablesLayer({
query: {
select: 'geometry',
from: ft_id
},
suppressInfoWindows: true,
map: map
});
google.maps.event.addListener(stations_layer, 'click', function(ev){
var station_id = ev.row.id.value;
simulation_panel.displayStation(station_id);
});
}
// GTFS layers - shapes.txt
ft_id = config.getParam('ft_layer_ids.gtfs_shapes');
if (ft_id !== null) {
edges_layer = new google.maps.FusionTablesLayer({
query: {
select: 'geometry',
from: ft_id
},
clickable: false,
map: map
});
}
// GTFS layers - stops.txt
ft_id = config.getParam('ft_layer_ids.gtfs_stops');
if (ft_id !== null) {
stations_layer = new google.maps.FusionTablesLayer({
query: {
select: 'geometry',
from: ft_id
},
suppressInfoWindows: true,
map: map
});
google.maps.event.addListener(stations_layer, 'click', function(ev){
var station_id = ev.row.stop_id.value;
simulation_panel.displayStation(station_id);
});
}
// Area mask
ft_id = config.getParam('ft_layer_ids.mask');
if (ft_id !== null) {
var layer = new google.maps.FusionTablesLayer({
query: {
select: 'geometry',
from: ft_id
},
clickable: false,
map: map
});
}
function trigger_toggleLayerVisibility() {
if (config.getParam('debug') !== null) {
console.log('Center: ' + map.getCenter().toUrlValue());
console.log('Zoom: ' + map.getZoom());
}
function toggleLayerVisibility(layer, hide) {
if ((typeof layer) === 'undefined') {
return;
}
if (hide) {
if (layer.getMap() !== null) {
layer.setMap(null);
}
} else {
if (layer.getMap() === null) {
layer.setMap(map);
}
}
}
var map_type_id = map.getMapTypeId();
var is_satellite = (map_type_id === google.maps.MapTypeId.SATELLITE) && (map.getTilt() === 0);
var config_preffix = is_satellite ? 'zoom.satellite' : 'zoom.roadmap';
var zoom = map.getZoom();
$.each(['stops', 'shapes'], function(k, layer_type){
var zoom_min = config.getParam(config_preffix + '.' + layer_type + '_min');
if (zoom_min === null) {
zoom_min = 0;
}
var zoom_max = config.getParam(config_preffix + '.' + layer_type + '_max');
if (zoom_max === null) {
zoom_max = 30;
}
var hide_layer = (zoom < zoom_min) || (zoom > zoom_max);
if (layer_type === 'stops') {
toggleLayerVisibility(stations_layer, hide_layer);
}
if (layer_type === 'shapes') {
toggleLayerVisibility(edges_layer, hide_layer);
}
});
}
google.maps.event.addListener(map, 'idle', trigger_toggleLayerVisibility);
google.maps.event.addListener(map, 'maptypeid_changed', trigger_toggleLayerVisibility);
trigger_toggleLayerVisibility();
}
google.maps.event.addListener(map, 'idle', function() {
if (map_inited === false) {
// TODO - FIXME later ?
// Kind of a hack, getBounds is ready only after a while since loading, so we hook in the 'idle' event
map_inited = true;
map_layers_add();
listener_helpers.notify('map_init');
function update_detail_view_state() {
if (map.getMapTypeId() !== google.maps.MapTypeId.SATELLITE) {
has_detail_view = false;
return;
}
if (map.getZoom() < 17) {
has_detail_view = false;
return;
}
if (map.getTilt() !== 0) {
has_detail_view = false;
return;
}
has_detail_view = true;
}
google.maps.event.addListener(map, 'zoom_changed', update_detail_view_state);
google.maps.event.addListener(map, 'tilt_changed', update_detail_view_state);
google.maps.event.addListener(map, 'maptypeid_changed', update_detail_view_state);
update_detail_view_state();
function update_extended_bounds() {
var map_bounds = map.getBounds();
var bounds_point = map_bounds.getSouthWest();
var new_bounds_sw = new google.maps.LatLng(bounds_point.lat() - map_bounds.toSpan().lat(), bounds_point.lng() - map_bounds.toSpan().lng());
bounds_point = map_bounds.getNorthEast();
var new_bounds_ne = new google.maps.LatLng(bounds_point.lat() + map_bounds.toSpan().lat(), bounds_point.lng() + map_bounds.toSpan().lng());
extended_bounds = new google.maps.LatLngBounds(new_bounds_sw, new_bounds_ne);
}
google.maps.event.addListener(map, 'bounds_changed', update_extended_bounds);
update_extended_bounds();
}
});
}
return {
init: init,
isDetailView: function() {
return has_detail_view;
},
getExtendedBounds: function() {
return extended_bounds;
}
};
})();
// Vehicle helpers
// Roles:
// - check backend for new vehicles
// - manages vehicle objects(class Vehicle) and animates them (see Vehicle.render method)
var vehicle_helpers = (function(){
var vehicle_detect = (function(){
var track_vehicle_name = null;
var track_vehicle_id = null;
function match_by_name(vehicle_name) {
if (track_vehicle_name === null) {
return false;
}
vehicle_name = vehicle_name.replace(/[^A-Z0-9]/i, '');
if (track_vehicle_name !== vehicle_name) {
return false;
}
return true;
}
function match(vehicle_name, vehicle_id) {
if (track_vehicle_id === null) {
track_vehicle_name = config.getParam('vehicle_name');
if (track_vehicle_name !== null) {
track_vehicle_name = track_vehicle_name.replace(/[^A-Z0-9]/i, '');
}
track_vehicle_id = config.getParam('vehicle_id');
}
if (track_vehicle_id === vehicle_id) {
return true;
}
return match_by_name(vehicle_name);
}
listener_helpers.subscribe('vehicles_load', function(){
if (config.getParam('action') !== 'vehicle_add') {
return;
}
function str_hhmm_2_sec_ar(str_hhmm) {
var sec_ar = [];
$.each(str_hhmm.split('_'), function(index, hhmm){
var hhmm_matches = hhmm.match(/([0-9]{2})([0-9]{2})/);
sec_ar.push(timer.getHMS2TS(hhmm_matches[1] + ':' + hhmm_matches[2] + ':00'));
});
return sec_ar;
}
var station_ids = config.getParam('station_ids').split('_');
$.each(station_ids, function(index, station_id_s){
station_ids[index] = station_id_s;
});
var vehicle_data = {
arrs: str_hhmm_2_sec_ar(config.getParam('arrs')),
deps: str_hhmm_2_sec_ar(config.getParam('deps')),
id: 'custom_vehicle',
name: decodeURIComponent(config.getParam('vehicle_name')),
sts: station_ids,
type: config.getParam('vehicle_type'),
edges: []
};
var v = new Vehicle(vehicle_data);
simulation_vehicles[vehicle_data.id] = v;
v.render();
simulation_panel.displayVehicle(v);
simulation_panel.followVehicle(v);
});
return {
match: match
};
})();
// Vehicle icons manager.
// Roles:
// - keep a reference for each vehicle type (IC, ICE, etc..)
var imagesPool = (function(){
var icons = {};
function iconGet(type) {
if (icons[type]) {
return icons[type];
}
var routes_config = config.getParam('routes');
if ((typeof routes_config[type]) === 'undefined') {
return null;
}
if (routes_config[type].icon === false) {
return null;
}
var url = routes_config[type].icon;
var icon = {
url: url,
size: new google.maps.Size(20, 20),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(10, 10)
};
icons[type] = icon;
return icon;
}
var vehicle_detail_base_zoom = 17;
var vehicle_detail_config = {
"s-bahn-rear": {
base_zoom_width: 33,
width: 228
},
"s-bahn-middle": {
base_zoom_width: 33,
width: 247
},
"s-bahn-front": {
base_zoom_width: 33,
width: 239
},
"s-bahn_old-rear": {
base_zoom_width: 26,
width: 153
},
"s-bahn_old-middle": {
base_zoom_width: 35,
width: 228
},
"s-bahn_old-front": {
base_zoom_width: 35,
width: 224
},
"ic-loco-c2": {
base_zoom_width: 36,
width: 225
},
"ic-coach": {
base_zoom_width: 36,
width: 254
},
"ic-loco": {
base_zoom_width: 19,
width: 126
},
"icn-rear": {
base_zoom_width: 32,
width: 207
},
"icn-middle": {
base_zoom_width: 32,
width: 218
},
"icn-front": {
base_zoom_width: 32,
width: 207
},
"ir-coach": {
base_zoom_width: 32,
width: 223
}
};
var vehicle_detail_icons = {};
var service_parts = {
s: {
offsets: [-40, -13, 14, 41],
vehicles: ['s-bahn-rear', 's-bahn-middle', 's-bahn-middle', 's-bahn-front']
},
sbahn_old: {
offsets: [-39, -14, 15, 44],
vehicles: ['s-bahn_old-rear', 's-bahn_old-middle', 's-bahn_old-middle', 's-bahn_old-front']
},
ic: {
offsets: [-110, -87, -58, -29, 0, 29, 58, 87],
vehicles: ['ic-loco', 'ic-coach', 'ic-coach', 'ic-coach', 'ic-coach', 'ic-coach', 'ic-coach', 'ic-loco-c2']
},
icn: {
offsets: [-78, -52, -26, 0, 26, 52, 78],
vehicles: ['icn-rear', 'icn-middle', 'icn-middle', 'icn-middle', 'icn-middle', 'icn-middle', 'icn-front']
},
ir: {
offsets: [-93, -67, -41, -15, 11, 37, 63, 84],
vehicles: ['ir-coach', 'ir-coach', 'ir-coach', 'ir-coach', 'ir-coach', 'ir-coach', 'ir-coach', 'ic-loco']
}
};
function getVehicleIcon(zoom, type, heading) {
var key = zoom + '_' + type + '_' + heading;
if (typeof vehicle_detail_icons[key] === 'undefined') {
var original_width = vehicle_detail_config[type].width;
var icon_width = vehicle_detail_config[type].base_zoom_width * Math.pow(2, parseInt(zoom - vehicle_detail_base_zoom, 10));
var base_url = 'http://static.vasile.ch/simcity/service-vehicle-detail';
var icon = {
url: base_url + '/' + type + '/' + heading + '.png',
size: new google.maps.Size(original_width, original_width),
origin: new google.maps.Point(0, 0),
scaledSize: new google.maps.Size(icon_width, icon_width),
anchor: new google.maps.Point(parseInt(icon_width/2, 10), parseInt(icon_width/2, 10))
};
vehicle_detail_icons[key] = icon;
}
return vehicle_detail_icons[key];
}
return {
iconGet: iconGet,
getServicePartsConfig: function(key) {
if ((typeof service_parts[key]) === 'undefined') {
key = 's';
}
return service_parts[key];
},
getVehicleIcon: getVehicleIcon
};
})();
var vehicle_ib = new InfoBox({
disableAutoPan: true,
pixelOffset: new google.maps.Size(10, 10),
vehicle_id: 0,
closeBoxURL: ''
});
var vehicleIDs = [];
function Vehicle(params) {
function parseTimes(times) {
var time_ar = [];
$.each(times, function(k, time){
// 32855 = 9 * 3600 + 7 * 60 + 35
if ((typeof time) === 'number') {
if (time < (2 * 24 * 3600)) {
time += timer.getTSMidnight();
}
time_ar.push(time);
return;
}
// 09:07:35
if (time.match(/^[0-9]{2}:[0-9]{2}:[0-9]{2}$/) !== null) {
time = timer.getHMS2TS(time);
time_ar.push(time);
return;
}
// 09:07
if (time.match(/^[0-9]{2}:[0-9]{2}$/) !== null) {
var hms = time + ':00';
time = timer.getHMS2TS(hms);
time_ar.push(time);
return;
}
});
return time_ar;
}
if ((typeof params.trip_id) === 'undefined') {
this.source = 'custom';
this.id = params.id;
this.name = params.name;
this.stations = params.sts;
this.edges = params.edges;
this.depS = parseTimes(params.deps);
this.arrS = parseTimes(params.arrs);
this.route_icon = params.type;
this.service_type = params.service_type;
$.each(params.edges, function(k, edges) {
if (k === 0) { return; }
linesPool.routeAdd(edges);
});
} else {
// GTFS approach
this.source = 'gtfs';
this.id = params.trip_id;
this.name = params.route_short_name;
this.service_type = '';
this.edges = [];
this.shape_id = params.shape_id;
var departures = [];
var arrivals = [];
var stations = [];
var shape_percent = [];
$.each(params.stops, function(k, stop){
if (k < (params.stops.length - 1)) {
departures.push(stop.departure_time);
}
if (k > 0) {
arrivals.push(stop.arrival_time);
}
stations.push(stop.stop_id);
shape_percent.push(stop.stop_shape_percent);
});
this.stations = stations;
this.depS = parseTimes(departures);
this.arrS = parseTimes(arrivals);
this.shape_percent = shape_percent;
this.route_icon = params.type;
}
var marker = new google.maps.Marker({
position: new google.maps.LatLng(0, 0),
map: null,
speed: null,
status: 'not on map'
});
var icon = imagesPool.iconGet(this.route_icon);
if (icon !== null) {
marker.setIcon(icon);
}
this.marker = marker;
this.detail_markers = [];
// TODO - FIXME .apply
var that = this;
google.maps.event.addListener(marker, 'click', function() {
simulation_panel.displayVehicle(that);
});
this.mouseOverMarker = function() {
if (map.getZoom() < config.getParam('zoom.vehicle_mouseover_min')) {
return;
}
if (vehicle_ib.get('vehicle_id') === that.id) { return; }
vehicle_ib.set('vehicle_id', that.id);
vehicle_ib.close();
var popup_div = $('#vehicle_popup');
$('span.vehicle_name', popup_div).text(that.name);
var route_config = config.getParam('routes')[that.route_icon];
if (route_config) {
$('span.vehicle_name', popup_div).css('background-color', route_config.route_color);
$('span.vehicle_name', popup_div).css('color', route_config.route_text_color);
}
$('.status', popup_div).html(marker.get('status'));
vehicle_ib.setContent($('#vehicle_popup_container').html());
vehicle_ib.open(map, this);
};
this.mouseOutMarker = function() {
vehicle_ib.set('vehicle_id', null);
vehicle_ib.close();
};
google.maps.event.addListener(marker, 'mouseover', this.mouseOverMarker);
google.maps.event.addListener(marker, 'mouseout', this.mouseOutMarker);
if (vehicle_detect.match(this.name, this.id)) {
simulation_panel.displayVehicle(this);
simulation_panel.followVehicle(this);
}
}
Vehicle.prototype.render = function() {
// TODO - FIXME .apply
var that = this;
function animate() {
var ts = timer.getTS();
var vehicle_position = null;
var route_percent = 0;
var d_AC = 0;
var animation_timeout = 1000;
for (var i=0; i<that.arrS.length; i++) {
if (ts < that.arrS[i]) {
var station_a = that.stations[i];
var station_b = that.stations[i+1];
var route_id = (that.source === 'gtfs') ? that.shape_id : that.edges[i+1];
var speed = that.marker.get('speed');
if (ts > that.depS[i]) {
var routeLength = linesPool.lengthGet(route_id);
// Vehicle is in motion between two stations
if ((speed === 0) || (speed === null)) {
var trackLength = routeLength;
if (that.source === 'gtfs') {
trackLength = routeLength * (that.shape_percent[i+1] - that.shape_percent[i]) / 100;
}
var speed = trackLength * 0.001 * 3600 / (that.arrS[i] - that.depS[i]);
that.marker.set('speed', parseInt(speed, 10));
that.marker.set('status', 'Heading to ' + stationsPool.get(station_b) + '(' + timer.getHM(that.arrS[i]) + ')<br/>Speed: ' + that.marker.get('speed') + ' km/h');
}
route_percent = (ts - that.depS[i])/(that.arrS[i] - that.depS[i]);
if (that.source === 'gtfs') {
route_percent = (that.shape_percent[i] + route_percent * (that.shape_percent[i+1] - that.shape_percent[i])) / 100;
}
d_AC = routeLength * route_percent;
} else {
// Vehicle is in a station
if ((speed !== 0) || (speed === null)) {
that.marker.set('status', 'Departing ' + stationsPool.get(station_a) + ' at ' + timer.getHM(that.depS[i]));
that.marker.set('speed', 0);
}
if (that.source === 'gtfs') {
route_percent = that.shape_percent[i] / 100;
}
}
var vehicle_position_data = linesPool.positionGet(route_id, route_percent);
if (vehicle_position_data === null) {
break;
}
var vehicle_position = vehicle_position_data.position;
if (that.marker.get('follow') === 'yes-init') {
that.marker.set('follow', 'yes');
map.panTo(vehicle_position);
if (map.getZoom() < config.getParam('zoom.vehicle_follow')) {
map.setZoom(config.getParam('zoom.vehicle_follow'));
}
map.setMapTypeId(google.maps.MapTypeId.SATELLITE);
map.bindTo('center', that.marker, 'position');
}
that.updateIcon(vehicle_position_data, d_AC, i);
if (map.getZoom() >= 12) {
animation_timeout = timer.getRefreshValue();
}
setTimeout(animate, animation_timeout);
break;
}
} // end arrivals loop
if (vehicle_position === null) {
that.marker.setMap(null);
delete simulation_vehicles[that.id];
}
}
animate();
};
Vehicle.prototype.updateIcon = function(data, d_AC, i) {
var service_parts = imagesPool.getServicePartsConfig(this.service_type);
var render_in_detail = data.is_detailed && (service_parts !== null);
var vehicle_position = data.position;
this.marker.setPosition(data.position);
if (render_in_detail) {
if (this.marker.getMap() !== null) {
this.marker.setMap(null);
}
if (map_helpers.getExtendedBounds().contains(vehicle_position)) {
var that = this;
$.each(service_parts.offsets, function(k, offset){
if ((typeof that.detail_markers[k]) === 'undefined') {
that.detail_markers[k] = new google.maps.Marker({
map: null
});
var marker = that.detail_markers[k];
google.maps.event.addListener(marker, 'mouseover', that.mouseOverMarker);
google.maps.event.addListener(marker, 'mouseout', that.mouseOutMarker);
google.maps.event.addListener(marker, 'click', function(){
simulation_panel.displayVehicle(that);
});
}
var marker = that.detail_markers[k];
var route = that.edges[i+1];
var route_length = linesPool.lengthGet(route);
var d_AC_new = d_AC + offset;
if ((d_AC + offset) > route_length) {
d_AC_new -= route_length;
route = that.edges[i+2];
}
var position_data = linesPool.projectDistanceAlongRoute(route, d_AC_new);
if (position_data === null) {
marker.setMap(null);
return;
}
var heading = parseInt(position_data.heading, 10);
if (heading < 0) {
heading += 360;
}
heading = ('00' + heading).slice(-3);
var zoom = map.getZoom();
var icon = imagesPool.getVehicleIcon(zoom, service_parts.vehicles[k], heading);
if (((typeof marker.getIcon()) === 'undefined') || (marker.getIcon().url !== icon.url) || (marker.get('zoom') !== zoom)) {
marker.setIcon(icon);
marker.set('zoom', map.getZoom());
}
marker.setPosition(position_data.position);
if (marker.getMap() === null) {
marker.setMap(map);
}
});
} else {
$.each(this.detail_markers, function(k, marker){
marker.setMap(null);
});
this.detail_markers = [];
}
} else {
$.each(this.detail_markers, function(k, marker){
marker.setMap(null);
});
this.detail_markers = [];
if (map.getBounds().contains(vehicle_position)) {
if (this.marker.getMap() === null) {
this.marker.setMap(map);
}
} else {
if (this.marker.getMap() !== null) {
this.marker.setMap(null);
}
}
}
};
return {
load: function() {
var hm = timer.getHM();
var url = config.getParam('api_paths.trips');
url = url.replace(/\[hhmm\]/, hm.replace(':', ''));
$.ajax({
url: url,
dataType: 'json',
success: function(vehicles) {
$.each(vehicles, function(index, data) {
var vehicle_id = ((typeof data.trip_id) === 'undefined') ? data.id : data.trip_id;
if ((typeof simulation_vehicles[vehicle_id]) !== 'undefined') {
return;
}
var v = new Vehicle(data);
v.render();
simulation_vehicles[vehicle_id] = v;
});
listener_helpers.notify('vehicles_load');
}
});
}
};
})();
listener_helpers.subscribe('map_init', function(){
function loadStations(url) {
if (url === null) {
return;
}
$.ajax({
url: url,
dataType: 'json',
success: function(geojson) {
if (typeof(geojson.features) === 'undefined') {
console.log('Malformed GeoJSON. URL: ' + url);
return;
}
stationsPool.addFeatures(geojson.features);
vehicle_helpers.load();
listener_helpers.subscribe('minute_changed', vehicle_helpers.load);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log('Error from server ' + textStatus + ' for url: ' + url);
}
});
}
// GTFS approach
var url = config.getParam('geojson.gtfs_shapes');
if (url !== null) {
$.ajax({
url: url,
dataType: 'json',
async: false,
success: function(geojson) {
if (typeof(geojson.features) === 'undefined') {
console.log('Malformed GeoJSON. URL: ' + url);
} else {
linesPool.loadGeoJSONShapes(geojson.features);
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.log('Error from server ' + textStatus + ' for url: ' + url);
}
});
}
loadStations(config.getParam('geojson.gtfs_stops'));
// Custom topology approach
var url = config.getParam('geojson.topology_edges');
if (url !== null) {
$.ajax({
url: url,
dataType: 'json',
async: false,
success: function(geojson) {
if (typeof(geojson.features) === 'undefined') {
console.log('Malformed GeoJSON. URL: ' + url);
} else {
linesPool.loadGeoJSONEdges(geojson.features);
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.log('Error from server ' + textStatus + ' for url: ' + url);
}
});
}
loadStations(config.getParam('geojson.topology_stations'));
});
function ui_init() {
var view_mode = config.getParam('view_mode');
var panel_display = (ua_is_mobile === false) && (view_mode !== 'iframe');
if (panel_display) {
$('#panel').removeClass('hidden');
}
var time_multiply = config.getParam('time_multiply');
if (time_multiply !== null) {
$('#time_multiply').val(time_multiply);
}
}
return {
init: function(){
config.init();
ui_init();
timer.init();
map_helpers.init();
simulation_panel.init();
},
getMap: function(){
return map;
}
};
})();
$(document).ready(simulation_manager.init);
| eubr-bigsea/transit-map | static/js/map.js | JavaScript | mit | 69,039 |
version https://git-lfs.github.com/spec/v1
oid sha256:2c648d581addc08fbd0fe28ad0d26ba08942ebfe6be59756e11ff9abcd9d3bbd
size 23184
| yogeshsaroya/new-cdnjs | ajax/libs/openlayers/2.12/lib/OpenLayers/Format/Atom.js | JavaScript | mit | 130 |
describe('minTime', function() {
beforeEach(function() {
affix('#cal');
});
var numToStringConverter = function(timeIn, mins) {
var time = (timeIn % 12) || 12;
var amPm = 'am';
if ((timeIn % 24) > 11) {
amPm = 'pm';
}
return time + (mins != null ? ':' + mins : '') + amPm;
};
describe('when using the default settings', function() {
describe('in agendaWeek', function() {
it('should start at 12am', function() {
var options = {
defaultView: 'agendaWeek'
};
$('#cal').njCalendar(options);
var firstSlotText = $('.fc-slats tr:eq(0) .fc-time').text();
expect(firstSlotText).toEqual('12am');
});
});
describe('in agendaDay', function() {
it('should start at 12am', function() {
var options = {
defaultView: 'agendaDay'
};
$('#cal').njCalendar(options);
var firstSlotText = $('.fc-slats tr:eq(0) .fc-time').text();
expect(firstSlotText).toEqual('12am');
});
});
});
describe('when using a whole number', function() {
var hourNumbers = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ];
describe('in agendaWeek', function() {
beforeEach(function() {
affix('#cal2');
});
hourNumbers.forEach(function(hourNumber) {
it('should start at ' + hourNumber, function() {
var options = {
defaultView: 'agendaWeek',
minTime: { hours: hourNumber }
};
$('#cal2').njCalendar(options);
var firstSlotText = $('.fc-slats tr:eq(0) .fc-time').text();
var expected = numToStringConverter(hourNumber);
expect(firstSlotText).toEqual(expected);
});
});
});
describe('in agendaDay', function() {
beforeEach(function() {
affix('#cal2');
});
hourNumbers.forEach(function(hourNumber) {
it('should start at ' + hourNumber, function() {
var options = {
defaultView: 'agendaDay',
minTime: hourNumber + ':00' // in addition, test string duration input
};
$('#cal2').njCalendar(options);
var firstSlotText = $('.fc-slats tr:eq(0) .fc-time').text();
var expected = numToStringConverter(hourNumber);
expect(firstSlotText).toEqual(expected);
});
});
});
});
describe('when using default slotInterval and \'uneven\' minTime', function() {
var hourNumbers = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ];
describe('in agendaWeek', function() {
beforeEach(function() {
affix('#cal2');
});
hourNumbers.forEach(function(hourNumber) {
it('should start at ' + hourNumber + ':20', function() {
var options = {
defaultView: 'agendaWeek',
minTime: { hours: hourNumber, minutes: 20 }
};
$('#cal2').njCalendar(options);
var slatRows = $('.fc-slats tr');
expect(slatRows.eq(0)).toHaveClass('fc-minor');
expect(slatRows.eq(1)).toHaveClass('fc-minor');
expect(slatRows.eq(2)).toHaveClass('fc-minor');
// TODO: fix bad behavior in src where no slots have text
});
});
});
describe('in agendaDay', function() {
beforeEach(function() {
affix('#cal2');
});
hourNumbers.forEach(function(hourNumber) {
it('should start at ' + hourNumber + ':20', function() {
var options = {
defaultView: 'agendaDay',
minTime: { hours: hourNumber, minutes: 20 }
};
$('#cal2').njCalendar(options);
var slatRows = $('.fc-slats tr');
expect(slatRows.eq(0)).toHaveClass('fc-minor');
expect(slatRows.eq(1)).toHaveClass('fc-minor');
expect(slatRows.eq(2)).toHaveClass('fc-minor');
// TODO: fix bad behavior in src where no slots have text
});
});
});
});
}); | jonathan-wheeler/fullcalendar | tests/automated/minTime.js | JavaScript | mit | 3,579 |
'use strict';
/*
* Regex
*/
var regex = {
facebookPattern: /(?:https?:\/\/)?(?:[\w\-]+\.)?facebook\.com\/(?:(?:\w)*#!\/)?(?:pages\/)?(?:[\w\-]*\/)*([\w\-\.]*)/, // jshint ignore:line
facebookPluginPattern: /.*%2F(\w+?)&/
};
module.exports = {
/**
* Returns the page id for a given URL
* e.g. : https://www.facebook.com/my_page_id => my_page_id
* http://www.facebook.com/pages/foo/Bar/123456 => 123456
*
* @param String URL FacebookURL
* @return Page ID
*/
getPageId: function (url) {
if (typeof url !== 'string') {
return null;
}
var match = url.replace(/\/$/, '').match(regex.facebookPattern);
if (match) {
var short_url = match[0],
id = match[1];
if (/plugins/.test(short_url)) {
var likeMatch = regex.facebookPluginPattern.exec(match.input);
if (likeMatch) { return likeMatch[1]; }
} else {
return id;
}
}
return null;
}
};
| Woorank/extract-facebook-pageid | index.js | JavaScript | mit | 979 |
"use strict";
exports.hmrReducer = function (appReducer) { return function (state, _a) {
var type = _a.type, payload = _a.payload;
switch (type) {
case 'HMR_SET_STATE': return payload;
default: return appReducer(state, { type: type, payload: payload });
}
}; };
//# sourceMappingURL=hmr-reducer.js.map | luiscgoulart/angular2-app1 | node_modules/angular2-hmr/dist/hmr-reducer.js | JavaScript | mit | 329 |
var url = require('url');
var semver = require('semver');
var nijs = require('nijs');
var inherit = require('nijs/lib/ast/util/inherit.js').inherit;
var base64js = require('base64-js');
/**
* Creates a new source instance. This function should never be used directly,
* instead use: Source.constructSource to construct a source object.
*
* @class Source
* @extends NixASTNode
* @classdesc Represents a file that is obtained from an external source
*
* @constructor
* @param {String} baseDir Directory in which the referrer's package.json configuration resides
* @param {String} dependencyName Name of the dependency
* @param {String} versionSpec Version specifier of the Node.js package to fetch
*/
function Source(baseDir, dependencyName, versionSpec) {
this.baseDir = baseDir;
this.dependencyName = dependencyName;
this.versionSpec = versionSpec;
}
/* Source inherits from NixASTNode */
inherit(nijs.NixASTNode, Source);
/**
* Constructs a specific kind of source by inspecting the version specifier.
*
* @param {String} registryURL URL of the NPM registry
* @param {?String} registryAuthToken Auth token for private NPM registry
* @param {String} baseDir Directory in which the referrer's package.json configuration resides
* @param {String} outputDir Directory in which the nix expression will be written
* @param {String} dependencyName Name of the dependency
* @param {String} versionSpec Version specifier of the Node.js package to fetch
* @param {Boolean} stripOptionalDependencies When enabled, the optional
* dependencies are stripped from the regular dependencies in the NPM registry
*/
Source.constructSource = function(registryURL, registryAuthToken, baseDir, outputDir, dependencyName, versionSpec, stripOptionalDependencies) {
// Load modules here, to prevent cycles in the include process
var GitSource = require('./GitSource.js').GitSource;
var HTTPSource = require('./HTTPSource.js').HTTPSource;
var LocalSource = require('./LocalSource.js').LocalSource;
var NPMRegistrySource = require('./NPMRegistrySource.js').NPMRegistrySource;
var parsedVersionSpec = semver.validRange(versionSpec, true);
var parsedUrl = url.parse(versionSpec);
if(parsedVersionSpec !== null) { // If the version is valid semver range, fetch the package from the NPM registry
return new NPMRegistrySource(baseDir, dependencyName, parsedVersionSpec, registryURL, registryAuthToken, stripOptionalDependencies);
} else if(parsedUrl.protocol == "github:") { // If the version is a GitHub repository, compose the corresponding Git URL and do a Git checkout
return new GitSource(baseDir, dependencyName, GitSource.composeGitURL("git://github.com", parsedUrl));
} else if(parsedUrl.protocol == "gist:") { // If the version is a GitHub gist repository, compose the corresponding Git URL and do a Git checkout
return new GitSource(baseDir, dependencyName, GitSource.composeGitURL("https://gist.github.com", parsedUrl));
} else if(parsedUrl.protocol == "bitbucket:") { // If the version is a Bitbucket repository, compose the corresponding Git URL and do a Git checkout
return new GitSource(baseDir, dependencyName, GitSource.composeGitURL("git://bitbucket.org", parsedUrl));
} else if(parsedUrl.protocol == "gitlab:") { // If the version is a Gitlab repository, compose the corresponding Git URL and do a Git checkout
return new GitSource(baseDir, dependencyName, GitSource.composeGitURL("https://gitlab.com", parsedUrl));
} else if(typeof parsedUrl.protocol == "string" && parsedUrl.protocol.substr(0, 3) == "git") { // If the version is a Git URL do a Git checkout
return new GitSource(baseDir, dependencyName, versionSpec);
} else if(parsedUrl.protocol == "http:" || parsedUrl.protocol == "https:") { // If the version is an HTTP URL do a download
return new HTTPSource(baseDir, dependencyName, versionSpec);
} else if(versionSpec.match(/^[a-zA-Z0-9_\-]+\/[a-zA-Z0-9\.]+[#[a-zA-Z0-9_\-]+]?$/)) { // If the version is a GitHub repository, compose the corresponding Git URL and do a Git checkout
return new GitSource(baseDir, dependencyName, "git://github.com/"+versionSpec);
} else if(parsedUrl.protocol == "file:") { // If the version is a file URL, simply compose a Nix path
return new LocalSource(baseDir, dependencyName, outputDir, parsedUrl.path);
} else if(versionSpec.substr(0, 3) == "../" || versionSpec.substr(0, 2) == "~/" || versionSpec.substr(0, 2) == "./" || versionSpec.substr(0, 1) == "/") { // If the version is a path, simply compose a Nix path
return new LocalSource(baseDir, dependencyName, outputDir, versionSpec);
} else { // In all other cases, just try the registry. Sometimes invalid semver ranges are encountered or a tag has been provided (e.g. 'latest', 'unstable')
return new NPMRegistrySource(baseDir, dependencyName, versionSpec, registryURL, registryAuthToken, stripOptionalDependencies);
}
};
/**
* Fetches the package metadata from the external source.
*
* @method
* @param {function(String)} callback Callback that gets invoked when the work
* is done. In case of an error, it will set the first parameter to contain
* an error message.
*/
Source.prototype.fetch = function(callback) {
callback("fetch() is not implemented, please use a prototype that inherits from Source");
};
/**
* Takes a dependency object from a lock file and converts it into a source object.
*
* @param {Object} dependencyObj Dependency object from the lock file
* @param {function(String)} callback Callback that gets invoked when the work
* is done. In case of an error, it will set the first parameter to contain
* an error message.
*/
Source.prototype.convertFromLockedDependency = function(dependencyObj, callback) {
callback("convertFromLockedDependency() is not implemented, please use a prototype that inherits from Source");
};
/**
* Converts NPM's integrity strings that have the following format:
* <algorithm>-<base64 hash> to a hash representation that Nix understands.
*
* @method
* @param {String} integrity NPM integrity string
*/
Source.prototype.convertIntegrityStringToNixHash = function(integrity) {
if(integrity.substr(0, 5) === "sha1-") {
var hash = base64js.toByteArray(integrity.substring(5));
this.hashType = "sha1";
this.sha1 = new Buffer(hash).toString('hex');
} else if(integrity.substr(0, 7) === "sha512-") {
this.hashType = "sha512";
this.sha512 = integrity.substring(7);
} else {
throw "Unknown integrity string: "+integrity;
}
};
/**
* @see NixASTNode#toNixAST
*/
Source.prototype.toNixAST = function() {
return {
name: this.config.name.replace("@", "_at_").replace("/", "_slash_"), // Escape characters from scoped package names that aren't allowed
packageName: this.config.name,
version: this.config.version
};
};
exports.Source = Source;
| svanderburg/npm2nix | lib/sources/Source.js | JavaScript | mit | 7,017 |
import React, { PropTypes } from 'react';
import EventImage from '../components/EventImage';
const Event = ({ eventUrl, images, ingress, startDate, title }) => (
<div>
<div className="col-sm-8 col-md-4">
<div className="hero-title">
<a href={eventUrl}>
<p>{ title }</p>
</a>
</div>
<div className="hero-ingress hidden-xs">
<p>{ ingress }</p>
</div>
</div>
<EventImage
date={startDate}
images={images}
eventUrl={eventUrl}
/>
</div>
);
Event.propTypes = {
eventUrl: PropTypes.string.isRequired,
images: EventImage.propTypes.images,
ingress: PropTypes.string.isRequired,
startDate: PropTypes.string.isRequired,
title: PropTypes.string.isRequired,
};
export default Event;
| dotKom/onlineweb4 | assets/frontpage/events/components/Event.js | JavaScript | mit | 778 |
'use strict';
function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }
/**
*
* saluki api 查看
*
* Created by joe on 16/12/26.
*/
var services = require('../grpc/index').services();
var consul = require('../grpc/consul');
module.exports = function () {
var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
return function () {
var _ref = _asyncToGenerator(function* (ctx, next) {
var url = ctx.url;
ctx.services = services;
if (url.endsWith('/saluki')) {
ctx.body = JSON.stringify(consul.getALL());
return;
}
yield next();
});
function saluki(_x2, _x3) {
return _ref.apply(this, arguments);
}
return saluki;
}();
}; | quancheng-ec/pomjs | dist/middleware/saluki.js | JavaScript | mit | 1,216 |
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} t
* @return {string}
*/
const tree2str = (t) => {
let ret = '';
if (t) {
ret += t.val;
if (t.left || t.right) {
ret += '(';
ret += tree2str(t.left);
ret += ')';
}
if (t.right) {
ret += `(${tree2str(t.right)})`;
}
}
return ret;
};
| JohnnieFucker/LeetCode | solutions/construct-string-from-binary-tree.js | JavaScript | mit | 501 |
export const IIcon = {
name: 'i-icon',
};
export default IIcon;
| vusion/proto-ui | src/components/i-icon.vue/index.js | JavaScript | mit | 69 |
import Objects from './'
import Character from './Character'
import Actions from '../actions'
import Attacks from '../actions/Attacks'
import Dash from '../actions/Dash'
const addMoveAnimations = function () {
Object.keys(this.directions).map(
(direction) => this.atlasAnimations.add({
action: Actions.move,
direction,
speed: 8
})
)
}
const addAtkAnimations = function () {
Object.keys(this.directions).map(
(direction) => this.atlasAnimations.add({
action: Actions.atk,
direction,
speed: 13
})
)
}
export default class extends Character {
constructor ({
game, x, y, name
}) {
super({
game,
x,
y,
name,
type: Objects.npc,
firstSprite: `${name}-move-down-1`
})
this.setActions([
new Attacks({
character: this,
attacks: [{id: 0, type: 'normal', time: 24, speed: 13, cooldown: 15}]
}),
new Dash({
character: this,
dash: {time: 15, speed: 300, cooldown: 15}
})
])
this.speed = 140
addMoveAnimations.call(this)
addAtkAnimations.call(this)
}
update () {
super.update()
}
}
| RafaelDelboni/phaser-dungeon | src/objects/Npc.js | JavaScript | mit | 1,172 |
var passport = require('passport');
var Auth0Strategy = require('passport-auth0');
var credentials = require('../config/credentials.js');
var strategy = new Auth0Strategy({
domain: credentials.domain,
clientID: credentials.clientID,
clientSecret: credentials.clientSecret,
callbackURL: '/callback'
}, function(accessToken, refreshToken, profile, done) {
//Some tracing info
console.log('profile is', profile);
return done(null, profile);
});
passport.use(strategy);
// This is not a best practice, but we want to keep things simple for now
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function(user, done) {
done(null, user);
});
module.exports = strategy; | feedhenry-templates/salesforce-auth0-cloud | lib/setup-passport.js | JavaScript | mit | 759 |
module.exports = require('../crud/list')({
view: 'users/manage',
model: require('../../models/user'),
sort: {
name: 1
}
});
| phoenixmusical/membres | lib/routes/users/manage.js | JavaScript | mit | 131 |
var goods = [
{ GoodId: 1, Name: '玫瑰', Price: 100, Total: 100, SellCount: 0 },
{ GoodId: 2, Name: '康乃馨', Price: 200, Total: 50, SellCount: 0 },
{ GoodId: 3, Name: '满天星', Price: 100, Total: 50, SellCount: 0 },
{ GoodId: 4, Name: '百合', Price: 500, Total: 200, SellCount: 0 }
];
function randomGood() {
var good = goods[Math.floor(Math.random() * 4)];
var buyCount = Math.ceil(Math.random() * (good.Total - good.SellCount < 10 ? good.Total - good.SellCount : 10));
good.SellCount += buyCount;
return { GoodId: goog.GoodId, BuyCount: buyCount };
}
var buyers = [];
function randomBuyer() {
if (Math.random() * 10 > 3 || buyers.length == 0) {
var buyerId = buyers.length + 1
var buyer = { BuyerId: buyerId, Name: 'buyer' + buyerId, Region: Math.floor(Math.random() * 34) };
buyers.push(buyer);
return buyer;
} else {
return buyers[Math.floor(Math.random() * buyers.length)];
}
}
var trades = [];
function randomTrade() {
var buyer = randomBuyer();
var good = randomGood();
// goods
}
function trade1() {
}
function dashboard(id, fData) {
var barColor = 'steelblue';
function segColor(c) { return { low: "#807dba", mid: "#e08214", high: "#41ab5d" }[c]; }
// compute total for each state.
fData.forEach(function (d) { d.total = d.freq.low + d.freq.mid + d.freq.high; });
// function to handle histogram.
function histoGram(fD) {
var hG = {}, hGDim = { t: 60, r: 0, b: 30, l: 0 };
hGDim.w = 500 - hGDim.l - hGDim.r,
hGDim.h = 300 - hGDim.t - hGDim.b;
//create svg for histogram.
var hGsvg = d3.select(id).append("svg")
.attr("width", hGDim.w + hGDim.l + hGDim.r)
.attr("height", hGDim.h + hGDim.t + hGDim.b).append("g")
.attr("transform", "translate(" + hGDim.l + "," + hGDim.t + ")");
// create function for x-axis mapping.
var x = d3.scale.ordinal().rangeRoundBands([0, hGDim.w], 0.1)
.domain(fD.map(function (d) { return d[0]; }));
// Add x-axis to the histogram svg.
hGsvg.append("g").attr("class", "x axis")
.attr("transform", "translate(0," + hGDim.h + ")")
.call(d3.svg.axis().scale(x).orient("bottom"));
// Create function for y-axis map.
var y = d3.scale.linear().range([hGDim.h, 0])
.domain([0, d3.max(fD, function (d) { return d[1]; })]);
// Create bars for histogram to contain rectangles and freq labels.
var bars = hGsvg.selectAll(".bar").data(fD).enter()
.append("g").attr("class", "bar");
//create the rectangles.
bars.append("rect")
.attr("x", function (d) { return x(d[0]); })
.attr("y", function (d) { return y(d[1]); })
.attr("width", x.rangeBand())
.attr("height", function (d) { return hGDim.h - y(d[1]); })
.attr('fill', barColor)
.on("mouseover", mouseover)// mouseover is defined below.
.on("mouseout", mouseout);// mouseout is defined below.
//Create the frequency labels above the rectangles.
bars.append("text").text(function (d) { return d3.format(",")(d[1]) })
.attr("x", function (d) { return x(d[0]) + x.rangeBand() / 2; })
.attr("y", function (d) { return y(d[1]) - 5; })
.attr("text-anchor", "middle");
function mouseover(d) { // utility function to be called on mouseover.
// filter for selected state.
var st = fData.filter(function (s) { return s.State == d[0]; })[0],
nD = d3.keys(st.freq).map(function (s) { return { type: s, freq: st.freq[s] }; });
// call update functions of pie-chart and legend.
pC.update(nD);
leg.update(nD);
}
function mouseout(d) { // utility function to be called on mouseout.
// reset the pie-chart and legend.
pC.update(tF);
leg.update(tF);
}
// create function to update the bars. This will be used by pie-chart.
hG.update = function (nD, color) {
// update the domain of the y-axis map to reflect change in frequencies.
y.domain([0, d3.max(nD, function (d) { return d[1]; })]);
// Attach the new data to the bars.
var bars = hGsvg.selectAll(".bar").data(nD);
// transition the height and color of rectangles.
bars.select("rect").transition().duration(500)
.attr("y", function (d) { return y(d[1]); })
.attr("height", function (d) { return hGDim.h - y(d[1]); })
.attr("fill", color);
// transition the frequency labels location and change value.
bars.select("text").transition().duration(500)
.text(function (d) { return d3.format(",")(d[1]) })
.attr("y", function (d) { return y(d[1]) - 5; });
}
return hG;
}
// function to handle pieChart.
function pieChart(pD) {
var pC = {}, pieDim = { w: 250, h: 250 };
pieDim.r = Math.min(pieDim.w, pieDim.h) / 2;
// create svg for pie chart.
var piesvg = d3.select(id).append("svg")
.attr("width", pieDim.w).attr("height", pieDim.h).append("g")
.attr("transform", "translate(" + pieDim.w / 2 + "," + pieDim.h / 2 + ")");
// create function to draw the arcs of the pie slices.
var arc = d3.svg.arc().outerRadius(pieDim.r - 10).innerRadius(0);
// create a function to compute the pie slice angles.
var pie = d3.layout.pie().sort(null).value(function (d) { return d.freq; });
// Draw the pie slices.
piesvg.selectAll("path").data(pie(pD)).enter().append("path").attr("d", arc)
.each(function (d) { this._current = d; })
.style("fill", function (d) { return segColor(d.data.type); })
.on("mouseover", mouseover).on("mouseout", mouseout);
// create function to update pie-chart. This will be used by histogram.
pC.update = function (nD) {
piesvg.selectAll("path").data(pie(nD)).transition().duration(500)
.attrTween("d", arcTween);
}
// Utility function to be called on mouseover a pie slice.
function mouseover(d) {
// call the update function of histogram with new data.
hG.update(fData.map(function (v) {
return [v.State, v.freq[d.data.type]];
}), segColor(d.data.type));
}
//Utility function to be called on mouseout a pie slice.
function mouseout(d) {
// call the update function of histogram with all data.
hG.update(fData.map(function (v) {
return [v.State, v.total];
}), barColor);
}
// Animating the pie-slice requiring a custom function which specifies
// how the intermediate paths should be drawn.
function arcTween(a) {
var i = d3.interpolate(this._current, a);
this._current = i(0);
return function (t) { return arc(i(t)); };
}
return pC;
}
// function to handle legend.
function legend(lD) {
var leg = {};
// create table for legend.
var legend = d3.select(id).append("table").attr('class', 'legend');
// create one row per segment.
var tr = legend.append("tbody").selectAll("tr").data(lD).enter().append("tr");
// create the first column for each segment.
tr.append("td").append("svg").attr("width", '16').attr("height", '16').append("rect")
.attr("width", '16').attr("height", '16')
.attr("fill", function (d) { return segColor(d.type); });
// create the second column for each segment.
tr.append("td").text(function (d) { return d.type; });
// create the third column for each segment.
tr.append("td").attr("class", 'legendFreq')
.text(function (d) { return d3.format(",")(d.freq); });
// create the fourth column for each segment.
tr.append("td").attr("class", 'legendPerc')
.text(function (d) { return getLegend(d, lD); });
// Utility function to be used to update the legend.
leg.update = function (nD) {
// update the data attached to the row elements.
var l = legend.select("tbody").selectAll("tr").data(nD);
// update the frequencies.
l.select(".legendFreq").text(function (d) { return d3.format(",")(d.freq); });
// update the percentage column.
l.select(".legendPerc").text(function (d) { return getLegend(d, nD); });
}
function getLegend(d, aD) { // Utility function to compute percentage.
return d3.format("%")(d.freq / d3.sum(aD.map(function (v) { return v.freq; })));
}
return leg;
}
// calculate total frequency by segment for all state.
var tF = ['low', 'mid', 'high'].map(function (d) {
return { type: d, freq: d3.sum(fData.map(function (t) { return t.freq[d]; })) };
});
// calculate total frequency by state for all segment.
var sF = fData.map(function (d) { return [d.State, d.total]; });
var hG = histoGram(sF), // create the histogram.
pC = pieChart(tF), // create the pie-chart.
leg = legend(tF); // create the legend.
}
var freqData = [
{ State: 'AL', freq: { low: 4786, mid: 1319, high: 249 } }
, { State: 'AZ', freq: { low: 1101, mid: 412, high: 674 } }
, { State: 'CT', freq: { low: 932, mid: 2149, high: 418 } }
, { State: 'DE', freq: { low: 832, mid: 1152, high: 1862 } }
, { State: 'FL', freq: { low: 4481, mid: 3304, high: 948 } }
, { State: 'GA', freq: { low: 1619, mid: 167, high: 1063 } }
, { State: 'IA', freq: { low: 1819, mid: 247, high: 1203 } }
, { State: 'IL', freq: { low: 4498, mid: 3852, high: 942 } }
, { State: 'IN', freq: { low: 797, mid: 1849, high: 1534 } }
, { State: 'KS', freq: { low: 162, mid: 379, high: 471 } }
];
dashboard('#dashboard', freqData);
nv.addGraph(function () {
var chart = nv.models.scatterChart()
.showDistX(true) //showDist, when true, will display those little distribution lines on the axis.
.showDistY(true)
.transitionDuration(350)
.color(d3.scale.category10().range());
//Configure how the tooltip looks.
chart.tooltipContent(function (key) {
return '<h3>' + key + '</h3>';
});
//Axis settings
chart.xAxis.tickFormat(d3.format('.02f'));
chart.yAxis.tickFormat(d3.format('.02f'));
//We want to show shapes other than circles.
chart.scatter.onlyCircles(false);
var myData = randomData(4, 40);
d3.select('#chart svg')
.datum(myData)
.call(chart);
nv.utils.windowResize(chart.update);
return chart;
});
/**************************************
* Simple test data generator
*/
function randomData(groups, points) { //# groups,# points per group
var data = [],
shapes = ['circle', 'cross', 'triangle-up', 'triangle-down', 'diamond', 'square'],
random = d3.random.normal();
for (i = 0; i < groups; i++) {
data.push({
key: 'Group ' + i,
values: []
});
for (j = 0; j < points; j++) {
data[i].values.push({
x: random()
, y: random()
, size: Math.random() //Configure the size of each scatter point
, shape: (Math.random() > 0.95) ? shapes[j % 6] : "circle" //Configure the shape of each scatter point.
});
}
}
return data;
}
| sanrabbit/d3js-slides | practice/C2C_Trade/main.js | JavaScript | mit | 11,837 |
module.exports = NotImplementedError => {
const throwNotImplemented = function () {
throw new NotImplementedError()
};
/**
* Controller control interface
*
* @interface
* @memberof module:client.synth
*/
var Controller = throwNotImplemented;
/**
* Asks the controller to start capturing control events
*
* @memberof module:client.synth.Controller
*
* @return {Promise}
*/
Controller.prototype.attach = throwNotImplemented;
/**
* Asks the controller to stop capturing control events
*
* @memberof module:client.synth.Controller
*
* @return {Promise}
*/
Controller.prototype.detach = throwNotImplemented;
return Controller;
};
| floriansimon1/learning.websynth | source/client/synth/controller.js | JavaScript | mit | 760 |
import Ember from 'ember';
import { stack } from 'd3-shape';
import addOptionsToStack from '../utils/add-options-to-stack';
export function d3Stack( [ data, args ], hash={}) {
return addOptionsToStack(stack(data, args), hash);
}
export default Ember.Helper.helper(d3Stack);
| LocusEnergy/ember-d3-helpers | addon/helpers/d3-stack.js | JavaScript | mit | 278 |
var PROPS = injectProps;
var hookOnReload = injectOnReload;
const io = require('socket.io-client');
const socket = io(`http://127.0.0.1:${PROPS.port}`);
const { id: ext_id } = chrome.runtime;
const onReload = (query = {}, cb) => {
query = Object.assign({
url: [`chrome-extension://${ext_id}/*`]
}, query);
chrome.tabs.query(query, (tabs) => {
cb(tabs);
hookOnReload();
chrome.runtime.reload();
});
};
const onReopen = (tabs = [], cb) => {
tabs.forEach((tab) => {
var { windowId, index, url, active, pinned, openerTabId } = tab;
var new_tab = { windowId, index, url, active, pinned, openerTabId };
chrome.tabs.create(new_tab);
});
cb(tabs);
}
socket.on('reload', onReload);
socket.on('reopen', onReopen); | padurets/web-extension-webpack-plugin | src/client.js | JavaScript | mit | 793 |
define(['views/Index','views/Cart','views/CategoryEdit','views/Categories','views/Product','views/Products','views/ProductEdit','views/ProductDetail','views/admin/Index','models/Product','models/Category','models/CartCollection','models/ProductCollection','models/CategoryCollection'], function(IndexView,CartView,CategoryEditView,CategoriesView,ProductView,ProductsView,ProductEditView,ProductDetailView,AdminIndexView,Product,Category,CartCollection,ProductCollection,CategoryCollection){
var BizRouter = Backbone.Router.extend({
currentView : null,
routes: {
'': 'index',
'index': 'index',
'cart': 'myCart',
'products(/:id)': 'products',
'product/add(/:cid)': 'productAdd',
'product/edit/:id': 'productEdit',
'product/view/:id': 'productView',
'categories(/:id)': 'categories',
'category/add(/:pid)': 'categoryAdd',
'category/edit/:id': 'categoryEdit',
'admin/index': 'adminIndex',
},
changeView: function(view){
if(null != this.currentView){
this.currentView.undelegateEvents();
}
this.currentView = view;
this.currentView.render();
},
index: function(){
this.changeView(new IndexView());
},
myCart: function(){
var cartCollection = new CartCollection();
cartCollection.url = '/cart';
this.changeView(new CartView({collection:cartCollection}));
cartCollection.fetch();
},
/** product related */
products: function(id){
var cid = id || '';
var productCollection = new ProductCollection();
productCollection.url = '/products?cid=' + cid;;
this.changeView(new ProductsView({collection: productCollection}));
productCollection.fetch();
},
productAdd: function(categoryId){
var cid = categoryId || '';
var productModel = new Product({
main_cat_id: cid,
});
this.changeView(new ProductEditView({model: productModel}));
},
productEdit: function(id){
var product = new Product();
product.url = '/products/' + id;
this.changeView(new ProductEditView({model: product}));
product.fetch();
},
productView: function(id){
var product = new Product();
product.url = '/products/' + id;
this.changeView(new ProductDetailView({model: product}));
product.fetch();
},
/** category related */
categories: function(id){
var pid = id || '';
var categoryCollection = new CategoryCollection();
categoryCollection.url = '/categories?pid=' + pid;
this.changeView(new CategoriesView({collection: categoryCollection}));
categoryCollection.fetch();
},
categoryAdd: function(parentId){
var pid = parentId || '';
var categoryModel = new Category({
parent: pid
});
this.changeView(new CategoryEditView({model: categoryModel}));
},
categoryEdit: function(id){
var category = new Category();
category.url = '/categories/' + id;
this.changeView(new CategoryEditView({model: category}));
category.fetch();
},
adminIndex: function(){
this.changeView(new AdminIndexView());
}
});
return new BizRouter();
}); | williambai/beyond-webapp | e-biz/public/js/router.js | JavaScript | mit | 3,019 |
import authorAPI from '../api/mock/mockAuthorAPI';
import * as types from './actionTypes';
import { beginAjaxCall } from './ajaxStatusActions';
const loadAuthorSuccess = (courses) => {
return {type : types.LOAD_AUTHOR_SUCCESS, courses };
};
const loadAuthors = () => {
return (dispatch) => {
dispatch(beginAjaxCall());
return authorAPI.getAllAuthors().then(authors => {
dispatch(loadAuthorSuccess(authors));
}).catch(error => {
throw(error);
});
};
};
export {
loadAuthors,
loadAuthorSuccess
};
| anztrax/react-redux-01 | src/actions/authorActions.js | JavaScript | mit | 536 |
function extensibleObject() {
let obj = {
extend: function(template){
for(let parentProp of Object.keys(template)){
if(typeof(template[parentProp]) == 'function'){
Object.getPrototypeOf(obj)[parentProp] = template[parentProp];
} else {
obj[parentProp] = template[parentProp];
}
}
}
};
return obj;
} | Michaela07313/JavaScript-Core | Object Composition - labs and exercises/ExtensibleObject.js | JavaScript | mit | 439 |
'use strict';
const migrate = require('../scripts/migrate-sql');
exports.up = db => migrate.migrate(db, '20180515155000-app-features.sql');
| keboola/developer-portal | migrations/20180515155000-app-features.js | JavaScript | mit | 142 |
const path = require('path');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const resolve = (dir) => {
return path.join(__dirname, '..', dir)
};
const isProduction = process.env.NODE_ENV === 'production';
const config = {
output: {
path: path.join(__dirname, '..', 'dist', 'assets'),
filename: '[name].[hash].js',
publicPath: '/assets/',
},
resolve: {
extensions: ['.js', '.vue', '.json'],
alias: {
'~': resolve('src'),
'vue$': 'vue/dist/vue.runtime.esm.js',
'vuex$': 'vuex/dist/vuex.esm.js',
},
},
module: {
rules: [
{
test: /\.js$/,
include: [
resolve('src'),
resolve('node_modules/@material'),
],
use: ['babel-loader'],
},
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
extractCSS: isProduction,
postcss: [
require('autoprefixer')({
browsers: ['IE 9', 'IE 10', 'IE 11', 'last 2 versions'],
}),
],
},
},
],
},
plugins: [
new CopyWebpackPlugin([
{
from: resolve('src/static'),
to: resolve('dist'),
},
]),
],
};
module.exports = config;
| mya-ake/vuejs-pwa-and-ssr-on-lambda | dev/webpack.base.config.js | JavaScript | mit | 1,237 |
var expect = require("chai").expect;
var MoodleExporter = require('../../MoodleExporter');
var xml2js = require('xml2js');
describe('MoodleExporter', function () {
var validSeed = 'abcd1234';
var validQD = {
"version": "0.1",
"questions": [{
"question": "mc-change-of-base",
"repeat": 2,
}]
};
describe('generateMoodleXML(qd, seed)', function () {
describe('throwing errors', function () {
describe('when qd is invalid problemType', function () {
it('should throw an error.', function () {
expect(function () {
MoodleExporter.generateMoodleXML({ "invalid": "qd" }, validSeed)
}).to.throw(Error);
});
});
describe('invalid seed', function () {
it("should throw an error", function () {
expect(function () {
MoodleExporter.generateMoodleXML(validQD, "invalid-seed");
}).to.throw(Error);
});
});
});
describe('successful conversion', function () {
var xmlResult, xmlString;
describe('general requirements', function () {
beforeEach(function (done) {
try {
xmlString = MoodleExporter.generateMoodleXML(validQD, validSeed);
} catch(e) {
console.log(e);
throw e;
}
xml2js.parseString(xmlString, function (err, result) {
xmlResult = result;
done();
});
});
describe('xml quiz tag', function () {
it('should set the quiz tag', function () {
expect(xmlResult.quiz).to.exist;
});
});
describe('xml question', function () {
it('should have the # of questions specified by the count parameter', function () {
expect(xmlResult.quiz.question.length).to.equal(2);
});
});
});
describe('multiple problemTypes', function () {
beforeEach(function (done) {
var qd = {
"version": "0.1",
"questions": [{
"question": "mc-change-of-base",
"repeat": 1,
},
{
"question": "fr-change-of-base",
"repeat": 1,
}]
};
xmlString = MoodleExporter.generateMoodleXML(qd, validSeed);
xml2js.parseString(xmlString, function (err, result) {
xmlResult = result;
done();
});
});
describe('first question title', function () {
it('should be Change of Base Multiple Choice', function () {
expect(xmlResult.quiz.question[0].name[0].text[0]).to.equal("Change of Base Multiple Choice");
});
});
describe('second question title', function () {
it('should be Change of Base Free Response', function () {
expect(xmlResult.quiz.question[1].name[0].text[0]).to.equal("Change of Base Free Response");
});
});
});
describe('different formats', function () {
describe('multiple choice format', function () {
beforeEach(function (done) {
problemTypeRequested = 'mc-change-of-base';
count = 2;
questionName = 'Sample Question Name';
var qd = {
"version": "0.1",
"questions": [{
"question": problemTypeRequested,
"repeat": count,
}]
};
xmlString = MoodleExporter.generateMoodleXML(qd, validSeed);
xml2js.parseString(xmlString, function (err, result) {
xmlResult = result;
done();
});
});
//TODO: fix output type references -- previously may have been question type MC vs free response
describe('xml output type', function () {
it('should have set the output type attribute to multichoice', function () {
for (var i = 0; xmlResult.quiz.question.length > i; i++)
expect(xmlResult.quiz.question[i].$.type).to.equal('multichoice');
});
});
describe('xml question title', function () {
it('should be Change of Base Multiple Choice', function () {
expect(xmlResult.quiz.question[0].name[0].text[0]).to.equal("Change of Base Multiple Choice");
});
});
});
describe('input format', function () {
beforeEach(function (done) {
problemTypeRequested = 'fr-change-of-base';
count = 2;
questionName = 'Sample Question Name';
var qd = {
"version": "0.1",
"questions": [{
"question": problemTypeRequested,
"repeat": count,
}]
};
xmlString = MoodleExporter.generateMoodleXML(qd, validSeed);
xml2js.parseString(xmlString, function (err, result) {
xmlResult = result;
done();
});
});
//TODO: fix output type references -- previously may have been question type MC vs free response
//TODO: shortanswer vs free-response
describe('xml output type property', function () {
it('should have set the output type attribute to shortanswer', function () {
for (var i = 0; xmlResult.quiz.question.length > i; i++)
expect(xmlResult.quiz.question[i].$.type).to.equal('shortanswer');
});
});
describe('xml question title', function () {
it('should be Change of Base Free Response', function () {
expect(xmlResult.quiz.question[0].name[0].text[0]).to.equal("Change of Base Free Response");
});
});
describe('question.answer.text', function () {
it('should exist', function () {
expect(xmlResult.quiz.question[0].answer[0].text).to.exist;
});
});
});
});
});
});
});
| project-awesome/project-awesome | test/MoodleExporter/index.js | JavaScript | mit | 7,608 |
import { expect } from 'chai';
import Urlsparser from '../src/app.js';
describe('wrong', () => {
it('...', () => {
const caps = () => {new Urlsparser('...')};
expect(caps).to.throw();
});
it('+++abs+', () => {
const caps = () => {new Urlsparser('+++abs+')};
expect(caps).to.throw();
});
it('0:5:92', () => {
const caps = () => {new Urlsparser('0:5:92')};
expect(caps).to.throw();
});
});
| rushix/urlsparser | test/wrong.js | JavaScript | mit | 429 |
import chai from 'chai';
import chaiAsPromised from 'chai-as-promised';
import sinon from 'sinon';
import sinonChai from 'sinon-chai';
import {BasePaginator, errors} from './base-paginator';
import PaginatorError from '../paginator-error';
import * as queryHandler from '../helpers/query-handler-stub';
import * as request from '../helpers/request-spy';
const {assert, expect} = chai;
chai.use(chaiAsPromised);
chai.use(sinonChai);
describe('drf-paginator', function() {
afterEach(function() {
request.spy.reset();
queryHandler.resetSpies();
});
describe('BasePaginator', function() {
let paginator;
const makePaginator = function(queryParams) {
paginator = new BasePaginator(request.spy)
.setQueryHandler(queryHandler.stub);
if (queryParams) {
paginator.setQueryParams(queryParams);
}
};
describe('page', function() {
beforeEach(function() {
makePaginator();
});
it('defaults to zero', function() {
expect(paginator.page).to.equal(0);
});
});
describe('queryHandler', function() {
beforeEach(function() {
paginator = new BasePaginator(request.spy);
});
it('defaults to `null`', function() {
expect(paginator.page).to.equal(0);
});
});
describe('next', function() {
beforeEach(function() {
makePaginator();
});
it('returns a promise that resolves', function() {
const promise = paginator.next();
return expect(promise).to.eventually.resolve;
});
it('returns a promise with a response object', function() {
const response = paginator.next();
return expect(response).to.eventually.be.an('object');
});
it('increments the page', function() {
expect(paginator.page).to.equal(0);
const page = paginator.next()
.then(() => paginator.page);
return expect(page).to.eventually.equal(1);
});
it('sends a request using the request function', function() {
const requestCallCount = paginator.next()
.then(request.getCallCount);
return expect(requestCallCount).to.eventually.equal(1);
});
});
describe('prev', function() {
beforeEach(function() {
makePaginator({ page: 2 });
});
it('returns a promise that resolves', function() {
const promise = paginator.prev();
return expect(promise).to.eventually.resolve;
});
it('returns a promise with a response object', function() {
const response = paginator.prev();
return expect(response).to.eventually.be.an('object');
});
it('decrements the page', function() {
expect(paginator.page).to.equal(2);
const page = paginator.prev()
.then(() => paginator.page);
return expect(page).to.eventually.equal(1);
});
it('sends a request using the request function', function() {
const requestCallCount = paginator.prev()
.then(request.getCallCount);
return expect(requestCallCount).to.eventually.equal(1);
});
});
describe('first', function() {
beforeEach(function() {
makePaginator();
});
it('returns a promise that resolves', function() {
const promise = paginator.first();
return expect(promise).to.eventually.resolve;
});
it('returns a promise with a response object', function() {
const response = paginator.first();
return expect(response).to.eventually.be.an('object');
});
it('sets the page to the first page ', function() {
expect(paginator.page).to.equal(0);
const page = paginator.first()
.then(() => paginator.page);
return expect(page).to.eventually.equal(1);
});
it('sends a request using the request function', function() {
const requestCallCount = paginator.first()
.then(request.getCallCount);
return expect(requestCallCount).to.eventually.equal(1);
});
});
describe('last', function() {
beforeEach(function() {
makePaginator();
});
it('returns a promise that resolves', function() {
const promise = paginator.last();
return expect(promise).to.eventually.resolve;
});
it('returns a promise with a response object', function() {
const response = paginator.last();
return expect(response).to.eventually.be.an('object');
});
it('sets the paginator\'s current page to the last page', function() {
expect(paginator.page).to.equal(0);
const page = paginator.last()
.then(() => paginator.page);
return expect(page).to.eventually.equal(10);
});
it('sends requests to get the page count and the last page.',
function() {
const requestCallCount = paginator.last()
.then(request.getCallCount);
return expect(requestCallCount).to.eventually.equal(2);
});
});
describe('current', function() {
beforeEach(function() {
makePaginator({ page: 1 });
});
it('returns a promise that resolves', function() {
const promise = paginator.current();
return expect(promise).to.eventually.resolve;
});
it('doesn\'t change the page', function() {
expect(paginator.page).to.equal(1);
const page = paginator.current()
.then(() => paginator.page);
return expect(page).to.eventually.equal(1);
});
it('sends a request using the request function', function() {
const requestCallCount = paginator.current()
.then(request.getCallCount);
return expect(requestCallCount).to.eventually.equal(1);
});
});
describe('fetchPage', function() {
beforeEach(function() {
makePaginator();
});
it('returns a promise that resolves', function() {
const promise = paginator.fetchPage(1);
return expect(promise).to.eventually.resolve;
});
it('returns a promise with a response object', function() {
const response = paginator.fetchPage(1);
return expect(response).to.eventually.be.an('object');
});
it('sends a request using the request function', function() {
const requestCallCount = paginator.fetchPage(1)
.then(request.getCallCount);
return expect(requestCallCount).to.eventually.equal(1);
});
it('returns a rejected promise for pages before the first page',
function() {
const promise = paginator.fetchPage(0);
return expect(promise).to.eventually.be.rejectedWith(Error);
});
it('rejects pages after the last page when the page count is known',
function() {
// The max page of the fixture is 10
const promise = paginator.fetchPageCount()
.then(() => paginator.fetchPage(13));
return expect(promise).to.eventually.be.rejectedWith(Error);
});
it('accepts pages after the last page when the page count is unknown',
function() {
const promise = paginator.fetchPage(13);
return expect(promise).to.eventually.resolve;
});
it('clone responses', function() {
const first = paginator.fetchPage(1);
const second = first.then(() => paginator.fetchPage(1));
return Promise.all([first, second])
.spread(assert.notStrictEqual);
});
it('caches requests', function() {
const first = paginator.fetchPage(1)
.then((res) => res.uniqueValue);
const second = first.then(() => paginator.fetchPage(1))
.then((res) => res.uniqueValue);
return Promise.all([first, second])
.spread(assert.strictEqual);
});
it('calls the query handler\'s `onResponse` method', function() {
const onResponseCallCount = paginator.fetchPage(1)
.then(() => queryHandler.stub.onResponse.callCount);
return expect(onResponseCallCount).to.eventually.equal(1);
});
it('throws an error if the query handler isn\'t set', function() {
paginator.queryHandler = null;
const check = function() {
paginator.fetchPage(1);
};
const msg = errors.queryHandlerMissing;
return expect(check).to.throw(PaginatorError, msg);
});
});
describe('fetchPageCount', function() {
beforeEach(function() {
makePaginator();
sinon.spy(paginator, 'fetchPage');
});
afterEach(function() {
paginator.fetchPage.restore();
});
it('returns a promise that resolves', function() {
const promise = paginator.fetchPageCount();
return expect(promise).to.eventually.resolve;
});
it('returns a promise with the paginator\'s page count', function() {
const pageCount = paginator.fetchPageCount();
return expect(pageCount).to.eventually.equal(10);
});
it('caches the page count', function() {
const fetchPageCallCount = paginator.fetchPageCount()
.then(() => paginator.fetchPageCount())
.then(() => paginator.fetchPage.callCount);
return expect(fetchPageCallCount).to.eventually.equal(1);
});
});
describe('setQueryHandler', function() {
beforeEach(function() {
paginator = new BasePaginator(request.spy);
});
it('sets the query handler', function() {
const obj = {};
paginator.setQueryHandler(obj);
expect(paginator.queryHandler).to.equal(obj);
});
it('is a fluent method', function() {
var result = paginator.setQueryHandler({});
expect(result).to.equal(paginator);
});
});
describe('setQueryParams', function() {
beforeEach(function() {
makePaginator();
});
it('sets the parameters in the query handler', function() {
const queryParams = { page: 42 };
paginator.setQueryParams(queryParams);
expect(paginator.queryHandler.setParams)
.to.have.been.calledWithMatch(queryParams);
});
it('updates the paginator\'s page based on the given parameters',
function() {
expect(paginator.page).to.equal(0);
paginator.setQueryParams({ page: 42 });
expect(paginator.page).to.equal(42);
});
it('is a fluent method', function() {
var result = paginator.setQueryParams({});
expect(result).to.equal(paginator);
});
});
});
});
| yola/drf-paginator | src/paginators/base-paginator-spec.js | JavaScript | mit | 10,685 |
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zm6.93 6h-2.95c-.32-1.25-.78-2.45-1.38-3.56 1.84.63 3.37 1.91 4.33 3.56zM12 4.04c.83 1.2 1.48 2.53 1.91 3.96h-3.82c.43-1.43 1.08-2.76 1.91-3.96zM4.26 14C4.1 13.36 4 12.69 4 12s.1-1.36.26-2h3.38c-.08.66-.14 1.32-.14 2s.06 1.34.14 2H4.26zm.82 2h2.95c.32 1.25.78 2.45 1.38 3.56-1.84-.63-3.37-1.9-4.33-3.56zm2.95-8H5.08c.96-1.66 2.49-2.93 4.33-3.56C8.81 5.55 8.35 6.75 8.03 8zM12 19.96c-.83-1.2-1.48-2.53-1.91-3.96h3.82c-.43 1.43-1.08 2.76-1.91 3.96zM14.34 14H9.66c-.09-.66-.16-1.32-.16-2s.07-1.35.16-2h4.68c.09.65.16 1.32.16 2s-.07 1.34-.16 2zm.25 5.56c.6-1.11 1.06-2.31 1.38-3.56h2.95c-.96 1.65-2.49 2.93-4.33 3.56zM16.36 14c.08-.66.14-1.32.14-2s-.06-1.34-.14-2h3.38c.16.64.26 1.31.26 2s-.1 1.36-.26 2h-3.38z" />
, 'LanguageSharp');
| kybarg/material-ui | packages/material-ui-icons/src/LanguageSharp.js | JavaScript | mit | 934 |
var keypress = require("keypress");
// var Spark = require("spark-io");
var Spark = require("../");
var five = require("johnny-five");
var Sumobot = require("sumobot")(five);
keypress(process.stdin);
var board = new five.Board({
io: new Spark({
token: process.env.SPARK_TOKEN,
deviceId: process.env.SPARK_DEVICE_2
})
});
board.on("ready", function() {
console.log("Welcome to Sumobot Jr: Light Bot!");
var bot = new Sumobot({
left: "D0",
right: "D1",
speed: 0.50
});
var light = new five.Sensor("A0");
var isQuitting = false;
light.on("change", function() {
if (isQuitting || this.value === null) {
return;
}
if (this.value < 512) {
bot.fwd();
} else {
bot.rev();
}
});
// Ensure the bot is stopped
bot.stop();
});
| gregory-j-weaver/nodebots-a2handsonmuseum | node_modules/particle-io/eg/lightbot.js | JavaScript | mit | 804 |
require([
'app/LoginRegisterCloudRequestPane',
'dojo/dom-construct',
'dojo/query'
], function(
WidgetUnderTest,
domConstruct,
query
) {
describe('app/LoginRegisterCloudRequestPane', function() {
var widget;
var destroy = function(widget) {
widget.destroyRecursive();
widget = null;
};
beforeEach(function() {
widget = new WidgetUnderTest(null, domConstruct.create('div', null, document.body));
query(
'input[type="text"], input[type="password"], input[type="email"]',
widget.domNode
).forEach(function(node) {
node.value = 'anything';
});
});
afterEach(function() {
if (widget) {
destroy(widget);
}
});
describe('Sanity', function() {
it('should create a LoginRegisterCloudRequestPane', function() {
expect(widget).toEqual(jasmine.any(WidgetUnderTest));
});
});
describe('Password Restrictions', function() {
it('should be 8 characters in length', function() {
expect(widget.validate('aB1234$&').result).toEqual(true);
expect(widget.validate('aB1&').result).toEqual(false);
});
it('should have one uppercase letter', function() {
expect(widget.validate('aB1234$&').result).toEqual(true);
expect(widget.validate('ab1234$&').result).toEqual(false);
});
it('should have one lowercase letter', function() {
expect(widget.validate('aB1234$&').result).toEqual(true);
expect(widget.validate('AB1234$&').result).toEqual(false);
});
it('should have one special character', function() {
expect(widget.validate('aB1234$&').result).toEqual(true);
expect(widget.validate('aB123456').result).toEqual(false);
});
it('should have one number', function() {
expect(widget.validate('aB1234$&').result).toEqual(true);
expect(widget.validate('aB!@#$%^').result).toEqual(false);
});
});
});
}); | agrc/PEL | src/app/tests/spec/SpecLoginRegisterCloudRequestPane.js | JavaScript | mit | 2,281 |
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var makeCommandAbsolute = exports.makeCommandAbsolute = function makeCommandAbsolute(p, c) {
switch (c.c) {
case 'm':
return { c: 'M', x: p.x + c.dx, y: p.y + c.dy };
case 'z':
return { c: 'Z' };
case 'l':
return { c: 'L', x: p.x + c.dx, y: p.y + c.dy };
case 'h':
return { c: 'L', x: p.x + c.dx, y: p.y };
case 'v':
return { c: 'L', y: p.y + c.dy, x: p.x };
case 'H':
return { c: 'L', x: c.x, y: p.y };
case 'V':
return { c: 'L', y: c.y, x: p.x };
case 'c':
return { c: 'C', x1: p.x + c.dx1, y1: p.y + c.dy1, x2: p.x + c.dx2, y2: p.y + c.dy2, x: p.x + c.dx, y: p.y + c.dy };
case 's':
return { c: 'S', x2: p.x + c.dx2, y2: p.y + c.dy2, x: p.x + c.dx, y: p.y + c.dy };
case 'q':
return { c: 'Q', x1: p.x + c.dx1, y1: p.y + c.dy1, x: p.x + c.dx, y: p.y + c.dy };
case 't':
return { c: 'T', x: p.x + c.dx, y: p.y + c.dy };
case 'a':
return { c: 'A', rx: c.rx, ry: c.ry, xAxisRotation: c.xAxisRotation, largeArcFlag: c.largeArcFlag, sweepFlag: c.sweepFlag, x: p.x + c.dx, y: p.y + c.dy };
default:
return c;
}
};
var applyCommand = exports.applyCommand = function applyCommand(position, begin, c) {
var dif = { dx: 0, dy: 0 };
if (c.c === 'm') dif = c;else if (c.c === 'l') dif = c;else if (c.c === 'c') dif = c;else if (c.c === 's') dif = c;else if (c.c === 'q') dif = c;else if (c.c === 't') dif = c;else if (c.c === 'a') dif = c;else if (c.c === 'h') dif = { dx: c.dx, dy: 0 };else if (c.c === 'v') dif = { dx: 0, dy: c.dy };else if (c.c === 'z') dif = { dx: begin.x - position.x, dy: begin.y - position.y };else if (c.c === 'V') return { x: position.x, y: c.y };else if (c.c === 'H') return { x: c.x, y: position.y };else if (c.c === 'Z') return begin;else {
return c;
}
return { x: position.x + dif.dx, y: position.y + dif.dy };
};
var normalizeData = exports.normalizeData = function normalizeData(d) {
var begin = { x: 0, y: 0 };
var position = { x: 0, y: 0 };
var result = [];
for (var i = 0; i < d.length; i++) {
var command = d[i];
var absoluteCommand = makeCommandAbsolute(position, command);
var newPosition = applyCommand(position, begin, absoluteCommand);
// Filter line commands which doesn't change position
var isLineCommand = absoluteCommand.c === 'L' || absoluteCommand.c === 'Z';
if (!isLineCommand || !pointEquals(newPosition, position)) {
result.push(absoluteCommand);
position = newPosition;
}
if (absoluteCommand.c === 'M') {
begin = absoluteCommand;
} else if (absoluteCommand.c === 'm') {
begin = applyCommand(position, begin, absoluteCommand);
}
}
return result;
};
var getSubPaths = exports.getSubPaths = function getSubPaths(d) {
if (d.length === 0) {
return [];
} else if (d[0].c !== 'M' && d[0].c !== 'm') {
throw new Error('Path must start with an "M" or "m" command, not "' + d[0].c + '" ');
}
var result = [];
var nextSubPath = [];
var lastM = { c: 'M', x: 0, y: 0 };
d.forEach(function (command) {
if (command.c === 'M') {
if (nextSubPath.length > 0) {
result.push(nextSubPath);
}
nextSubPath = [command];
lastM = command;
} else if (command.c === 'Z') {
nextSubPath.push(command);
result.push(nextSubPath);
nextSubPath = [];
} else {
if (nextSubPath.length === 0) {
nextSubPath.push(lastM);
}
nextSubPath.push(command);
}
});
if (nextSubPath.length > 0) {
result.push(nextSubPath);
}
return result;
};
var isSubPathClosed = exports.isSubPathClosed = function isSubPathClosed(begin, d) {
if (d.length < 2) {
return true;
}
var lastCommand = d[d.length - 1];
if (lastCommand.c === 'Z') {
return true;
}
return lastCommand.x === begin.x && lastCommand.y === begin.y;
};
var pointEquals = exports.pointEquals = function pointEquals(p1, p2) {
return p1.x === p2.x && p1.y === p2.y;
}; | koluch/svg-path-round-corners | dist/es5/utils.js | JavaScript | mit | 4,444 |
"use strict"
/**
* `format` constructor.
*
* @api public
*/
const checkStatusCode = require('./helpers');
module.exports = {
create : (statusCode, error, message, data) => {
if(!statusCode) throw new Error('Status code is required')
if( isNaN( Number( statusCode))) throw new Error('Status code not a number')
this.statusCode = statusCode
this.error = error || null
this.data = data || null
this.message = checkStatusCode(this.statusCode, message)
return this
},
success: (message, data) => {
this.statusCode = 200
this.error = false
this.data = data || null
this.message = message || 'OK'
return this
},
badRequest: (message, data) => {
this.statusCode = 400
this.error = true
this.data = data || null
this.message = message || 'Bad Request'
return this
},
unAuthorized: (message, data) => {
this.statusCode = 401
this.error = true
this.data = data || null
this.message = message || 'Unauthorized'
return this
},
forbidden: (message, data) => {
this.statusCode = 403
this.error = true
this.data = data || null
this.message = message || 'Forbidden'
return this
},
notFound: (message, data) => {
this.statusCode = 404
this.error = true
this.data = data || null
this.message = message || 'Not Found'
return this
},
notAllowed: (message, data) => {
this.statusCode = 405
this.error = true
this.data = data || null
this.message = message || 'Method Not Allowed'
return this
},
requestTimeout: (message, data) => {
this.statusCode = 408
this.error = true
this.data = data || null
this.message = message || 'Request Timeout'
return this
},
internalError: (message, data) => {
this.statusCode = 500
this.error = true
this.data = data || null
this.message = message || 'Internal Server Error'
return this
},
badGateway: (message, data) => {
this.statusCode = 502
this.error = true
this.data = data || null
this.message = message || 'Bad Gateway'
return this
},
unavailable: (message, data) => {
this.statusCode = 503
this.error = true
this.data = data || null
this.message = message || 'Service Unavailable'
return this
},
gatewayTimeout: (message, data) => {
this.statusCode = 504
this.error = true
this.data = data || null
this.message = message || 'Gateway Timeout'
return this
}
}
| GJ2511/response-format | lib/format.js | JavaScript | mit | 2,391 |
'use strict';
var request = require('supertest'),
chai = require('chai'),
expect = chai.expect,
routeValidator = require('../lib/index'),
validator = require('validator'),
express = require('express'),
bodyParser = require('body-parser'),
async = require('async');
describe('INTEGRATION index', function () {
describe('#validates(config)', function () {
describe('basic route validation', function () {
var app;
before( function () {
app = express();
app.get('/items/:item', routeValidator.validate({
params: {
item: { isMongoId: true, isRequired: true }
}
}), function (req, res) {
return res.status(200).end();
});
});
it('should send a 400 when route fails validation', function (done) {
request(app)
.get('/items/aasdklfjklsadlfjik')
.expect(400, done);
});
it('should send a 200 when route passes validation', function (done) {
request(app)
.get('/items/507f1f77bcf86cd799439011')
.expect(200, done);
});
it('should not care if you pass in properties it does not know about', function (done) {
request(app)
.get('/items/507f1f77bcf86cd799439011')
.query({
foo: 'bar',
notes: ''
})
.expect(200, done);
});
it('should ignore properties that you configure that it does not have a method to do' , function (done) {
// i.e. 'description' is set on the validation config object for documentation purposes,
// but routeValidator doesn't care and just ignores it
request(app)
.get('/items/507f1f77bcf86cd799439011')
.expect(200, done);
});
});
describe('validates req.params', function () {
var app;
before( function () {
app = express();
app.get('/items/:item', routeValidator.validate({
params: {
item: { isMongoId: true, isRequired: true }
}
}), function (req, res) {
return res.status(200).end();
});
app.get('/items/:item/messages/:message', routeValidator.validate({
params: {
item: { isMongoId: true, isRequired: true },
message: { isMongoId: true, isRequired: true }
}
}), function (req, res) {
return res.status(200).end();
});
});
it('should validate params passed into route, on success', function (done) {
request(app)
.get('/items/507f1f77bcf86cd799439011')
.expect(200, done);
});
it('should validate params passed into route, on failure', function (done) {
request(app)
.get('/items/banana')
.expect(400, function (err, res) {
if (err) return done(err);
expect(res.body).to.have.property('error').that.contains('params.item');
return done();
});
});
it('should handle multiple params passed into route, on success', function (done) {
request(app)
.get('/items/507f1f77bcf86cd799439011/messages/407f1f77bcf86cd799439011')
.expect(200, done);
});
it('should handle multiple params passed into route, on failure', function (done) {
request(app)
.get('/items/507f1f77bcf86cd799439011/messages/banana')
.expect(400, function (err, res) {
if (err) return done(err);
expect(res.body).to.have.property('error').that.contains('params.message');
return done();
});
});
});
describe('validates req.body', function () {
var app;
before( function () {
app = express();
app.use(bodyParser.json());
app.post('/items', routeValidator.validate({
body: {
name: { isRequired: true },
date: { isRequired: true, isDate: true },
type: { isRequired: true, isIn: ['lawn', 'garden', 'tools'] },
user: { isRequired: true, isEmail: true },
uuid: { isRequired: false, isUUID: true },
url: { isURL: true },
rate: { isInt: true, toInt: true }
}
}), function (req, res) {
return res.status(200).end();
});
});
it('should validate params passed into body, on success', function (done) {
request(app)
.post('/items')
.send({
name: 'Chainsaw',
date: new Date(),
type: 'tools',
user: 'stevie@tool.com',
uuid: 'A987FBC9-4BED-3078-CF07-9141BA07C9F3',
url: 'http://tool.com/chainsaw/real-big'
})
.expect(200, done);
});
it('should validate params passed into body, on failure', function (done) {
request(app)
.post('/items')
.send({
name: 'Chainsaw',
date: new Date(),
type: 'tool', // invalid
user: 'stevie@tool.com',
uuid: 'A987FBC9-4BED-3078-CF07-9141BA07C9F3',
url: 'http://tool.com/chainsaw/real-big'
})
.expect(400, function (err, res) {
if (err) return done(err);
expect(res.body).to.have.property('error').that.contains('body.type');
return done();
});
});
it('should enforce isRequired', function (done) {
request(app)
.post('/items')
.send({
name: 'Chainsaw',
date: new Date(),
type: 'tools',
// user: 'stevie@tool.com',
uuid: 'A987FBC9-4BED-3078-CF07-9141BA07C9F3',
url: 'http://tool.com/chainsaw/real-big'
})
.expect(400, function (err, res) {
if (err) return done(err);
expect(res.body).to.have.property('error').that.contains('body.user');
return done();
});
});
it('should not fail validation when isRequired is set to false and param is not set', function (done) {
request(app)
.post('/items')
.send({
name: 'Chainsaw',
date: new Date(),
type: 'tools',
user: 'stevie@tool.com',
// uuid: 'A987FBC9-4BED-3078-CF07-9141BA07C9F3',
url: 'http://tool.com/chainsaw/real-big'
})
.set('Authorization', 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==')
.expect(200, done);
});
it('should not fail validation when isRequired is not set and param is not set', function (done) {
request(app)
.post('/items')
.send({
name: 'Chainsaw',
date: new Date(),
type: 'tools',
user: 'stevie@tool.com',
uuid: 'A987FBC9-4BED-3078-CF07-9141BA07C9F3',
// url: 'http://tool.com/chainsaw/real-big'
})
.expect(200, done);
});
it('should validate params if they exist, even if isRequired is set to false', function (done) {
request(app)
.post('/items')
.send({
name: 'Chainsaw',
date: new Date(),
type: 'tools',
user: 'stevie@tool.com',
uuid: 'banana', // invalid and not required
url: 'http://tool.com/chainsaw/real-big'
})
.expect(400, function (err, res) {
if (err) return done(err);
expect(res.body).to.have.property('error').that.contains('body.uuid');
return done();
});
});
});
describe('validates req.query', function () {
var app;
before( function () {
app = express();
app.use(bodyParser.json());
app.get('/items', routeValidator.validate({
query: {
since: { isDate: true },
limit: { isInt: true, isRequired: true },
page: { isInt: true, isRequired: false },
sort: { isRequired: true }
}
}), function (req, res) {
return res.status(200).end();
});
});
it('should validate query params, on success', function (done) {
request(app)
.get('/items')
.query({
since: new Date(),
limit: 20,
page: 1,
sort: 'date'
})
.expect(200, done);
});
it('should validate query params, on failure', function (done) {
request(app)
.get('/items')
.query({
since: new Date(),
limit: 'get me all of it', // invalid
page: 1,
sort: 'date'
})
.expect(400, function (err, res) {
if (err) return done(err);
expect(res.body).to.have.property('error').that.contains('query.limit');
return done();
});
});
it('should enforce isRequired', function (done) {
request(app)
.get('/items')
.query({
since: new Date(),
// limit: 20,
page: 1,
sort: 'date'
})
.expect(400, function (err, res) {
if (err) return done(err);
expect(res.body).to.have.property('error').that.contains('query.limit');
return done();
});
});
it('should not fail validation when isRequired is set to false and param is not set', function (done) {
request(app)
.get('/items')
.query({
since: new Date(),
limit: 20,
// page: 1,
sort: 'date'
})
.expect(200, done);
});
it('should not fail validation when isRequired is not set and param is not set', function (done) {
request(app)
.get('/items')
.query({
// since: new Date(),
limit: 20,
page: 1,
sort: 'date'
})
.expect(200, done);
});
it('should validate params if they exist, even if isRequired is set to false', function (done) {
request(app)
.get('/items')
.query({
since: 'yesterday', // invalid
limit: 20,
page: 1,
sort: 'date'
})
.expect(400, function (err, res) {
if (err) return done(err);
expect(res.body).to.have.property('error').that.contains('query.since');
return done();
});
});
});
describe('validates req.headers', function () {
var app;
before( function () {
app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.post('/items', routeValidator.validate({
body: {
name: { isRequired: true }
},
headers: {
'content-type': { isRequired: true, equals: 'application/json' },
'authorization': { isRequired: true },
'accept-version': { isRequired: false, isIn: ['1.0', '2.0'] }
}
}), function (req, res) {
return res.status(200).end();
});
});
it('should validate headers, on success', function (done) {
request(app)
.post('/items')
.send({
name: 'Chainsaw'
})
.set('Authorization', 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==')
.set('Accept-Version', '1.0')
.expect(200, done);
});
it('should validate headers, on failure', function (done) {
request(app)
.post('/items')
.type('form')
.send({
name: 'Chainsaw'
})
.set('Authorization', 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==')
.expect(400, function (err, res) {
if (err) return done(err);
expect(res.body).to.have.property('error').that.contains('headers.content-type');
return done();
});
});
it('should enforce isRequired', function (done) {
request(app)
.post('/items')
.send({
name: 'Chainsaw'
})
.expect(400, function (err, res) {
if (err) return done(err);
expect(res.body).to.have.property('error').that.contains('headers.authorization');
return done();
});
});
it('should validate headers if they exist, even if isRequired is set to false', function (done) {
request(app)
.post('/items')
.send({
name: 'Chainsaw'
})
.set('Authorization', 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==')
.set('Accept-Version', '0.0')
.expect(400, function (err, res) {
if (err) return done(err);
expect(res.body).to.have.property('error').that.contains('headers.accept-version');
return done();
});
});
});
describe('with default coercers', function () {
var app;
before( function () {
app = express();
app.use(bodyParser.json());
app.put('/items/:item', routeValidator.validate({
body: {
user: { isRequired: false, isEmail: true, normalizeEmail: true },
rate: { isRequired: true, isInt: true, toInt: true }
},
params: {
item: { isMongoId: true, isRequired: true }
}
}), function (req, res) {
// Make sure values are coerced
if (typeof req.body.rate !== 'number' || !validator.isLowercase(req.body.user)) {
console.log(JSON.stringify(req.body, null, 2));
return res.status(500).end();
}
return res.status(200).end();
});
});
it('should coerce values when configured with coercers', function (done) {
request(app)
.put('/items/507f1f77bcf86cd799439011')
.send({
user: 'SteveO@googleMail.com',
rate: '100'
})
.expect(200, done);
});
});
describe('set callNext in route', function () {
var app;
before( function () {
app = express();
app.use(bodyParser.json());
app.get('/users', routeValidator.validate({
query: {
since: { isDate: true },
limit: { isInt: true, isRequired: true },
page: { isInt: true, isRequired: false },
sort: { isRequired: true }
},
callNext: true
}), function (req, res) {
return res.status(200).end();
});
app.use( function (err, req, res, next) { // jshint ignore:line
return res.status(400).send({
error: err.message,
message: 'calledNext'
});
});
});
it('should do nothing different if callNext is set to true and validation passes', function (done) {
request(app)
.get('/users')
.query({
since: new Date(),
limit: 20,
page: 1,
sort: 'email'
})
.expect(200, done);
});
it('should call next(err) if validation fails and callNext is set to true', function (done) {
request(app)
.get('/users')
.query({
since: new Date(),
limit: 'twenty', // invalid
page: 1,
sort: 'email'
})
.expect(400, function (err, res) {
console.log(JSON.stringify(res.body, null, 2));
if (err) return done(err);
expect(res.body).to.have.property('message').that.equals('calledNext');
expect(res.body).to.have.property('error').that.contains('query.limit');
return done();
});
});
});
describe('set errorHandler in route', function () {
var app;
before( function () {
app = express();
app.get('/users/:user', routeValidator.validate({
params: {
user: { isRequired: true, isEmail: true }
},
errorHandler: function (err, req, res) {
return res.status(400).send({
message: 'routeErrorHandler',
error: err.message
});
}
}), function (req, res) {
return res.status(200).end();
});
});
it('should do nothing different if errorHandler is set to true and validation passes', function (done) {
request(app)
.get('/users/stevie@tool.com')
.expect(200, done);
});
it('should call errorHandler(err, req, res, next) if validation fails and errorHandler is set to true', function (done) {
request(app)
.get('/users/banana')
.expect(400, function (err, res) {
if (err) return done(err);
expect(res.body).to.have.property('message').that.equals('routeErrorHandler');
expect(res.body).to.have.property('error').that.contains('params.user');
return done();
});
});
});
describe('when configured scope is undefined', function () {
var app;
before( function () {
app = express();
// req.body will always be undefined because there is no body parser
app.post('/items', routeValidator.validate({
body: {
name: { isRequired: true }
}
}), function (req, res) {
return res.status(200).end();
});
app.post('/users', routeValidator.validate({
body: {
email: { isRequired: false }
}
}), function (req, res) {
return res.status(200).end();
});
});
it('should invalidate the request if config has required field', function (done) {
request(app)
.post('/items')
.send({
name: 'Chainsaw'
})
.expect(400, function (err, res) {
if (err) return done(err);
expect(res.body).to.have.property('error').that.contains('body.name');
return done();
});
});
it('should not invalidate the request if config has no required fields', function (done) {
request(app)
.post('/users')
.expect(200, done);
});
});
describe('prop.message is set', function () {
var app, message = 'Custom Message';
before( function () {
app = express();
app.get('/items/:item', routeValidator.validate({
params: {
item: { isRequired: true, isMongoId: false, message: message }
}
}), function (req, res) {
return res.status(200).end();
});
});
it('should send prop.message as a custom error message', function (done) {
request(app)
.get('/items/abc')
.expect(400, function (err, res) {
if (err) return done(err);
expect(res.body).to.have.property('error').that.equals(message);
return done();
});
});
});
});
/***********
NEEDS TO TEST PRECENDENCE OF ERROR HANDLING DECISIONS
1. config.errorHandler
2. config.callNext
3. routeValidator._callNext
4. routeValidator._errorHandler
Test Cases
1. callNext set to false in config, true in app
***********/
describe('#set(key, value)', function () {
var errorHandler, callNext;
before( function () {
errorHandler = routeValidator._errorHandler;
callNext = routeValidator._callNext;
});
after( function () {
routeValidator._errorHandler = errorHandler;
routeValidator._callNext = callNext;
});
it('should allow setting callNext to pass err into next rather than default behavior', function () {
routeValidator.set('callNext', true);
expect(routeValidator).to.have.property('_callNext').that.is.true;
});
it('should allow setting the errorHandler to override default behavior', function () {
var newErrorHandler = function (err, req, res) {
return res.status(404).send({
message: 'errorHandled'
});
};
routeValidator.set('errorHandler', newErrorHandler);
expect(routeValidator).to.have.property('_errorHandler').that.equals(newErrorHandler);
});
it('should do nothing if key is not recognized', function () {
routeValidator.set('invalid', 'banana');
expect(routeValidator).to.not.have.property('invalid');
});
});
describe('#addValidator(name, fn)', function () {
var isNumeric, app;
before( function () {
isNumeric = routeValidator._validators.isNumeric;
app = express();
app.use(bodyParser.json());
app.post('/users', routeValidator.validate({
body: {
name: { isRequired: true },
age: { isRequired: true, isValidAge: true },
email: { isRequired: true, isEmail: true }
}
}), function (req, res) {
return res.status(200).end();
});
app.put('/users/:user', routeValidator.validate({
body: {
age: { isNumeric: true, isRequired: true }
}
}), function (req, res) {
return res.status(200).end();
});
});
after( function () {
routeValidator._validators.isNumeric = isNumeric;
});
it('should not add validator or break if not passed a function', function () {
routeValidator.addValidator('isNotFunction', 'banana');
expect(routeValidator._validators).to.not.have.property('isNotFunction');
});
it('should allow adding a custom validator', function (done) {
routeValidator.addValidator('isValidAge', function (str) {
var age = +str;
return age ? (age > 0 && age < 120) : false;
});
expect(routeValidator._validators).to.have.property('isValidAge');
async.parallel([
function (callback) {
request(app)
.post('/users')
.send({
name: 'Billy',
age: 23,
email: 'billy@hillbilly.com'
})
.expect(200, function (err, res) {
console.log(JSON.stringify(res.body,null,2));
return done(err);
});
},
function (callback) {
request(app)
.post('/users')
.send({
name: 'Invalid',
age: 2000,
email: 'invalid@timeless.com'
})
.expect(400, function (err, res) {
if (err) return callback(err);
expect(res.body).to.have.property('error').that.contains('body.age');
return callback();
});
}
], done);
});
it('should override existing validators of the same name', function (done) {
// Overrides existing validator
routeValidator.addValidator('isNumeric', function (str) {
var validNumbers = ['one', 'two', 'three', 'four', 'five', 'six', 'seven'];
return validNumbers.indexOf(str) !== -1;
});
expect(routeValidator._validators).to.have.property('isNumeric');
async.parallel([
function (callback) {
request(app)
.put('/users/billy')
.send({
age: 'seven'
})
.expect(200, callback);
},
function (callback) {
request(app)
.put('/users/invalid')
.send({
age: 20
})
.expect(400, function (err, res) {
if (err) return callback(err);
expect(res.body).to.have.property('error').that.contains('body.age');
return callback();
});
}
], done);
});
});
describe('#addValidators(obj)', function () {
var isNumeric, app;
before( function () {
isNumeric = routeValidator._validators.isNumeric;
app = express();
app.use(bodyParser.json());
app.post('/turtles', routeValidator.validate({
body: {
size: { isRequired: true, isNumeric: true },
weight: { isRequired: true, isTurtleWeight: true },
name: { isRequired: true }
}
}), function (req, res) {
return res.status(200).end();
});
});
after( function () {
routeValidator._validators.isNumeric = isNumeric;
});
it('should not break if passing in an empty object', function () {
routeValidator.addValidators({});
});
it('should not add validator or break if key is not function', function () {
routeValidator.addValidators({
// Adds invalid
isNotValidator: 'oops'
});
expect(routeValidator._validators).to.not.have.property('isNotValidator');
});
it('should allow passing in an object of validators and set them internally', function (done) {
routeValidator.addValidators({
// Overrides existing
isNumeric: function (str) {
var validNumbers = ['eight', 'nine', 'ten'];
return validNumbers.indexOf(str) !== -1;
},
// Adds new
isTurtleWeight: function (str) {
var weight = +str;
return weight ? (weight > 10 && weight < 800) : false;
}
});
expect(routeValidator._validators).to.have.property('isNumeric');
expect(routeValidator._validators).to.have.property('isTurtleWeight');
async.parallel([
function (callback) {
request(app)
.post('/turtles')
.send({
size: 'nine',
weight: 500,
name: 'Stanley'
})
.expect(200, callback);
},
function (callback) {
request(app)
.post('/turtles')
.send({
size: 9,
weight: 600,
name: 'Loopie'
})
.expect(400, function (err, res) {
if (err) return callback(err);
expect(res.body).to.have.property('error').that.contains('body.size');
return callback();
});
},
function (callback) {
request(app)
.post('/turtles')
.send({
size: 'ten',
weight: 60000,
name: 'Loopie'
})
.expect(400, function (err, res) {
if (err) return callback(err);
expect(res.body).to.have.property('error').that.contains('body.weight');
return callback();
});
}
], done);
});
});
describe('addCoercer()', function () {
var app;
before( function () {
app = express();
app.get('/turtles', routeValidator.validate({
query: {
sizeStr: { isRequired: false, toLowerCaseSize: true, isIn: ['eight', 'nine', 'ten'] },
weightRange: { isRequired: false, isWeightRange: true, toRangeArray: true }
}
}), function (req, res) {
if (req.query.weightRange) {
// Make sure that it was converted properly
// '100-500' -> [100, 500]
var range = req.query.weightRange;
if (!(range instanceof Array) || range.length !== 2 ||
typeof range[0] !== 'number' || typeof range[1] !== 'number') {
return res.status(500).end();
}
}
return res.status(200).end();
});
});
describe('config.stage === "before"', function () {
it('should be able to add a custom coercer run before validation', function (done) {
routeValidator.addCoercer('toLowerCaseSize', {
stage: 'before',
coerce: function (str) {
return str.toLowerCase();
}
});
expect(routeValidator._before).to.have.property('toLowerCaseSize');
async.parallel([
function (callback) {
request(app)
.get('/turtles')
.query({
sizeStr: 'EIGHT'
})
.expect(200, callback);
},
function (callback) {
request(app)
.get('/turtles')
.query({
sizeStr: 'nine'
})
.expect(200, callback);
}
], done);
});
it('should not add coercer if it is not a function', function () {
routeValidator.addCoercer('apple', {
stage: 'before',
coerce: 'apple'
});
expect(routeValidator._before).to.not.have.property('apple');
});
});
describe('config.stage === "after"', function () {
it('should be able to add a custom coercer run before validation', function (done) {
routeValidator.addValidator('isWeightRange', function (str) {
var arr = str.split('-');
return +arr[0] && +arr[1];
});
routeValidator.addCoercer('toRangeArray', {
stage: 'after',
coerce: function (str) {
var arr = str.split('-');
arr[0] = +arr[0];
arr[1] = +arr[1];
return arr;
}
});
expect(routeValidator._after).to.have.property('toRangeArray');
async.parallel([
function (callback) {
request(app)
.get('/turtles')
.query({
weightRange: '500'
})
.expect(400, callback);
},
function (callback) {
request(app)
.get('/turtles')
.query({
weightRange: '100-500'
})
.expect(200, callback);
}
], done);
});
it('should not add coercer if it is not a function', function () {
routeValidator.addCoercer('peach', {
stage: 'after',
coerce: 'peach'
});
expect(routeValidator._before).to.not.have.property('peach');
});
});
describe('invalid config.stage', function () {
it('should do nothing if config.stage is invalid', function () {
routeValidator.addCoercer('banana', {
stage: 'banana',
coerce: function () {
return 'banana';
}
});
expect(routeValidator._before).to.not.have.property('banana');
});
it('should do nothing if config.stage is not set', function () {
routeValidator.addCoercer('pear', {
coerce: function () {
return 'pear';
}
});
expect(routeValidator._before).to.not.have.property('pear');
});
});
});
describe('#addCoercers(obj)', function () {
var toDate, app;
before( function () {
toDate = routeValidator._before.toDate;
app = express();
app.get('/turtles', routeValidator.validate({
query: {
slug: { isRequired: false, toLowerCase: true, replaceSpaces: true },
minDate: { toDate: true }
}
}), function (req, res) {
if (req.query.slug && req.query.slug.indexOf(' ') !== -1) {
return res.status(500).end();
}
return res.status(200).end();
});
});
after( function () {
routeValidator._before.toDate = toDate;
});
it('should not break if passing in an empty object', function () {
routeValidator.addCoercers({});
});
it('should not add coercer or break if key is not a config object', function () {
routeValidator.addCoercers({
// Adds invalid
isNotCoercer: 'oops',
alsoNotCoercer: {
stage: 'notAstage',
coerce: function () {
return true;
}
},
andNotOne: {
stage: 'before',
coerce: 'funky'
}
});
expect(routeValidator._before).to.not.have.property('isNotCoercer');
expect(routeValidator._after).to.not.have.property('isNotCoercer');
expect(routeValidator._before).to.not.have.property('alsoNotCoercer');
expect(routeValidator._after).to.not.have.property('alsoNotCoercer');
expect(routeValidator._before).to.not.have.property('addNotOne');
expect(routeValidator._after).to.not.have.property('addNotOne');
});
it('should allow passing in an object of validators and set them internally', function (done) {
routeValidator.addCoercers({
// Overrides existing
toDate: {
stage: 'after',
coerce: function () {
return 'date';
}
},
// Adds new
toLowerCase: {
stage: 'before',
coerce: function (str) {
return str.toLowerCase();
}
},
replaceSpaces: {
stage: 'after',
coerce: function (str) {
return str.replace(/\s/g, '-');
}
}
});
expect(routeValidator._after).to.have.property('toDate');
expect(routeValidator._before).to.have.property('toLowerCase');
expect(routeValidator._after).to.have.property('replaceSpaces');
async.parallel([
function (callback) {
request(app)
.get('/turtles')
.query({
minDate: new Date()
})
.expect(200, callback);
},
function (callback) {
request(app)
.get('/turtles')
.query({
name: 'Mr Turtles'
})
.expect(200, callback);
},
function (callback) {
request(app)
.get('/turtles')
.query({
slug: 'My Sweet Turtle'
})
.expect(200, callback);
}
], done);
});
});
}); | mmerkes/express-route-validator | test/index.js | JavaScript | mit | 33,849 |
'use strict';
var async = require('async');
var _ = require('lodash');
var yamlReader = require('./yaml-reader/yaml-reader');
var fliprValidation = require('flipr-validation');
module.exports = validateConfig;
function validateConfig(options, cb) {
var validateOptions = {
rules: options.rules,
};
async.auto({
config: _.partial(yamlReader, options),
validate: ['config', function(callback, results){
validateOptions.config = results.config;
callback(null, fliprValidation(validateOptions));
}]
}, function(err, results){
if(err)
return void cb(err);
return void cb(null, results.validate);
});
} | gshively11/node-flipr-yaml | lib/validate-config.js | JavaScript | mit | 651 |
const { Device, UdpServer } = require('tplink-smarthome-simulator');
function startSimulator() {
const port = null;
const emeter = {
realtime: {
current: 1.1256,
voltage: 122.049119,
power: 3.14,
total: 51.493,
},
};
const devices = [];
devices.push(
new Device({
port,
model: 'hs100',
data: { alias: 'Mock HS100', mac: 'aa:aa:aa:8f:58:18', deviceId: 'A100' },
})
);
devices.push(
new Device({
port,
model: 'hs105',
data: { alias: 'Mock HS105', mac: 'aa:aa:aa:d8:bf:d4', deviceId: 'A105' },
})
);
devices.push(
new Device({
port,
model: 'hs110',
data: {
alias: 'Mock HS110',
mac: 'aa:aa:aa:0d:91:8c',
deviceId: 'A110',
emeter,
},
})
);
devices.push(
new Device({
port,
model: 'hs110v2',
data: {
alias: 'Mock HS110v2',
mac: 'aa:aa:aa:B7:F3:50',
deviceId: 'A110F2',
emeter,
},
})
);
devices.push(
new Device({
port,
model: 'hs200',
data: { alias: 'Mock HS200', mac: 'aa:aa:aa:46:b4:24', deviceId: 'A200' },
})
);
devices.push(
new Device({
port,
model: 'hs220',
data: { alias: 'Mock HS220', mac: 'aa:aa:aa:46:b5:34', deviceId: 'A220' },
})
);
devices.push(
new Device({
port,
model: 'hs300',
data: {
alias: 'Mock HS300',
mac: 'aa:aa:aa:EE:0C:9D',
deviceId: 'A300',
emeter,
},
})
);
devices.push(
new Device({
port,
model: 'lb100',
data: {
alias: 'Mock LB100',
mac: 'aa:aa:aa:49:ca:42',
deviceId: 'BB100',
},
})
);
devices.push(
new Device({
port,
model: 'lb120',
data: {
alias: 'Mock LB120',
mac: 'aa:aa:aa:90:9b:da',
deviceId: 'BB120',
},
})
);
devices.push(
new Device({
port,
model: 'lb130',
data: {
alias: 'Mock LB130',
mac: 'aa:aa:aa:b1:04:d3',
deviceId: 'BB130',
},
})
);
devices.forEach((d) => {
d.start();
});
UdpServer.start();
}
module.exports = { startSimulator };
| plasticrake/homebridge-hs100 | test/setup/simulator.js | JavaScript | mit | 2,234 |
function foo() {
var x = 2;
var xxx = 1;
if (xxx) {
console.log(xxx + x);
}
}
| babel/babili | packages/babel-plugin-minify-mangle-names/__tests__/fixtures/name-collisions/actual.js | JavaScript | mit | 90 |
const Room = ({routeParams}) => <h1>{routeParams.name} Room</h1>
module.exports = Room | MoonTahoe/cyber-chat | components/containers/Room.js | JavaScript | mit | 87 |
'use strict';
var storageKey = 'VN_TRANSLATE';
// ReSharper disable once InconsistentNaming
function Translate($translate, $translatePartialLoader, storage, options, disableTranslations) {
this.$translate = $translate;
this.$translatePartialLoader = $translatePartialLoader;
this.storage = storage;
this.disableTranslations = disableTranslations;
this.configure(angular.extend(options, this.getConfig()));
this.addPart = $translatePartialLoader.addPart;
}
Translate.prototype.getConfig = function() {
var storage = this.storage;
var config = JSON.parse(storage.get(storageKey)) || {};
var lang = storage.get('NG_TRANSLATE_LANG_KEY');
if (!this.disableTranslations && lang && lang !== 'undefined') {
config.lang = lang;
}
return config;
};
Translate.prototype.configure = function(config) {
config = angular.extend(this.getConfig(), config);
this.storage.set(storageKey, JSON.stringify(config));
this.$translate.use(config.lang);
};
Translate.prototype.addParts = function() {
if (this.disableTranslations) {
return true;
}
var loader = this.$translatePartialLoader;
angular.forEach(arguments, function(part) {
loader.addPart(part);
});
return this.$translate.refresh();
};
function TranslateProvider($translateProvider) {
this.$translateProvider = $translateProvider;
this.setPreferredLanguage = $translateProvider.preferredLanguage;
}
TranslateProvider.prototype.$get = [
'$translate', '$translatePartialLoader', 'storage',
function($translate, $translatePartialLoader, storage) {
var options = this.options;
return new Translate($translate, $translatePartialLoader, storage, {
region: options.region,
lang: options.lang,
country: options.country
}, options.disableTranslations);
}
];
TranslateProvider.prototype.configure = function(options) {
options = angular.extend({ region: 'us', lang: 'en', country: 'us' }, options);
if (options.lang) {
this.setPreferredLanguage(options.lang);
}
this.options = options;
if (!options.disableTranslations) {
this.initTranslateProvider(options.lang);
}
};
TranslateProvider.prototype.initTranslateProvider = function(lang) {
var $translateProvider = this.$translateProvider;
$translateProvider.useLoader('$translatePartialLoader', {
urlTemplate: '/translations/{part}/{lang}.json'
});
if (lang === 'en') {
$translateProvider.useMessageFormatInterpolation();
}
$translateProvider.useMissingTranslationHandlerLog();
$translateProvider.useLocalStorage();
};
angular.module('Volusion.toolboxCommon')
.provider('translate', ['$translateProvider', TranslateProvider]);
| tylertadej/vn-toolbox-common | app/scripts/translation/translate-provider.js | JavaScript | mit | 2,589 |
import Database from "almaden";
import Collection from "../../lib/collection.js";
import Model from "../../../";
import {ModelQuery} from "../../lib/modelFinder.js";
import {User} from "../testClasses.js";
import databaseConfig from "../databaseConfig.json";
let userFixtures = require("../fixtures/users.json");
describe("Model.find", () => {
let users,
userCollection;
before(() => {
Model.database = new Database(databaseConfig);
Model.database.mock({}); // Catch-all for database
});
after(() => {
// Remove database from model to prevent
// polluting another file via the prototype
Model.database = undefined;
});
beforeEach(done => {
userCollection = new Collection(User);
userFixtures.forEach((userFiture) => {
userCollection.push(new User(userFiture));
});
Model.database.mock({
"select * from `users` where `mom_id` = 1":
userFixtures
});
User
.find
.where("momId", "=", 1)
.results((error, fetchedUsers) => {
users = fetchedUsers;
done();
});
});
it("should return a ModelQuery instance", () => {
User.find.should.be.instanceOf(ModelQuery);
});
it("should return a collection", () => {
users.should.be.instanceOf(Collection);
});
it("should return the right collection", () => {
users.should.eql(userCollection);
});
it("should allow to search all models that matchs a certain condition", () => {
users.length.should.equal(5);
});
describe(".all", () => {
beforeEach(done => {
User.find
.all
.where("momId", 1)
.results((error, fetchedUsers) => {
users = fetchedUsers;
done();
});
});
it("should return just all users matching the condition", () => {
users.length.should.equal(5);
});
});
describe(".deleted", () => {
class SoftUser extends Model {
initialize() {
this.softDelete;
}
}
beforeEach(done => {
Model.database.mock({
"select * from `soft_users` where `mom_id` = 1 and `deleted_at` is not null":
userFixtures
});
SoftUser.find
.all
.where("momId", 1)
.deleted
.results((error, fetchedUsers) => {
users = fetchedUsers;
done();
});
});
it("should return just all users matching the condition", () => {
users.length.should.equal(5);
});
});
describe("(with a different database for a model)", () => {
class Car extends Model {}
let car,
database,
query;
describe("(static way)", () => {
beforeEach(() => {
database = new Database(databaseConfig);
Car.database = database;
query = database.spy("select * from `cars`", []);
car = new Car();
});
it("should use the specific model class database", (done) => {
Car.find.all.results(() => {
query.callCount.should.equal(1);
done();
});
});
});
describe("(instance way)", () => {
beforeEach(() => {
database = new Database(databaseConfig);
Car.database = null;
car = new Car({id: 2}, {database: database});
query = database.spy("select * from `cars` where `id` = 2 limit 1", []);
});
it("should use the specific model instance database", (done) => {
car.fetch(() => {
query.callCount.should.equal(1);
done();
});
});
});
});
});
| FreeAllMedia/dovima | es6/spec/model/find.spec.js | JavaScript | mit | 3,578 |
this.recline = this.recline || {};
this.recline.Backend = this.recline.Backend || {};
this.recline.Backend.Memory = this.recline.Backend.Memory || {};
(function(my, recline) {
"use strict";
my.__type__ = 'memory';
// private data - use either jQuery or Underscore Deferred depending on what is available
var Deferred = (typeof jQuery !== "undefined" && jQuery.Deferred) || _.Deferred;
// ## Data Wrapper
//
// Turn a simple array of JS objects into a mini data-store with
// functionality like querying, faceting, updating (by ID) and deleting (by
// ID).
//
// @param records list of hashes for each record/row in the data ({key:
// value, key: value})
// @param fields (optional) list of field hashes (each hash defining a field
// as per recline.Model.Field). If fields not specified they will be taken
// from the data.
my.Store = function(records, fields) {
var self = this;
this.records = records;
// backwards compatability (in v0.5 records was named data)
this.data = this.records;
if (fields) {
this.fields = fields;
} else {
if (records) {
this.fields = _.map(records[0], function(value, key) {
return {id: key, type: 'string'};
});
}
}
this.update = function(doc) {
_.each(self.records, function(internalDoc, idx) {
if(doc.id === internalDoc.id) {
self.records[idx] = doc;
}
});
};
this.remove = function(doc) {
var newdocs = _.reject(self.records, function(internalDoc) {
return (doc.id === internalDoc.id);
});
this.records = newdocs;
};
this.save = function(changes, dataset) {
var self = this;
var dfd = new Deferred();
// TODO _.each(changes.creates) { ... }
_.each(changes.updates, function(record) {
self.update(record);
});
_.each(changes.deletes, function(record) {
self.remove(record);
});
dfd.resolve();
return dfd.promise();
},
this.query = function(queryObj) {
var dfd = new Deferred();
var numRows = queryObj.size || this.records.length;
var start = queryObj.from || 0;
var results = this.records;
results = this._applyFilters(results, queryObj);
results = this._applyFreeTextQuery(results, queryObj);
// TODO: this is not complete sorting!
// What's wrong is we sort on the *last* entry in the sort list if there are multiple sort criteria
_.each(queryObj.sort, function(sortObj) {
var fieldName = sortObj.field;
results = _.sortBy(results, function(doc) {
var _out = doc[fieldName];
return _out;
});
if (sortObj.order == 'desc') {
results.reverse();
}
});
var facets = this.computeFacets(results, queryObj);
var out = {
total: results.length,
hits: results.slice(start, start+numRows),
facets: facets
};
dfd.resolve(out);
return dfd.promise();
};
// in place filtering
this._applyFilters = function(results, queryObj) {
var filters = queryObj.filters;
// register filters
var filterFunctions = {
term : term,
terms : terms,
range : range,
geo_distance : geo_distance
};
var dataParsers = {
integer: function (e) { return parseFloat(e, 10); },
'float': function (e) { return parseFloat(e, 10); },
number: function (e) { return parseFloat(e, 10); },
string : function (e) { return e.toString(); },
date : function (e) { return moment(e).valueOf(); },
datetime : function (e) { return new Date(e).valueOf(); }
};
var keyedFields = {};
_.each(self.fields, function(field) {
keyedFields[field.id] = field;
});
function getDataParser(filter) {
var fieldType = keyedFields[filter.field].type || 'string';
return dataParsers[fieldType];
}
// filter records
return _.filter(results, function (record) {
var passes = _.map(filters, function (filter) {
return filterFunctions[filter.type](record, filter);
});
// return only these records that pass all filters
return _.all(passes, _.identity);
});
// filters definitions
function term(record, filter) {
var parse = getDataParser(filter);
var value = parse(record[filter.field]);
var term = parse(filter.term);
return (value === term);
}
function terms(record, filter) {
var parse = getDataParser(filter);
var value = parse(record[filter.field]);
var terms = parse(filter.terms).split(",");
return (_.indexOf(terms, value) >= 0);
}
function range(record, filter) {
var fromnull = (_.isUndefined(filter.from) || filter.from === null || filter.from === '');
var tonull = (_.isUndefined(filter.to) || filter.to === null || filter.to === '');
var parse = getDataParser(filter);
var value = parse(record[filter.field]);
var from = parse(fromnull ? '' : filter.from);
var to = parse(tonull ? '' : filter.to);
// if at least one end of range is set do not allow '' to get through
// note that for strings '' <= {any-character} e.g. '' <= 'a'
if ((!fromnull || !tonull) && value === '') {
return false;
}
return ((fromnull || value >= from) && (tonull || value <= to));
}
function geo_distance() {
// TODO code here
}
};
// we OR across fields but AND across terms in query string
this._applyFreeTextQuery = function(results, queryObj) {
if (queryObj.q) {
var terms = queryObj.q.split(' ');
var patterns=_.map(terms, function(term) {
return new RegExp(term.toLowerCase());
});
results = _.filter(results, function(rawdoc) {
var matches = true;
_.each(patterns, function(pattern) {
var foundmatch = false;
_.each(self.fields, function(field) {
var value = rawdoc[field.id];
if ((value !== null) && (value !== undefined)) {
value = value.toString();
} else {
// value can be null (apparently in some cases)
value = '';
}
// TODO regexes?
foundmatch = foundmatch || (pattern.test(value.toLowerCase()));
// TODO: early out (once we are true should break to spare unnecessary testing)
// if (foundmatch) return true;
});
matches = matches && foundmatch;
// TODO: early out (once false should break to spare unnecessary testing)
// if (!matches) return false;
});
return matches;
});
}
return results;
};
this.computeFacets = function(records, queryObj) {
var facetResults = {};
if (!queryObj.facets) {
return facetResults;
}
_.each(queryObj.facets, function(query, facetId) {
// TODO: remove dependency on recline.Model
facetResults[facetId] = new recline.Model.Facet({id: facetId}).toJSON();
facetResults[facetId].termsall = {};
});
// faceting
_.each(records, function(doc) {
_.each(queryObj.facets, function(query, facetId) {
var fieldId = query.terms.field;
var val = doc[fieldId];
var tmp = facetResults[facetId];
if (val) {
tmp.termsall[val] = tmp.termsall[val] ? tmp.termsall[val] + 1 : 1;
} else {
tmp.missing = tmp.missing + 1;
}
});
});
_.each(queryObj.facets, function(query, facetId) {
var tmp = facetResults[facetId];
var terms = _.map(tmp.termsall, function(count, term) {
return { term: term, count: count };
});
tmp.terms = _.sortBy(terms, function(item) {
// want descending order
return -item.count;
});
tmp.terms = tmp.terms.slice(0, 10);
});
return facetResults;
};
};
}(this.recline.Backend.Memory, this.recline));
| acouch/recline | src/backend.memory.js | JavaScript | mit | 8,305 |
var fs = require('fs');
/*var mulu = fs.readFileSync('./mulu.html','utf8');
var sutra = mulu.replace(/<sutra>/g,'#<sutra>').split(/#/);
var vol = function(sutra){
for (var i in sutra){
var vol = sutra[i].match(/<vol>(.+)<\/vol>/);
var sutraid = sutra[i].match(/<sutraid n="(.+)"\/>/);
if (vol == null || sutraid == null) {
console.log('');
} else {
console.log(sutraid[1],vol[0]);
}
}
}
var cname = function(sutra){
for (var i in sutra){
var cname = sutra[i].match(/<taisho.+chi="(.+)\/">/g);
var sutraid = sutra[i].match(/<sutraid n="(.+)"\/>/);
if (cname == null || sutraid == null) {
console.log('');
} else {
console.log(sutraid[1],cname.map(function(cname){
var chiname = cname.replace(/<taisho.+chi="(.+)\/>/g,"$1");
return chiname;
}));
}
}
}*/
///////////////////////////////////////////////////////////
fs.readdir('input',function(err,files){
if (files[0] == ".DS_Store") files.splice(0,1);
//console.log(files,files.length);
files.map(persutra);
})
var persutra = function(fn){
var text = fs.readFileSync('./input/'+fn,'utf8');
var sutra = JSON.parse(text);
console.log(sutraid(fn));
console.log(findeachtag(sutra));
//var sutra = arr[3]['མདོ་མིང་།'];
//console.log(sutra);
}
var sutraid = function(id){
var sutraid = id.match(/J\d+((\([a-z]\))|(\,\d+))*/)[0];
return ('<sutra>' + breakline + '<sutraid n="' + sutraid + '"/>');
}
var findeachtag = function(arr){
var trans = 'translator';
var tname = arr[3]['མདོ་མིང་།'];
var aname = arr[3]['མདོ་མིང་གཞན།'];
var sname = arr[3]['རྒྱ་གར་མདོ་མིང་།'];
var homage = arr[3]['བསྒྱུར་ཕྱག'];
var subject = arr[3]['བརྗོད་བྱ།'];
var yana = arr[3]['ཐེག་པ།'];
var charka = arr[3]['དཀའ། འཁོར་ལོ།'];
var location = arr[3]['གནས་ཕུན་སུམ་ཚོགས་པ།'];
var audience = arr[3]['འཁོར་ཕུན་སུམ་ཚོགས་པ།'];
var aurthor = arr[3]['སྟོན་པ་ཕུན་སུམ་ཚོགས་པ།'];
var requester = arr[3]['ཞུ་བ་པོ་ཕུན་སུམ་ཚོགས་པ།'];
var dharma = arr[3]['ཆོས་ཕུན་སུམ་ཚོགས་པ།'];
var purpose = arr[3]['ཆོས་ཀྱི་དགོས་དོན།'];
var collect = arr[3]['བསྡུས་པའི་དོན། ལེའུ།'];
var bampo = arr[3]['བམ་པོ། ཤོ་ལོ་ཀ'];
var relation = arr[3]['མཚམས་སྦྱར་བའི་གོ་རིམ།'];
var debate = arr[3]['རྒལ་ལན།'];
var translator = arr[3]['ལོ་ཙཱ་བ།'];
var reviser = arr[3]['ཞུ་དག་པ།'];
//var cname = arr[3]['རྒྱ་ནག་མདོ་མིང་།'];
if (arr[1]['ལོ་ཙཱ་བ།'] == 'translator_revisor' || arr[2]['ལོ་ཙཱ་བ།'] == 'translator_revisor') trans = 'translator_reviser';
return "<tname>" + tname + "</tname>" + breakline + "<aname>" + aname + "</aname>" + breakline +
"<sname>" + sname + "</sname>" + breakline + "<cname></cname>" + breakline + "<vol></vol>" + breakline +
"<homage>" + homage + "</homage>" + breakline + "<subject>" + subject + "</subject>" + breakline +
"<yana>" + yana + "</yana>" + breakline + "<charka>" + charka + "</charka>" + breakline + "<location>" +
location + "</location>" + breakline + "<audience>" + audience + "</audience>" + breakline + "<aurthor>" +
aurthor + "</aurthor>" + breakline + "<requester>" + requester + "</requester>" + breakline + "<dharma>" +
dharma + "</dharma>" + breakline + "<purpose>" + purpose + "</purpose>" + breakline + "<collect>" + collect +
"</collect>" + breakline + "<bampo>" + bampo + "</bampo>" + breakline + "<relation>" + relation + "</relation>" +
breakline + "<debate>" + debate + "</debate>" + breakline + "<" + trans + ">" + translator + "</" + trans + ">" +
breakline + "<reviser>" + reviser + "</reviser>" + breakline + "</sutra>";
}
var breakline = RegExp('\n');
/*var writexml = function(xml){
fs.writeFileSync('bio.xml',JSON.stringify(xml,'',' '),'utf8');
}*/
| zhandi100/biography_xlsx_xml | bio_json_xml.js | JavaScript | mit | 4,254 |
/*
* grunt-simple-templates
* https://github.com/jclem/grunt-simple-templates
*
* Copyright (c) 2013 Jonathan Clem
* Licensed under the MIT license.
*/
'use strict';
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
jshint: {
all: [
'Gruntfile.js',
'tasks/*.js',
'<%= nodeunit.tests %>',
],
options: {
jshintrc: '.jshintrc',
},
},
// Before generating any new files, remove any previously-created files.
clean: {
tests: ['tmp'],
},
// Configuration to be run (and then tested).
templates: {
default_options: {
src: "test/fixtures/",
dest: "tmp/default_options"
},
custom_options: {
src: "test/fixtures/",
dest: "tmp/custom_options",
options: {
namespace: "CUSTOM_TEMPLATES",
extension: "hbs"
}
}
},
// Unit tests.
nodeunit: {
tests: ['test/*_test.js'],
},
});
// Actually load this plugin's task(s).
grunt.loadTasks('tasks');
// These plugins provide necessary tasks.
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-nodeunit');
// Whenever the "test" task is run, first clean the "tmp" dir, then run this
// plugin's task(s), then test the result.
grunt.registerTask('test', ['clean', 'templates', 'nodeunit']);
// By default, lint and run all tests.
grunt.registerTask('default', ['jshint', 'test']);
};
| jclem/grunt-simple-templates | Gruntfile.js | JavaScript | mit | 1,560 |
import { setData } from '@progress/kendo-angular-intl';
setData({
name: "fr-SN",
likelySubtags: {
fr: "fr-Latn-FR"
},
identity: {
language: "fr",
territory: "SN"
},
territory: "SN",
calendar: {
patterns: {
d: "dd/MM/y",
D: "EEEE d MMMM y",
m: "d MMM",
M: "d MMMM",
y: "MMM y",
Y: "MMMM y",
F: "EEEE d MMMM y HH:mm:ss",
g: "dd/MM/y HH:mm",
G: "dd/MM/y HH:mm:ss",
t: "HH:mm",
T: "HH:mm:ss",
s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss",
u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'"
},
dateTimeFormats: {
full: "{1} 'à' {0}",
long: "{1} 'à' {0}",
medium: "{1} 'à' {0}",
short: "{1} {0}",
availableFormats: {
d: "d",
E: "E",
Ed: "E d",
Ehm: "E h:mm a",
EHm: "E HH:mm",
Ehms: "E h:mm:ss a",
EHms: "E HH:mm:ss",
Gy: "y G",
GyMMM: "MMM y G",
GyMMMd: "d MMM y G",
GyMMMEd: "E d MMM y G",
h: "h a",
H: "HH 'h'",
hm: "h:mm a",
Hm: "HH:mm",
hms: "h:mm:ss a",
Hms: "HH:mm:ss",
hmsv: "h:mm:ss a v",
Hmsv: "HH:mm:ss v",
hmv: "h:mm a v",
Hmv: "HH:mm v",
M: "L",
Md: "dd/MM",
MEd: "E dd/MM",
MMM: "LLL",
MMMd: "d MMM",
MMMEd: "E d MMM",
MMMMd: "d MMMM",
"MMMMW-count-one": "'semaine' W 'de' MMM",
"MMMMW-count-other": "'semaine' W 'de' MMM",
ms: "mm:ss",
y: "y",
yM: "MM/y",
yMd: "dd/MM/y",
yMEd: "E dd/MM/y",
yMMM: "MMM y",
yMMMd: "d MMM y",
yMMMEd: "E d MMM y",
yMMMM: "MMMM y",
yQQQ: "QQQ y",
yQQQQ: "QQQQ y",
"yw-count-one": "'semaine' w 'de' y",
"yw-count-other": "'semaine' w 'de' y"
}
},
timeFormats: {
full: "HH:mm:ss zzzz",
long: "HH:mm:ss z",
medium: "HH:mm:ss",
short: "HH:mm"
},
dateFormats: {
full: "EEEE d MMMM y",
long: "d MMMM y",
medium: "d MMM y",
short: "dd/MM/y"
},
days: {
format: {
abbreviated: [
"dim.",
"lun.",
"mar.",
"mer.",
"jeu.",
"ven.",
"sam."
],
narrow: [
"D",
"L",
"M",
"M",
"J",
"V",
"S"
],
short: [
"di",
"lu",
"ma",
"me",
"je",
"ve",
"sa"
],
wide: [
"dimanche",
"lundi",
"mardi",
"mercredi",
"jeudi",
"vendredi",
"samedi"
]
},
"stand-alone": {
abbreviated: [
"dim.",
"lun.",
"mar.",
"mer.",
"jeu.",
"ven.",
"sam."
],
narrow: [
"D",
"L",
"M",
"M",
"J",
"V",
"S"
],
short: [
"di",
"lu",
"ma",
"me",
"je",
"ve",
"sa"
],
wide: [
"dimanche",
"lundi",
"mardi",
"mercredi",
"jeudi",
"vendredi",
"samedi"
]
}
},
months: {
format: {
abbreviated: [
"janv.",
"févr.",
"mars",
"avr.",
"mai",
"juin",
"juil.",
"août",
"sept.",
"oct.",
"nov.",
"déc."
],
narrow: [
"J",
"F",
"M",
"A",
"M",
"J",
"J",
"A",
"S",
"O",
"N",
"D"
],
wide: [
"janvier",
"février",
"mars",
"avril",
"mai",
"juin",
"juillet",
"août",
"septembre",
"octobre",
"novembre",
"décembre"
]
},
"stand-alone": {
abbreviated: [
"janv.",
"févr.",
"mars",
"avr.",
"mai",
"juin",
"juil.",
"août",
"sept.",
"oct.",
"nov.",
"déc."
],
narrow: [
"J",
"F",
"M",
"A",
"M",
"J",
"J",
"A",
"S",
"O",
"N",
"D"
],
wide: [
"janvier",
"février",
"mars",
"avril",
"mai",
"juin",
"juillet",
"août",
"septembre",
"octobre",
"novembre",
"décembre"
]
}
},
quarters: {
format: {
abbreviated: [
"T1",
"T2",
"T3",
"T4"
],
narrow: [
"1",
"2",
"3",
"4"
],
wide: [
"1er trimestre",
"2e trimestre",
"3e trimestre",
"4e trimestre"
]
},
"stand-alone": {
abbreviated: [
"T1",
"T2",
"T3",
"T4"
],
narrow: [
"1",
"2",
"3",
"4"
],
wide: [
"1er trimestre",
"2e trimestre",
"3e trimestre",
"4e trimestre"
]
}
},
dayPeriods: {
format: {
abbreviated: {
midnight: "min.",
am: "AM",
noon: "midi",
pm: "PM",
morning1: "mat.",
afternoon1: "ap.m.",
evening1: "soir",
night1: "nuit"
},
narrow: {
midnight: "min.",
am: "AM",
noon: "midi",
pm: "PM",
morning1: "mat.",
afternoon1: "ap.m.",
evening1: "soir",
night1: "nuit"
},
wide: {
midnight: "minuit",
am: "AM",
noon: "midi",
pm: "PM",
morning1: "du matin",
afternoon1: "de l’après-midi",
evening1: "du soir",
night1: "de nuit"
}
},
"stand-alone": {
abbreviated: {
midnight: "min.",
am: "AM",
noon: "midi",
pm: "PM",
morning1: "mat.",
afternoon1: "ap.m.",
evening1: "soir",
night1: "nuit"
},
narrow: {
midnight: "min.",
am: "AM",
noon: "midi",
pm: "PM",
morning1: "mat.",
afternoon1: "ap.m.",
evening1: "soir",
night1: "nuit"
},
wide: {
midnight: "minuit",
am: "AM",
noon: "midi",
pm: "PM",
morning1: "matin",
afternoon1: "après-midi",
evening1: "soir",
night1: "nuit"
}
}
},
eras: {
format: {
wide: {
0: "avant Jésus-Christ",
1: "après Jésus-Christ",
"0-alt-variant": "avant l’ère commune",
"1-alt-variant": "de l’ère commune"
},
abbreviated: {
0: "av. J.-C.",
1: "ap. J.-C.",
"0-alt-variant": "AEC",
"1-alt-variant": "EC"
},
narrow: {
0: "av. J.-C.",
1: "ap. J.-C.",
"0-alt-variant": "AEC",
"1-alt-variant": "EC"
}
}
},
gmtFormat: "UTC{0}",
gmtZeroFormat: "UTC",
dateFields: {
era: {
wide: "ère",
short: "ère",
narrow: "ère"
},
year: {
wide: "année",
short: "an",
narrow: "a"
},
quarter: {
wide: "trimestre",
short: "trim.",
narrow: "trim."
},
month: {
wide: "mois",
short: "m.",
narrow: "m."
},
week: {
wide: "semaine",
short: "sem.",
narrow: "sem."
},
weekOfMonth: {
wide: "Week Of Month",
short: "Week Of Month",
narrow: "Week Of Month"
},
day: {
wide: "jour",
short: "j",
narrow: "j"
},
dayOfYear: {
wide: "Day Of Year",
short: "Day Of Year",
narrow: "Day Of Year"
},
weekday: {
wide: "jour de la semaine",
short: "jour de la semaine",
narrow: "jour de la semaine"
},
weekdayOfMonth: {
wide: "Weekday Of Month",
short: "Weekday Of Month",
narrow: "Weekday Of Month"
},
dayperiod: {
short: "cadran",
wide: "cadran",
narrow: "cadran"
},
hour: {
wide: "heure",
short: "h",
narrow: "h"
},
minute: {
wide: "minute",
short: "min",
narrow: "min"
},
second: {
wide: "seconde",
short: "s",
narrow: "s"
},
zone: {
wide: "fuseau horaire",
short: "fuseau horaire",
narrow: "fuseau horaire"
}
}
},
firstDay: 1
});
| antpost/antpost-client | node_modules/@progress/kendo-angular-intl/locales/fr-SN/calendar.js | JavaScript | mit | 13,207 |
require('./navbar-list');
class ScrollSpy {
/**
* @param {NavBarList} navBarList
* @param {number} offset
*/
constructor (navBarList, offset) {
this.navBarList = navBarList;
this.offset = offset;
}
scrollEventListener () {
let activeLinkTarget = null;
let linkTargets = this.navBarList.getTargets();
let offset = this.offset;
let linkTargetsPastThreshold = [];
linkTargets.forEach(function (linkTarget) {
if (linkTarget) {
let offsetTop = linkTarget.getBoundingClientRect().top;
if (offsetTop < offset) {
linkTargetsPastThreshold.push(linkTarget);
}
}
});
if (linkTargetsPastThreshold.length === 0) {
activeLinkTarget = linkTargets[0];
} else if (linkTargetsPastThreshold.length === linkTargets.length) {
activeLinkTarget = linkTargets[linkTargets.length - 1];
} else {
activeLinkTarget = linkTargetsPastThreshold[linkTargetsPastThreshold.length - 1];
}
if (activeLinkTarget) {
this.navBarList.clearActive();
this.navBarList.setActive(activeLinkTarget.getAttribute('id'));
}
}
spy () {
window.addEventListener(
'scroll',
this.scrollEventListener.bind(this),
true
);
}
}
module.exports = ScrollSpy;
| webignition/web.client.simplytestable.com | assets/js/user-account/scrollspy.js | JavaScript | mit | 1,465 |
var d = require('../dtrace-provider');
var dtp = d.createDTraceProvider('test');
dtp.addProbe('probe1', 'int', 'int');
dtp.addProbe('probe2', 'int', 'int');
dtp.enable();
var dtp2 = d.createDTraceProvider('test');
dtp2.addProbe('probe3', 'int', 'int');
dtp2.addProbe('probe1', 'int', 'int');
dtp2.enable();
var dtp3 = d.createDTraceProvider('test', 'mymod1');
dtp3.addProbe('probe1', 'int', 'int');
dtp3.addProbe('probe2', 'int', 'int');
dtp3.enable();
var dtp4 = d.createDTraceProvider('test', 'mymod2');
dtp4.addProbe('probe1', 'int', 'int');
dtp4.addProbe('probe3', 'int', 'int');
dtp4.enable();
dtp.fire('probe1', function () {
return ([12, 3]);
});
dtp2.fire('probe1', function () {
return ([12, 73]);
});
dtp3.fire('probe1', function () {
return ([12, 3]);
});
dtp4.fire('probe1', function () {
return ([12, 73]);
});
| hejiheji001/HexoBlog | node_modules/hexo/node_modules/bunyan/node_modules/dtrace-provider/test/disambiguation_fire.js | JavaScript | mit | 885 |
'use strict';
// Given a bound list and the time steps,
// return the LB and UB at each timestep.
// List is in format of {LB:lb,UB:ub}
var months = ['JAN','FEB','MAR','APR','MAY','JUN','JUL','AUG','SEP','OCT','NOV','DEC'];
function getMonth(dateString) {
var m = parseInt(dateString.split('-')[1])-1;
return months[m];
}
module.exports = function(bounds, steps, callback) {
var steps_bound = [];
var month, month_cost = {};
var i,bound;
var bm = []; // Temporary bounds
// Start with no bounds
steps.forEach(function(step) {
// lb, ub, lb defined
steps_bound.push([0, null, false]);
});
var c = 0;
bounds.forEach(function(bound, index){
switch(bound.type) {
case 'NOB': // We are good
return;
case 'LBC':
for(i = 0; i < steps.length; i++) {
if( steps_bound[i][0] === null || steps_bound[i][0] < bound.bound ){
steps_bound[i][0] = bound.bound;
steps_bound[i][2] = true;
}
}
return;
case 'LBM':
case 'LBT':
var b;
bm = {};
bound.bound.forEach(function(b) {
bm[b[0]] = b[1];
});
for(i = 0; i < steps.length; i++) {
// Almost the same code for LBM and LBT
b = (bound.type === 'LBM') ? bm[getMonth(steps[i])] : bm[steps[i]];
if( (typeof b !== 'undefined' && b !== null) && (steps_bound[i][0] === null || steps_bound[i][0] < b) ){
steps_bound[i][0] = b;
steps_bound[i][2] = true;
}
}
return;
case 'UBC':
for( i = 0; i < steps.length; i++ ){
if( steps_bound[i][1] === null || steps_bound[i][1] > bound.bound) {
steps_bound[i][1] = bound.bound;
}
}
return;
case 'UBM':
case 'UBT':
bm = {};
bound.bound.forEach(function(b) {
bm[b[0]] = b[1];
});
for( i = 0; i < steps.length; i++ ){
// Almost the same code for BM and BT
b = (bound.type === 'UBM') ? bm[getMonth(steps[i])] : bm[steps[i]];
if( (typeof b !== 'undefined' && b !== null ) && (steps_bound[i][1] === null || steps_bound[i][1] > b) ) {
steps_bound[i][1] = b;
}
}
return;
case 'EQT':
var b;
bm = {};
bound.bound.forEach(function(b) {
bm[b[0]] = b[1];
});
for( i = 0; i < steps.length; i++ ){
b = bm[steps[i]];
if( typeof b !=='undefined' && b !== null) {
if( steps_bound[i][0] === null || steps_bound[i][0] < b ) {
steps_bound[i][0] = b;
steps_bound[i][2] = true;
}
if( steps_bound[i][1] === null || steps_bound[i][1] > b ) {
steps_bound[i][1] = b;
}
}
}
return;
default :
throw new Error('Bad Bound Type: '+bound.type);
}
});
return steps_bound.map((bound) => {
return {
LB : bound[0],
UB : bound[1],
LBDefined : bound[2]
}
});
};
| ucd-cws/calvin-network-tools | nodejs/matrix/bound.js | JavaScript | mit | 3,324 |
/**
*
*/
define(['jquery', 'dropzone', 'pica', 'bootstrap'], function($, dropzone, pica, bootstrap) {
'use strict';
var Dropzone = window.Dropzone;
Dropzone.autoDiscover = false;
function dataURItoBlob(dataURI) {
// convert base64/URLEncoded data component to raw binary data held in a string
var byteString;
if (dataURI.split(',')[0].indexOf('base64') >= 0)
byteString = atob(dataURI.split(',')[1]);
else
byteString = unescape(dataURI.split(',')[1]);
// separate out the mime component
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
// write the bytes of the string to a typed array
var ia = new Uint8Array(byteString.length);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ia], {type:mimeString});
}
function base64ToArrayBuffer(dataURI) {
var byteString;
if (dataURI.split(',')[0].indexOf('base64') >= 0)
byteString = atob(dataURI.split(',')[1]);
else
byteString = unescape(dataURI.split(',')[1]);
// separate out the mime component
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
// write the bytes of the string to a typed array
var ia = new Uint8Array(byteString.length);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return ia.buffer;
}
function base64ToFile(dataURI, origFile) {
var byteString, mimestring;
if (dataURI.split(',')[0].indexOf('base64') !== -1) {
byteString = atob(dataURI.split(',')[1]);
} else {
byteString = decodeURI(dataURI.split(',')[1]);
}
mimestring = dataURI.split(',')[0].split(':')[1].split(';')[0];
var content = new Array();
for (var i = 0; i < byteString.length; i++) {
content[i] = byteString.charCodeAt(i);
}
var newFile = {};
try {
newFile = new File(
[new Uint8Array(content)], origFile.name, { 'type': mimestring }
);
} catch (error) {
// create Blob instead File because in IE constructor for File object doesn't exsist'
newFile = new Blob(
[new Uint8Array(content)], { 'type': mimestring }
);
newFile.name = origFile.name;
}
// Copy props set by the dropzone in the original file
var origProps = [
"upload", "status", "previewElement", "previewTemplate", "accepted"
];
$.each(origProps, function (i, p) {
newFile[p] = origFile[p];
});
return newFile;
}
// http://stackoverflow.com/questions/7584794/accessing-jpeg-exif-rotation-data-in-javascript-on-the-client-side
function getOrientation(buffer) {
var view = new DataView(buffer);
if (view.getUint16(0, false) != 0xFFD8) return -2;
var length = view.byteLength, offset = 2;
while (offset < length) {
var marker = view.getUint16(offset, false);
offset += 2;
if (marker == 0xFFE1) {
if (view.getUint32(offset += 2, false) != 0x45786966) return -1;
var little = view.getUint16(offset += 6, false) == 0x4949;
offset += view.getUint32(offset + 4, little);
var tags = view.getUint16(offset, little);
offset += 2;
for (var i = 0; i < tags; i++)
if (view.getUint16(offset + (i * 12), little) == 0x0112)
return view.getUint16(offset + (i * 12) + 8, little);
}
else if ((marker & 0xFF00) != 0xFF00) break;
else offset += view.getUint16(offset, false);
}
return -1;
}
function rotate(image, w, h, orientation) {
var canvas = document.createElement('canvas');
var ctx = canvas.getContext("2d");
var cw = image.width, ch = image.height, cx = 0, cy = 0, degree = 0;
switch (orientation) {
case -2: // not jpeg
case -1: // not defined
break;
case 1: // normal
break;
case 2: // flip
break;
case 3: // 180
degree = 180;
cx = image.width * (-1);
cy = image.height * (-1);
break;
case 4: // 180 flip
break;
case 5: // 270 flip
break;
case 6: // 270
degree = 90;
cw = image.height;
ch = image.width;
cy = image.height * (-1);
break;
case 7: // 90 flip
break;
case 8: // 90
degree = 270;
cw = image.height;
ch = image.width;
cx = image.width * (-1);
break;
}
canvas.setAttribute('width', cw);
canvas.setAttribute('height', ch);
ctx.rotate(degree * Math.PI / 180);
ctx.drawImage(image, cx, cy);
return canvas;
}
function initFileUpload() {
$('#js-completed-hint').hide();
var dropzone = new Dropzone('.dropzone', {
url: "/file/upload",
method: "post",
maxFilesize: 20,
addRemoveLinks: true,
autoQueue: false,
parallelUploads: 1
});
var uid = $('#js-content').data('uid');
$.each(window.checklist_files, function (index, value) {
var file = { name: value.filename, size: value.size };
var thumbnail = '//' + window.location.host + '/uploads/' + uid + '/' + value.filename;
dropzone.emit('addedfile', file);
if (value.filetype == 'image') {
dropzone.createThumbnailFromUrl(file, thumbnail);
} else if (value.filetype == 'document') {
dropzone.createThumbnailFromUrl(file, '/static/img/excelfile.png');
}
dropzone.emit('complete', file);
});
dropzone.on('queuecomplete', function (data) {
$('#js-completed-hint').hide();
$('#js-completed-btn').removeAttr('disabled');
});
dropzone.on('removedfile', function (origFile) {
$.post('/uploads/remove/' + uid + '/' + origFile.name);
});
dropzone.on("addedfile", function(origFile) {
var MAX_WIDTH = 800;
var MAX_HEIGHT = 800;
var reader = new FileReader();
var imageExts = ['jpg', 'jpeg', 'png', 'gif'];
$('#js-completed-btn').attr('disabled', 'disabled');
$('#js-completed-hint').show();
// Convert file to img
reader.addEventListener("load", function (event) {
var fileExt = origFile.name.split('.').pop().toLowerCase();
if ($.inArray(fileExt, imageExts) < 0) {
dropzone.enqueueFile(origFile);
return;
}
var orientation = getOrientation(base64ToArrayBuffer(event.target.result));
console.log(orientation);
var origImg = new Image();
origImg.src = event.target.result;
origImg.addEventListener("load", function (event) {
var width = event.target.width;
var height = event.target.height;
// Don't resize if it's small enough
if (width <= MAX_WIDTH && height <= MAX_HEIGHT) {
dropzone.enqueueFile(origFile);
return;
}
// Calc new dims otherwise
if (width > height) {
if (width > MAX_WIDTH) {
height *= MAX_WIDTH / width;
width = MAX_WIDTH;
}
} else {
if (height > MAX_HEIGHT) {
width *= MAX_HEIGHT / height;
height = MAX_HEIGHT;
}
}
// Resize
var canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
pica.resizeCanvas(origImg, canvas, 3, function () {
var rotatedCanvas = rotate(canvas, width, height, orientation);
var resizedFile = base64ToFile(rotatedCanvas.toDataURL(), origFile);
// Replace original with resized
var origFileIndex = dropzone.files.indexOf(origFile);
dropzone.files[origFileIndex] = resizedFile;
// Enqueue added file manually making it available for
// further processing by dropzone
dropzone.enqueueFile(resizedFile);
});
});
});
reader.readAsDataURL(origFile);
});
}
$(document).ready(function () {
initFileUpload();
var uid = $('#js-content').data('uid');
var noticeSent = $('#js-content').data('notice-sent');
$('#js-completed-btn').click(function (evt) {
if (noticeSent == 'False')
$('#myModal').modal('show');
else
$('#js-content').hide();
});
$('#js-modal-complete').click(function (evt) {
if (noticeSent == 'False') {
$.post('/checklist/complete/' + uid, { 'author_email': $('#js-author-email').val() }, function (data) {
$('#myModal').modal('hide');
$('#js-content').hide();
}).fail(function () {
$('#myModal').modal('hide');
$('#js-content').hide();
});
}
});
});
}); | nixxa/SecretShopper | frontui/static/scripts/checklist.addfiles.view.js | JavaScript | mit | 10,262 |
/* global sinon */
import React, { Component } from 'react';
import TestUtils from 'react-dom/test-utils';
import { expect } from 'chai';
import NotificationSystem from 'NotificationSystem';
import { positions, levels } from 'constants';
import merge from 'object-assign';
const defaultNotification = {
title: 'This is a title',
message: 'This is a message',
level: 'success'
};
const style = {
Containers: {
DefaultStyle: {
width: 600
},
tl: {
width: 800
}
}
};
describe('Notification Component', function() {
let node;
let instance;
let component;
let clock;
let notificationObj;
const ref = 'notificationSystem';
this.timeout(10000);
beforeEach(() => {
// We need to create this wrapper so we can use refs
class ElementWrapper extends Component {
render() {
return <NotificationSystem ref={ ref } style={ style } allowHTML={ true } noAnimation={ true } />;
}
}
node = window.document.createElement('div');
instance = TestUtils.renderIntoDocument(React.createElement(ElementWrapper), node);
component = instance.refs[ref];
notificationObj = merge({}, defaultNotification);
clock = sinon.useFakeTimers();
});
afterEach(() => {
clock.restore();
});
it('should be rendered', done => {
component = TestUtils.findRenderedDOMComponentWithClass(instance, 'notifications-wrapper');
expect(component).to.not.be.null;
done();
});
it('should hold the component ref', done => {
expect(component).to.not.be.null;
done();
});
it('should render a single notification', done => {
component.addNotification(defaultNotification);
let notification = TestUtils.scryRenderedDOMComponentsWithClass(instance, 'notification');
expect(notification.length).to.equal(1);
done();
});
it('should not set a notification visibility class when the notification is initially added', done => {
component.addNotification(defaultNotification);
let notification = TestUtils.findRenderedDOMComponentWithClass(instance, 'notification');
expect(notification.className).to.not.match(/notification-hidden/);
expect(notification.className).to.not.match(/notification-visible/);
done();
});
it('should set the notification class to visible after added', done => {
component.addNotification(defaultNotification);
let notification = TestUtils.findRenderedDOMComponentWithClass(instance, 'notification');
expect(notification.className).to.match(/notification/);
clock.tick(400);
expect(notification.className).to.match(/notification-visible/);
done();
});
it('should add additional classes to the notification if specified', done => {
component.addNotification(Object.assign({},defaultNotification, {className: 'FOO'}));
let notification = TestUtils.findRenderedDOMComponentWithClass(instance, 'notification');
expect(notification.className).to.contain(' FOO');
done();
});
it('should render notifications in all positions with all levels', done => {
let count = 0;
for (let position of Object.keys(positions)) {
for (let level of Object.keys(levels)) {
notificationObj.position = positions[position];
notificationObj.level = levels[level];
component.addNotification(notificationObj);
count++;
}
}
let containers = [];
for (let position of Object.keys(positions)) {
containers.push(TestUtils.findRenderedDOMComponentWithClass(instance, 'notifications-' + positions[position]));
}
containers.forEach(function(container) {
for (let level of Object.keys(levels)) {
let notification = container.getElementsByClassName('notification-' + levels[level]);
expect(notification).to.not.be.null;
}
});
let notifications = TestUtils.scryRenderedDOMComponentsWithClass(instance, 'notification');
expect(notifications.length).to.equal(count);
done();
});
it('should render multiple notifications', done => {
const randomNumber = Math.floor(Math.random(5, 10));
for (let i = 1; i <= randomNumber; i++) {
component.addNotification(defaultNotification);
}
let notifications = TestUtils.scryRenderedDOMComponentsWithClass(instance, 'notification');
expect(notifications.length).to.equal(randomNumber);
done();
});
it('should not render notifications with the same uid', done => {
notificationObj.uid = 500;
component.addNotification(notificationObj);
component.addNotification(notificationObj);
let notification = TestUtils.scryRenderedDOMComponentsWithClass(instance, 'notification');
expect(notification.length).to.equal(1);
done();
});
it('should remove a notification after autoDismiss', function(done) {
notificationObj.autoDismiss = 2;
component.addNotification(notificationObj);
clock.tick(3000);
let notification = TestUtils.scryRenderedDOMComponentsWithClass(instance, 'notification');
expect(notification.length).to.equal(0);
done();
});
it('should remove a notification using returned object', done => {
let notificationCreated = component.addNotification(defaultNotification);
let notification = TestUtils.scryRenderedDOMComponentsWithClass(instance, 'notification');
expect(notification.length).to.equal(1);
component.removeNotification(notificationCreated);
clock.tick(1000);
let notificationRemoved = TestUtils.scryRenderedDOMComponentsWithClass(instance, 'notification');
expect(notificationRemoved.length).to.equal(0);
done();
});
it('should remove a notification using uid', done => {
let notificationCreated = component.addNotification(defaultNotification);
let notification = TestUtils.scryRenderedDOMComponentsWithClass(instance, 'notification');
expect(notification.length).to.equal(1);
component.removeNotification(notificationCreated.uid);
clock.tick(200);
let notificationRemoved = TestUtils.scryRenderedDOMComponentsWithClass(instance, 'notification');
expect(notificationRemoved.length).to.equal(0);
done();
});
it('should edit an existing notification using returned object', (done) => {
const notificationCreated = component.addNotification(defaultNotification);
const notification = TestUtils.scryRenderedDOMComponentsWithClass(instance, 'notification');
expect(notification.length).to.equal(1);
const newTitle = 'foo';
const newContent = 'foobar';
component.editNotification(notificationCreated, { title: newTitle, message: newContent });
clock.tick(1000);
const notificationEdited = TestUtils.findRenderedDOMComponentWithClass(instance, 'notification');
expect(notificationEdited.getElementsByClassName('notification-title')[0].textContent).to.equal(newTitle);
expect(notificationEdited.getElementsByClassName('notification-message')[0].textContent).to.equal(newContent);
done();
});
it('should edit an existing notification using uid', (done) => {
const notificationCreated = component.addNotification(defaultNotification);
const notification = TestUtils.scryRenderedDOMComponentsWithClass(instance, 'notification');
expect(notification.length).to.equal(1);
const newTitle = 'foo';
const newContent = 'foobar';
component.editNotification(notificationCreated.uid, { title: newTitle, message: newContent });
clock.tick(1000);
const notificationEdited = TestUtils.findRenderedDOMComponentWithClass(instance, 'notification');
expect(notificationEdited.getElementsByClassName('notification-title')[0].textContent).to.equal(newTitle);
expect(notificationEdited.getElementsByClassName('notification-message')[0].textContent).to.equal(newContent);
done();
});
it('should remove all notifications', done => {
component.addNotification(defaultNotification);
component.addNotification(defaultNotification);
component.addNotification(defaultNotification);
let notification = TestUtils.scryRenderedDOMComponentsWithClass(instance, 'notification');
expect(notification.length).to.equal(3);
component.clearNotifications();
clock.tick(200);
let notificationRemoved = TestUtils.scryRenderedDOMComponentsWithClass(instance, 'notification');
expect(notificationRemoved.length).to.equal(0);
done();
});
it('should dismiss notification on click', done => {
component.addNotification(notificationObj);
let notification = TestUtils.findRenderedDOMComponentWithClass(instance, 'notification');
TestUtils.Simulate.click(notification);
clock.tick(1000);
let notificationRemoved = TestUtils.scryRenderedDOMComponentsWithClass(instance, 'notification');
expect(notificationRemoved.length).to.equal(0);
done();
});
it('should dismiss notification on click of dismiss button', done => {
component.addNotification(notificationObj);
let dismissButton = TestUtils.findRenderedDOMComponentWithClass(instance, 'notification-dismiss');
TestUtils.Simulate.click(dismissButton);
clock.tick(1000);
let notificationRemoved = TestUtils.scryRenderedDOMComponentsWithClass(instance, 'notification');
expect(notificationRemoved.length).to.equal(0);
done();
});
it('should not render title if not provided', done => {
delete notificationObj.title;
component.addNotification(notificationObj);
let notification = TestUtils.scryRenderedDOMComponentsWithClass(instance, 'notification-title');
expect(notification.length).to.equal(0);
done();
});
it('should not render message if not provided', done => {
delete notificationObj.message;
component.addNotification(notificationObj);
let notification = TestUtils.scryRenderedDOMComponentsWithClass(instance, 'notification-message');
expect(notification.length).to.equal(0);
done();
});
it('should not dismiss the notificaion on click if dismissible is false', done => {
notificationObj.dismissible = false;
component.addNotification(notificationObj);
let notification = TestUtils.findRenderedDOMComponentWithClass(instance, 'notification');
TestUtils.Simulate.click(notification);
let notificationAfterClicked = TestUtils.findRenderedDOMComponentWithClass(instance, 'notification');
expect(notificationAfterClicked).to.not.be.null;
done();
});
it('should not dismiss the notification on click if dismissible is none', done => {
notificationObj.dismissible = 'none';
component.addNotification(notificationObj);
let notification = TestUtils.findRenderedDOMComponentWithClass(instance, 'notification');
TestUtils.Simulate.click(notification);
let notificationAfterClicked = TestUtils.findRenderedDOMComponentWithClass(instance, 'notification');
expect(notificationAfterClicked).to.exist;
done();
});
it('should not dismiss the notification on click if dismissible is button', done => {
notificationObj.dismissible = 'button';
component.addNotification(notificationObj);
let notification = TestUtils.findRenderedDOMComponentWithClass(instance, 'notification');
TestUtils.Simulate.click(notification);
let notificationAfterClicked = TestUtils.findRenderedDOMComponentWithClass(instance, 'notification');
expect(notificationAfterClicked).to.exist;
done();
});
it('should render a button if action property is passed', done => {
defaultNotification.action = {
label: 'Click me',
callback: function() {}
};
component.addNotification(defaultNotification);
let button = TestUtils.findRenderedDOMComponentWithClass(instance, 'notification-action-button');
expect(button).to.not.be.null;
done();
});
it('should execute a callback function when notification button is clicked', done => {
let testThis = false;
notificationObj.action = {
label: 'Click me',
callback: function() {
testThis = true;
}
};
component.addNotification(notificationObj);
let button = TestUtils.findRenderedDOMComponentWithClass(instance, 'notification-action-button');
TestUtils.Simulate.click(button);
expect(testThis).to.equal(true);
done();
});
it('should accept an action without callback function defined', done => {
notificationObj.action = {
label: 'Click me'
};
component.addNotification(notificationObj);
let button = TestUtils.findRenderedDOMComponentWithClass(instance, 'notification-action-button');
TestUtils.Simulate.click(button);
let notification = TestUtils.scryRenderedDOMComponentsWithClass(instance, 'notification');
expect(notification.length).to.equal(0);
done();
});
it('should execute a callback function on add a notification', done => {
let testThis = false;
notificationObj.onAdd = function() {
testThis = true;
};
component.addNotification(notificationObj);
expect(testThis).to.equal(true);
done();
});
it('should execute a callback function on remove a notification', done => {
let testThis = false;
notificationObj.onRemove = function() {
testThis = true;
};
component.addNotification(notificationObj);
let notification = TestUtils.findRenderedDOMComponentWithClass(instance, 'notification');
TestUtils.Simulate.click(notification);
expect(testThis).to.equal(true);
done();
});
it('should render a children if passed', done => {
defaultNotification.children = (
<div className="custom-container"></div>
);
component.addNotification(defaultNotification);
let customContainer = TestUtils.findRenderedDOMComponentWithClass(instance, 'custom-container');
expect(customContainer).to.not.be.null;
done();
});
it('should pause the timer if a notification has a mouse enter', done => {
notificationObj.autoDismiss = 2;
component.addNotification(notificationObj);
let notification = TestUtils.findRenderedDOMComponentWithClass(instance, 'notification');
TestUtils.Simulate.mouseEnter(notification);
clock.tick(4000);
let _notification = TestUtils.findRenderedDOMComponentWithClass(instance, 'notification');
expect(_notification).to.not.be.null;
done();
});
it('should resume the timer if a notification has a mouse leave', done => {
notificationObj.autoDismiss = 2;
component.addNotification(notificationObj);
let notification = TestUtils.findRenderedDOMComponentWithClass(instance, 'notification');
TestUtils.Simulate.mouseEnter(notification);
clock.tick(800);
TestUtils.Simulate.mouseLeave(notification);
clock.tick(2000);
let _notification = TestUtils.scryRenderedDOMComponentsWithClass(instance, 'notification');
expect(_notification.length).to.equal(0);
done();
});
it('should allow HTML inside messages', done => {
defaultNotification.message = '<strong class="allow-html-strong">Strong</strong>';
component.addNotification(defaultNotification);
let notification = TestUtils.findRenderedDOMComponentWithClass(instance, 'notification-message');
let htmlElement = notification.getElementsByClassName('allow-html-strong');
expect(htmlElement.length).to.equal(1);
done();
});
it('should render containers with a overriden width', done => {
notificationObj.position = 'tc';
component.addNotification(notificationObj);
let notification = TestUtils.findRenderedDOMComponentWithClass(instance, 'notifications-tc');
let width = notification.style.width;
expect(width).to.equal('600px');
done();
});
it('should render a notification with specific style based on position', done => {
notificationObj.position = 'bc';
component.addNotification(notificationObj);
let notification = TestUtils.findRenderedDOMComponentWithClass(instance, 'notification');
let bottomPosition = notification.style.bottom;
expect(bottomPosition).to.equal('-100px');
done();
});
it('should render containers with a overriden width for a specific position', done => {
notificationObj.position = 'tl';
component.addNotification(notificationObj);
let notification = TestUtils.findRenderedDOMComponentWithClass(instance, 'notifications-tl');
let width = notification.style.width;
expect(width).to.equal('800px');
done();
});
it('should throw an error if no level is defined', done => {
delete notificationObj.level;
expect(() => component.addNotification(notificationObj)).to.throw(/notification level is required/);
done();
});
it('should throw an error if a invalid level is defined', done => {
notificationObj.level = 'invalid';
expect(() => component.addNotification(notificationObj)).to.throw(/is not a valid level/);
done();
});
it('should throw an error if a invalid position is defined', done => {
notificationObj.position = 'invalid';
expect(() => component.addNotification(notificationObj)).to.throw(/is not a valid position/);
done();
});
it('should throw an error if autoDismiss is not a number', done => {
notificationObj.autoDismiss = 'string';
expect(() => component.addNotification(notificationObj)).to.throw(/\'autoDismiss\' must be a number./);
done();
});
it('should render 2nd notification below 1st one', done => {
component.addNotification(merge({}, defaultNotification, {title: '1st'}));
component.addNotification(merge({}, defaultNotification, {title: '2nd'}));
const notifications = TestUtils.scryRenderedDOMComponentsWithClass(instance, 'notification');
expect(notifications[0].getElementsByClassName('notification-title')[0].textContent).to.equal('1st');
expect(notifications[1].getElementsByClassName('notification-title')[0].textContent).to.equal('2nd');
done();
});
});
describe('Notification Component with newOnTop=true', function() {
let node;
let instance;
let component;
let clock;
let notificationObj;
const ref = 'notificationSystem';
this.timeout(10000);
beforeEach(() => {
// We need to create this wrapper so we can use refs
class ElementWrapper extends Component {
render() {
return <NotificationSystem ref={ ref } style={ style } allowHTML={ true } noAnimation={ true } newOnTop={ true } />;
}
}
node = window.document.createElement("div");
instance = TestUtils.renderIntoDocument(React.createElement(ElementWrapper), node);
component = instance.refs[ref];
notificationObj = merge({}, defaultNotification);
clock = sinon.useFakeTimers();
});
afterEach(() => {
clock.restore();
});
it('should render 2nd notification above 1st one', done => {
component.addNotification(merge({}, defaultNotification, {title: '1st'}));
component.addNotification(merge({}, defaultNotification, {title: '2nd'}));
const notifications = TestUtils.scryRenderedDOMComponentsWithClass(instance, 'notification');
expect(notifications[0].getElementsByClassName('notification-title')[0].textContent).to.equal('2nd');
expect(notifications[1].getElementsByClassName('notification-title')[0].textContent).to.equal('1st');
done();
});
}); | igorprado/react-notification-system | test/notification-system.test.js | JavaScript | mit | 19,158 |
const AssignmentExpression = require('./AssignmentExpression');
const Class = require('./Class');
const DecoratorDescriptor = require('./DecoratorDescriptor');
const ExpressionStatement = require('./ExpressionStatement');
const Function = require('./Function');
const Identifier = require('./Identifier');
const MemberExpression = require('./MemberExpression');
const ModuleDeclarationInterface = require('./ModuleDeclarationInterface');
const VariableDeclaration = require('./VariableDeclaration');
/**
* @memberOf Jymfony.Component.Autoloader.Parser.AST
*/
class ExportNamedDeclaration extends implementationOf(ModuleDeclarationInterface) {
/**
* Constructor.
*
* @param {Jymfony.Component.Autoloader.Parser.AST.SourceLocation} location
* @param {Jymfony.Component.Autoloader.Parser.AST.VariableDeclaration} declarations
* @param {Jymfony.Component.Autoloader.Parser.AST.ExportSpecifier[]} specifiers
* @param {Jymfony.Component.Autoloader.Parser.AST.Literal} source
*/
__construct(location, declarations, specifiers, source) {
/**
* @type {Jymfony.Component.Autoloader.Parser.AST.SourceLocation}
*/
this.location = location;
/**
* @type {Jymfony.Component.Autoloader.Parser.AST.VariableDeclaration}
*
* @private
*/
this._declarations = declarations;
/**
* @type {Jymfony.Component.Autoloader.Parser.AST.ExportSpecifier[]}
*
* @private
*/
this._specifiers = specifiers;
/**
* @type {Jymfony.Component.Autoloader.Parser.AST.Literal}
*
* @private
*/
this._source = source;
/**
* @type {string}
*/
this.docblock = null;
/**
* @type {null|[string, Jymfony.Component.Autoloader.Parser.AST.ExpressionInterface][]}
*/
this.decorators = null;
}
/**
* @inheritdoc
*/
compile(compiler) {
if (null === this._declarations) {
for (const specifier of this._specifiers) {
compiler.compileNode(
new ExpressionStatement(null, new AssignmentExpression(
null,
'=',
new MemberExpression(null, new Identifier(null, 'exports'), specifier.exported),
specifier.local
))
);
compiler._emit(';\n');
}
return;
}
compiler.compileNode(this._declarations);
compiler._emit(';\n');
if (this._declarations instanceof VariableDeclaration) {
for (const declarator of this._declarations.declarators) {
ExportNamedDeclaration._exportDeclarator(compiler, declarator);
}
} else if (this._declarations instanceof DecoratorDescriptor) {
compiler.compileNode(
new ExpressionStatement(null, new AssignmentExpression(
null, '=',
new MemberExpression(null, new Identifier(null, 'exports'), new Identifier(null, this._declarations.mangledName)),
new Identifier(null, this._declarations.mangledName)
))
);
} else if (this._declarations instanceof Function || this._declarations instanceof Class) {
if (this.decorators) {
this._declarations.declarators = this.decorators;
}
compiler.compileNode(
new ExpressionStatement(null, new AssignmentExpression(
null,
'=',
new MemberExpression(null, new Identifier(null, 'exports'), this._declarations.id),
this._declarations.id
))
);
}
}
/**
* Compile a declarator export.
*
* @param {Jymfony.Component.Autoloader.Parser.Compiler} compiler
* @param {Jymfony.Component.Autoloader.Parser.AST.VariableDeclarator} declarator
*
* @private
*/
static _exportDeclarator(compiler, declarator) {
for (const exportedName of declarator.id.names) {
compiler.compileNode(
new ExpressionStatement(null, new AssignmentExpression(
null,
'=',
new MemberExpression(null, new Identifier(null, 'exports'), exportedName),
exportedName
))
);
}
}
}
module.exports = ExportNamedDeclaration;
| massimilianobraglia/jymfony | src/Component/Autoloader/src/Parser/AST/ExportNamedDeclaration.js | JavaScript | mit | 4,617 |
export const APP_LAYOUT_INIT = 'APP_LAYOUT_INIT';
export const APP_LAYOUT_CHANGE = 'APP_LAYOUT_CHANGE';
| dunwu/react-app | codes/src/view/general/setting/redux/constants.js | JavaScript | mit | 104 |
/*
Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang("specialchar", "es", {euro: "Símbolo de euro", lsquo: "Comilla simple izquierda", rsquo: "Comilla simple derecha", ldquo: "Comilla doble izquierda", rdquo: "Comilla doble derecha", ndash: "Guión corto", mdash: "Guión medio largo", iexcl: "Signo de admiración invertido", cent: "Símbolo centavo", pound: "Símbolo libra", curren: "Símbolo moneda", yen: "Símbolo yen", brvbar: "Barra vertical rota", sect: "Símbolo sección", uml: "Diéresis", copy: "Signo de derechos de autor", ordf: "Indicador ordinal femenino", laquo: "Abre comillas angulares",
not: "Signo negación", reg: "Signo de marca registrada", macr: "Guión alto", deg: "Signo de grado", sup2: "Superíndice dos", sup3: "Superíndice tres", acute: "Acento agudo", micro: "Signo micro", para: "Signo de pi", middot: "Punto medio", cedil: "Cedilla", sup1: "Superíndice uno", ordm: "Indicador orginal masculino", raquo: "Cierra comillas angulares", frac14: "Fracción ordinaria de un quarto", frac12: "Fracción ordinaria de una mitad", frac34: "Fracción ordinaria de tres cuartos", iquest: "Signo de interrogación invertido", Agrave: "Letra A latina mayúscula con acento grave",
Aacute: "Letra A latina mayúscula con acento agudo", Acirc: "Letra A latina mayúscula con acento circunflejo", Atilde: "Letra A latina mayúscula con tilde", Auml: "Letra A latina mayúscula con diéresis", Aring: "Letra A latina mayúscula con aro arriba", AElig: "Letra Æ latina mayúscula", Ccedil: "Letra C latina mayúscula con cedilla", Egrave: "Letra E latina mayúscula con acento grave", Eacute: "Letra E latina mayúscula con acento agudo", Ecirc: "Letra E latina mayúscula con acento circunflejo", Euml: "Letra E latina mayúscula con diéresis",
Igrave: "Letra I latina mayúscula con acento grave", Iacute: "Letra I latina mayúscula con acento agudo", Icirc: "Letra I latina mayúscula con acento circunflejo", Iuml: "Letra I latina mayúscula con diéresis", ETH: "Letra Eth latina mayúscula", Ntilde: "Letra N latina mayúscula con tilde", Ograve: "Letra O latina mayúscula con acento grave", Oacute: "Letra O latina mayúscula con acento agudo", Ocirc: "Letra O latina mayúscula con acento circunflejo", Otilde: "Letra O latina mayúscula con tilde", Ouml: "Letra O latina mayúscula con diéresis",
times: "Signo de multiplicación", Oslash: "Letra O latina mayúscula con barra inclinada", Ugrave: "Letra U latina mayúscula con acento grave", Uacute: "Letra U latina mayúscula con acento agudo", Ucirc: "Letra U latina mayúscula con acento circunflejo", Uuml: "Letra U latina mayúscula con diéresis", Yacute: "Letra Y latina mayúscula con acento agudo", THORN: "Letra Thorn latina mayúscula", szlig: "Letra s latina fuerte pequeña", agrave: "Letra a latina pequeña con acento grave", aacute: "Letra a latina pequeña con acento agudo",
acirc: "Letra a latina pequeña con acento circunflejo", atilde: "Letra a latina pequeña con tilde", auml: "Letra a latina pequeña con diéresis", aring: "Letra a latina pequeña con aro arriba", aelig: "Letra æ latina pequeña", ccedil: "Letra c latina pequeña con cedilla", egrave: "Letra e latina pequeña con acento grave", eacute: "Letra e latina pequeña con acento agudo", ecirc: "Letra e latina pequeña con acento circunflejo", euml: "Letra e latina pequeña con diéresis", igrave: "Letra i latina pequeña con acento grave",
iacute: "Letra i latina pequeña con acento agudo", icirc: "Letra i latina pequeña con acento circunflejo", iuml: "Letra i latina pequeña con diéresis", eth: "Letra eth latina pequeña", ntilde: "Letra n latina pequeña con tilde", ograve: "Letra o latina pequeña con acento grave", oacute: "Letra o latina pequeña con acento agudo", ocirc: "Letra o latina pequeña con acento circunflejo", otilde: "Letra o latina pequeña con tilde", ouml: "Letra o latina pequeña con diéresis", divide: "Signo de división", oslash: "Letra o latina minúscula con barra inclinada",
ugrave: "Letra u latina pequeña con acento grave", uacute: "Letra u latina pequeña con acento agudo", ucirc: "Letra u latina pequeña con acento circunflejo", uuml: "Letra u latina pequeña con diéresis", yacute: "Letra u latina pequeña con acento agudo", thorn: "Letra thorn latina minúscula", yuml: "Letra y latina pequeña con diéresis", OElig: "Diptongo OE latino en mayúscula", oelig: "Diptongo oe latino en minúscula", 372: "Letra W latina mayúscula con acento circunflejo", 374: "Letra Y latina mayúscula con acento circunflejo",
373: "Letra w latina pequeña con acento circunflejo", 375: "Letra y latina pequeña con acento circunflejo", sbquo: "Comilla simple baja-9", 8219: "Comilla simple alta invertida-9", bdquo: "Comillas dobles bajas-9", hellip: "Puntos suspensivos horizontales", trade: "Signo de marca registrada", 9658: "Apuntador negro apuntando a la derecha", bull: "Viñeta", rarr: "Flecha a la derecha", rArr: "Flecha doble a la derecha", hArr: "Flecha izquierda derecha doble", diams: "Diamante negro", asymp: "Casi igual a"}); | bkovacev/gae-student-portal | vendor/ckeditor/plugins/specialchar/dialogs/lang/es.js | JavaScript | mit | 5,205 |
var helloWorldController = function(app){
app.get('/hello/world', function(request, response){
var responseObject = { "hello": "world"}
response.send(responseObject);
});
};
module.exports = helloWorldController; | shawnmcginty/expressjs-rest-boilerplate | app/controllers/helloWorldController.js | JavaScript | mit | 222 |
(function(){
angular.module('form', ['participants'])
.component('formComp', {
templateUrl: 'components/form/template.html',
bindings: {
addParticipant: '<'
},
controller: function(Participants){
this.participant = {};
this.submit = function(participant){
if (!this.password) {
delete this.participant.pass;
}
if (!this.email) {
delete this.participant.email;
}
this.addParticipant(participant);
};
}
});
})();
| kucharskimaciej/lets-run | source/components/form/component.js | JavaScript | mit | 558 |
define(['../../moduleDef', 'angular'], function(module, angular) {
'use strict';
module.provider('$dateParser', function() {
var proto = Date.prototype;
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
var defaults = this.defaults = {
format: 'shortDate',
strict: false
};
this.$get = function($locale) {
var DateParserFactory = function(config) {
var options = angular.extend({}, defaults, config);
var $dateParser = {};
var regExpMap = {
'sss' : '[0-9]{3}',
'ss' : '[0-5][0-9]',
's' : options.strict ? '[1-5]?[0-9]' : '[0-5][0-9]',
'mm' : '[0-5][0-9]',
'm' : options.strict ? '[1-5]?[0-9]' : '[0-5][0-9]',
'HH' : '[01][0-9]|2[0-3]',
'H' : options.strict ? '[0][1-9]|[1][012]' : '[01][0-9]|2[0-3]',
'hh' : '[0][1-9]|[1][012]',
'h' : options.strict ? '[1-9]|[1][012]' : '[0]?[1-9]|[1][012]',
'a' : 'AM|PM',
'EEEE' : $locale.DATETIME_FORMATS.DAY.join('|'),
'EEE' : $locale.DATETIME_FORMATS.SHORTDAY.join('|'),
'dd' : '[0-2][0-9]{1}|[3][01]{1}',
'd' : options.strict ? '[1-2]?[0-9]{1}|[3][01]{1}' : '[0-2][0-9]{1}|[3][01]{1}',
'MMMM' : $locale.DATETIME_FORMATS.MONTH.join('|'),
'MMM' : $locale.DATETIME_FORMATS.SHORTMONTH.join('|'),
'MM' : '[0][1-9]|[1][012]',
'M' : options.strict ? '[1-9]|[1][012]' : '[0][1-9]|[1][012]',
'yyyy' : '(?:(?:[1]{1}[0-9]{1}[0-9]{1}[0-9]{1})|(?:[2]{1}[0-9]{3}))(?![[0-9]])',
'yy' : '(?:(?:[0-9]{1}[0-9]{1}))(?![[0-9]])'
};
var setFnMap = {
'sss' : proto.setMilliseconds,
'ss' : proto.setSeconds,
's' : proto.setSeconds,
'mm' : proto.setMinutes,
'm' : proto.setMinutes,
'HH' : proto.setHours,
'H' : proto.setHours,
'hh' : proto.setHours,
'h' : proto.setHours,
'dd' : proto.setDate,
'd' : proto.setDate,
'a' : function(value) { var hours = this.getHours(); return this.setHours(value.match(/pm/i) ? hours + 12 : hours); },
'MMMM' : function(value) { return this.setMonth($locale.DATETIME_FORMATS.MONTH.indexOf(value)); },
'MMM' : function(value) { return this.setMonth($locale.DATETIME_FORMATS.SHORTMONTH.indexOf(value)); },
'MM' : function(value) { return this.setMonth(1 * value - 1); },
'M' : function(value) { return this.setMonth(1 * value - 1); },
'yyyy' : proto.setFullYear,
'yy' : function(value) { return this.setFullYear(2000 + 1 * value); },
'y' : proto.setFullYear
};
var regex, setMap;
$dateParser.init = function() {
$dateParser.$format = $locale.DATETIME_FORMATS[options.format] || options.format;
regex = regExpForFormat($dateParser.$format);
setMap = setMapForFormat($dateParser.$format);
};
$dateParser.isValid = function(date) {
if(angular.isDate(date)) return !isNaN(date.getTime());
return regex.test(date);
};
$dateParser.parse = function(value, baseDate) {
if(angular.isDate(value)) return value;
var matches = regex.exec(value);
if(!matches) return false;
var date = baseDate || new Date(0);
for(var i = 0; i < matches.length - 1; i++) {
setMap[i] && setMap[i].call(date, matches[i+1]);
}
return date;
};
// Private functions
function setMapForFormat(format) {
var keys = Object.keys(setFnMap), i;
var map = [], sortedMap = [];
// Map to setFn
var clonedFormat = format;
for(i = 0; i < keys.length; i++) {
if(format.split(keys[i]).length > 1) {
var index = clonedFormat.search(keys[i]);
format = format.split(keys[i]).join('');
if(setFnMap[keys[i]]) map[index] = setFnMap[keys[i]];
}
}
// Sort result map
angular.forEach(map, function(v) {
sortedMap.push(v);
});
return sortedMap;
}
function escapeReservedSymbols(text) {
return text.replace(/\//g, '[\\/]').replace('/-/g', '[-]').replace(/\./g, '[.]').replace(/\\s/g, '[\\s]');
}
function regExpForFormat(format) {
var keys = Object.keys(regExpMap), i;
var re = format;
// Abstract replaces to avoid collisions
for(i = 0; i < keys.length; i++) {
re = re.split(keys[i]).join('${' + i + '}');
}
// Replace abstracted values
for(i = 0; i < keys.length; i++) {
re = re.split('${' + i + '}').join('(' + regExpMap[keys[i]] + ')');
}
format = escapeReservedSymbols(format);
return new RegExp('^' + re + '$', ['i']);
}
$dateParser.init();
return $dateParser;
};
return DateParserFactory;
};
});
});
| olegsmetanin/apinet-client-donotuse | src/core/directives/datepicker/date-parser.js | JavaScript | mit | 4,998 |
/**
* @copyright 2013 Sonia Keys
* @copyright 2016 commenthol
* @license MIT
* @module solarxyz
*/
/**
* Solarxyz: Chapter 26, Rectangular Coordinates of the Sun.
*/
import base from './base.js'
import nutation from './nutation.js'
import solar from './solar.js'
/**
* Position returns rectangular coordinates referenced to the mean equinox of date.
* @param {planetposition.Planet} earth - VSOP87Planet Earth
* @param {Number} jde - Julian ephemeris day
* @return {object} rectangular coordinates
* {Number} x
* {Number} y
* {Number} z
*/
export function position (earth, jde) { // (e *pp.V87Planet, jde float64) (x, y, z float64)
// (26.1) p. 171
const { lon, lat, range } = solar.trueVSOP87(earth, jde)
const [sε, cε] = base.sincos(nutation.meanObliquity(jde))
const [ss, cs] = base.sincos(lon)
const sβ = Math.sin(lat)
const x = range * cs
const y = range * (ss * cε - sβ * sε)
const z = range * (ss * sε + sβ * cε)
return { x, y, z }
}
/**
* LongitudeJ2000 returns geometric longitude referenced to equinox J2000.
* @param {planetposition.Planet} earth - VSOP87Planet Earth
* @param {Number} jde - Julian ephemeris day
* @return {Number} geometric longitude referenced to equinox J2000.
*/
export function longitudeJ2000 (earth, jde) {
const lon = earth.position2000(jde).lon
return base.pmod(lon + Math.PI - 0.09033 / 3600 * Math.PI / 180, 2 * Math.PI)
}
/**
* PositionJ2000 returns rectangular coordinates referenced to equinox J2000.
* @param {planetposition.Planet} earth - VSOP87Planet Earth
* @param {Number} jde - Julian ephemeris day
* @return {object} rectangular coordinates
* {Number} x
* {Number} y
* {Number} z
*/
export function positionJ2000 (earth, jde) {
const { x, y, z } = xyz(earth, jde)
// (26.3) p. 174
return {
x: x + 0.00000044036 * y - 0.000000190919 * z,
y: -0.000000479966 * x + 0.917482137087 * y - 0.397776982902 * z,
z: 0.397776982902 * y + 0.917482137087 * z
}
}
export function xyz (earth, jde) {
const { lon, lat, range } = earth.position2000(jde)
const s = lon + Math.PI
const β = -lat
const [ss, cs] = base.sincos(s)
const [sβ, cβ] = base.sincos(β)
// (26.2) p. 172
const x = range * cβ * cs
const y = range * cβ * ss
const z = range * sβ
return { x, y, z }
}
/**
* PositionB1950 returns rectangular coordinates referenced to B1950.
*
* Results are referenced to the mean equator and equinox of the epoch B1950
* in the FK5 system, not FK4.
*
* @param {planetposition.Planet} earth - VSOP87Planet Earth
* @param {Number} jde - Julian ephemeris day
* @return {object} rectangular coordinates
* {Number} x
* {Number} y
* {Number} z
*/
export function positionB1950 (earth, jde) { // (e *pp.V87Planet, jde float64) (x, y, z float64)
const { x, y, z } = xyz(earth, jde)
return {
x: 0.999925702634 * x + 0.012189716217 * y + 0.000011134016 * z,
y: -0.011179418036 * x + 0.917413998946 * y - 0.397777041885 * z,
z: -0.004859003787 * x + 0.397747363646 * y + 0.917482111428 * z
}
}
const ζt = [2306.2181, 0.30188, 0.017998]
const zt = [2306.2181, 1.09468, 0.018203]
const θt = [2004.3109, -0.42665, -0.041833]
/**
* PositionEquinox returns rectangular coordinates referenced to an arbitrary epoch.
*
* Position will be computed for given Julian day "jde" but referenced to mean
* equinox "epoch" (year).
*
* @param {planetposition.Planet} earth - VSOP87Planet Earth
* @param {Number} jde - Julian ephemeris day
* @param {Number} epoch
* @return {object} rectangular coordinates
* {Number} x
* {Number} y
* {Number} z
*/
export function positionEquinox (earth, jde, epoch) {
const xyz = positionJ2000(earth, jde)
const x0 = xyz.x
const y0 = xyz.y
const z0 = xyz.z
const t = (epoch - 2000) * 0.01
const ζ = base.horner(t, ζt) * t * Math.PI / 180 / 3600
const z = base.horner(t, zt) * t * Math.PI / 180 / 3600
const θ = base.horner(t, θt) * t * Math.PI / 180 / 3600
const [sζ, cζ] = base.sincos(ζ)
const [sz, cz] = base.sincos(z)
const [sθ, cθ] = base.sincos(θ)
const xx = cζ * cz * cθ - sζ * sz
const xy = sζ * cz + cζ * sz * cθ
const xz = cζ * sθ
const yx = -cζ * sz - sζ * cz * cθ
const yy = cζ * cz - sζ * sz * cθ
const yz = -sζ * sθ
const zx = -cz * sθ
const zy = -sz * sθ
const zz = cθ
return {
x: xx * x0 + yx * y0 + zx * z0,
y: xy * x0 + yy * y0 + zy * z0,
z: xz * x0 + yz * y0 + zz * z0
}
}
export default {
position,
longitudeJ2000,
positionJ2000,
xyz,
positionB1950,
positionEquinox
}
| commenthol/astronomia | src/solarxyz.js | JavaScript | mit | 4,608 |
/**
* New node file
*/
var log4js = require('log4js');
var UserSession = require('./UserSession');
/* Room corresponds to each conference room*/
function UsersRegistry() {
"use strict";
/* If this constructor is called without the "new" operator, "this" points
* to the global object. Log a warning and call it correctly. */
if (false === (this instanceof UsersRegistry)) {
console.log('Warning: UsersRegistry constructor called without "new" operator');
return new UsersRegistry();
}
var log = log4js.getLogger('web');
var usersByName = {};
var usersBySessionId = {};
var idCounter = 0;
this.register = function(usersession){
usersByName[usersession.getName()] = usersession;
usersBySessionId[usersession.getWebSessionId()] = usersession;
}
this.getByName = function(name){
return usersByName[name];
}
this.exists = function(name) {
var isUserExists = !!usersByName[name];
return isUserExists;
}
this.getBySession = function(id){
return usersBySessionId[id];
}
this.removeBySession = function(id) {
var user = this.getBySession(id);
if(user){
delete usersByName[user.getName()];
delete usersBySessionId [user.getWebSessionId()];
}
return user;
}
this.nextUniqueId = function() {
idCounter++;
if(idCounter < 0){
idCounter = 1; // reset the counter, we will never have 65535 simultaneous clients anytime soon.
// lets try finding number which does not exist in our map
while (idExists(idCounter)) idCounter++;
}
return idCounter.toString();
}
this.idExists = function(id){
if (!usersBySessionId[id])
return false;
return true;
}
this.printRegistryInfo = function(){
//log.debug("usersByName --> ", usersByName);
//log.debug("usersBySessionId --> ", usersByName);
}
}
module.exports.UsersRegistry = UsersRegistry; | ajaytripathi/groupvideocall | model/UsersRegistry.js | JavaScript | mit | 1,820 |
describe('TimeFilter', function () {
beforeEach(module('ngMovies'));
var TimeFilter;
beforeEach(inject(function ($filter) {
TimeFilter = $filter('TimeFilter');
}));
it('should be a filter', function () {
expect(TimeFilter).not.toBe(undefined);
});
it('should convert minutes to hours', function () {
expect(TimeFilter('110 min')).toBe('1 hour 50 minutes');
expect(TimeFilter('120 min')).toBe('2 hours');
expect(TimeFilter('140 min')).toBe('2 hours 20 minutes');
expect(TimeFilter('15 min')).toBe('15 minutes');
});
it('should handle invalid time', function () {
expect(TimeFilter('N/A')).toBe('N/A');
expect(TimeFilter('Error')).toBe('N/A');
});
});
| jillesme/ng-movies | public/test/spec/TimeFilter.spec.js | JavaScript | mit | 710 |
// import should from 'should';
import { createStore } from 'redux';
import reredeux, { deux, LABELS } from '../src';
const { INIT, SELECT, ACTION, REDUCER, VALUE } = LABELS;
import todo from './todo';
import counter from './counter';
import phonebook from './phonebook';
const app = reredeux('example', [
counter,
todo,
deux('nest', [
phonebook
])
]);
let store;
let state;
describe('app', () => {
beforeEach(() => {
store = createStore(app[REDUCER], app[INIT]);
state = store.getState();
});
describe(INIT, () => {
describe('example', () => {
describe('counter', () => {
it('eql to 0', () => {
state.example.counter
.should.be.eql(0);
});
});
describe('todo', () => {
it('', () => {
state.example.todo
.should.be.eql([
{ name: 'brush teeth', complete: true },
{ name: 'dishes' , complete: false },
]);
});
});
describe('nest', () => {
describe('phonebook', () => {
it('== []', () => {
state.example.nest.phonebook
.should.be.eql([
{ name: 'person1', number: '1(222)333-4444'},
{ name: 'person2', number: '1(333)444-5555'},
]);
});
});
});
});
});
describe(SELECT, () => {
describe('example', () => {
describe('counter', () => {
describe(VALUE, () => {
it('== 0', () => {
app[SELECT].example.counter[VALUE](state)
.should.be.eql(0);
});
});
describe('succ', () => {
it('== 1', () => {
app[SELECT].example.counter.succ(state)
.should.be.eql(1);
});
});
describe('pred', () => {
it('== -1', () => {
app[SELECT].example.counter.pred(state)
.should.be.eql(-1);
});
});
});
describe('todo', () => {
describe('value', () => {
it('returns all the data', () => {
app[SELECT].example.todo.value(state)
.should.be.eql([
{ name: 'brush teeth', complete: true },
{ name: 'dishes' , complete: false },
]);
});
});
describe('titles', () => {
it('returns a list of todo titles', () => {
app[SELECT].example.todo.titles(state)
.should.be.eql(['brush teeth', 'dishes']);
});
});
describe('statuses', () => {
it('returns a list of completion status', () => {
app[SELECT].example.todo.statuses(state)
.should.be.eql([true, false]);
});
});
describe('completed', () => {
it('returns only complete todos', () => {
app[SELECT].example.todo.completed(state)
.should.be.eql([
{ name: 'brush teeth', complete: true },
]);
});
});
describe('pending', () => {
it('returns only incomplete todos', () => {
app[SELECT].example.todo.pending(state)
.should.be.eql([
{ name: 'dishes' , complete: false },
]);
});
});
});
describe('nest', () => {
describe('phonebook', () => {
describe('value', () => {
it('returns the list of entries', () => {
app[SELECT].example.nest.phonebook.value(state)
.should.be.eql([
{ name: 'person1', number: '1(222)333-4444'},
{ name: 'person2', number: '1(333)444-5555'},
]);
});
});
describe('nameToNumber', () => {
it('returns the map from name to number', () => {
app[SELECT].example.nest.phonebook.nameToNumber(state)
.should.be.eql({
'person1': { name: 'person1', number: '1(222)333-4444'},
'person2': { name: 'person2', number: '1(333)444-5555'},
});
});
});
describe('numberToName', () => {
it('returns the map from number to name', () => {
app[SELECT].example.nest.phonebook.numberToName(state)
.should.be.eql({
'1(222)333-4444': { name: 'person1', number: '1(222)333-4444'},
'1(333)444-5555': { name: 'person2', number: '1(333)444-5555'},
});
});
});
});
});
});
});
describe(ACTION, () => {
it('increment', () => {
app[ACTION].increment()
.should.have.property('type');
app[ACTION].increment()
.should.not.have.property('payload');
});
it('decrement', () => {
app[ACTION].decrement()
.should.have.property('type');
app[ACTION].decrement()
.should.not.have.property('payload');
});
});
describe(REDUCER, () => {
describe('counter', () => {
it('increment', () => {
store.dispatch(app[ACTION].increment());
state = store.getState();
state.example.counter
.should.be.eql(1);
});
it('decrement', () => {
store.dispatch(app[ACTION].decrement());
state = store.getState();
state.example.counter
.should.be.eql(-1);
});
});
});
});
| MrRacoon/reredeux | example/test.js | JavaScript | mit | 5,467 |
module.exports = function (grunt) {
// Project configuration.
grunt.initConfig({
// Metadata.
pkg : grunt.file.readJSON('storelocator.jquery.json'),
banner : '/*! <%= pkg.title || pkg.name %> - v<%= pkg.version %> - ' +
'<%= grunt.template.today("yyyy-mm-dd") %>\n' +
'<%= pkg.homepage ? "* " + pkg.homepage + "\\n" : "" %>' +
'* Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %>;' +
' Licensed <%= _.map(pkg.licenses, "type").join(", ") %> */\n',
// Task configuration.
clean : {
files: ['dist']
},
sass : {
dist: {
files: {
'dist/assets/css/storelocator.css' : 'src/css/storelocator.scss',
'dist/assets/css/bootstrap-example.css' : 'src/css/bootstrap-example.scss'
}
}
},
concat : {
options: {
stripBanners: true
},
dist : {
src : ['src/js/jquery.<%= pkg.name %>.js'],
dest: 'dist/assets/js/plugins/storeLocator/jquery.<%= pkg.name %>.js'
}
},
uglify: {
dist: {
files: {
'dist/assets/js/plugins/storeLocator/jquery.<%= pkg.name %>.min.js': '<%= concat.dist.dest %>',
'dist/assets/js/libs/handlebars.min.js' : 'libs/handlebars/*.js',
'dist/assets/js/geocode.min.js' : 'src/js/geocode.js',
'dist/assets/js/libs/markerclusterer.min.js' : 'libs/markerclusterer/*.js',
}
}
},
qunit : {
files: ['test/**/*.html']
},
jshint : {
gruntfile: {
options: {
jshintrc: '.jshintrc'
},
src : 'Gruntfile.js'
},
src : {
options: {
jshintrc: 'src/.jshintrc'
},
globals: {
jQuery: true,
google: true
},
src : ['src/**/*.js']
},
test : {
options: {
jshintrc: 'test/.jshintrc'
},
src : ['test/**/*.js']
}
},
usebanner: {
dist: {
options: {
position: 'top',
banner : '<%= banner %>'
},
files : {
'dist/assets/js/plugins/storeLocator/jquery.<%= pkg.name %>.js' : 'dist/assets/js/plugins/storeLocator/jquery.<%= pkg.name %>.js',
'dist/assets/js/plugins/storeLocator/jquery.<%= pkg.name %>.min.js': 'dist/assets/js/plugins/storeLocator/jquery.<%= pkg.name %>.min.js'
}
}
},
cssmin : {
dist: {
files: {
'dist/assets/css/storelocator.min.css': 'dist/assets/css/storelocator.css',
'dist/assets/css/bootstrap-example.min.css': 'dist/assets/css/bootstrap-example.css'
}
}
},
handlebars : {
dist: {
files: {
'dist/assets/js/plugins/storeLocator/templates/compiled/standard-templates.js': 'src/templates/standard/*.html',
'dist/assets/js/plugins/storeLocator/templates/compiled/kml-templates.js': 'src/templates/kml/*.html'
}
}
},
watch : {
gruntfile: {
files: '<%= jshint.gruntfile.src %>',
tasks: ['jshint:gruntfile']
},
src : {
files : ['src/**/*'],
tasks : ['sass', 'concat', 'uglify', 'usebanner', 'cssmin'],
options: {
spawn : false
}
},
test : {
files: '<%= jshint.test.src %>',
tasks: ['jshint:test', 'qunit']
}
}
});
// These plugins provide necessary tasks.
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-sass');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-qunit');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-banner');
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-contrib-handlebars');
// Build
grunt.registerTask('build', ['sass', 'concat', 'uglify', 'usebanner', 'cssmin']);
//Watch src build
grunt.registerTask('watchsrc', ['watch:src']);
};
| bjorn2404/jQuery-Store-Locator-Plugin | Gruntfile.js | JavaScript | mit | 3,809 |
import { expect } from 'chai';
import productReducer from './productReducer';
import * as actions from '../actions/productActions';
import * as types from '../constants/actionTypes';
import initialState from './initialState';
describe('Product Reducer', () => {
it ('should set isFetching to true on all request actions', () => {
let newState = productReducer({ ...initialState.products }, actions.updateProduct({}));
expect(newState.isFetching).to.equal(true);
newState = productReducer({ ...initialState.products }, actions.deleteProduct(0));
expect(newState.isFetching).to.equal(true);
newState = productReducer({ ...initialState.products }, actions.createProduct({}));
expect(newState.isFetching).to.equal(true);
newState = productReducer({ ...initialState.products }, actions.getProduct(0));
expect(newState.isFetching).to.equal(true);
newState = productReducer({ ...initialState.products }, actions.getAllProducts());
expect(newState.isFetching).to.equal(true);
});
it ('should set isFetching to false on all request completions', () => {
let newState = productReducer({ ...initialState.products, isFetching: true }, { type: types.PRODUCTS_REQUEST_SUCCESS });
expect(newState.isFetching).to.equal(false);
newState = productReducer({ ...initialState.products, isFetching: true }, { type: types.PRODUCT_REQUEST_SUCCESS });
expect(newState.isFetching).to.equal(false);
newState = productReducer({ ...initialState.products, isFetching: true }, { type: types.UPDATE_PRODUCT_SUCCESS });
expect(newState.isFetching).to.equal(false);
newState = productReducer({ ...initialState.products, isFetching: true }, { type: types.DELETE_PRODUCT_SUCCESS });
expect(newState.isFetching).to.equal(false);
newState = productReducer({ ...initialState.products, isFetching: true }, { type: types.PRODUCT_REQUEST_FAILURE });
expect(newState.isFetching).to.equal(false);
});
it ('should set editing values on modal actions', () => {
const product = {
id: 0,
name: 'test'
};
const action = actions.showEditModal(product);
let newState = productReducer({ ...initialState.products }, action);
expect(newState.editing.modalOpen).to.equal(true);
expect(newState.editing.product).to.deep.equal(product);
newState = productReducer(newState, actions.closeEditModal());
expect(newState.editing.modalOpen).to.equal(false);
});
it (`should set product list on ${types.UPDATE_PRODUCT_SUCCESS}`, () => {
const state = {
list: [{
id: 1,
name: 'test'
},{
id: 2,
name: 'test'
}]
};
const newName = 'test2';
const action = {
type: types.UPDATE_PRODUCT_SUCCESS,
result: {
id: 1,
name: newName
}
};
let newState = productReducer(state, action);
expect(newState.list[1].name).to.equal(newName);
});
it (`should set product list on ${types.CREATE_PRODUCT_SUCCESS}`, () => {
const state = {
list: [{
id: 1,
name: 'test'
},{
id: 2,
name: 'test'
}]
};
const action = {
type: types.CREATE_PRODUCT_SUCCESS,
result: {
id: 3,
name: 'test3'
}
};
let newState = productReducer(state, action);
expect(newState.list[2].name).to.equal('test3');
});
it (`should set product list on ${types.DELETE_PRODUCT_SUCCESS}`, () => {
const state = {
list: [{
id: 1,
name: 'test'
},{
id: 2,
name: 'test'
}]
};
const action = {
type: types.DELETE_PRODUCT_SUCCESS,
result: {
id: 1
}
};
let newState = productReducer(state, action);
expect(newState.list[0].id).to.equal(2);
});
it (`should set error on ${types.PRODUCT_REQUEST_FAILURE}`, () => {
const error = {
message: 'test'
};
const action = {
type: types.PRODUCT_REQUEST_FAILURE,
error
};
let newState = productReducer({ ...initialState.products }, action);
expect(newState.error).to.deep.equal(error);
});
});
| nibblesnbits/slingshot-sagas | src/reducers/productReducer.spec.js | JavaScript | mit | 4,145 |
/*
* /MathJax-v2/localization/en/en.js
*
* Copyright (c) 2009-2018 The MathJax Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
MathJax.Localization.addTranslation("en",null,{menuTitle:"English",version:"2.7.8",isLoaded:true,domains:{_:{version:"2.7.8",isLoaded:true,strings:{CookieConfig:"MathJax has found a user-configuration cookie that includes code to be run. Do you want to run it?\n\n(You should press Cancel unless you set up the cookie yourself.)",MathProcessingError:"Math processing error",MathError:"Math error",LoadFile:"Loading %1",Loading:"Loading",LoadFailed:"File failed to load: %1",ProcessMath:"Processing math: %1%%",Processing:"Processing",TypesetMath:"Typesetting math: %1%%",Typesetting:"Typesetting",MathJaxNotSupported:"Your browser does not support MathJax",ErrorTips:"Debugging tips: use %%1, inspect %%2 in the browser console"}},FontWarnings:{},"HTML-CSS":{},HelpDialog:{},MathML:{},MathMenu:{},TeX:{}},plural:function(a){if(a===1){return 1}return 2},number:function(a){return a}});MathJax.Ajax.loadComplete("[MathJax]/localization/en/en.js");
| sserrot/champion_relationships | venv/Lib/site-packages/notebook/static/components/MathJax/localization/en/en.js | JavaScript | mit | 1,613 |
;(function(){
'use strict'
const express = require('express');
const router = express.Router();
router.post('/', function(req, res){
console.error('route: /create, ip: %s, time: %s', req.ip, new Date().toTimeString().substr(0,9));
console.error(Object.keys(req));
console.error(req.body);
res.status(200).json('user created!');
});
module.exports = router;
})(); | btthomas/secret-santa | controllers/create.js | JavaScript | mit | 391 |
#!/usr/bin/env node
/* Passphrases | https://github.com/micahflee/passphrases
Copyright (C) 2015 Micah Lee <micah@micahflee.com>
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 fs = require('fs-extra');
var path = require('path');
var child_process = require('child_process');
var NwBuilder = require('node-webkit-builder');
// are we building a package to distribute?
var buildPackage = (process.argv[2] == '--package');
if(buildPackage) {
process.umask(0022);
// clean up from last time
try {
fs.removeSync('./dist');
fs.mkdirSync('./dist');
} catch(e) {}
}
// learn version of app
var version = JSON.parse(fs.readFileSync('./src/package.json'))['version'];
function build(options, callback) {
var nw = new NwBuilder(options);
nw.on('log', console.log);
nw.build().then(function () {
callback();
}).catch(function(err) {
console.log('');
console.log('Build complete.');
console.log('');
callback(err);
});
}
// options for all platforms
var options = { files: './src/**' }
// Linux
if(process.platform == 'linux') {
options.platforms = ['linux32', 'linux64'];
build(options, function(err){
if(err) throw err;
if(buildPackage) {
console.log('Note that there is no simple way to build source packages yet.');
function copyBinaryPackageSync(pkgName, arch) {
try {
// create directory structure
fs.mkdirsSync('./dist/' + pkgName + '/opt');
fs.mkdirsSync('./dist/' + pkgName + '/usr/bin');
fs.mkdirsSync('./dist/' + pkgName + '/usr/share/pixmaps');
fs.mkdirsSync('./dist/' + pkgName + '/usr/share/applications');
// copy binaries
fs.copySync('./build/Passphrases/' + arch, './dist/' + pkgName + '/opt/Passphrases');
// copy icon, .desktop
fs.copySync('./packaging/passphrases.png', './dist/' + pkgName + '/usr/share/pixmaps/passphrases.png');
fs.copySync('./packaging/passphrases.desktop', './dist/' + pkgName + '/usr/share/applications/passphrases.desktop');
// create passphrases symlink
fs.symlinkSync('../../opt/Passphrases/Passphrases', './dist/' + pkgName + '/usr/bin/passphrases');
} catch(e) { throw e; }
}
function copyAndReplace(src_filename, dest_filename, arch, replaceArch) {
var text = fs.readFileSync(src_filename, { encoding: 'utf8' });
text = text.replace('{{version}}', version);
if(arch == 'linux32') text = text.replace('{{arch}}', replaceArch);
if(arch == 'linux64') text = text.replace('{{arch}}', replaceArch);
fs.writeFileSync(dest_filename, text);
}
// can we make debian packages?
child_process.exec('which dpkg-deb', function(err, stdout, stderr){
if(err || stdout == '') {
console.log('Cannot find dpkg-deb, skipping building Debian package');
return;
}
// building two .deb packages, for linux32 and linux64
['linux32', 'linux64'].forEach(function(arch){
if(!arch) return;
var debArch;
if(arch == 'linux32') debArch = 'i386';
if(arch == 'linux64') debArch = 'amd64';
var pkgName = 'passphrases_' + version + '-1_{{arch}}';
pkgName = pkgName.replace('{{arch}}', debArch);
copyBinaryPackageSync(pkgName, arch);
// write the debian control file
fs.mkdirsSync('./dist/' + pkgName + '/DEBIAN');
copyAndReplace('./packaging/DEBIAN/control', './dist/' + pkgName + '/DEBIAN/control', arch, debArch);
// build .deb packages
console.log('Building ' + pkgName + '.deb');
child_process.exec('dpkg-deb --build ' + pkgName, { cwd: './dist' }, function(err, stdout, stderr){
if(err) throw err;
});
});
});
// can we make rpm packages?
child_process.exec('which rpmbuild', function(err, stdout, stderr){
if(err || stdout == '') {
console.log('Cannot find rpmbuild, skipping building Red Hat package');
return;
}
// building two .rpm packages, for linux32 and linux64
['linux32', 'linux64'].forEach(function(arch){
if(!arch) return;
// following instructions from:
// https://stackoverflow.com/questions/880227/what-is-the-minimum-i-have-to-do-to-create-an-rpm-file
var rpmArch;
if(arch == 'linux32') rpmArch = 'i686';
if(arch == 'linux64') rpmArch = 'x86_64';
fs.mkdirsSync('./dist/' + rpmArch + '/RPMS');
fs.mkdirsSync('./dist/' + rpmArch + '/SRPMS');
fs.mkdirsSync('./dist/' + rpmArch + '/BUILD');
fs.mkdirsSync('./dist/' + rpmArch + '/SOURCES');
fs.mkdirsSync('./dist/' + rpmArch + '/SPECS');
fs.mkdirsSync('./dist/' + rpmArch + '/tmp');
var pkgName = 'passphrases-' + version;
copyBinaryPackageSync(rpmArch + '/' + pkgName, arch);
// write the spec file
copyAndReplace('./packaging/SPECS/passphrases.spec', './dist/' + rpmArch + '/SPECS/passphrases.spec', arch, rpmArch);
// tarball the source
console.log('Compressing binary for ' + arch);
child_process.exec('tar -zcf SOURCES/' + pkgName + '.tar.gz ' + pkgName + '/', { cwd: './dist/' + rpmArch }, function(err, stdout, stderr){
if(err) {
console.log('Error after compressing - ' + arch, err);
return;
}
console.log('Building ' + pkgName + '.rpm (' + arch + ')');
var topDir = path.resolve('./dist/' + rpmArch);
child_process.exec('rpmbuild --define \'_topdir ' + topDir +'\' -ba dist/' + rpmArch + '/SPECS/passphrases.spec', function(err, stdout, stderr){
if(err) {
console.log('Error after rpmbuild - ' + arch, err);
return;
}
});
});
});
});
}
});
}
// OSX
else if(process.platform == 'darwin') {
options.platforms = ['osx32'];
options.macIcns = './packaging/icon.icns';
build(options, function(err){
if(err) throw err;
if(buildPackage) {
// copy .app folder
fs.copySync('./build/Passphrases/osx32/Passphrases.app', './dist/Passphrases.app');
// codesigning
console.log('Codesigning');
var signingIdentityApp = '3rd Party Mac Developer Application: Micah Lee';
var signingIdentityInstaller = 'Developer ID Installer: Micah Lee';
child_process.exec('codesign --force --deep --verify --verbose --sign "' + signingIdentityApp + '" Passphrases.app', { cwd: './dist' }, function(err, stdout, stderr){
if(err) {
console.log('Error during codesigning', err);
return;
}
// build a package
child_process.exec('productbuild --component Passphrases.app /Applications Passphrases.pkg --sign "' + signingIdentityInstaller + '"', { cwd: './dist' }, function(err, stdout, stderr){
if(err) {
console.log('Error during productbuild', err);
return;
}
console.log('All done');
});
});
}
});
}
// Windows
else if(process.platform == 'win32') {
options.platforms = ['win32'];
options.winIco = './packaging/icon.ico';
build(options, function(err){
if(err) throw err;
if(buildPackage) {
// copy binaries
fs.copySync('./build/passphrases/win32', './dist/Passphrases');
// copy license
fs.copySync('./LICENSE.md', './dist/Passphrases/LICENSE.md');
// codesign Passphrases.exe
child_process.execSync('signtool.exe sign /v /d "Passphrases" /a /tr "http://www.startssl.com/timestamp" .\\dist\\Passphrases\\Passphrases.exe');
// make the installer
child_process.execSync('makensisw packaging\\windows_installer.nsi');
// codesign the installer
child_process.execSync('signtool.exe sign /v /d "Passphrases" /a /tr "http://www.startssl.com/timestamp" .\\dist\\Passphrases_Setup.exe');
}
});
}
// unsupported platform
else {
console.log('Error: unrecognized platform');
process.exit();
}
| micahflee/passphrases | build.js | JavaScript | mit | 9,210 |
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
var async = require("async");
var path = require("path");
var Tapable = require("tapable");
var ContextModule = require("./ContextModule");
var ContextElementDependency = require("./dependencies/ContextElementDependency");
function ContextModuleFactory(resolvers) {
Tapable.call(this);
this.resolvers = resolvers;
}
module.exports = ContextModuleFactory;
ContextModuleFactory.prototype = Object.create(Tapable.prototype);
ContextModuleFactory.prototype.create = function(context, dependency, callback) {
this.applyPluginsAsyncWaterfall("before-resolve", {
context: context,
request: dependency.request,
recursive: dependency.recursive,
regExp: dependency.regExp
}, function(err, result) {
if(err) return callback(err);
// Ignored
if(!result) return callback();
var context = result.context;
var request = result.request;
var recursive = result.recursive;
var regExp = result.regExp;
var loaders, resource, loadersPrefix = "";
var idx = request.lastIndexOf("!");
if(idx >= 0) {
loaders = request.substr(0, idx+1);
for(var i = 0; i < loaders.length && loaders[i] === "!"; i++) {
loadersPrefix += "!";
}
loaders = loaders.substr(i).replace(/!+$/, "").replace(/!!+/g, "!");
if(loaders == "") loaders = [];
else loaders = loaders.split("!");
resource = request.substr(idx+1);
} else {
loaders = [];
resource = request;
}
async.parallel([
this.resolvers.context.resolve.bind(this.resolvers.context, context, resource),
async.map.bind(async, loaders, this.resolvers.loader.resolve.bind(this.resolvers.loader, context))
], function(err, result) {
if(err) return callback(err);
this.applyPluginsAsyncWaterfall("after-resolve", {
loaders: loadersPrefix + result[1].join("!") + (result[1].length > 0 ? "!" : ""),
resource: result[0],
recursive: recursive,
regExp: regExp
}, function(err, result) {
if(err) return callback(err);
// Ignored
if(!result) return callback();
return callback(null, new ContextModule(this.resolveDependencies.bind(this), result.resource, result.recursive, result.regExp, result.loaders));
}.bind(this));
}.bind(this));
}.bind(this));
};
ContextModuleFactory.prototype.resolveDependencies = function resolveDependencies(fs, resource, recursive, regExp, callback) {
(function addDirectory(directory, callback) {
fs.readdir(directory, function(err, files) {
if(!files || files.length == 0) return callback();
async.map(files, function(seqment, callback) {
var subResource = path.join(directory, seqment)
fs.stat(subResource, function(err, stat) {
if(err) return callback(err);
if(stat.isDirectory()) {
if(!recursive) return callback();
addDirectory.call(this, subResource, callback);
} else if(stat.isFile()) {
var obj = {
context: resource,
request: "." + subResource.substr(resource.length).replace(/\\/g, "/")
};
this.applyPluginsAsyncWaterfall("alternatives", [obj], function(err, alternatives) {
alternatives = alternatives.filter(function(obj) {
return regExp.test(obj.request);
}).map(function(obj) {
var dep = new ContextElementDependency(obj.request);
dep.optional = true;
return dep;
});
callback(null, alternatives);
});
} else callback();
}.bind(this));
}.bind(this), function(err, result) {
if(err) return callback(err);
if(!result) return callback(null, []);
callback(null, result.filter(function(i) { return !!i; }).reduce(function(a, i) {
return a.concat(i);
}, []));
});
}.bind(this));
}.call(this, resource, callback));
};
| sahat/webpack | lib/ContextModuleFactory.js | JavaScript | mit | 3,781 |
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _from = require('babel-runtime/core-js/array/from');
var _from2 = _interopRequireDefault(_from);
exports.default = sortChunks;
var _toposort = require('toposort');
var _toposort2 = _interopRequireDefault(_toposort);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// see https://github.com/jantimon/html-webpack-plugin/blob/8131d8bb1dc9b185b3c1709264a3baf32ef799bc/lib/chunksorter.js
function sortChunks(chunks, chunkGroups) {
// We build a map (chunk-id -> chunk) for faster access during graph building.
var nodeMap = {};
chunks.forEach(function (chunk) {
nodeMap[chunk.id] = chunk;
});
// Add an edge for each parent (parent -> child)
var edges = chunkGroups.reduce(function (result, chunkGroup) {
return result.concat((0, _from2.default)(chunkGroup.parentsIterable, function (parentGroup) {
return [parentGroup, chunkGroup];
}));
}, []);
var sortedGroups = _toposort2.default.array(chunkGroups, edges);
// flatten chunkGroup into chunks
var sortedChunks = sortedGroups.reduce(function (result, chunkGroup) {
return result.concat(chunkGroup.chunks);
}, []).map(function (chunk) {
return (// use the chunk from the list passed in, since it may be a filtered list
nodeMap[chunk.id]
);
}).filter(function (chunk, index, self) {
// make sure exists (ie excluded chunks not in nodeMap)
var exists = !!chunk;
// make sure we have a unique list
var unique = self.indexOf(chunk) === index;
return exists && unique;
});
return sortedChunks;
} | Dans-labs/dariah | client/node_modules/mochapack/lib/webpack/util/sortChunks.js | JavaScript | mit | 1,662 |
"use strict"
const should = require('should')
const rewire = require('rewire')
const IC = rewire('../commands/new.js')
describe('New command',() => {
let mockFS = {
outputFile : (filename,content) => {
console.log(`mock writing to ${filename}`);
return {
then : () => { return { catch : () => {} }}
}
}
}
let mockFindADRDir = ( callback,startFrom,notFoundHandler) => { callback('.') }
let mockEditorCommand = "mockEditor"
let mockPropUtil = {
parse : (file,opts,cb) => {
cb(undefined,{editor : mockEditorCommand})
}
}
let dummyLaunchEditor = _ => {}
let commonMocks = {
fs : mockFS
, propUtil : mockPropUtil
, launchEditorForADR : dummyLaunchEditor
, writeADR : (adrFilename,newADR) => { console.log(`Pretending to write to ${adrFilename}`)}
}
function modifiedCommonMocks(specificMocks) {
let copy = {}
for (var k in commonMocks) copy[k] = commonMocks[k]
for (var j in specificMocks) copy[j] = specificMocks[j]
return copy;
}
it("Should fail if passed an invalid title - that can't be used as a filename", () => {
let revert = IC.__set__({
findADRDir : (startFrom, callback,notFoundHandler) => { callback('.') }
, withAllADRFiles : (callback) => { callback(['1-adr1.md','2-adr2.md'])}
})
let block = () => {IC(["bla","###"])}
block.should.throw()
revert()
})
it ("Should assign the next number for the new ADR - one higher than the last available ADR", () => {
let testTitle = "test"
let mocksWithHighestNumber = n => {
return {
findADRDir : mockFindADRDir
, withAllADRFiles : callback => {callback(['1-adr1.md', n + '-adr2.md'])}
, adrContent : (num,title,date) => { num.should.eql(n+1)}
}
}
var revert = IC.__set__(modifiedCommonMocks(mocksWithHighestNumber(2)))
IC([testTitle])
revert()
revert = IC.__set__(modifiedCommonMocks(mocksWithHighestNumber(5)))
IC(["test"])
revert();
})
it("Should use the title given as title parts when creating the new ADR content", () => {
let testTitle = "test"
var revert = IC.__set__(modifiedCommonMocks({
findADRDir : mockFindADRDir
, withAllADRFiles : (callback) => { callback(['1-adr1.md'])}
, adrContent : (num,title,date) => {
title.should.eql(testTitle)
}
}))
IC([testTitle])
revert();
let adrWithSeveralParts = ["adr","part","2"]
revert = IC.__set__(modifiedCommonMocks({
findADRDir : mockFindADRDir
, withAllADRFiles : (callback) => { callback(['1-adr1.md'])}
, adrContent : (num,title,date) => {
console.log(`Title mock got: ${title}`)
title.should.eql(adrWithSeveralParts.join(' '))
}
}))
IC(adrWithSeveralParts)
revert();
})
it("should attempt writing the content to a file", function() {
let testTitle = "test"
var revert = IC.__set__(modifiedCommonMocks({
findADRDir : mockFindADRDir
, withAllADRFiles : (callback) => { callback(['1-adr1.md'])}
, common : {
writeTextFileAndNotifyUser : (filename, content, msg) => {
filename.should.startWith('2') //default file name scheme starts with the expected ID
content.should.match(new RegExp(testTitle)) //The title should be somewhere in the content
msg.should.startWith('Writing')
}
}
}))
IC([testTitle])
revert()
})
})
| slior/adrflow | src/test/newTests.js | JavaScript | mit | 3,468 |
'use strict';
exports.__esModule = true;
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _Broadcasts = require('./Broadcasts');
var _PropTypes = require('./PropTypes');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
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) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Link = function (_React$Component) {
_inherits(Link, _React$Component);
function Link() {
var _temp, _this, _ret;
_classCallCheck(this, Link);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, _React$Component.call.apply(_React$Component, [this].concat(args))), _this), _this.handleClick = function (event) {
if (_this.props.onClick) _this.props.onClick(event);
if (!event.defaultPrevented && // onClick prevented default
!_this.props.target && // let browser handle "target=_blank" etc.
!isModifiedEvent(event) && isLeftClickEvent(event)) {
event.preventDefault();
_this.handleTransition();
}
}, _this.handleTransition = function () {
var router = _this.context.router;
var _this$props = _this.props,
to = _this$props.to,
replace = _this$props.replace;
var navigate = replace ? router.replaceWith : router.transitionTo;
navigate(to);
}, _temp), _possibleConstructorReturn(_this, _ret);
}
Link.prototype.render = function render() {
var _this2 = this;
var router = this.context.router;
var _props = this.props,
to = _props.to,
style = _props.style,
activeStyle = _props.activeStyle,
className = _props.className,
activeClassName = _props.activeClassName,
getIsActive = _props.isActive,
activeOnlyWhenExact = _props.activeOnlyWhenExact,
replace = _props.replace,
children = _props.children,
rest = _objectWithoutProperties(_props, ['to', 'style', 'activeStyle', 'className', 'activeClassName', 'isActive', 'activeOnlyWhenExact', 'replace', 'children']);
return _react2.default.createElement(
_Broadcasts.LocationSubscriber,
null,
function (location) {
var isActive = getIsActive(location, createLocationDescriptor(to), _this2.props);
// If children is a function, we are using a Function as Children Component
// so useful values will be passed down to the children function.
if (typeof children == 'function') {
return children({
isActive: isActive,
location: location,
href: router ? router.createHref(to) : to,
onClick: _this2.handleClick,
transition: _this2.handleTransition
});
}
// Maybe we should use <Match> here? Not sure how the custom `isActive`
// prop would shake out, also, this check happens a LOT so maybe its good
// to optimize here w/ a faster isActive check, so we'd need to benchmark
// any attempt at changing to use <Match>
return _react2.default.createElement('a', _extends({}, rest, {
href: router ? router.createHref(to) : to,
onClick: _this2.handleClick,
style: isActive ? _extends({}, style, activeStyle) : style,
className: isActive ? [className, activeClassName].join(' ').trim() : className,
children: children
}));
}
);
};
return Link;
}(_react2.default.Component);
Link.defaultProps = {
replace: false,
activeOnlyWhenExact: false,
className: '',
activeClassName: '',
style: {},
activeStyle: {},
isActive: function isActive(location, to, props) {
return pathIsActive(to.pathname, location.pathname, props.activeOnlyWhenExact) && queryIsActive(to.query, location.query);
}
};
Link.contextTypes = {
router: _PropTypes.routerContext.isRequired
};
if (process.env.NODE_ENV !== 'production') {
Link.propTypes = {
to: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.object]).isRequired,
replace: _react.PropTypes.bool,
activeStyle: _react.PropTypes.object,
activeClassName: _react.PropTypes.string,
activeOnlyWhenExact: _react.PropTypes.bool,
isActive: _react.PropTypes.func,
children: _react.PropTypes.oneOfType([_react.PropTypes.node, _react.PropTypes.func]),
// props we have to deal with but aren't necessarily
// part of the Link API
style: _react.PropTypes.object,
className: _react.PropTypes.string,
target: _react.PropTypes.string,
onClick: _react.PropTypes.func
};
}
// we should probably use LocationUtils.createLocationDescriptor
var createLocationDescriptor = function createLocationDescriptor(to) {
return (typeof to === 'undefined' ? 'undefined' : _typeof(to)) === 'object' ? to : { pathname: to };
};
var pathIsActive = function pathIsActive(to, pathname, activeOnlyWhenExact) {
return activeOnlyWhenExact ? pathname === to : pathname.indexOf(to) === 0;
};
var queryIsActive = function queryIsActive(query, activeQuery) {
if (activeQuery == null) return query == null;
if (query == null) return true;
return deepEqual(query, activeQuery);
};
var isLeftClickEvent = function isLeftClickEvent(event) {
return event.button === 0;
};
var isModifiedEvent = function isModifiedEvent(event) {
return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);
};
var deepEqual = function deepEqual(a, b) {
if (a == b) return true;
if (a == null || b == null) return false;
if (Array.isArray(a)) {
return Array.isArray(b) && a.length === b.length && a.every(function (item, index) {
return deepEqual(item, b[index]);
});
}
if ((typeof a === 'undefined' ? 'undefined' : _typeof(a)) === 'object') {
for (var p in a) {
if (!Object.prototype.hasOwnProperty.call(a, p)) {
continue;
}
if (a[p] === undefined) {
if (b[p] !== undefined) {
return false;
}
} else if (!Object.prototype.hasOwnProperty.call(b, p)) {
return false;
} else if (!deepEqual(a[p], b[p])) {
return false;
}
}
return true;
}
return String(a) === String(b);
};
exports.default = Link; | millerman86/CouponProject | node_modules/react-router/Link.js | JavaScript | mit | 7,927 |
module.exports = {
entry: {
main: ['babel-polyfill', './lib/index.js'],
test: ['babel-polyfill', 'mocha!./test/index.js'],
},
output: {
path: __dirname,
filename: '[name].bundle.js',
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel',
query: {
presets: ['es2015', 'react'],
},
},
{ test: /\.css$/, loader: 'style!css' },
{ test: /\.scss$/, loader: 'style!css!sass' },
{ test: /\.svg/, loader: 'svg-url-loader'},
{ test: /\.png$/, loader: "url-loader", query: { mimetype: "image/png" },
},
{ test: /\.(jpe?g|png|gif|svg)$/i, loaders: [
'file?hash=sha512&digest=hex&name=[hash].[ext]',
'image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false']
}
],
},
resolve: {
extensions: ['', '.js', '.jsx', '.json', '.scss', '.css'],
},
};
| Peter-Springer/peter-springer.github.io | webpack.config.js | JavaScript | mit | 952 |
/***********************
* WholeCellViz visualizations should extend the Visualization class using this template:
*
* var NewVisualization = Visualization2D.extend({
* getData: function(md){
* this.data = this.getSeriesData('getSeriesData.php', {sim_id:md.sim_id, class_name: md.class_name, attr_name: 'attr_name'});
* },
*
* calcLayout: function(){
* },
*
* drawDynamicObjects: function(t){
* this.drawObject({
* 'strokeStyle': strokeStyle,
* 'fillStyle': fillStyle,
* 'data': getDataPoint(this.data, t),
* drawFunc: function(self, ctx, data){
* },
* tipFunc: function(self, data){
* },
* clickFunc: function(self, data){
* },
* });
* },
* });
*
* Author: Jonathan Karr, jkarr@stanford.edu
* Author: Ruby Lee
* Affiliation: Covert Lab, Department of Bioengineering, Stanford University
* Last updated:9/2/2012
************************/
var CellShapeVisualization = Visualization2D.extend({
arrowLength: 10,
arrowWidth: Math.PI / 8,
membraneColor: '#3d80b3',
cellColor: '#C9E7FF',
textColor: '#666666',
lineColor: '#666666',
getData: function(md){
this._super(md);
this.getSeriesData('getSeriesData.php', {sim_id:md.sim_id, class_name: 'Geometry', attr_name: 'width_1'}, 'width');
this.getSeriesData('getSeriesData.php', {sim_id:md.sim_id, class_name: 'Geometry', attr_name: 'cylindricalLength_1'}, 'cylindricalLength');
this.getSeriesData('getSeriesData.php', {sim_id:md.sim_id, class_name: 'Geometry', attr_name: 'pinchedDiameter_1'}, 'pinchedDiameter');
this.getSeriesData('getSeriesData.php', {sim_id:md.sim_id, class_name: 'Geometry', attr_name: 'volume_1'}, 'volume');
this.getSeriesData('getSeriesData.php', {sim_id:md.sim_id, class_name: 'Summary', attr_name: 'mass_1'}, 'mass');
},
getDataSuccess: function() {
if (undefined == this.data.width
|| undefined == this.data.cylindricalLength
|| undefined == this.data.pinchedDiameter
|| undefined == this.data.volume
|| undefined == this.data.mass
)
return;
this.data.width = this.data.width.data;
this.data.cylindricalLength = this.data.cylindricalLength.data;
this.data.pinchedDiameter = this.data.pinchedDiameter.data;
this.data.volume = this.data.volume.data;
this.data.mass = this.data.mass.data;
this.data.width[this.data.width.length-1] = this.data.width[this.data.width.length - 2];
this.data.cylindricalLength[this.data.cylindricalLength.length-1] = this.data.cylindricalLength[this.data.cylindricalLength.length-2];
this.data.pinchedDiameter[this.data.pinchedDiameter.length-1] = this.data.pinchedDiameter[this.data.pinchedDiameter.length-2];
this.timeMin = this.data.width[0][0];
this.timeMax = Math.max(
this.data.width[this.data.width.length - 1][0],
this.data.cylindricalLength[this.data.cylindricalLength.length - 1][0],
this.data.pinchedDiameter[this.data.pinchedDiameter.length - 1][0],
this.data.volume[this.data.volume.length - 1][0],
this.data.mass[this.data.mass.length - 1][0]);
this._super();
},
calcLayout: function(){
var maxWidth = 0;
var maxHeight = 0;
var w, pD, cL;
for (var t = this.timeMin; t <= this.timeMax; t+= 100){
w = getDataPoint(this.data.width, t);
pD = getDataPoint(this.data.pinchedDiameter, t);
cL = getDataPoint(this.data.cylindricalLength, t);
maxWidth = Math.max(maxWidth, w + cL + (w - pD));
maxHeight = Math.max(maxHeight, w);
}
w = this.data.width[this.data.width.length-1][1]
pD = this.data.pinchedDiameter[this.data.pinchedDiameter.length-1][1]
cL = this.data.cylindricalLength[this.data.cylindricalLength.length-1][1]
maxWidth = Math.max(maxWidth, w + cL + (w - pD));
maxHeight = Math.max(maxHeight, w);
this.scale = Math.min((this.width-4) / maxWidth, (this.height-4) / maxHeight);
},
drawDynamicObjects: function(t){
var data = {
width: getDataPoint(this.data.width, t),
pinchedDiameter: getDataPoint(this.data.pinchedDiameter, t),
cylindricalLength: getDataPoint(this.data.cylindricalLength, t),
volume: getDataPoint(this.data.volume, t),
mass: getDataPoint(this.data.mass, t),
};
data.septumLength = (data.width - data.pinchedDiameter) / 2;
this.drawCell(data);
this.drawCellMeasurements(data);
},
drawCell: function(data){
this.drawObject({
'strokeStyle': this.membraneColor,
'fillStyle': this.cellColor,
'data': data,
drawFunc: function(self, ctx, data){
var W = self.width;
var H = self.height;
var w = self.scale * data.width;
var sL = self.scale * data.septumLength;
var cL = self.scale * data.cylindricalLength;
ctx.lineWidth = 2;
ctx.moveTo(W / 2 + sL, H / 2 - w / 2);
//right-top cylinder and spherical cap
ctx.arcTo2(
W / 2 + sL + cL / 2 + w / 2, H / 2 - w / 2,
W / 2 + sL + cL / 2 + w / 2, H / 2,
w / 2,
W / 2 + sL + cL / 2, H / 2 - w / 2,
W / 2 + sL + cL / 2 + w / 2, H / 2);
ctx.arcTo2(
W / 2 + sL + cL / 2 + w / 2, H / 2 + w / 2,
W / 2 + sL + cL / 2, H / 2 + w / 2,
w / 2,
W / 2 + sL + cL / 2 + w / 2, H / 2,
W / 2 + sL + cL / 2, H / 2 + w / 2);
if (sL > 0){
//bottom-right cylinder
ctx.lineTo(W / 2 + sL, H / 2 + w / 2);
//bottom septum
ctx.arcTo2(
W / 2, H / 2 + w / 2,
W / 2, H / 2 + w / 2 - sL,
sL,
W / 2 + sL, H / 2 + w / 2,
W / 2, H / 2 + w / 2 - sL);
ctx.arcTo2(
W / 2, H / 2 + w / 2,
W / 2 - sL, H / 2 + w / 2,
sL,
W / 2, H / 2 + w / 2 - sL,
W / 2 - sL, H / 2 + w / 2);
//bottom-left cylinder
ctx.lineTo(W / 2 - sL - cL / 2, H / 2 + w / 2);
}else{
//bottom cylinder
ctx.lineTo(W / 2 - sL - cL / 2, H / 2 + w / 2);
}
//left spherical cap
ctx.arcTo2(
W / 2 - sL - cL / 2 - w / 2, H / 2 + w / 2,
W / 2 - sL - cL / 2 - w / 2, H / 2,
w / 2,
W / 2 - sL - cL / 2, H / 2 + w / 2,
W / 2 - sL - cL / 2 - w/2, H / 2);
ctx.arcTo2(
W / 2 - sL - cL / 2 - w / 2, H / 2 - w / 2,
W / 2 - sL - cL / 2, H / 2 - w / 2,
w / 2,
W / 2 - sL - cL / 2 - w/2, H / 2,
W / 2 - sL - cL / 2, H / 2 - w/2);
if (sL > 0){
//top-left cylinder
ctx.lineTo(W / 2 - sL, H / 2 - w / 2);
//top septum
ctx.arcTo2(
W / 2, H / 2 - w / 2,
W / 2, H / 2 - w / 2 + sL,
sL,
W / 2 - sL, H / 2 - w / 2,
W / 2, H / 2 - w / 2 + sL);
ctx.arcTo2(
W / 2, H / 2 - w / 2,
W / 2 + sL, H / 2 - w / 2,
sL,
W / 2, H / 2 - w / 2 + sL,
W / 2 + sL, H / 2 - w / 2);
//top-right cylinder
ctx.moveTo(W / 2 + sL + w / 2, H / 2 - w / 2);
}
//close path
ctx.closePath();
},
});
},
drawCellMeasurements: function(data){
this.drawObject({
isLabel:false,
'strokeStyle': this.lineColor,
'fillStyle': this.lineColor,
'data': data,
drawFunc: function(self, ctx, data){
var W = self.width;
var H = self.height;
var w = self.scale * data.width;
var sL = self.scale * data.septumLength;
var cL = self.scale * data.cylindricalLength;
var pD = self.scale * data.pinchedDiameter;
var x1, x2, x3, x4, labelX;
ctx.lineWidth = 1;
ctx.font = self.bigFontSize + "px " + self.fontFamily;
//height
txt = Math.round(data.width * 1e9) + ' nm';
var showHeight = - sL - cL / 2 + self.bigFontSize / 2 < - ctx.measureText(txt).width / 2 - 4;
if (showHeight){
ctx.arrowTo(
W / 2 - sL - cL / 2, H / 2 + (ctx.measureText(txt).width/2 + 4),
W / 2 - sL - cL / 2, H / 2 + (w / 2 - 4),
0, 1, self.arrowWidth, self.arrowLength, 2);
ctx.arrowTo(
W / 2 - sL - cL / 2, H / 2 - (ctx.measureText(txt).width/2 + 4),
W / 2 - sL - cL / 2, H / 2 - (w / 2 - 4),
0, 1, self.arrowWidth, self.arrowLength, 2);
}
//pinched diameter
if (data.pinchedDiameter < 0.95 * data.width && pD > 40){
txt = Math.round(data.pinchedDiameter * 1e9) + ' nm';
ctx.arrowTo(
W / 2, H / 2 + (ctx.measureText(txt).width/2 + 4),
W / 2, H / 2 + pD / 2,
0, 1, self.arrowWidth, self.arrowLength, 2);
ctx.arrowTo(
W / 2, H / 2 - (ctx.measureText(txt).width/2 + 4),
W / 2, H / 2 - pD / 2,
0, 1, self.arrowWidth, self.arrowLength, 2);
}
//width
var labelX;
if (data.pinchedDiameter < 0.95 * data.width && pD > 40){
labelX = W / 2 + (sL + cL / 2 + w / 2) / 2;
}else{
labelX = W / 2;
}
var txtWidth = Math.max(
ctx.measureText(Math.round((data.width + data.cylindricalLength + 2 * data.septumLength) * 1e9) + ' nm').width,
ctx.measureText((data.volume * 1e18).toFixed(1) + ' aL').width,
ctx.measureText((data.mass * 5.61).toFixed(1) + ' fg').width
);
x1 = W / 2 - (sL + cL / 2 + self.bigFontSize / 2 + 4);
x2 = W / 2 - (txtWidth / 2 + 4);
ctx.arrowTo(
(showHeight ? Math.min(x1, x2) : x2), H / 2,
W / 2 - (sL + cL / 2 + w / 2 - 4), H / 2,
0, 1, self.arrowWidth, self.arrowLength, 2);
x1 = W / 2 - (sL + cL / 2 - self.bigFontSize / 2 - 4);
x2 = labelX - (txtWidth / 2 + 4);
if (data.pinchedDiameter < 0.95 * data.width && pD > 40){
x3 = W / 2 - (self.bigFontSize / 2 + 4);
x4 = W / 2 + (self.bigFontSize / 2 + 4);
ctx.dashedLine(x1, H / 2, x3, H / 2, 2);
ctx.dashedLine(x4, H / 2, x2, H / 2, 2);
}else if(x1 < x2){
ctx.dashedLine(x1, H / 2, x2, H / 2, 2);
}
ctx.arrowTo(
labelX + (txtWidth / 2 + 4), H / 2,
W / 2 + (sL + cL / 2 + w / 2 - 4), H / 2,
0, 1, self.arrowWidth, self.arrowLength, 2);
},
});
this.drawObject({
isLabel:false,
'fillStyle': this.textColor,
'data': data,
drawFunc: function(self, ctx, data){
var W = self.width;
var H = self.height;
var w = self.scale * data.width;
var sL = self.scale * data.septumLength;
var cL = self.scale * data.cylindricalLength;
var pD = self.scale * data.pinchedDiameter;
var labelX;
ctx.font = self.bigFontSize + "px " + self.fontFamily;
//height
txt = Math.round(data.width * 1e9) + ' nm';
if (- sL - cL / 2 + self.bigFontSize / 2 < - ctx.measureText(txt).width / 2 - 4){
ctx.save();
ctx.translate(W / 2 - sL - cL / 2, H / 2);
ctx.rotate(-Math.PI / 2);
ctx.fillText(txt, -ctx.measureText(txt).width / 2, 0.3 * self.bigFontSize);
ctx.restore();
}
//pinched diameter
if (data.pinchedDiameter < 0.95 * data.width && pD > 40){
txt = Math.round(data.pinchedDiameter * 1e9) + ' nm';
ctx.save();
ctx.translate(W / 2, H / 2);
ctx.rotate(-Math.PI / 2);
ctx.fillText(txt, -ctx.measureText(txt).width / 2, 0.3 * self.bigFontSize);
ctx.restore();
}
//width
if (data.pinchedDiameter < 0.95 * data.width && pD > 40){
labelX = W / 2 + (sL + cL / 2 + w / 2) / 2;
}else{
labelX = W / 2;
}
txt = Math.round((data.width + data.cylindricalLength + 2 * data.septumLength) * 1e9) + ' nm';
ctx.fillText(txt, labelX - ctx.measureText(txt).width / 2, H / 2 + 0.3 * self.bigFontSize);
txt = (data.volume * 1e19).toFixed(1) + ' aL';
ctx.fillText(txt, labelX - ctx.measureText(txt).width / 2, H / 2 + 0.3 * self.bigFontSize - (self.bigFontSize + 2));
txt = (data.mass * 5.61).toFixed(1) + ' fg';
ctx.fillText(txt, labelX - ctx.measureText(txt).width / 2, H / 2 + 0.3 * self.bigFontSize + (self.bigFontSize + 2));
},
});
},
});
var CellShapeVisualization3D = Visualization3D.extend({
cameraOffX:0,
cameraOffY:0,
getData: function(md){
this._super(md);
this.data = {metadata: md};
this.getSeriesData('getSeriesData.php', {sim_id:md.sim_id, class_name: 'Geometry', attr_name: 'width_1'}, 'width');
this.getSeriesData('getSeriesData.php', {sim_id:md.sim_id, class_name: 'Geometry', attr_name: 'cylindricalLength_1'}, 'cylindricalLength');
this.getSeriesData('getSeriesData.php', {sim_id:md.sim_id, class_name: 'Geometry', attr_name: 'pinchedDiameter_1'}, 'pinchedDiameter');
this.getSeriesData('getSeriesData.php', {sim_id:md.sim_id, class_name: 'Geometry', attr_name: 'volume_1'}, 'volume');
this.getSeriesData('getSeriesData.php', {sim_id:md.sim_id, class_name: 'Summary', attr_name: 'mass_1'}, 'mass');
},
getDataSuccess: function () {
if (undefined == this.data.width
|| undefined == this.data.cylindricalLength
|| undefined == this.data.pinchedDiameter
|| undefined == this.data.volume
|| undefined == this.data.mass)
return;
this.data.width = this.data.width.data;
this.data.cylindricalLength = this.data.cylindricalLength.data;
this.data.pinchedDiameter = this.data.pinchedDiameter.data;
this.data.volume = this.data.volume.data;
this.data.mass = this.data.mass.data;
this.data.width[this.data.width.length-1] = this.data.width[this.data.width.length-2];
this.data.cylindricalLength[this.data.cylindricalLength.length-1] = this.data.cylindricalLength[this.data.cylindricalLength.length-2];
this.data.pinchedDiameter[this.data.pinchedDiameter.length-1] = this.data.pinchedDiameter[this.data.pinchedDiameter.length-2];
this.timeMin = this.data.width[0][0];
this.timeMax = Math.max(
this.data.width[this.data.width.length - 1][0],
this.data.cylindricalLength[this.data.cylindricalLength.length - 1][0],
this.data.pinchedDiameter[this.data.pinchedDiameter.length - 1][0],
this.data.volume[this.data.volume.length - 1][0],
this.data.mass[this.data.mass.length - 1][0]);
this.maxWidth = 0;
this.maxHeight = 0;
var w, pD, cL;
for (var t = this.timeMin; t <= this.timeMax; t+= 100){
w = getDataPoint(this.data.width, t);
pD = getDataPoint(this.data.pinchedDiameter, t);
cL = getDataPoint(this.data.cylindricalLength, t);
this.maxWidth = Math.max(this.maxWidth, w + cL + (w - pD));
this.maxHeight = Math.max(this.maxHeight, w);
}
w = this.data.width[this.data.width.length-1][1]
pD = this.data.pinchedDiameter[this.data.pinchedDiameter.length-1][1]
cL = this.data.cylindricalLength[this.data.cylindricalLength.length-1][1]
this.maxWidth = Math.max(this.maxWidth, w + cL + (w - pD));
this.maxHeight = Math.max(this.maxHeight, w);
//super
this._super();
},
initCamera: function(){
this.camera = new THREE.PerspectiveCamera(45, 1, 0.1, 20000);
this.scene.add(this.camera);
this.camera.lookAt(this.scene.position);
},
initLights: function(){
this.lights = {
point: [],
spot: [],
};
//point lights
for (var i = 0; i < 4; i++){
var light = new THREE.PointLight(0xffffff);
this.scene.add(light);
this.lights.point.push(light);
}
//spotlight
var light = new THREE.SpotLight(0xffffff);
light.shadowCameraVisible = false;
light.shadowDarkness = 0.25;
light.intensity = 0.1;
light.castShadow = true;
this.scene.add(light);
this.lights.spot.push(light);
},
initControls: function(){
this.controls = new THREE.TrackballControls( this.camera );
},
enableControls: function(){
if (!this.isEnabled)
return
var that = this;
requestAnimationFrame(function (){
that.enableControls();
if (~$('#timeline').timeline('getPlaying'))
that.drawDynamicContent(that.time);
});
},
calcLayout: function(){
//renderer
$(this.renderer.domElement).css({position: 'absolute', left: 0, top: -3});
this.renderer.setSize(this.width, this.height);
//camera
this.camera.aspect = this.width / this.height;
this.camera.position.set(this.cameraOffX, this.cameraOffY, 200);
this.camera.updateProjectionMatrix();
//lights
this.lights.point[0].position.set(0, 200, 200);
this.lights.point[1].position.set(0, 200, -200);
this.lights.point[2].position.set(0, -200, -200);
this.lights.point[3].position.set(0, -200, 200);
this.lights.spot[0].position.set(0, 500, 0);
},
drawStaticObjects: function(){
//remove old background
if (this.background)
this.scene.remove(this.background);
//add background
var geometry = new THREE.PlaneGeometry(1000, 1000, 100, 100);
var material = new THREE.MeshBasicMaterial({color: 0xffffff});
this.background = new THREE.Mesh(geometry, material);
this.background.doubleSided = false;
this.background.receiveShadow = true;
this.background.position.y = -50;
this.scene.add(this.background);
},
drawDynamicObjects: function(t){
//clear
if (this.cellObjects3d){
for (var i = 0; i < this.cellObjects3d.length; i++){
this.scene.remove(this.cellObjects3d[i]);
}
}
//add cell
this.cellObjects3d = [];
var mesh;
var scene = this.scene;
//offset
var offY = 20;
//sizes
scale = 200 / this.maxWidth;
label = this.data.metadata.sim_name;
w = scale * getDataPoint(this.data.width, t);
pD = scale * getDataPoint(this.data.pinchedDiameter, t);
cL = scale * getDataPoint(this.data.cylindricalLength, t);
v = getDataPoint(this.data.volume, t);
m = getDataPoint(this.data.mass, t);
sL = (w - pD) / 2;
//cell
mesh = new THREE.Mesh(
new CellGeometry(w, cL, pD, sL),
new THREE.MeshLambertMaterial({
'color': 0x3d80b3,
transparent:true,
opacity:0.8,
})
);
mesh.castShadow = true;
mesh.position.set(0, offY, 0);
scene.add(mesh);
this.cellObjects3d.push(mesh);
if (!$('#config').config('getShowLabels'))
return;
//measures
var mesh = THREE.addText(this.scene,
Math.round(w/scale * 1e9) + ' nm',
3, -(sL + cL/2), 10+offY, 0, true);
this.cellObjects3d.push(mesh);
textW = mesh.geometry.boundingBox.max.x - mesh.geometry.boundingBox.min.x;
this.cellObjects3d = this.cellObjects3d.concat(THREE.addArrow(this.scene,
-(sL + cL/2), -w/2 + offY, 0,
-(sL + cL/2), -(textW/2 + 2)+10 + offY, 0,
true, false));
this.cellObjects3d = this.cellObjects3d.concat(THREE.addArrow(this.scene,
-(sL + cL/2), (textW/2 + 2)+10 + offY, 0,
-(sL + cL/2), w/2 + offY, 0,
false, true));
if (sL > 0.1 * w){
var mesh = THREE.addText(this.scene,
Math.round((w - 2 * sL) / scale * 1e9) + ' nm',
3, 0, offY, 0, true);
this.cellObjects3d.push(mesh);
textW = mesh.geometry.boundingBox.max.x - mesh.geometry.boundingBox.min.x;
this.cellObjects3d = this.cellObjects3d.concat(THREE.addArrow(this.scene,
0, -(w/2 - sL) + offY, 0,
0, -(textW/2 + 2) + offY, 0,
true, false));
this.cellObjects3d = this.cellObjects3d.concat(THREE.addArrow(this.scene,
0, (textW/2 + 2) + offY, 0,
0, (w/2 - sL) + offY, 0,
false, true));
var mesh = THREE.addText(this.scene,
Math.round((w + cL + 2 * sL) / scale * 1e9) + ' nm',
3, (sL + cL/2 + w/2) / 2, offY, 0, false);
this.cellObjects3d.push(mesh);
textW = mesh.geometry.boundingBox.max.x - mesh.geometry.boundingBox.min.x;
this.cellObjects3d = this.cellObjects3d.concat(THREE.addArrow(this.scene,
-(sL + cL/2 + w/2), offY, 0,
-3, offY, 0,
true, false));
this.cellObjects3d = this.cellObjects3d.concat(THREE.addArrow(this.scene,
3, offY, 0,
(sL + cL/2 + w/2) / 2 - (textW/2 + 2), offY, 0,
false, false));
this.cellObjects3d = this.cellObjects3d.concat(THREE.addArrow(this.scene,
(sL + cL/2 + w/2) / 2 + (textW/2 + 2), offY, 0,
(sL + cL/2 + w/2), offY, 0,
false, true));
}else{
var mesh = THREE.addText(this.scene,
Math.round((w + cL + 2 * sL) / scale * 1e9) + ' nm',
3, (sL + cL/2 + w/2) / 2, offY, 0, false);
this.cellObjects3d.push(mesh);
textW = mesh.geometry.boundingBox.max.x - mesh.geometry.boundingBox.min.x;
this.cellObjects3d = this.cellObjects3d.concat(THREE.addArrow(this.scene,
-(sL + cL/2 + w/2), offY, 0,
(sL + cL/2 + w/2) / 2 - (textW/2 + 2), offY, 0,
true, false));
this.cellObjects3d = this.cellObjects3d.concat(THREE.addArrow(this.scene,
(sL + cL/2 + w/2) / 2 + (textW/2 + 2), offY, 0,
(sL + cL/2 + w/2), offY, 0,
false, true));
}
//label
this.cellObjects3d.push(THREE.addText(scene,
label,
3, 0, -w / 2 - 5 + offY, 0, false));
this.cellObjects3d.push(THREE.addText(scene,
(v * 1e18).toFixed(1) + ' aL, ' + (m * 5.61).toFixed(1) + ' fg',
2, 0, -w / 2 - 9 + offY, 0, false));
}
});
var CellShapeVisualization3DIntro = CellShapeVisualization3D.extend({
cameraOffX:-100,
cameraOffY: 100,
getData: function(md){
this._super(md);
this.timeMin = 29000;
this.timeMax = 29000;
},
});
var CellGeometry = function ( w, cL, pD, sL ) {
THREE.Geometry.call( this );
///////////////////////////
// geometry
///////////////////////////
this.cell = {
width: w,
cyclindricalLength: cL,
pinchedDiameter: pD,
septumLength: sL,
totalLength: w + cL + 2 * sL,
};
///////////////////////////
//vertices
//////////////////////////
var vertices = [], uvs = [], thetas = [];
//left-sphere
var tmp = this.calcRings(-sL - cL/2 - w/2, -sL - cL/2, 20, false);
vertices = vertices.concat(tmp.vertices);
uvs = uvs.concat(tmp.uvs);
thetas = thetas.concat(tmp.thetas);
//left-cylinder
var tmp = this.calcRings(-sL -cL/2, -sL, 1, true);
vertices = vertices.concat(tmp.vertices);
uvs = uvs.concat(tmp.uvs);
thetas = thetas.concat(tmp.thetas);
//left-septum
var tmp = this.calcRings(-sL, 0, 20, true);
vertices = vertices.concat(tmp.vertices);
uvs = uvs.concat(tmp.uvs);
thetas = thetas.concat(tmp.thetas);
//right-septum
var tmp = this.calcRings(0, sL, 20, true);
vertices = vertices.concat(tmp.vertices);
uvs = uvs.concat(tmp.uvs);
thetas = thetas.concat(tmp.thetas);
//right-cylinder
var tmp = this.calcRings(sL, sL + cL/2, 1, true);
vertices = vertices.concat(tmp.vertices);
uvs = uvs.concat(tmp.uvs);
thetas = thetas.concat(tmp.thetas);
//right-sphere
var tmp = this.calcRings(sL + cL/2, sL + cL/2 + w/2, 20, true);
vertices = vertices.concat(tmp.vertices);
uvs = uvs.concat(tmp.uvs);
thetas = thetas.concat(tmp.thetas);
///////////////////////////
//faces
///////////////////////////
for (var i = 0; i < vertices.length - 1; i ++ ) {
for (var j = 0; j < vertices[i].length - 1; j ++ ) {
var u = j / (vertices[i].length - 1);
var u2 = (j + 1) / (vertices[i].length - 1);
var v1 = vertices[ i ][ j ];
var v2 = vertices[ i + 1 ][ j ];
var v3 = vertices[ i + 1 ][ j + 1 ];
var v4 = vertices[ i ][ j + 1 ];
var n1 = new THREE.Vector3(Math.tan(thetas[i]), Math.sin( u * Math.PI * 2 ), Math.cos( u * Math.PI * 2 )).normalize();
var n2 = new THREE.Vector3(Math.tan(thetas[i + 1]), Math.sin( u * Math.PI * 2 ), Math.cos( u * Math.PI * 2 )).normalize();
var n3 = new THREE.Vector3(Math.tan(thetas[i + 1]), Math.sin( u2 * Math.PI * 2 ), Math.cos( u2 * Math.PI * 2 )).normalize();
var n4 = new THREE.Vector3(Math.tan(thetas[i]), Math.sin( u2 * Math.PI * 2 ), Math.cos( u2 * Math.PI * 2 )).normalize();
var uv1 = uvs[ i ][ j ].clone();
var uv2 = uvs[ i + 1 ][ j ].clone();
var uv3 = uvs[ i + 1 ][ j + 1 ].clone();
var uv4 = uvs[ i ][ j + 1 ].clone();
this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
}
}
///////////////////////////
// superclass stuff
///////////////////////////
this.computeCentroids();
this.computeFaceNormals();
}
CellGeometry.prototype = Object.create( THREE.Geometry.prototype );
CellGeometry.prototype.calcRings = function (x1, x2, nSegments, i1){
var totLen = this.cell.totalLength;
var vertices = [], uvs = [], thetas = [];
for (var i = i1; i <= nSegments; i ++ ) {
var x = x1 + (x2 - x1) * i / nSegments;
var tmp = this.calcRingVertices(x);
vertices.push(tmp.vertices );
uvs.push(tmp.uvs);
thetas.push(tmp.theta);
}
return {
'vertices': vertices,
'uvs': uvs,
'thetas': thetas,
};
}
CellGeometry.prototype.calcRingVertices = function (x){
var totLen = this.cell.totalLength;
var radius = this.calcRadius(x);
var v = (x + totLen / 2) / totLen;
var nSegments = 32;
var vertices = [];
var uvs = [];
for (var j = 0; j <= nSegments; j ++ ) {
var u = j / nSegments;
var vertex = new THREE.Vector3();
vertex.x = x;
vertex.y = radius * Math.sin( u * Math.PI * 2 );
vertex.z = radius * Math.cos( u * Math.PI * 2 );
this.vertices.push( vertex );
vertices.push( this.vertices.length - 1 );
uvs.push( new THREE.UV( u, 1 - v ) );
}
return {
'vertices': vertices,
'uvs': uvs,
'theta': this.calcTheta(x),
};
}
CellGeometry.prototype.calcRadius = function (x){
var w = this.cell.width;
var cL = this.cell.cyclindricalLength;
var sL = this.cell.septumLength;
var absX = Math.abs(x);
if (absX <= sL)
return (w / 2 - sL) + Math.sqrt( Math.pow(sL, 2) - Math.pow(sL - absX, 2) );
else if (absX <= sL + cL / 2)
return w / 2;
else
return Math.sqrt( Math.pow(w / 2, 2) - Math.pow(absX - sL - cL / 2, 2) );
}
CellGeometry.prototype.calcTheta = function (x){
var w = this.cell.width;
var cL = this.cell.cyclindricalLength;
var sL = this.cell.septumLength;
var absX = Math.abs(x);
if (absX <= sL)
return Math.sign(x) * Math.asin((sL - absX) / sL);
else if (absX <= sL + cL / 2)
return 0;
else
return Math.sign(x) * Math.asin((absX - sL - cL / 2) / (w / 2));
}
var ChromosomeVisualization = Visualization2D.extend({
//options
chrLen: 580076,
ntPerSegment: 1e5,
segmentLabelWidth: 40,
segmentLabelMargin: 2,
chrSpacing: 1,
segmentSpacing: 0.25,
dataRelHeight: 0.75,
chrRelHeight: 1,
chrDataSpacing: 0.25,
getData: function(md){
this._super(md);
this.data = {md: md};
this.getSeriesData('getSeriesData.php', {sim_id:md.sim_id, class_name: md.class_name, attr_name: 'singleStrandedRegions'}, 'ssData');
this.getSeriesData('getSeriesData.php', {sim_id:md.sim_id, class_name: md.class_name, attr_name: 'doubleStrandedRegions'}, 'dsData');
switch (md.attr_name){
case 'DNA_replication_with_proteins_and_damage':
this.showDataTracks = true;
this.getSeriesData('getSeriesData.php', {sim_id:md.sim_id, class_name: md.class_name, attr_name: 'monomerBoundSites'}, 'monData');
this.getSeriesData('getSeriesData.php', {sim_id:md.sim_id, class_name: md.class_name, attr_name: 'complexBoundSites'}, 'cpxData');
this.getSeriesData('getSeriesData.php', {sim_id:md.sim_id, class_name: md.class_name, attr_name: 'strandBreaks'}, 'strndBreakData');
this.getSeriesData('getSeriesData.php', {sim_id:md.sim_id, class_name: md.class_name, attr_name: 'damagedBases'}, 'dmgBasesData');
break;
case 'DNA_replication':
default:
this.showDataTracks = false;
break;
}
},
getDataSuccess: function (){
if (undefined == this.data.ssData
|| undefined == this.data.dsData)
return;
if (this.data.md.attr_name == 'DNA_replication_with_proteins_and_damage' &&
(undefined == this.data.monData
|| undefined == this.data.cpxData
|| undefined == this.data.strndBreakData
|| undefined == this.data.dmgBasesData))
return
this.ssData = this.data.ssData;
this.dsData = this.data.dsData;
this.monData = this.data.monData;
this.cpxData = this.data.cpxData;
this.strndBreakData = this.data.strndBreakData;
this.dmgBasesData = this.data.dmgBasesData;
this.timeMin = this.dsData[0].time[0];
this.timeMax = this.dsData[this.dsData.length-1].time[0];
this._super();
},
exportData: function(){
var data = {
ssData: this.ssData,
dsData: this.dsData,
};
switch (md.attr_name){
case 'DNA_replication_with_proteins_and_damage':
data['monData'] = this.monData;
data['cpxData'] = this.cpxData;
data['strndBreakData'] = this.strndBreakData;
data['dmgBasesData'] = this.dmgBasesData;
break;
case 'DNA_replication':
default:
break;
}
return data;
},
calcLayout: function(){
this.numSegments = Math.ceil(this.chrLen / this.ntPerSegment);
this.segmentHeight = this.height / (this.chrSpacing + 2 * (this.numSegments + this.segmentSpacing * (this.numSegments - 1)));
this.segmentSeparation = (1 + this.segmentSpacing) * this.segmentHeight;
this.chrSeparation = (this.chrSpacing + 1 * (this.numSegments + this.segmentSpacing * (this.numSegments - 1))) * this.segmentHeight;
this.legendX = this.width - 57;
this.chrWidth = this.legendX - 5 - this.segmentLabelWidth - this.segmentLabelMargin;
this.ntLength = this.chrWidth / this.ntPerSegment;
if (this.showDataTracks){
var scale = this.segmentHeight / (2 * this.dataRelHeight + 2 * this.chrDataSpacing + this.chrRelHeight);
this.dataHeight = scale * this.dataRelHeight
this.dataTrackY1 = -1;
this.chrSegmentY = scale * (this.dataRelHeight + this.chrDataSpacing);
this.dataTrackY2 = scale * (this.dataRelHeight + 2 * this.chrDataSpacing + this.chrRelHeight) - 1;
this.chrHeight = scale * this.chrRelHeight;
}else{
this.dataHeight = 0;
this.dataTrackY1 = 0;
this.dataTrackY2 = 0;
this.chrSegmentY = 0;
this.chrHeight = this.segmentHeight;
}
},
drawDynamicObjects: function(t){
var chrStyle;
//chromosome
this.drawChromosomes();
//single stranded regions
this.drawPolymerizedRegions(getDataPoint(this.ssData, t), ['#3d80b3', '#C9E7FF'], 1,
[this.chrSegmentY-0.5, this.chrSegmentY+0.5]);
//double stranded regions
this.drawPolymerizedRegions(getDataPoint(this.dsData, t), ['#3d80b3', '#C9E7FF'], this.chrHeight/2,
[this.chrSegmentY-this.chrHeight/4, this.chrSegmentY+this.chrHeight/4]);
//selected attribute
if (this.showDataTracks){
this.drawDataTrack(getDataPoint(this.monData, t), '#3db34a', this.dataHeight, [this.dataTrackY1, this.dataTrackY2], 500);
this.drawDataTrack(getDataPoint(this.cpxData, t), '#3db34a', this.dataHeight, [this.dataTrackY1, this.dataTrackY2], 500);
this.drawDataTrack(getDataPoint(this.strndBreakData, t), '#cd0a0a', this.dataHeight, [this.dataTrackY1, this.dataTrackY2], 200);
this.drawDataTrack(getDataPoint(this.dmgBasesData, t), '#e78f08', this.dataHeight, [this.dataTrackY1, this.dataTrackY2], 200);
}
//legend
this.drawLegendEntry(t, 0, 'Mother', '#3d80b3', 5);
this.drawLegendEntry(t, 1, 'Daughter', '#C9E7FF', 5);
this.drawLegendEntry(t, 2, 'ssDNA', '#3d80b3', 1);
this.drawLegendEntry(t, 3, 'dsDNA', '#3d80b3', 5);
if (this.showDataTracks){
this.drawLegendEntry(t, 4, 'Methylation', '#e78f08', 5);
this.drawLegendEntry(t, 5, 'Protein', '#3db34a', 5);
this.drawLegendEntry(t, 6, 'Strand break', '#cd0a0a', 5);
}
},
drawChromosomes: function(){
this.drawObject({
strokeStyle: '#e8e8e8',
fillStyle: '#222222',
drawFunc: function(self, ctx, data){
var txt;
ctx.lineWidth = 2;
for (var i = 0; i < 2; i++){
for (var j = 0; j < self.numSegments; j++){
var y = i * self.chrSeparation + j * self.segmentSeparation + self.chrSegmentY + self.chrHeight / 2;
//draw chromosome
ctx.moveTo(self.segmentLabelWidth + self.segmentLabelMargin, y);
ctx.lineTo(self.segmentLabelWidth + self.segmentLabelMargin + (((Math.min((j + 1) * self.ntPerSegment, self.chrLen) - 1) % self.ntPerSegment) + 1) / self.ntPerSegment * self.chrWidth, y);
//position label
txt = (j * self.ntPerSegment + 1).toString();
ctx.font = self.smallFontSize + "px " + self.fontFamily;
ctx.fillText(txt, self.segmentLabelWidth - ctx.measureText(txt).width, y + 0.4 * self.smallFontSize);
}
txt = 'Chromosome ' + (i+1);
y = i * self.chrSeparation + (self.segmentSeparation * (self.numSegments - 1) + self.segmentHeight) / 2;
ctx.save();
ctx.font = self.bigFontSize + "px " + self.fontFamily;
ctx.translate(self.bigFontSize / 2, y);
ctx.rotate(-Math.PI / 2);
ctx.fillText(txt, -ctx.measureText(txt).width / 2, 0.4 * self.bigFontSize);
ctx.restore();
}
},
});
},
drawPolymerizedRegions: function(data, fillStyle, trackHeight, trackOffY) {
if (data == undefined)
return;
var strandArr = data.strand;
var posArr = data.pos;
var valArr = data.val;
var offX = this.segmentLabelWidth + this.segmentLabelMargin;
var sX = 1 / this.ntPerSegment * this.chrWidth;
for (var i = 0; i < strandArr.length; i++) {
var offY = Math.floor((strandArr[i] - 1) / 2) * this.chrSeparation + trackOffY[(strandArr[i]-1) % 2];
var elWidth = valArr[i];
jMin = Math.floor(posArr[i] / this.ntPerSegment);
jMax = Math.ceil((posArr[i] + elWidth) / this.ntPerSegment);
for (var j = jMin; j < jMax; j++){
var y = offY + j * this.segmentSeparation;
var x1, x2;
if (j == jMin)
x1 = offX + (((posArr[i] - 1) % this.ntPerSegment) + 1) * sX;
else
x1 = offX;
if (j == jMax - 1)
x2 = offX + (((posArr[i] + elWidth - 1) % this.ntPerSegment) + 1) * sX;
else
x2 = offX + this.chrWidth;
var thisFillStyle;
if ((strandArr[i] == 2 &&
((strandArr.length == 4 && posArr[i] == 1 && valArr[i] == this.chrLen) ||
(strandArr.length > 2 && (posArr[i] == 1 || posArr[i] + valArr[i] - 1 == this.chrLen || (posArr[i] < this.chrLen/2 && valArr[i] < 5000))))) ||
strandArr[i] == 3){
thisFillStyle = fillStyle[1];
}else{
thisFillStyle = fillStyle[0];
}
this.drawObject({
'fillStyle': thisFillStyle,
'data': {'x': x1, 'y': y + (this.chrHeight - trackHeight) / 2, 'w': x2 - x1, 'h': trackHeight},
'drawFunc': function(self, ctx, data){
ctx.rect(data.x, data.y, data.w, data.h);
},
});
}
}
},
drawDataTrack: function(data, fillStyle, trackHeight, trackOffY, elDefaultWidth) {
if (data == undefined)
return;
this.drawObject({
'fillStyle': fillStyle,
'data': {'data': data, 'trackHeight': trackHeight},
'drawFunc': function(self, ctx, data){
var strandArr = data.data.strand;
var posArr = data.data.pos;
var valArr = data.data.val;
var offX = self.segmentLabelWidth + self.segmentLabelMargin;
var sX = 1 / self.ntPerSegment * self.chrWidth;
var elWidth = elDefaultWidth;
for (var i = 0; i < strandArr.length; i++) {
var offY = Math.floor((strandArr[i] - 1) / 2) * self.chrSeparation + trackOffY[(strandArr[i]-1) % 2];
if (elDefaultWidth == undefined)
elWidth = valArr[i];
jMin = Math.floor(posArr[i] / self.ntPerSegment);
jMax = Math.ceil((posArr[i] + elWidth) / self.ntPerSegment);
for (var j = jMin; j < jMax; j++){
var y = offY + j * self.segmentSeparation;
var x1, x2;
if (j == jMin)
x1 = offX + (((posArr[i] - 1) % self.ntPerSegment) + 1) * sX;
else
x1 = offX;
if (j == jMax - 1)
x2 = offX + (((posArr[i] + elWidth - 1) % self.ntPerSegment) + 1) * sX;
else
x2 = offX + self.chrWidth;
ctx.fillRect(x1, y + (self.chrHeight - trackHeight) / 2, x2 - x1, data.trackHeight);
}
}
},
});
},
drawLegendEntry: function(t, row, txt, strokeStyle, lineWidth){
this.drawObject({
'strokeStyle': strokeStyle,
fillStyle: '#222222',
data: {'t': t, 'row': row, 'txt': txt, 'lineWidth': lineWidth},
drawFunc: function(self, ctx, data){
var x = self.legendX;
var y = data.row * self.bigFontSize * 1.2 + 0.25 * self.bigFontSize;
ctx.lineWidth = data.lineWidth;
ctx.moveTo(x, y);
ctx.lineTo(x + 5, y);
ctx.font = self.bigFontSize + "px " + self.fontFamily;
ctx.fillText(data.txt,
x + 8,
y + 0.3 * self.bigFontSize);
},
});
},
});
var ChromosomeCircleVisualization = Visualization2D.extend({
//options
chrLen: 580076,
relChrRadius: 1,
relChrHalfHeight: 0.1,
relChrDataSpacing: 0.01,
relDataHeight: 0.1,
relChrSpacing: 0.05,
getData: function(md){
this._super(md);
this.getSeriesData('getKBData.php', {'type': 'Metabolite'}, 'metabolites');
this.getSeriesData('getKBData.php', {'type': 'ProteinMonomer'}, 'proteinMonomers');
this.getSeriesData('getKBData.php', {'type': 'ProteinComplex'}, 'proteinComplexs');
this.getSeriesData('getSeriesData.php', {sim_id:md.sim_id, class_name: md.class_name, attr_name: 'singleStrandedRegions'}, 'ssData');
this.getSeriesData('getSeriesData.php', {sim_id:md.sim_id, class_name: md.class_name, attr_name: 'doubleStrandedRegions'}, 'dsData');
this.getSeriesData('getSeriesData.php', {sim_id:md.sim_id, class_name: md.class_name, attr_name: 'monomerBoundSites'}, 'monData');
this.getSeriesData('getSeriesData.php', {sim_id:md.sim_id, class_name: md.class_name, attr_name: 'complexBoundSites'}, 'cpxData');
this.getSeriesData('getSeriesData.php', {sim_id:md.sim_id, class_name: md.class_name, attr_name: 'strandBreaks'}, 'strndBreakData');
this.getSeriesData('getSeriesData.php', {sim_id:md.sim_id, class_name: md.class_name, attr_name: 'damagedBases'}, 'dmgBasesData');
},
getDataSuccess: function () {
if (undefined == this.data.metabolites
|| undefined == this.data.proteinMonomers
|| undefined == this.data.proteinComplexs
|| undefined == this.data.ssData
|| undefined == this.data.dsData
|| undefined == this.data.monData
|| undefined == this.data.cpxData
|| undefined == this.data.strndBreakData
|| undefined == this.data.dmgBasesData)
return;
this.metabolites = this.data.metabolites;
this.proteinMonomers = this.data.proteinMonomers;
this.proteinComplexs = this.data.proteinComplexs;
this.ssData = this.data.ssData;
this.dsData = this.data.dsData;
this.monData = this.data.monData;
this.cpxData = this.data.cpxData;
this.strndBreakData = this.data.strndBreakData;
this.dmgBasesData = this.data.dmgBasesData
this.timeMin = this.dsData[0].time[0];
this.timeMax = this.dsData[this.dsData.length-1].time[0];
this._super();
},
exportData: function(){
return {
ssData: this.ssData,
dsData: this.dsData,
monData: this.monData,
cpxData: this.cpxData,
strndBreakData: this.strndBreakData,
dmgBasesData: this.dmgBasesData,
};
},
calcLayout: function(){
var scale = Math.min(
this.height / 2 / (this.relChrRadius + this.relChrHalfHeight + this.relChrDataSpacing + this.relDataHeight),
this.width / (4 * (this.relChrRadius + this.relChrHalfHeight + this.relChrDataSpacing + this.relDataHeight) + this.relChrSpacing)
);
this.chrRadius = scale * this.relChrRadius;
this.chrHalfHeight = scale * this.relChrHalfHeight;
this.chrDataSpacing = scale * this.relChrDataSpacing;
this.dataHeight = scale * this.relDataHeight;
this.chrSpacing = scale * this.relChrSpacing;
this.chrX = [
this.width / 2 - (this.chrSpacing / 2 + this.chrRadius + this.chrHalfHeight + this.chrDataSpacing + this.dataHeight),
this.width / 2 + (this.chrSpacing / 2 + this.chrRadius + this.chrHalfHeight + this.chrDataSpacing + this.dataHeight),
];
this.chrRadii = [
this.chrRadius + this.chrHalfHeight / 2,
this.chrRadius - this.chrHalfHeight / 2,
];
this.dataRadii = [
this.chrRadius + (this.chrHalfHeight + this.chrDataSpacing + this.dataHeight / 2),
this.chrRadius - (this.chrHalfHeight + this.chrDataSpacing + this.dataHeight / 2),
];
},
drawDynamicObjects: function(t){
var chrStyle;
//chromosome
this.drawChromosomes();
//single stranded regions
var ssChrLens = this.drawPolymerizedRegions(getDataPoint(this.ssData, t), ['#3d80b3', '#C9E7FF'], 1, function(self, data){
return sprintf('single-stranded polymerized region at position %d of length %d on (%s) strand', data.pos, data.val, (data.strand % 2 == 0 ? '-' : '+'));
});
//double stranded regions
var dsChrLens = this.drawPolymerizedRegions(getDataPoint(this.dsData, t), ['#3d80b3', '#C9E7FF'], this.chrHalfHeight, function(self, data){
return sprintf('double-stranded polymerized region at position %d of length %d', data.pos, data.val);
});
//print chromosome labels
this.drawChromosomeLabels(t, ssChrLens, dsChrLens);
//selected attribute
this.drawDataTrack(getDataPoint(this.strndBreakData, t), '#cd0a0a', 200, function (self, data){
return sprintf('Strand break at position %d (%s)', data.pos, (data.strand % 2 == 0 ? '-' : '+'));
});
this.drawDataTrack(getDataPoint(this.dmgBasesData, t), '#e78f08', 200, function(self, data){
return sprintf('Damaged base %s at position %d (%s)', self.metabolites[data.val].name, data.pos, (data.strand % 2 == 0 ? '-' : '+'));
});
this.drawDataTrack(getDataPoint(this.monData, t), '#3db34a', 500, function (self, data){
return sprintf('Bound protein %s at position %d (%s)', self.proteinComplexs[data.val].name, data.pos, (data.strand % 2 == 0 ? '-' : '+'));
});
this.drawDataTrack(getDataPoint(this.cpxData, t), '#3db34a', 500, function (self, data){
return sprintf('Bound protein %s at position %d (%s)', self.proteinComplexs[data.val].name, data.pos, (data.strand % 2 == 0 ? '-' : '+'));
});
},
drawChromosomes: function(){
for (var i = 0; i < 2; i++){
this.drawObject({
strokeStyle: '#e8e8e8',
data: i,
drawFunc: function(self, ctx, i){
ctx.lineWidth = 1;
ctx.arc(self.chrX[i], self.height / 2, self.chrRadius, 0, 2 * Math.PI);
},
});
}
},
drawChromosomeLabels: function(t, ssChrLens, dsChrLens){
var y = [
this.height / 2 - 1.7 * this.bigFontSize - 2,
this.height / 2 - 0.7 * this.bigFontSize - 1,
this.height / 2 + 0.3 * this.bigFontSize - 0,
this.height / 2 + 1.3 * this.bigFontSize + 1,
this.height / 2 + 2.3 * this.bigFontSize + 2,
];
this.drawLegendEntry(t, this.chrX[0], 0, y[0], 'Chromosome 1', undefined, 0, this.bigFontSize);
this.drawLegendEntry(t, this.chrX[1], 0, y[0], 'Chromosome 2', undefined, 0, this.bigFontSize);
this.drawLegendEntry(t, this.chrX[0], -1, y[1], 'Mother', '#3d80b3', 5, this.smallFontSize);
this.drawLegendEntry(t, this.chrX[0], -1, y[2], 'Daughter', '#C9E7FF', 5, this.smallFontSize);
this.drawLegendEntry(t, this.chrX[0], 1, y[1], 'ssDNA', '#3d80b3', 1, this.smallFontSize);
this.drawLegendEntry(t, this.chrX[0], 1, y[2], 'dsDNA', '#3d80b3', 5, this.smallFontSize);
this.drawLegendEntry(t, this.chrX[0], -1, y[3], 'Methylation', '#e78f08', 5, this.smallFontSize);
this.drawLegendEntry(t, this.chrX[0], 1, y[3], 'Protein', '#3db34a', 5, this.smallFontSize);
this.drawLegendEntry(t, this.chrX[0], -1, y[4], 'Strand break', '#cd0a0a', 5, this.smallFontSize);
},
drawLegendEntry: function(t, x, col, y, txt, strokeStyle, lineWidth, fontSize){
this.drawObject({
isLabel:true,
'strokeStyle': strokeStyle,
fillStyle: '#222222',
data: {'t': t, 'x': x, 'col': col, 'y': y, 'txt': txt, 'lineWidth': lineWidth, 'fontSize': fontSize},
drawFunc: function(self, ctx, data){
ctx.font = data.fontSize + "px " + self.fontFamily;
var offX = 0;
switch (data.col){
case -1:
offX = -(
+ 5
+ 3
+ ctx.measureText('Strand break').width
+ 10
+ 5
+ 3
+ ctx.measureText('Protein').width
) / 2;
break;
case 0:
offX = - ctx.measureText(data.txt).width / 2;
break;
case 1:
offX = -(
+ 5
+ 3
+ ctx.measureText('Strand break').width
+ 10
+ 5
+ 3
+ ctx.measureText('Protein').width
) / 2
+ 5
+ 3
+ ctx.measureText('Strand break').width
+ 10;
break;
}
if (data.lineWidth > 0){
ctx.lineWidth = data.lineWidth;
ctx.moveTo(offX + data.x, data.y);
ctx.lineTo(offX + data.x + 5, data.y);
}
ctx.fillText(data.txt,
data.x + (data.lineWidth > 0 ? 8 : 0) + offX,
data.y + 0.3 * data.fontSize);
},
});
},
drawPolymerizedRegions: function(data, strokeStyle, lineWidth, tipFunc) {
var chrLens = [0, 0];
if (data == undefined)
return chrLens;
var strandArr = data.strand;
var posArr = data.pos;
var valArr = data.val;
for (var i = 0; i < strandArr.length; i++) {
var thisStrokeStyle;
if ((strandArr[i] == 2 &&
((strandArr.length == 4 && posArr[i] == 1 && valArr[i] == this.chrLen) ||
(strandArr.length > 2 && (posArr[i] == 1 || posArr[i] + valArr[i] - 1 == this.chrLen || (posArr[i] < this.chrLen/2 && valArr[i] < 5000))))) ||
strandArr[i] == 3){
thisStrokeStyle = strokeStyle[1];
}else{
thisStrokeStyle = strokeStyle[0];
}
chrLens[Math.ceil(strandArr[i] / 2) - 1] += valArr[i];
this.drawObject({
'strokeStyle': thisStrokeStyle,
'data': {strand: strandArr[i], pos: posArr[i], val: valArr[i], 'lineWidth': lineWidth},
'drawFunc': function(self, ctx, data){
ctx.lineWidth = data.lineWidth;
ctx.arc(
self.chrX[Math.floor((data.strand - 1) / 2)], self.height / 2,
self.chrRadius - (2 * ((data.strand - 1) % 2) - 1) * lineWidth / 2,
data.pos / self.chrLen * 2 * Math.PI,
(data.pos + data.val) / self.chrLen * 2 * Math.PI);
},
'tipFunc': tipFunc,
});
}
return chrLens;
},
drawDataTrack: function(data, strokeStyle, elDefaultLength, tipFunc) {
if (data == undefined)
return;
var strandArr = data.strand;
var posArr = data.pos;
var valArr = data.val;
for (var i = 0; i < strandArr.length; i++) {
this.drawObject({
'strokeStyle': strokeStyle,
'data': {strand: strandArr[i], pos: posArr[i], val: valArr[i], len: Math.max(elDefaultLength, valArr[i])},
'drawFunc': function(self, ctx, data){
ctx.lineWidth = self.dataHeight;
ctx.arc(
self.chrX[Math.floor((data.strand - 1) / 2)], self.height / 2,
self.dataRadii[(data.strand - 1) % 2],
data.pos / self.chrLen * 2 * Math.PI,
(data.pos + data.len) / self.chrLen * 2 * Math.PI);
},
'tipFunc': tipFunc,
});
}
},
});
var ChromosomeSpaceTimeVisualization = Visualization2D.extend({
chrLen: 580076,
axisLeft: 30,
axisRight: 0,
axisTop: 5,
axisBottom: 25,
axisLineWidth: 0.5,
timeStep: 100,
getData: function(md){
this._super(md);
//genes
this.getSeriesData('getKBData.php', {type: 'Gene'}, 'genes');
//replisome dynamics
this.getSeriesData('getSeriesData.php', {sim_id:md.sim_id, class_name: 'Summary', attr_name: 'replisome_1'}, 'replisome1');
this.getSeriesData('getSeriesData.php', {sim_id:md.sim_id, class_name: 'Summary', attr_name: 'replisome_2'}, 'replisome2');
//DnaA dynamics
this.getSeriesData('getSeriesData.php', {sim_id:md.sim_id, class_name: 'Summary', attr_name: 'dnaAFunctionalBoxes_' + 1}, 'dnaA1');
this.getSeriesData('getSeriesData.php', {sim_id:md.sim_id, class_name: 'Summary', attr_name: 'dnaAFunctionalBoxes_' + 2}, 'dnaA2');
this.getSeriesData('getSeriesData.php', {sim_id:md.sim_id, class_name: 'Summary', attr_name: 'dnaAFunctionalBoxes_' + 3}, 'dnaA3');
this.getSeriesData('getSeriesData.php', {sim_id:md.sim_id, class_name: 'Summary', attr_name: 'dnaAFunctionalBoxes_' + 4}, 'dnaA4');
this.getSeriesData('getSeriesData.php', {sim_id:md.sim_id, class_name: 'Summary', attr_name: 'dnaAFunctionalBoxes_' + 5}, 'dnaA5');
},
getDataSuccess: function () {
if (undefined == this.data.genes
|| undefined == this.data.replisome1
|| undefined == this.data.replisome2
|| undefined == this.data.dnaA1
|| undefined == this.data.dnaA2
|| undefined == this.data.dnaA3
|| undefined == this.data.dnaA4
|| undefined == this.data.dnaA5)
return;
//genes
this.genes = this.data.genes;
this.genes.sort(function(a, b){
return parseInt(a.coordinate) - parseInt(b.coordinate);
});
//dynamics
this.data = {
dnaPol: [
this.data.replisome1.data,
this.data.replisome2.data,
],
dnaA: [
this.data.dnaA1.data,
this.data.dnaA2.data,
this.data.dnaA3.data,
this.data.dnaA4.data,
this.data.dnaA5.data,
],
dnaATotal: [],
};
this.timeMin = Math.min(this.data.dnaPol[0][0][0], this.data.dnaPol[1][0][0]);
this.timeMax = Math.max(this.data.dnaPol[0][this.data.dnaPol[0].length-1][0], this.data.dnaPol[1][this.data.dnaPol[1].length-1][0])
this.timeMin = Math.floor(this.timeMin / 2 / 3600) * 2 * 3600;
for (var t = this.timeMin; t <= this.timeMax; t += this.timeStep){
var cnt = 0;
for (var i = 0; i < this.data.dnaA.length; i++){
cnt += getDataPoint(this.data.dnaA[i], t, true);
}
this.data.dnaATotal.push([t, cnt]);
}
//super
this._super();
},
calcLayout: function(){
this.axisX = this.axisLeft + this.axisLineWidth / 2;
this.axisY = this.axisTop + this.axisLineWidth / 2;
this.axisWidth = this.width - this.axisLeft - this.axisLineWidth;
this.axisHeight = this.height - this.axisTop - this.axisBottom - this.axisLineWidth;
},
drawStaticObjects: function(){
//DnaA
for (var t = this.timeMin; t <= this.timeMax; t += this.timeStep){
var cnt = 0;
for (var i = 0; i < this.data.dnaA.length; i++){
cnt += getDataPoint(this.data.dnaA[i], t, true);
}
if (cnt == 0)
continue;
var r = 61 * cnt / 29 + 255 * (29 - cnt) / 29;
var g = 179 * cnt / 29 + 255 * (29 - cnt) / 29;
var b = 74 * cnt / 29 + 255 * (29 - cnt) / 29;
this.drawObject({
strokeStyle: sprintf('rgb(%d,%d,%d)', r, g, b),
data: t,
drawFunc: function(self, ctx, data){
ctx.lineWidth = 2;
ctx.moveTo(
self.axisX + self.axisWidth * Math.max(0, (t - self.timeStep / 2 - self.timeMin) / (self.timeMax - self.timeMin)),
self.axisY + self.axisHeight / 2);
ctx.lineTo(
self.axisX + self.axisWidth * Math.min(1, (t + self.timeStep / 2 - self.timeMin) / (self.timeMax - self.timeMin)),
self.axisY + self.axisHeight / 2);
},
tipFunc: function(self, t){
var txt = 'Time: ' + formatTime(t, '') + '<br/>';
for (var i = 0; i < self.data.dnaA.length; i++){
txt += sprintf('R%d: %d<br/>', i + 1, Math.round(getDataPoint(self.data.dnaA[i], t, true)));
}
return txt;
},
});
}
//DNA pol
var x1 = undefined;
var x2 = undefined;
var y1 = undefined;
var y2 = undefined;
for (var i = 0; i < this.data.dnaPol.length; i++){
var datai = this.data.dnaPol[i];
for (var t = this.timeMin; t <= this.timeMax; t += this.timeStep){
var pos = Math.round(getDataPoint(datai, t, true));
if (pos == 0){
x2 = undefined;
y2 = undefined;
}else{
x2 = this.axisX + this.axisWidth * (t - this.timeMin) / (this.timeMax - this.timeMin);
if (i % 2 == 0)
y2 = this.axisY + this.axisHeight * (pos - this.chrLen / 2) / this.chrLen;
else
y2 = this.axisY + this.axisHeight * (pos + this.chrLen / 2) / this.chrLen;
if (x1 != undefined){
//hit detection
this.drawObject({
strokeStyle: '#000000',
globalAlpha: 0,
data: {'t': t, 'strand':i, 'pos':pos, 'x1': x1, 'y1': y1, 'x2': x2, 'y2': y2},
drawFunc: function(self, ctx, data){
ctx.lineWidth = data.x2 - data.x1;
ctx.moveTo((data.x1+data.x2)/2, Math.min(data.y1, data.y2)-10)
ctx.lineTo((data.x1+data.x2)/2, Math.max(data.y1, data.y2)+10);
},
tipFunc: function(self, data){
var gene = getGeneByPos(self.genes, data.pos);
var txt = '';
txt += 'Time: ' + formatTime(data.t, '') + '<br/>';
txt += 'Strand: ' + (data.strand == 0 ? '-' : '+') + '<br/>';
txt += 'Position: ' + data.pos + '<br/>';
txt += 'TU: ' + (gene ? gene.transcription_units[0] : 'N/A') + '<br/>';
txt += 'Gene: ' + (gene ? gene.name : 'N/A') + '<br/>';
return txt;
},
});
//data
this.drawObject({
strokeStyle: '#3d80b3',
data: {'t': t, 'x1': x1, 'y1': y1, 'x2': x2, 'y2': y2},
drawFunc: function(self, ctx, data){
ctx.lineWidth = 1;
ctx.moveTo(data.x1, data.y1);
ctx.lineTo(data.x2, data.y2);
},
});
}
}
x1 = x2;
y1 = y2;
}
}
//axis
this.drawObject({
'strokeStyle': '#222222',
drawFunc: function(self, ctx, data){
var txt, x, y;
ctx.lineWidth = self.axisLineWidth;
ctx.rect(self.axisX, self.axisY,
self.axisWidth, self.axisHeight);
//y-axis
txt = 'Position';
ctx.save();
ctx.font = self.bigFontSize + "px " + self.fontFamily;
ctx.translate(self.bigFontSize / 2, self.axisHeight / 2);
ctx.rotate(-Math.PI / 2);
ctx.fillText(txt, -ctx.measureText(txt).width / 2, 0.3 * self.bigFontSize);
ctx.restore();
ctx.font = self.smallFontSize + "px " + self.fontFamily;
var labels = [[0, 'terC'], [self.chrLen/2, 'oriC'], [self.chrLen, 'terC']];
for (var i = 0; i < labels.length; i++){
x = self.axisX;
y = self.axisY + self.axisHeight * labels[i][0] / self.chrLen;
ctx.moveTo(x, y);
ctx.lineTo(x-3, y);
txt = labels[i][1];
ctx.fillText(txt,
x - 5 - ctx.measureText(txt).width,
y + 0.3 * self.smallFontSize);
}
//x-axis
txt = 'Time (h)';
ctx.font = self.bigFontSize + "px " + self.fontFamily;
ctx.fillText(txt,
self.axisX + self.axisWidth / 2 - ctx.measureText(txt).width / 2,
self.height - 0.2 * self.bigFontSize);
ctx.font = self.smallFontSize + "px " + self.fontFamily;
for (var t = self.timeMin; t <= Math.floor(self.timeMax / (2 * 3600)) * 2 * 3600; t += 2 * 3600){
x = self.axisX + self.axisWidth * (t - self.timeMin) / (self.timeMax - self.timeMin);
y = self.axisY + self.axisHeight;
ctx.moveTo(x, y);
ctx.lineTo(x, y+3);
txt = (t / 3600).toString();
ctx.fillText(txt,
x - ctx.measureText(txt).width / 2,
y + 5 + 0.7 * self.smallFontSize);
}
},
});
},
drawDynamicObjects: function(t){
if (t < this.timeMin || t > this.timeMax)
return;
//DNA Pol
this.drawObject({
isLabel:true,
strokeStyle: '#3d80b3',
fillStyle: '#222222',
data: t,
drawFunc: function(self, ctx, t){
var x = self.axisX + 5;
var y = self.axisY + 5 + 0.35 * self.bigFontSize;
ctx.lineWidth = 5;
ctx.moveTo(x, y);
ctx.lineTo(x + 5, y);
var val1 = Math.round(getDataPoint(self.data.dnaPol[1], t, true));
var val2 = Math.round(getDataPoint(self.data.dnaPol[1], t, true));
if (val1 == 0)
val1 = 'N/A';
if (val2 == 0)
val2 = 'N/A';
ctx.font = self.bigFontSize + "px " + self.fontFamily;
ctx.fillText('DNA Pol (+' + val1 + ', -' + val2 + ')', x + 8, y + 0.35 * self.bigFontSize);
},
});
//DnaA
this.drawObject({
isLabel:true,
strokeStyle: 'rgb(61,179,74)',
fillStyle: '#222222',
data: t,
drawFunc: function(self, ctx, t){
var x = self.axisX + 5;
var y = self.axisY + 5 + 0.35 * self.bigFontSize + self.bigFontSize * 1.2;
ctx.lineWidth = 5;
ctx.moveTo(x, y)
ctx.lineTo(x + 5, y);
var val = [];
for (var i = 0; i < self.data.dnaA.length; i++){
val.push('R' + (i + 1) + ': ' + Math.round(getDataPoint(self.data.dnaA[i], t, true)));
}
ctx.font = self.bigFontSize + "px " + self.fontFamily;
ctx.fillText('DnaA (' + val.join(', ') + ')', x + 8, y + 0.35 * self.bigFontSize);
},
});
//progress line
this.drawObject({
strokeStyle: '#cd0a0a',
data: t,
drawFunc: function(self, ctx, t){
//red vertical line
var x = self.axisX + self.axisWidth * (t - self.timeMin) / (self.timeMax - self.timeMin);
ctx.lineWidth = 1;
ctx.moveTo(x, self.axisY);
ctx.lineTo(x, self.axisY + self.axisHeight);
},
});
},
});
var DnaAVisualization = Visualization2D.extend({
getData: function(md){
this._super(md);
for (var i = 1; i <= 5; i++) {
this.getSeriesData('getSeriesData.php', {
'sim_id': md.sim_id,
'class_name': 'Summary',
'attr_name': 'dnaAFunctionalBoxes_' + i,
}, i);
}
},
getDataSuccess: function () {
for (var i = 1; i <= 5; i++) {
if (this.data[i] == undefined)
return;
}
var tmp = this.data;
this.data = [];
for (var i = 1; i <= 5; i++) {
this.data.push(tmp[i].data);
}
this.timeMin = this.data[0][0][0];
this.timeMax = this.data[0][this.data[0].length-1][0];
this._super();
},
calcLayout: function(){
this.chrH = this.height * 0.8;
this.chrX = this.width / 12;
},
drawDynamicObjects: function(t){
// draw chromosome
this.drawObject({
strokeStyle: '#aaaaaa',
drawFunc: function(self, ctx, dataPt){
ctx.lineWidth = 2;
ctx.moveTo(0, self.chrH);
ctx.lineTo(self.width, self.chrH);
},
});
// label functional boxes
this.drawObject({
strokeStyle: '#3d80b3',
fillStyle: '#222222',
drawFunc: function(self, ctx, dataPt){
for (var i = 1; i <= 5; i++) {
var x = self.width / 6 * (6 - i);
ctx.lineWidth = 4;
ctx.font = "10px " + self.fontFamily;
ctx.moveTo(x, self.chrH);
ctx.lineTo(x + 20, self.chrH);
ctx.fillText('R' + i.toString(), x + 5, self.chrH + 12);
}
},
});
// label oriC
this.drawObject({
strokeStyle: '#222222',
fillStyle: '#222222',
drawFunc: function(self, ctx, dataPt){
ctx.lineWidth = 4;
ctx.font = "10px " + self.fontFamily;
ctx.moveTo(self.chrX, self.chrH - 5);
ctx.lineTo(self.chrX, self.chrH + 5);
ctx.fillText('oriC', self.chrX - 8, self.chrH + 15);
},
});
// draw dnaA proteins
for (var i = 0; i < 5; i++) {
var cnt = Math.round(getDataPoint(this.data[i], t, true));
var x = this.width / 6 * (5 - i) + 10;
for (var j = 1; j <= cnt; j++) {
this.drawObject({
data:{'x': x, 'y': this.chrH - j * 10},
strokeStyle: '#222222',
fillStyle: '#3d80b3',
drawFunc: function(self, ctx, data){
ctx.lineWidth = 1;
ctx.arc(data.x, data.y, 5, 0, 2 * Math.PI, false);
ctx.closePath();
},
});
}
}
},
});
var FtsZRingVisualization = Visualization2D.extend({
thickStrokeWidth:5,
thinStrokeWidth:1,
getData: function(md){
this._super(md);
this.getSeriesData('getSeriesData.php', {sim_id: md.sim_id, class_name: md.class_name, attr_name: 'animation'}, 'ring');
this.getSeriesData('getSeriesData.php', {sim_id: md.sim_id, class_name:'Geometry', attr_name: 'width_1'}, 'width');
this.getSeriesData('getSeriesData.php', {sim_id: md.sim_id, class_name: 'Geometry', attr_name: 'pinchedDiameter_1'}, 'pinchedDiameter');
this.getSeriesData('getSeriesData.php', {sim_id: md.sim_id, class_name: 'Geometry', attr_name: 'cylindricalLength_1'}, 'cylindricalLength');
},
getDataSuccess: function () {
if (undefined == this.data.ring
|| undefined == this.data.width
|| undefined == this.data.pinchedDiameter
|| undefined == this.data.cylindricalLength)
return;
this.data = {
ring: this.data.ring,
width: this.data.width.data,
pinchedDiameter: this.data.pinchedDiameter.data,
cylindricalLength: this.data.cylindricalLength.data,
};
this.timeMax = Math.max(
this.data.width[this.data.width.length - 1][0] - 1,
this.data.pinchedDiameter[this.data.pinchedDiameter.length - 1][0],
this.data.cylindricalLength[this.data.cylindricalLength.length - 1][0]
);
this.timeMin = Math.min(this.timeMax, this.data.ring.start_time);
this._super();
},
calcLayout: function(){
//to correct for scaling from data generation
this.scale = 1.15 * Math.min((this.width - this.thickStrokeWidth) / 520, (this.height - this.thickStrokeWidth) / 250);
this.xOffset = - 520 / 2 * this.scale + this.width / 2;
this.yOffset = - 250 / 2 * this.scale + this.height / 2;
//septum radius
this.radius = (Math.min(this.width, this.height) - this.thickStrokeWidth) / 2;
},
drawDynamicObjects: function(t){
t = Math.min(t, this.timeMax);
//cell membrane
var width = Math.max(this.data.width[0][1], getDataPoint(this.data.width, t, false));
var pD = getDataPoint(this.data.pinchedDiameter, t, true);
var cL = getDataPoint(this.data.cylindricalLength, t, true);
this.drawObject({
data: this.radius * width / this.data.width[0][1],
strokeStyle: '#cccccc',
drawFunc: function(self, ctx, radius){
ctx.lineWidth = 1;
ctx.arc(self.width / 2, self.height / 2, radius, 0, 2 * Math.PI);
},
});
//get FtsZ data
var dataPt = getDataPoint(this.data.ring.data, t);
if (dataPt == undefined){
dataPt = {
angles_edges_one_bent: [],
angles_edges_two_bent: [],
coords_edges_one_straight: [],
coords_edges_two_straight: [],
};
}else{
//radius
var r = this.scale * dataPt.r;
// draw edges with one straight filament
this.drawObject({
data: dataPt,
strokeStyle: '#3d80b3',
drawFunc: function(self, ctx, dataPt){
ctx.lineWidth = self.thinStrokeWidth;
for (var i = 0; i < dataPt.coords_edges_one_straight.length; i++) {
ctx.moveTo(
self.scale * dataPt.coords_edges_one_straight[i][0] + self.xOffset,
self.scale * dataPt.coords_edges_one_straight[i][1] + self.yOffset);
ctx.lineTo(
self.scale * dataPt.coords_edges_one_straight[i][2] + self.xOffset,
self.scale * dataPt.coords_edges_one_straight[i][3] + self.yOffset);
}
},
});
// draw edges with two straight filaments
this.drawObject({
data: dataPt,
strokeStyle: "#3d80b3",
drawFunc: function(self, ctx, dataPt){
ctx.lineWidth = self.thickStrokeWidth;
for (var i = 0; i < dataPt.coords_edges_two_straight.length; i++) {
ctx.moveTo(
self.scale * dataPt.coords_edges_two_straight[i][0] + self.xOffset,
self.scale * dataPt.coords_edges_two_straight[i][1] + self.yOffset);
ctx.lineTo(
self.scale * dataPt.coords_edges_two_straight[i][2] + self.xOffset,
self.scale * dataPt.coords_edges_two_straight[i][3] + self.yOffset);
}
},
});
// draw edges with one bent filament
for (var i = 0; i < dataPt.angles_edges_one_bent.length; i++) {
this.drawObject({
data: {'r': r, 'edge': dataPt.angles_edges_one_bent[i]},
strokeStyle: "#aaaaaa",
drawFunc: function(self, ctx, data){
ctx.lineWidth = self.thinStrokeWidth;
ctx.arc(self.width/2, self.height/2, data.r, data.edge[0], data.edge[1], false);
},
});
}
// draw edges with two bent filaments
for (var i = 0; i < dataPt.angles_edges_two_bent.length; i++) {
this.drawObject({
data: {'r': r, 'edge': dataPt.angles_edges_two_bent[i]},
strokeStyle: "#aaaaaa",
drawFunc: function(self, ctx, data){
ctx.lineWidth = self.thickStrokeWidth;
ctx.arc(self.width/2, self.height/2, data.r, data.edge[0], data.edge[1], false);
},
});
}
}
//write status
this.drawObject({
isLabel:true,
data: [
'Width: ' + (width * 1e9).toFixed(1) + ' nm',
'Length: ' + ((2 * width + cL + pD) * 1e9).toFixed(1) + ' nm',
'Septum: ' + (pD * 1e9).toFixed(1) + ' nm',
'FtsZ Bent: ' + dataPt.angles_edges_one_bent.length + '/' + dataPt.angles_edges_two_bent.length,
'FtsZ Straight: ' + dataPt.coords_edges_one_straight.length + '/' + dataPt.coords_edges_two_straight.length,
],
fillStyle: '#222222',
drawFunc: function(self, ctx, txt){
ctx.font = self.bigFontSize + "px " + self.fontFamily;
for (var i = 0; i < txt.length; i++){
ctx.fillText(txt[i],
self.width / 2 - ctx.measureText(txt[i]).width / 2,
self.height / 2 + 0.4 * self.bigFontSize + i * (self.bigFontSize + 2) - ((self.bigFontSize + 2) * txt.length) / 2);
}
},
});
},
});
var GeneExpressionHeatmapVisualization = HeatmapVisualization.extend({
axisTitle: ['RNA', 'Prot Mmr', 'Prot Cpx'],
axisTipFuncs: [
function(self, data){
var rna = self.rnas[data.row];
return sprintf('<h1>%s</h1>%sTime: %s<br/>Copy number: %d',
rna.wid, (rna.name ? rna.name + '<br/>' : ''), formatTime(data.time, ''), data.val);
},
function(self, data){
var pm = self.proteinMonomers[data.row];
return sprintf('<h1>%s</h1>%sTime: %s<br/>Copy number: %d',
pm.wid, (pm.name ? pm.name + '<br/>' : ''), formatTime(data.time, ''), data.val);
},
function(self, data){
var pc = self.proteinComplexs[data.row];
return sprintf('<h1>%s</h1>%sTime: %s<br/>Copy number: %d',
pc.wid, (pc.name ? pc.name + '<br/>' : ''), formatTime(data.time, ''), data.val);
},
],
getData: function(md){
this._super(md);
this.getSeriesData('getKBData.php', {'type': 'TranscriptonUnit'}, 'rnas');
this.getSeriesData('getKBData.php', {'type': 'ProteinMonomer'}, 'proteinMonomers');
this.getSeriesData('getKBData.php', {'type': 'ProteinComplex'}, 'proteinComplexs');
this.getSeriesData('getSeriesData.php', {
sim_id:md.sim_id,
class_name: 'Rna',
attr_name: 'counts_*',
attr_min: 694,
attr_max:1040,
}, 'rnaDynamics');
this.getSeriesData('getSeriesData.php', {
sim_id: md.sim_id,
class_name: 'ProteinMonomer',
attr_name: 'counts_*',
attr_min: 2411,
attr_max:2892,
}, 'monDynamics');
this.getSeriesData('getSeriesData.php', {
sim_id:md.sim_id,
class_name: 'ProteinComplex',
attr_name: 'counts_*',
attr_min: 202,
attr_max:402,
}, 'cpxDynamics');
},
getDataSuccess: function () {
if (undefined == this.data.rnas
|| undefined == this.data.proteinMonomers
|| undefined == this.data.proteinComplexs
|| undefined == this.data.rnaDynamics
|| undefined == this.data.monDynamics
|| undefined == this.data.cpxDynamics)
return;
this.rnas = this.data.rnas;
this.proteinMonomers = this.data.proteinMonomers;
this.proteinComplexs = this.data.proteinComplexs;
this.data = [
this.data.rnaDynamics.data,
this.data.monDynamics.data,
this.data.cpxDynamics.data,
];
this._super();
},
});
var RNAExpressionMapVisualization = ChromosomeMapVisualization.extend({
getData: function(md){
this._super(md);
//structural data
this.getSeriesData('getKBData.php', {'type': 'Gene'}, 'genes');
this.getSeriesData('getKBData.php', {'type': 'TranscriptonUnit'}, 'tus');
//dynamic data
this.getSeriesData('getSeriesData.php', {
sim_id:md.sim_id,
class_name: 'Rna',
attr_name: 'counts_*',
attr_min: 694,
attr_max:1040,
}, 'dynamics');
},
getDataSuccess: function (){
if (this.data.genes == undefined || this.data.tus == undefined || this.data.dynamics == undefined)
return;
//genes
var tmp = this.data.genes;
var genes = [];
for (var i = 0; i < tmp.length; i++){
genes[tmp[i].wid] = tmp[i];
}
//tus
var tus = this.data.tus;
this.objects = [];
for (var i = 0; i < tus.length; i++){
if (genes[tus[i].genes[0]].type == 'mRNA'){
var startCoord = NaN;
var endCoord = NaN;
for (var j = 0; j < tus[i].genes.length; j++){
var gene = genes[tus[i].genes[j]];
startCoord = Math.nanmin(startCoord, parseInt(gene.coordinate));
endCoord = Math.nanmax(endCoord, parseInt(gene.coordinate) + parseInt(gene.length) - 1);
}
this.objects.push($.extend(tus[i], {
'coordinate': startCoord,
'length': endCoord - startCoord + 1,
'direction': genes[tus[i].genes[0]].direction,
}));
}else{
for (var j = 0; j < tus[i].genes.length; j++){
this.objects.push(genes[tus[i].genes[j]]);
}
}
}
//dynamics
this.data = this.data.dynamics.data;
this._super();
},
});
var NascentRNAExpressionMapVisualization = ChromosomeMapVisualization.extend({
timeStep: 100,
getData: function(md){
this._super(md);
//structural data
this.getSeriesData('getKBData.php', {'type': 'Gene'}, 'genes');
this.getSeriesData('getKBData.php', {'type': 'TranscriptonUnit'}, 'tus');
//dynamic data
this.getSeriesData('getSeriesData.php', {
sim_id:md.sim_id,
class_name: 'Transcript',
attr_name: 'boundTranscriptionUnits_*',
}, 'boundTUs');
this.getSeriesData('getSeriesData.php', {
sim_id:md.sim_id,
class_name: 'Transcript',
attr_name: 'boundTranscriptProgress_*',
}, 'boundProgs');
},
getDataSuccess: function () {
if (undefined == this.data.genes
|| undefined == this.data.tus
|| undefined == this.data.boundTUs
|| undefined == this.data.boundProgs)
return;
//genes
var tmp = this.data.genes;
var genes = [];
for (var i = 0; i < tmp.length; i++){
genes[tmp[i].wid] = tmp[i];
}
//tus
var tus = this.data.tus;
this.objects = [];
for (var i = 0; i < tus.length; i++){
var startCoord = NaN;
var endCoord = NaN;
for (var j = 0; j < tus[i].genes.length; j++){
var gene = genes[tus[i].genes[j]];
startCoord = Math.nanmin(startCoord, parseInt(gene.coordinate));
endCoord = Math.nanmax(endCoord, parseInt(gene.coordinate) + parseInt(gene.length) - 1);
}
this.objects.push($.extend(tus[i], {
'coordinate': startCoord,
'length': endCoord - startCoord + 1,
'direction': genes[tus[i].genes[0]].direction,
}));
}
//dynamics
var boundTUs = this.data.boundTUs.data;
var boundProgs = this.data.boundProgs.data;
var timeMin = boundTUs[0][0][0];
var timeMax = boundTUs[0][boundTUs[0].length - 1][0];
this.data = [];
for (var i = 0; i < this.objects.length; i++){
var datai = [];
for (var t = timeMin; t <= timeMax; t += this.timeStep){
datai.push([t, 0]);
}
this.data.push(datai);
}
for (var i = 0; i < boundTUs.length; i++){
var j = -1;
for (var t = timeMin; t <= timeMax; t += this.timeStep){
j++;
bnd = getDataPoint(boundTUs[i], t, false);
prog = getDataPoint(boundProgs[i], t, false);
if (!bnd || !prog)
continue;
this.data[bnd - 1][j][1]++;
}
}
//super
this._super();
},
});
var ProteinMonomerExpressionMapVisualization = ChromosomeMapVisualization.extend({
getData: function(md){
this._super(md);
//structural data
this.getSeriesData('getKBData.php', {'type': 'Gene'}, 'genes');
this.getSeriesData('getKBData.php', {'type': 'ProteinMonomer'}, 'mons');
//dynamic data
this.getSeriesData('getSeriesData.php', {
sim_id:md.sim_id,
class_name: 'ProteinMonomer',
attr_name: 'counts_*',
attr_min: 2411,
attr_max: 2892,
}, 'dynamics');
},
getDataSuccess: function(){
if (undefined == this.data.genes
|| undefined == this.data.mons
|| undefined == this.data.dynamics)
return;
//genes
var tmp = this.data.genes;
var genes = [];
for (var i = 0; i < tmp.length; i++){
genes[tmp[i].wid] = tmp[i];
}
//monomers
var mons = this.data.mons;
this.objects = [];
for (var i = 0; i < mons.length; i++){
this.objects.push(genes[mons[i].gene]);
}
//dynamics
this.data = this.data.dynamics.data;
//super class method
this._super();
},
});
var NascentProteinMonomerExpressionMapVisualization = ChromosomeMapVisualization.extend({
timeStep: 100,
getData: function(md){
this._super(md);
//structural data
this.getSeriesData('getKBData.php', {'type': 'Gene'}, 'genes');
this.getSeriesData('getKBData.php', {'type': 'ProteinMonomer'}, 'mons');
//dynamic data
this.getSeriesData('getSeriesData.php', {
sim_id:md.sim_id,
class_name: 'Ribosome',
attr_name: 'boundMRNAs_*'
}, 'dynamics');
},
getDataSuccess: function() {
if (undefined == this.data.genes
|| undefined == this.data.mons
|| undefined == this.data.dynamics
)
return;
//genes
var tmp = this.data.genes;
var genes = [];
for (var i = 0; i < tmp.length; i++){
genes[tmp[i].wid] = tmp[i];
}
//monomers
var mons = this.data.mons;
this.objects = [];
for (var i = 0; i < mons.length; i++){
this.objects.push(genes[mons[i].gene]);
}
//dynamics
var boundMRNAs = this.data.dynamics.data;
var timeMin = boundMRNAs[0][0][0];
var timeMax = boundMRNAs[0][boundMRNAs[0].length - 1][0];
this.data = [];
for (var i = 0; i < this.objects.length; i++){
var datai = [];
for (var t = timeMin; t <= timeMax; t += this.timeStep){
datai.push([t, 0]);
}
this.data.push(datai);
}
for (var i = 0; i < boundMRNAs.length; i++){
var j = -1;
for (var t = timeMin; t <= timeMax; t += this.timeStep){
j++;
bnd = getDataPoint(boundMRNAs[i], t, false);
if (!bnd)
continue;
this.data[bnd - 1][j][1]++;
}
}
//super class method
this._super();
},
});
var EnergyHeatmapVisualization = Visualization2D.extend({
getData: function(md){
this._super(md);
this.getSeriesData('getSeriesData.php', {sim_id:md.sim_id, class_name: md.class_name, attr_name: 'attr_name'});
},
calcLayout: function(){
},
drawDynamicObjects: function(t){
/*this.drawObject({
'strokeStyle': strokeStyle,
'fillStyle': fillStyle,
'data': getDataPoint(this.data, t),
drawFunc: function(self, ctx, data){
},
tipFunc: function(self, data){
},
clickFunc: function(self, data){
},
});*/
},
});
var MetabolicMapVisualization = Visualization2D.extend({
maxMetConc: 100, //uM
maxRxnFlux: 1e3, //Hz
getData: function(md){
this._super(md);
//KB data
this.getSeriesData('getKBData.php', {'type': 'Metabolite'}, 'metabolites');
this.getSeriesData('getKBData.php', {'type': 'Reaction'}, 'reactions');
//map
this.getSeriesData('data/metabolicMap.json', undefined, 'map');
//concentrations and fluxes
this.getSeriesData('getSeriesData.php', {sim_id:md.sim_id, class_name: 'Geometry', attr_name: 'volume_1'}, 'volume');
this.getSeriesData('getSeriesData.php', {sim_id:md.sim_id, class_name: 'Metabolite', attr_name: 'counts_*'}, 'metaboliteConcs');
this.getSeriesData('getSeriesData.php', {sim_id:md.sim_id, class_name: 'MetabolicReaction', attr_name: 'fluxs_*'}, 'reactionFluxs');
},
getDataSuccess: function () {
if (undefined == this.data.metabolites
|| undefined == this.data.reactions
|| undefined == this.data.map
|| undefined == this.data.volume
|| undefined == this.data.metaboliteConcs
|| undefined == this.data.reactionFluxs)
return;
//kb
this.metabolites = this.data.metabolites;
this.reactions = this.data.reactions;
//map
this.map = this.data.map;
var minX = NaN;
var maxX = NaN;
var minY = NaN;
var maxY = NaN;
for (var i = 0; i < this.map.metabolites.length; i++){
minX = Math.nanmin(minX, this.map.metabolites[i].x);
maxX = Math.nanmax(maxX, this.map.metabolites[i].x);
minY = Math.nanmin(minY, this.map.metabolites[i].y);
maxY = Math.nanmax(maxY, this.map.metabolites[i].y);
}
for (var i = 0; i < this.map.reactions.length; i++){
var path, tmp, x1, x2, y1, y2;
path = this.map.reactions[i].path.split(' ');
tmp = path[1].split(', ');
x1 = parseInt(tmp[0]);
y1 = parseInt(tmp[1]);
tmp = path[path.length - 1].split(', ');
x2 = parseInt(tmp[0]);
y2 = parseInt(tmp[1]);
minX = Math.nanmin(minX, Math.min(x1, x2));
maxX = Math.nanmax(maxX, Math.max(x1, x2));
minY = Math.nanmin(minY, Math.min(y1, y2));
maxY = Math.nanmax(maxY, Math.max(y1, y2));
}
this.minX = minX;
this.maxX = maxX;
this.minY = minY;
this.maxY = maxY;
//dynamics
this.volume = this.data.volume.data;
this.metaboliteConcs = this.data.metaboliteConcs.data;
this.reactionFluxs = this.data.reactionFluxs.data;
this.timeMin = this.volume[0][0];
this.timeMax = this.volume[this.volume.length-1][0];
//super
this._super();
},
exportData: function(){
return {
volume: this.volume,
metaboliteConcs: this.metaboliteConcs,
reactionFluxs: this.reactionFluxs,
};
},
calcLayout: function(){
this.legendW = 10;
this.legendX = this.width - this.legendW;
this.legendTop = this.bigFontSize + 3;
this.legendBottom = this.height - this.bigFontSize - 3;
this.legendH = this.legendBottom - this.legendTop;
this.metMaxR = 3;
this.metConcScale = this.metMaxR / this.maxMetConc;
this.mapX = this.metMaxR + 1;
this.mapY = this.metMaxR + 1;
this.mapW = (this.legendX - 5) - 2 * (this.metMaxR + 1);
this.mapH = this.height - 2 * (this.metMaxR + 1);
this.scaleX = this.mapW / (this.maxX - this.minX);
this.scaleY = this.mapH / (this.maxY - this.minY);
this.arrowWidth = Math.PI / 8;
this.arrowLen = (this.legendX - 5) / 100;
},
drawStaticObjects: function(){
this.drawColorScale(
this.legendX, this.legendTop, this.legendW, this.legendH,
{r: 61, g: 128, b: 179},
{r: 240, g: 240, b: 240},
true);
},
drawDynamicObjects: function(t){
//metabolites
var V = getDataPoint(this.volume, t, true);
for (var i = 0; i < this.map.metabolites.length; i++){
conc = getDataPoint(this.metaboliteConcs[this.map.metabolites[i].idx - 1], t, true) / 6.022e23 / V * 1e6;
this.drawObject({
'strokeStyle': '#3d80b3',
'fillStyle': '#C9E7FF',
'data': {'map': this.map.metabolites[i], 'conc':conc},
drawFunc: function(self, ctx, data){
ctx.lineWidth = 1;
ctx.arc(
self.mapX + self.scaleX * (data.map.x - self.minX),
self.mapY + self.scaleY * (data.map.y - self.minY),
Math.max(1, Math.min(self.metMaxR, self.metConcScale * data.conc)), 0, 2 * Math.PI);
},
tipFunc: function(self, data){
return sprintf('<b>%s</b><br/><span style="white-space:nowrap;">Compartment: %s<br/>Concentration: %s μM</span>',
self.metabolites[data.map.idx - 1].name, data.map.c_wid, data.conc.toFixed(2));
},
});
this.drawObject({
isLabel:true,
'fillStyle': '#222222',
'data': {'map': this.map.metabolites[i], 'conc':conc},
drawFunc: function(self, ctx, data){
wid = self.metabolites[data.map.idx - 1].wid;
ctx.font = self.smallFontSize + "px " + self.fontFamily;
ctx.fillText(wid,
self.mapX + self.scaleX * (data.map.x - self.minX) - ctx.measureText(wid).width/2,
self.mapY + self.scaleY * (data.map.y - self.minY) + 0.4 * self.smallFontSize);
},
tipFunc: function(self, data){
return sprintf('<b>%s</b><br/><span style="white-space:nowrap;">Compartment: %s<br/>Concentration: %s μM</span>',
self.metabolites[data.map.idx - 1].name, data.map.c_wid, data.conc.toFixed(2));
},
});
}
//reactions
for (var i = 0; i < this.map.reactions.length; i++){
var val = getDataPoint(this.reactionFluxs[this.map.reactions[i].met_idx - 1], t, true);
if (val == 0){
var style = '#E1E1E1';
}else if (val < 0){
var f = Math.max(0, Math.min(1, Math.log(-val) / Math.log(this.maxRxnFlux)));
var style = 'rgb('
+ Math.round(f * 61 + (1-f) * 240) + ','
+ Math.round(f * 128 + (1-f) * 240) + ','
+ Math.round(f * 179 + (1-f) * 240) + ')';
}else{
var f = Math.max(0, Math.min(1, Math.log(val) / Math.log(this.maxRxnFlux)));
var style = 'rgb('
+ Math.round(f * 61 + (1-f) * 240) + ','
+ Math.round(f * 128 + (1-f) * 240) + ','
+ Math.round(f * 179 + (1-f) * 240) + ')';
}
this.drawReaction(this.map.reactions[i], val, style, undefined);
this.drawReaction(this.map.reactions[i], val, undefined, style);
}
},
drawReaction: function(map, val, strokeStyle, fillStyle){
this.drawObject({
'strokeStyle': strokeStyle,
'fillStyle': fillStyle,
'data': {'map': map, 'val':val, 'fill': fillStyle != undefined},
drawFunc: function(self, ctx, data){
ctx.lineWidth = 1;
segments = data.map.path.match(/([MLC])( ([0-9]+,[0-9]+))+/g);
var x, y, dy, dx;
for (var j = 0; j < segments.length; j++){
var tmp = segments[j].substr(2).split(/[ ,]/);
var pts = [];
for (var k = 0; k < tmp.length; k += 2){
pts.push([
self.mapX + self.scaleX * (parseFloat(tmp[k]) - self.minX),
self.mapY + self.scaleY * (parseFloat(tmp[k + 1]) - self.minY),
]);
}
switch (segments[j].substr(0, 1)){
case 'M':
ctx.moveTo(pts[0][0], pts[0][1]);
break;
case 'L':
if (!data.fill){
ctx.lineTo(pts[0][0], pts[0][1]);
}else if (j == segments.length - 1 && data.val > 0){
dx = pts[0][0] - x;
dy = pts[0][1] - y;
ctx.arrowTo(pts[0][0]-dx*1e-2, pts[0][1]-dy*1e-2, pts[0][0], pts[0][1], 0, 1, self.arrowWidth, self.arrowLen);
}else if (j == 1 && data.val < 0){
dx = x - pts[0][0];
dy = y - pts[0][1];
ctx.arrowTo(x-dx*1e-2, y-dy*1e-2, x, y, 0, 1, self.arrowWidth, self.arrowLen);
}
break;
case 'C':
if (!data.fill){
ctx.bezierCurveTo(pts[0][0], pts[0][1], pts[1][0], pts[1][1], pts[2][0], pts[2][1]);
}else if (j == segments.length - 1 && data.val > 0){
dx = -3 * pts[1][0] + 3 * pts[2][0];
dy = -3 * pts[1][1] + 3 * pts[2][1];
ctx.arrowTo(pts[2][0]-dx*1e-2, pts[2][1]-dy*1e-2, pts[2][0], pts[2][1], 0, 1, self.arrowWidth, self.arrowLen);
}else if (j == 1 && data.val < 0){
dx = x - pts[0][0];
dy = y - pts[0][1];
ctx.arrowTo(x-dx*1e-2, y-dy*1e-2, x, y, 0, 1, self.arrowWidth, self.arrowLen);
}
break;
}
x = pts[pts.length - 1][0];
y = pts[pts.length - 1][1];
}
},
tipFunc: function(self, data){
return sprintf('<b>%s</b><br/><span style="white-space:nowrap;">Flux: %s Hz</span>',
self.reactions[data.map.idx - 1].name,
data.val.toFixed(1));
},
});
this.drawObject({
isLabel:true,
'fillStyle': '#222222',
'data': {'map': map, 'val':val, 'fill': fillStyle != undefined},
drawFunc: function(self, ctx, data){
segments = data.map.path.match(/([MLC])( ([0-9]+,[0-9]+))+/g);
var tmp = segments[0].substr(2).split(/[ ,]/);
var x0 = tmp[0];
var y0 = tmp[1];
var tmp = segments[segments.length-1].substr(2).split(/[ ,]/);
var x1 = tmp[tmp.length-2];
var y1 = tmp[tmp.length-1];
x0 = self.mapX + self.scaleX * (parseFloat(x0) - self.minX)
x1 = self.mapX + self.scaleX * (parseFloat(x1) - self.minX)
y0 = self.mapY + self.scaleY * (parseFloat(y0) - self.minY)
y1 = self.mapY + self.scaleY * (parseFloat(y1) - self.minY)
var x = (x0 + x1) / 2;
var y = (y0 + y1) / 2;
wid = self.reactions[data.map.idx - 1].wid;
ctx.font = self.smallFontSize + "px " + self.fontFamily;
ctx.fillText(wid,
x - ctx.measureText(wid).width / 2,
y + 0.4 * self.smallFontSize);
},
tipFunc: function(self, data){
return sprintf('<b>%s</b><br/><span style="white-space:nowrap;">Flux: %s Hz</span>',
self.reactions[data.map.idx - 1].name,
data.val.toFixed(1));
},
});
},
});
var TranslationVisualization = ChromosomeMapVisualization.extend({
timeStep:100,
legendW:19,
getData: function(md){
this._super(md);
//structural data
this.getSeriesData('getKBData.php', {'type': 'Gene'}, 'genes');
this.getSeriesData('getKBData.php', {'type': 'ProteinMonomer'}, 'proteinMonomers');
//dynamic data
this.getSeriesData('getSeriesData.php', {sim_id:md.sim_id, class_name: 'Ribosome', attr_name: 'boundMRNAs_*'}, 'boundMRNAs');
this.getSeriesData('getSeriesData.php', {sim_id:md.sim_id, class_name: 'Ribosome', attr_name: 'mRNAPositions_*'}, 'mRNAPositions');
},
getDataSuccess: function () {
if (undefined == this.data.genes
|| undefined == this.data.proteinMonomers
|| undefined == this.data.boundMRNAs
|| undefined == this.data.mRNAPositions
)
return;
//genes
var tmp = this.data.genes;
var genes = [];
for (var i = 0; i < tmp.length; i++){
genes[tmp[i].wid] = tmp[i];
}
//monomers
this.proteinMonomers = this.data.proteinMonomers;
this.objects = [];
for (var i = 0; i < this.proteinMonomers.length; i++){
this.objects.push(genes[this.proteinMonomers[i].gene]);
}
//dynamics
var boundMRNAs = this.data.boundMRNAs.data;
var mRNAPositions = this.data.mRNAPositions.data;
this.timeMin = boundMRNAs[0][0][0];
this.timeMax = boundMRNAs[0][boundMRNAs[0].length - 1][0];
this.data = [];
for (var i = 0; i < this.objects.length; i++){
var datai = [];
for (var t = this.timeMin; t <= this.timeMax; t += this.timeStep){
datai.push([0, 0]);
}
this.data.push(datai);
}
var maxVal = 0;
for (var i = 0; i < boundMRNAs.length; i++){
var j = -1;
for (var t = this.timeMin; t <= this.timeMax; t += this.timeStep){
j++;
bnd = getDataPoint(boundMRNAs[i], t, false);
if (!bnd)
continue;
mR = getDataPoint(mRNAPositions[i], t, true);
this.data[bnd - 1][j][0] = Math.max(this.data[bnd - 1][j][0], mR);
this.data[bnd - 1][j][1]++;
maxVal = Math.max(maxVal, this.data[bnd - 1][j][1]);
}
}
//////////////////
//super
/////////////////
this.parent.parent().panel('clearPanelLoadingIndicator');
//set time
var timeline = $('#timeline');
timeline.timeline('updateTimeRange');
this.time = timeline.timeline('getTime');
if (isNaN(this.time))
this.time = this.timeMin;
//resize canvases
this.resize(this.parent.width(), this.parent.height(), true);
//set data loaded
this.dataLoaded = true;
},
getDataPoint: function(row, t){
if (t < this.timeMin || t > this.timeMax)
return undefined;
var idx = Math.floor((t - this.timeMin) / this.timeStep);
var v1 = this.data[row][idx];
if (this.data[row].length <= idx + 1){
return v1;
}else{
var v2 = this.data[row][idx + 1];
var dt = (t - this.timeMin) % this.timeStep;
//return closer value -- do this because averaging throws an error for an unknown reason
if (dt < this.timeStep / 2)
return v1
else
return v2;
//average
return [
(v1[0] * (this.timeStep - dt) + v2[0] * dt) / this.timeStep,
(v1[1] * (this.timeStep - dt) + v2[1] * dt) / this.timeStep,
];
}
},
drawObjectForward: function(ctx, x, y, w, h, row, val){
var len = this.objects[row].length / 3;
ctx.lineWidth = 0.25;
if ((this.isDrawingForExport || this.isDrawingForDisplay) && val && val[0]){
ctx.rect(x, y, w * Math.min(1, val[0] / len), h);
}
if (this.isDrawingForExport || this.isDrawingStaticContent){
ctx.rect(x, y, w, h);
}
},
drawObjectReverse: function(ctx, x, y, w, h, row, val){
this.drawObjectForward(ctx, x, y, w, h, row, val);
},
getObjectFillStyle: function(row, val){
if (!val || val[1] == 0)
return undefined;
if (val[1] == 1)
return '#3d80b3';
return '#3db34a';
},
drawColorScale: function(x, y, w, h, cLo, cHi, noShowBlack, labelLo, labelHi, nSegments){
this.drawObject({
fillStyle: '#222222',
data: {'x': x, 'y': y, 'w': w},
drawFunc: function (self, ctx, data) {
var w = data.w - 3 - ctx.measureText('>1').width;
ctx.font = self.smallFontSize + "px " + self.fontFamily;
ctx.fillText('1', data.x + data.w - ctx.measureText('1').width,
data.y + w/2);
},
});
this.drawObject({
strokeStyle: '#222222',
fillStyle: '#3d80b3',
data: {'x': x, 'y': y, 'w': w},
drawFunc: function (self, ctx, data) {
var w = data.w - 3 - ctx.measureText('>1').width;
ctx.rect(data.x, data.y, w, w);
},
});
this.drawObject({
fillStyle: '#222222',
data: {'x': x, 'y': y, 'w': w},
drawFunc: function (self, ctx, data) {
var w = data.w - 3 - ctx.measureText('>1').width;
var spcg = 3/2 * w;
ctx.font = self.smallFontSize + "px " + self.fontFamily;
ctx.fillText('>1', data.x + data.w - ctx.measureText('>1').width,
data.y + w/2 + spcg);
},
});
this.drawObject({
strokeStyle: '#222222',
fillStyle: '#3db34a',
data: {'x': x, 'y': y, 'w': w},
drawFunc: function (self, ctx, data) {
var w = data.w - 3 - ctx.measureText('>1').width;
var spcg = 3/2 * w;
ctx.rect(data.x, data.y + spcg, w, w);
},
});
}
});
/* helper functions */
function getGeneByPos(genes, pos, iMin, iMax){
if (iMin == undefined)
iMin = 0;
if (iMax == undefined)
iMax = genes.length - 1;
if (iMin == iMax){
var gene = genes[iMin];
if (pos >= gene.coordinate && pos <= gene.coordinate + gene.length)
return gene;
else
return undefined;
}
if (iMax - iMin == 1){
return getGeneByPos(genes, pos, iMin, iMin) || getGeneByPos(genes, pos, iMax, iMax);
}
var i = Math.floor((iMin + iMax) / 2);
if (pos < genes[i].coordinate)
return getGeneByPos(genes, pos, iMin, i - 1);
else
return getGeneByPos(genes, pos, i, iMax);
} | CovertLab/WholeCellViz | js/WholeCellViz-visualizations.js | JavaScript | mit | 88,122 |
var webpackConfig = require("./webpack.config.js");
webpackConfig.devtool = "inline-source-map";
delete webpackConfig.externals;
delete webpackConfig.entry;
delete webpackConfig.output;
module.exports = function (config) {
config.set({
basePath: ".",
frameworks: ["es6-shim", "chai", "mocha", "sinon"],
files: ["tests.bundle.js"],
preprocessors: {
"tests.bundle.js": ["webpack", "sourcemap"],
},
reporters: ["dots", "coverage"],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ["Chrome"],
singleRun: false,
concurrency: Infinity,
webpack: webpackConfig,
webpackMiddleware: {
noInfo: false,
},
coverageReporter: {
type: "lcov",
dir: "coverage/",
},
});
};
| jessepollak/payment | karma.conf.js | JavaScript | mit | 788 |
import React from 'react';
import {
header,
tabs,
tab,
description,
importExample,
title,
divider,
example,
playground,
api,
testkit,
} from 'wix-storybook-utils/Sections';
import { storySettings } from '../test/storySettings';
import Star from 'wix-ui-icons-common/Star';
import * as examples from './examples';
import CounterBadge from '..';
export default {
category: storySettings.category,
storyName: 'CounterBadge',
component: CounterBadge,
componentPath: '..',
componentProps: {
size: 'small',
children: 1,
skin: 'general',
showShadow: false,
},
exampleProps: {
children: [
{ label: 'number', value: 1 },
{ label: 'string', value: 'New!' },
{ label: 'node', value: <Star /> },
],
},
sections: [
header({
component: <CounterBadge>1</CounterBadge>,
}),
tabs([
tab({
title: 'Description',
sections: [
description({
title: 'Description',
text:
'`CounterBadge` gives you a quick preview to indicate more action is required.',
}),
importExample("import { CounterBadge } from 'wix-style-react';"),
divider(),
title('Examples'),
example({
title: 'Number counter',
text:
'The most common use of CounterBadge is with a number value truncated to 99. CounterBadge comes in two sizes `small` (default) and `medium`.',
source: examples.numbers,
}),
example({
title: 'Skins',
text:
'Background color can be one of the following: `general`, `danger`, `urgent`, `standard`, `warning`, `success` and `light`.',
source: examples.skins,
}),
example({
title: 'Shadow',
text: 'CounterBadge can add a shadow using `showShadow` prop',
source: examples.shadow,
}),
example({
title: 'Custom node',
text: 'CounterBadge can display a custom node, like an icon.',
source: examples.custom,
}),
example({
title: 'Advanced',
text: 'An example for a CounterBadge counting items in cart.',
source: examples.advanced,
}),
],
}),
...[
{ title: 'API', sections: [api()] },
{ title: 'Testkit', sections: [testkit()] },
{ title: 'Playground', sections: [playground()] },
].map(tab),
]),
],
};
| wix/wix-style-react | packages/wix-style-react/src/CounterBadge/docs/index.story.js | JavaScript | mit | 2,553 |
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
Object.defineProperty(exports, "__esModule", { value: true });
var core_1 = require("@angular/core");
var paginated_list_component_1 = require("../../paginated-list/paginated-list.component");
var TopicTrendingComponent = (function (_super) {
__extends(TopicTrendingComponent, _super);
function TopicTrendingComponent(route, postService, topicService) {
var _this = _super.call(this) || this;
_this.route = route;
_this.postService = postService;
_this.topicService = topicService;
return _this;
}
TopicTrendingComponent.prototype.ngOnInit = function () {
var _this = this;
this.route.params.subscribe(function (params) {
_this.id = +params['id'];
_this.topicService.getDetail(_this.id)
.then(function (res) { return _this.topic = res; });
});
_super.prototype.ngOnInit.call(this);
};
TopicTrendingComponent.prototype.loadNextPage = function (currentPage, perPage) {
var _this = this;
this.postService.getTrending(currentPage, perPage, this.id)
.then(function (res) { return _this.addPage(res); });
};
return TopicTrendingComponent;
}(paginated_list_component_1.PaginatedListComponent));
TopicTrendingComponent = __decorate([
core_1.Component({
selector: 'app-topic-trending',
templateUrl: './topic-trending.component.html',
styleUrls: ['./topic-trending.component.css']
})
], TopicTrendingComponent);
exports.TopicTrendingComponent = TopicTrendingComponent;
| frostblooded/kanq | client/src/app/topic/topic-trending/topic-trending.component.js | JavaScript | mit | 2,642 |
jQuery.each(("blur focus focusin focusout click dblclick " +
"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave").split(" "),
function(i, name) {
jQuery.fn[name] = function() {
var el = this[0];
var ev = document.createEvent('MouseEvent');
ev.initMouseEvent(
name,
true /* bubble */, true /* cancelable */,
window, null,
0, 0, 0, 0, /* coordinates */
false, false, false, false, /* modifier keys */
0 /*left*/, null
);
el.dispatchEvent(ev);
};
} );
| johnmeilleur/ng-officeuifabric | src/core/jquery.phantomjs.fix.js | JavaScript | mit | 574 |
import React from 'react';
import PropTypes from 'prop-types';
import Header from './Header';
// This is a class-based component because the current
// version of hot reloading won't hot reload a stateless
// component at the top-level.
class App extends React.Component {
render() {
return (
<div className="container">
<Header/>
{this.props.children}
</div>
);
}
}
App.propTypes = {
children: PropTypes.element
};
export default App;
| pawelzysk1989/game-store | src/components/App.js | JavaScript | mit | 481 |
/**
* Copyright (c) 2014, Oracle and/or its affiliates.
* All rights reserved.
*/
"use strict";var l={"PRY_ASUNCION":[null,"Assun\u00E7\u00E3o"],"BRA_BRASILIA":[null,"Bras\u00EDlia"],"URY_MONTEVIDEO":[null,"Montevid\u00E9u"],"COL_BOGOTA":[null,"Bogot\u00E1"],"TTO_PORT_OF_SPAIN":[null,"Porto de Espanha"],"BRA_SAO_PAULO":[null,"S\u00E3o Paulo"]};(this?this:window)['DvtBaseMapManager']['_UNPROCESSED_MAPS'][2].push(["southAmerica","cities",l]); | jobinesh/jet-examples | node-jet1.2.0-mongo-app/public/js/libs/oj/v1.2.0/resources/internal-deps/dvt/thematicMap/resourceBundles/SouthAmericaCitiesBundle_pt_BR.js | JavaScript | mit | 451 |
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
extend = require('mongoose-schema-extend'),
Schema = mongoose.Schema,
moment = require('moment'),
crypto = require('crypto');
/**
* A Validation function for local strategy properties
*/
var validateLocalStrategyProperty = function(property) {
return ((this.provider !== 'local' && !this.updated) || property.length);
};
/**
* A Validation function for local strategy password
*/
var validateLocalStrategyPassword = function(password) {
return (this.provider !== 'local' || (password && password.length > 6));
};
/**
* User Schema
*/
var UserSchema = new Schema({
firstName: {
type: String,
trim: true,
default: '',
validate: [validateLocalStrategyProperty, 'Please fill in your first name']
},
lastName: {
type: String,
trim: true,
default: '',
validate: [validateLocalStrategyProperty, 'Please fill in your last name']
},
email: {
type: String,
trim: true,
default: '',
validate: [validateLocalStrategyProperty, 'Please fill in your email'],
match: [/.+\@.+\..+/, 'Please fill a valid email address']
},
username: {
type: String,
required: 'Please fill in a username',
trim: true
},
password: {
type: String,
default: '',
validate: [validateLocalStrategyPassword, 'Password should be longer']
},
salt: {
type: String
},
provider: {
type: String,
required: 'Provider is required',
},
providerData: {},
additionalProvidersData: {},
updated: {
type: Date
},
created: {
type: Date,
default: Date.now
}
}, {
collection: 'users',
discriminatorKey: '_type'
});
/**
* SkillCategory Schema
*/
var SkillCategorySchema = new Schema({
name: {
type: String,
required: 'Name of skill category is important'
}
});
/**
* Skill Schema
*/
var SkillSchema = new Schema({
name: {
type: String
},
category: {
type: Schema.ObjectId,
ref: 'SkillCategory'
},
});
/**
* Assessment Schema
*/
var AssessmentSchema = new Schema({
assessment_name: {
type: String,
trim: true,
required: 'Name of assessment is important'
},
assessment_date: {
type: Date,
required: 'Date of assessment is important'
},
applicantId: {
type: Schema.ObjectId,
ref: 'Applicant'
},
instructorId: {
type: Schema.ObjectId,
ref: 'Instructor'
},
score: {
type: Number,
required: 'The Applicant score is compulsory'
}
});
/**
* Placement Schema
*/
var PlacementSchema = new Schema({
company: {
type: String,
trim: true,
required: 'Name of company is important'
},
jobDescription: {
type: String,
required: 'Job description is important'
},
start_date: {
type: Date,
required: 'Start date is important'
},
end_date: {
type: Date,
required: 'End date is important'
}
});
/**
*
* Applicant Schema, Trainee and Fellow
*/
var ApplicantSchema = UserSchema.extend({
testScore: {
type: Number,
required: 'Applicant score must be submitted'
},
cvPath: {
type: String
},
photo_path: String,
role: {
type: String,
enum: ['applicant', 'trainee', 'fellow']
},
status: {
name: {
type: String,
enum: ['pending', 'rejected', 'selected for bootcamp', 'selected for interview'],
default: 'pending'
},
reason: {
type: String,
default: ''
}
},
portfolio: {
type: String
},
skillSet: [{
skill: {
type: Schema.Types.ObjectId,
ref: 'Skill'
},
rating: {
type: Number
}
}],
skillSummary: {},
profile: {
type: String
},
campId: {
type: Schema.ObjectId,
ref: 'Bootcamp'
},
assessments: [AssessmentSchema],
placements: [{
type: Schema.Types.ObjectId,
ref: 'Placement'
}]
});
/**
* Instructor Schema
*/
var InstructorSchema = UserSchema.extend({
experience: {
type: String
},
photo: {
type: String
},
role: {
type: String,
enum: ['instructor', 'admin']
},
skillSet: [SkillSchema]
});
/**
* Bootcamp Schema
*/
var BootcampSchema = new Schema({
camp_name: {
type: String,
trim: true
},
location: {
type: String,
required: 'Please fill in the Bootcamp location',
default: 'Lagos',
trim: true
},
start_date: {
type: Date
},
end_date: {
type: Date
},
created: {
type: Date,
default: Date.now
},
applicants: [{
type: Schema.Types.ObjectId,
ref: 'Applicant'
}]
});
/**
* Hook a pre save method to hash the password
*/
UserSchema.pre('save', function(next) {
if (this.password && this.password.length > 6) {
this.salt = new Buffer(crypto.randomBytes(16).toString('base64'), 'base64');
this.password = this.hashPassword(this.password);
}
next();
});
ApplicantSchema.pre('save', function(next) {
if (this.password && this.password.length > 6) {
this.salt = new Buffer(crypto.randomBytes(16).toString('base64'), 'base64');
if (this.constructor.name === 'EmbeddedDocument') {
var TempApplicant = mongoose.model('Applicant');
var embeddedDocApplicant = new TempApplicant(this);
this.password = embeddedDocApplicant.hashPassword(this.password);
} else {
this.password = this.hashPassword(this.password);
}
}
next();
});
InstructorSchema.pre('save', function(next) {
if (this.password && this.password.length > 6) {
this.salt = new Buffer(crypto.randomBytes(16).toString('base64'), 'base64');
this.password = this.hashPassword(this.password);
}
next();
});
BootcampSchema.pre('save', function(next) {
if (this.start_date && this.location) {
this.camp_name = moment(this.start_date).format('MMMM D, YYYY') + ', ' + this.location;
}
next();
});
SkillSchema.post('save', function(next) {
var skill = this;
var Applicant = mongoose.model('Applicant');
Applicant.find().exec(function(err, applicants) {
applicants.forEach(function(applicant) {
Applicant.update({
_id: applicant._id
}, {
$push: {
'skillSet': {
skill: skill._id,
rating: 0
}
}
}, function(err) {
if (err) {
return {
message: 'Couldn\'t add skill to applicant'
};
}
});
});
});
});
ApplicantSchema.post('save', function(next) {
var applicant = this;
var Skill = mongoose.model('Skill');
var Applicant = mongoose.model('Applicant');
//Initialize skill summary
var SkillCategory = mongoose.model('SkillCategory');
var skillSummary = {};
SkillCategory.find().exec(function(err, skillCategories) {
skillCategories.forEach(function(category) {
skillSummary[category.name] = 0;
});
Skill.find().exec(function(err, skills) {
skills.forEach(function(skill) {
Applicant.update({
_id: applicant._id
}, {
$push: {
'skillSet': {
skill: skill._id,
rating: 0
}
},
$set: {
'skillSummary': skillSummary
}
}, function(err) {
if (err) {
return {
message: 'Couldn\'t add skill to applicant'
};
}
});
});
});
});
});
/**
* Create instance method for hashing a password
*/
UserSchema.methods.hashPassword = function(password) {
if (this.salt && password) {
return crypto.pbkdf2Sync(password, this.salt, 10000, 64).toString('base64');
} else {
return password;
}
};
ApplicantSchema.methods.hashPassword = function(password) {
if (this.salt && password) {
return crypto.pbkdf2Sync(password, this.salt, 10000, 64).toString('base64');
} else {
return password;
}
};
InstructorSchema.methods.hashPassword = function(password) {
if (this.salt && password) {
return crypto.pbkdf2Sync(password, this.salt, 10000, 64).toString('base64');
} else {
return password;
}
};
/**
* Create instance method for authenticating user
*/
UserSchema.methods.authenticate = function(password) {
return this.password === this.hashPassword(password);
};
ApplicantSchema.methods.authenticate = function(password) {
return this.password === this.hashPassword(password);
};
InstructorSchema.methods.authenticate = function(password) {
return this.password === this.hashPassword(password);
};
/**
* Find possible not used username
*/
UserSchema.statics.findUniqueUsername = function(username, suffix, callback) {
var _this = this;
var possibleUsername = username + (suffix || '');
_this.findOne({
username: possibleUsername
}, function(err, user) {
if (!err) {
if (!user) {
callback(possibleUsername);
} else {
return _this.findUniqueUsername(username, (suffix || 0) + 1, callback);
}
} else {
callback(null);
}
});
};
ApplicantSchema.statics.findUniqueUsername = function(username, suffix, callback) {
var _this = this;
var possibleUsername = username + (suffix || '');
_this.findOne({
username: possibleUsername
}, function(err, user) {
if (!err) {
if (!user) {
callback(possibleUsername);
} else {
return _this.findUniqueUsername(username, (suffix || 0) + 1, callback);
}
} else {
callback(null);
}
});
};
InstructorSchema.statics.findUniqueUsername = function(username, suffix, callback) {
var _this = this;
var possibleUsername = username + (suffix || '');
_this.findOne({
username: possibleUsername
}, function(err, user) {
if (!err) {
if (!user) {
callback(possibleUsername);
} else {
return _this.findUniqueUsername(username, (suffix || 0) + 1, callback);
}
} else {
callback(null);
}
});
};
mongoose.model('Placement', PlacementSchema);
mongoose.model('User', UserSchema);
mongoose.model('Applicant', ApplicantSchema);
mongoose.model('Instructor', InstructorSchema);
mongoose.model('Bootcamp', BootcampSchema);
mongoose.model('SkillCategory', SkillCategorySchema);
mongoose.model('Skill', SkillSchema);
mongoose.model('Assessment', AssessmentSchema);
| andela-ogaruba/AndelaAPI | app/models/user.server.model.js | JavaScript | mit | 11,542 |
'use strict';
var assert = require('assert');
var run = require('./helpers').runMocha;
var args = [];
describe('suite w/no callback', function() {
it('should throw a helpful error message when a callback for suite is not supplied', function(done) {
run(
'suite/suite-no-callback.fixture.js',
args,
function(err, res) {
if (err) {
return done(err);
}
var result = res.output.match(/no callback was supplied/) || [];
assert.equal(result.length, 1);
done();
},
{stdio: 'pipe'}
);
});
});
describe('skipped suite w/no callback', function() {
it('should not throw an error when a callback for skipped suite is not supplied', function(done) {
run('suite/suite-skipped-no-callback.fixture.js', args, function(err, res) {
if (err) {
return done(err);
}
var pattern = new RegExp('Error', 'g');
var result = res.output.match(pattern) || [];
assert.equal(result.length, 0);
done();
});
});
});
describe('skipped suite w/ callback', function() {
it('should not throw an error when a callback for skipped suite is supplied', function(done) {
run('suite/suite-skipped-callback.fixture.js', args, function(err, res) {
if (err) {
return done(err);
}
var pattern = new RegExp('Error', 'g');
var result = res.output.match(pattern) || [];
assert.equal(result.length, 0);
done();
});
});
});
describe('suite returning a value', function() {
it('should give a deprecation warning for suite callback returning a value', function(done) {
run(
'suite/suite-returning-value.fixture.js',
args,
function(err, res) {
if (err) {
return done(err);
}
var pattern = new RegExp('Deprecation Warning', 'g');
var result = res.output.match(pattern) || [];
assert.equal(result.length, 1);
done();
},
{stdio: 'pipe'}
);
});
});
| boneskull/mocha | test/integration/suite.spec.js | JavaScript | mit | 1,999 |