code
stringlengths
2
1.05M
/* 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"});
var helloWorldController = function(app){ app.get('/hello/world', function(request, response){ var responseObject = { "hello": "world"} response.send(responseObject); }); }; module.exports = helloWorldController;
(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); }; } }); })();
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; }; }); });
/** * @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 }
/** * 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;
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'); }); });
// 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); }); }); }); });
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']); };
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); }); });
/* * /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");
;(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; })();
#!/usr/bin/env node /* Passphrases | https://github.com/micahflee/passphrases Copyright (C) 2015 Micah Lee <[email protected]> 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(); }
/* 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)); };
'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; }
"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() }) })
'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;
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'], }, };
/*********************** * 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, [email protected] * 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 &mu;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 &mu;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); }
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/", }, }); };
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), ]), ], };
"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;
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); }; } );
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;
/** * 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]);
'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);
'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'} ); }); });
/* * Wegas * http://wegas.albasim.ch * * Copyright (c) 2013, 2014, 2015 School of Business and Engineering Vaud, Comem * Licensed under the MIT License */ /** * @fileoverview * @author Francois-Xavier Aeberhard <[email protected]> * @author Cyril Junod <cyril.junod at gmail.com> */ YUI.add('wegas-helper', function(Y) { "use strict"; var Wegas = Y.namespace("Wegas"), Helper; /** * @name Y.Wegas.Helper * @class * @constructor */ Helper = { /** * Generate ID an unique id based on current time. * @function * @static * @return {Number} time * @description */ genId: function() { var now = new Date(); return now.getHours() + now.getMinutes() + now.getSeconds(); }, /** * Escape a html string by replacing <, > and " by their html entities. * * @function * @static * @param {String} str * @return {String} Escaped string */ htmlEntities: function(str) { return String(str).replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/"/g, '&quot;'); }, /** * Replace any text line return * @function * @static * @param {String} str the string to escape * @param {String} replaceBy The value to replace with, default is \<br \/\> * @return {String} Escaped string */ nl2br: function(str, replaceBy) { replaceBy = replaceBy || '<br />'; return (String(str)).replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + replaceBy + '$2'); }, escapeJSString: function(str) { return str.replace(/"/g, "\\\"").replace(/(\r\n|\n\r|\r|\n)/g, ""); //.replace(/(\r\n|\n\r|\r|\n)/g, "\\n"); }, unesacapeJSString: function(str) { return str.replace(/\\"/g, '"'); }, escapeCSSClass: function(str) { return str.replace(/ /g, "-").toLowerCase(); }, stripHtml: function(html) { var div = document.createElement("div"); div.innerHTML = html; return div.textContent || div.innerText || ""; }, trimLength: function(string, length, after) { after = after || "..."; return string.length > length ? string.substring(0, length - after.length) + after : string.substring(0, length); }, /** * Format a date, using provided format string. * * @function * @static * @argument {Number} timestamp * @argument {String} fmt the format to apply, ex. '%d.%M.%Y at %H:%i:%s' <br /> * d Day of the month, 2 digits with leading zeros <br /> * m Numeric representation of a month, with leading zeros <br /> * M A short textual representation of a month, three letters <br /> * Y A full numeric representation of a year, 4 digits <br /> * H 24-hour format of an hour with leading zeros <br /> * i Minutes with leading zeros <br /> * s Seconds, with leading zeros <br /> * @returns {String} formated date */ formatDate: function(timestamp, fmt) { var date = new Date(timestamp), months = ["Jan", "Feb", "Mar", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; function pad(value) { return (value.toString().length < 2) ? '0' + value : value; } return fmt.replace(/%([a-zA-Z])/g, function(_, fmtCode) { switch (fmtCode) { case 'Y': return date.getFullYear(); case 'M': return months[date.getMonth()]; case 'm': return pad(date.getMonth() + 1); case 'd': return pad(date.getDate()); case 'H': return pad(date.getHours()); case 'i': return pad(date.getMinutes()); case 's': return pad(date.getSeconds()); default: throw new Error('Unsupported format code: ' + fmtCode); } }); }, /** * Returns a time lapse between provided timestamp and now, e.g. "a month ago", * "2 hours ago", "10 minutes ago" * @function * @static * @argument {Number} timestamp * @return {String} The formatted time */ smartDate: function(timestamp, prefix) { var date = new Date(timestamp), now = new Date(), diffN = now.getTime() - timestamp, oneMinute = 60 * 1000, oneHour = 60 * oneMinute, oneDay = 24 * oneHour; // oneMonth = 30 * oneDay, // oneYear = 365 * oneDay; if (!date.getTime()) { return "undefined"; } if (diffN < oneMinute) { // last minute return Math.round(diffN / 1000) + " seconds ago"; } else if (diffN < oneHour) { // last hour return Math.round(diffN / oneMinute) + " minutes ago"; } else if (diffN < oneDay && now.getDay() === date.getDay()) { // Today return (prefix ? "at " : "") + Helper.formatDate(timestamp, "%H:%i"); } else if (date.getYear() === now.getYear()) { // This year return (prefix ? "the " : "") + Helper.formatDate(timestamp, "%d %M"); } else { // Older return (prefix ? "the " : "") + Helper.formatDate(timestamp, "%d %M %Y"); } }, /** * Java hashCode implementation * @param {String} value to hash * @returns {Number} */ hashCode: function(value) { return Y.Array.reduce(value.split(""), 0, function(prev, curr) { prev = ((prev << 5) - prev) + curr.charCodeAt(0); return (prev |= 0); //Force 32 bits }); }, /** * Return an object with functions (first level only, not objects in object...) * that will execute the supplied function in the supplied object's context, * optionally adding any additional supplied parameters to the beginning of * the arguments collection the supplied to the function. * @param {Object} o the object with in functions to execute on the context object. * @param {Object} c the execution context. * @param {any} 0..n arguments to include before the arguments the function is executed with. * @returns An object with the wrapped functions. */ superbind: function(o, c) { var i, args = arguments.length > 0 ? Y.Array(arguments, 0, true) : null; for (i in o) { if (o.hasOwnProperty(i)) { args[0] = o[i]; o[i] = Y.bind.apply(c, args); } } return o; }, getURLParameter: function(name) { var param = ((new RegExp(name + '=' + '(.+?)(&|$)')).exec(location.search) || [, null])[1]; return param ? decodeURIComponent(param) : param; }, getURLParameters: function() { var match, search = /([^&=]+)=?([^&]*)/g, query = window.location.search.substring(1), params = {}; while (match = search.exec(query)) { params[decodeURIComponent(match[1])] = decodeURIComponent(match[2]); } return params; }, setURLParameters: function(params) { var par, str = [], tmp; for (par in params) { if (params.hasOwnProperty(par)) { tmp = encodeURIComponent(par); if (params[par]) { tmp += "=" + encodeURIComponent(params[par]); } str.push(tmp); } } window.location.search = "?" + str.join("&"); }, getFilename: function(path) { return path.replace(/^.*[\\\/]/, ''); }, /** * @function * source: http://stackoverflow.com/a/15203639 * @param {type} el * @returns {Boolean} */ isElementVisible: function(el) { if (el.getDOMNode) { el = el.getDOMNode(); } var eap, rect = el.getBoundingClientRect(), docEl = document.documentElement, vWidth = window.innerWidth || docEl.clientWidth, vHeight = window.innerHeight || docEl.clientHeight, efp = function(x, y) { return document.elementFromPoint(x, y); }, contains = "contains" in el ? "contains" : "compareDocumentPosition", has = contains === "contains" ? 1 : 0x14; // Return false if it's not in the viewport if (rect.right < 0 || rect.bottom < 0 || rect.left > vWidth || rect.top > vHeight) { return false; } // Return true if any of its four corners are visible return ((eap = efp(rect.left, rect.top)) === el || el[contains](eap) === has || (eap = efp(rect.right, rect.top)) === el || el[contains](eap) === has || (eap = efp(rect.right, rect.bottom)) === el || el[contains](eap) === has || (eap = efp(rect.left, rect.bottom)) === el || el[contains](eap) === has); }, /** * */ scrollIntoViewIfNot: function(node, alignTop) { if (!Helper.isElementVisible(node)) { node.scrollIntoView(alignTop); } }, /** * Quote a given string to be passed in a regular expression * * @param str String the string to quote * @returns String the quoted string */ RegExpQuote: function(str) { return (String(str)).replace(/([.*?+\^$\[\]\\(){}|\-])/g, "\\$1"); } }; Wegas.Helper = Helper; Wegas.superbind = Helper.superbind; /** * */ Wegas.Timer = Y.Base.create("wegas-timer", Y.Base, [], { start: function() { if (!this.handler) { this.handler = Y.later(this.get("duration"), this, this.timeOut); } return this; }, reset: function() { this.cancel(); return this.start(); }, cancel: function() { if (this.handler) { this.handler.cancel(); this.handler = null; } return this; }, timeOut: function() { this.cancel(); this.fire("timeOut"); return this; }, destructor: function() { this.cancel(); } }, { ATTRS: { duration: { value: 400 } } }); Y.Object.filter = function(o, fn) { var r = {}; Y.Object.each(o, function(i, k) { if (fn(i, k)) { r[k] = i; } }); return r; }; /** * asynchronous function queuing, chain asychronous operations * * @class Y.Wegas.Helper.Queue * @constructor */ Helper.Queue = (function() { /** * * @constructor Q * @returns {_L250.Q} */ var Q = function() { this._f = []; // function queue this._a = []; // arguments queue this._lock = false; }, doNext = function(queue) { var cb; if (queue._f.length && !queue._lock) { queue._lock = true; cb = queue._f.shift(); cb.apply(cb, [queue].concat(queue._a.shift())); } }; Q.prototype = { /*@lends Y.Wegas.Helper.Queue#*/ /** * Add a function to queue and runs it if lock is released. * Chainable. * @param {Function} cb callback function * @param {Any*} args additional arguments passed to callback function. * @returns {_L250.Q.prototype} */ add: function(cb, args) { if (typeof cb !== "function") { return this; } this._f.push(cb); this._a.push(Array.prototype.splice.call(arguments, 0, 1)); doNext(this); return this; }, /** * release lock and run next function if any. * @returns {undefined} */ next: function() { this._lock = false; doNext(this); }, /** * remove further callbacks. * Chainable. * @returns {_L254.Q.prototype} */ empty: function() { this._f.length = 0; this._a.length = 0; return this; } }; return Q; }()); Helper.Diacritics = (function() { /** * Map originally at * http://web.archive.org/web/20120918093154/http://lehelk.com/2011/05/06/script-to-remove-diacritics/ */ var DIACRITICS = { 'a': /[\u0061\u24D0\uFF41\u1E9A\u00E0\u00E1\u00E2\u1EA7\u1EA5\u1EAB\u1EA9\u00E3\u0101\u0103\u1EB1\u1EAF\u1EB5\u1EB3\u0227\u01E1\u00E4\u01DF\u1EA3\u00E5\u01FB\u01CE\u0201\u0203\u1EA1\u1EAD\u1EB7\u1E01\u0105\u2C65\u0250]/g, 'aa': /[\uA733]/g, 'ae': /[\u00E6\u01FD\u01E3]/g, 'ao': /[\uA735]/g, 'au': /[\uA737]/g, 'av': /[\uA739\uA73B]/g, 'ay': /[\uA73D]/g, 'b': /[\u0062\u24D1\uFF42\u1E03\u1E05\u1E07\u0180\u0183\u0253]/g, 'c': /[\u0063\u24D2\uFF43\u0107\u0109\u010B\u010D\u00E7\u1E09\u0188\u023C\uA73F\u2184]/g, 'd': /[\u0064\u24D3\uFF44\u1E0B\u010F\u1E0D\u1E11\u1E13\u1E0F\u0111\u018C\u0256\u0257\uA77A]/g, 'dz': /[\u01F3\u01C6]/g, 'e': /[\u0065\u24D4\uFF45\u00E8\u00E9\u00EA\u1EC1\u1EBF\u1EC5\u1EC3\u1EBD\u0113\u1E15\u1E17\u0115\u0117\u00EB\u1EBB\u011B\u0205\u0207\u1EB9\u1EC7\u0229\u1E1D\u0119\u1E19\u1E1B\u0247\u025B\u01DD]/g, 'f': /[\u0066\u24D5\uFF46\u1E1F\u0192\uA77C]/g, 'g': /[\u0067\u24D6\uFF47\u01F5\u011D\u1E21\u011F\u0121\u01E7\u0123\u01E5\u0260\uA7A1\u1D79\uA77F]/g, 'h': /[\u0068\u24D7\uFF48\u0125\u1E23\u1E27\u021F\u1E25\u1E29\u1E2B\u1E96\u0127\u2C68\u2C76\u0265]/g, 'hv': /[\u0195]/g, 'i': /[\u0069\u24D8\uFF49\u00EC\u00ED\u00EE\u0129\u012B\u012D\u00EF\u1E2F\u1EC9\u01D0\u0209\u020B\u1ECB\u012F\u1E2D\u0268\u0131]/g, 'j': /[\u006A\u24D9\uFF4A\u0135\u01F0\u0249]/g, 'k': /[\u006B\u24DA\uFF4B\u1E31\u01E9\u1E33\u0137\u1E35\u0199\u2C6A\uA741\uA743\uA745\uA7A3]/g, 'l': /[\u006C\u24DB\uFF4C\u0140\u013A\u013E\u1E37\u1E39\u013C\u1E3D\u1E3B\u017F\u0142\u019A\u026B\u2C61\uA749\uA781\uA747]/g, 'lj': /[\u01C9]/g, 'm': /[\u006D\u24DC\uFF4D\u1E3F\u1E41\u1E43\u0271\u026F]/g, 'n': /[\u006E\u24DD\uFF4E\u01F9\u0144\u00F1\u1E45\u0148\u1E47\u0146\u1E4B\u1E49\u019E\u0272\u0149\uA791\uA7A5]/g, 'nj': /[\u01CC]/g, 'o': /[\u006F\u24DE\uFF4F\u00F2\u00F3\u00F4\u1ED3\u1ED1\u1ED7\u1ED5\u00F5\u1E4D\u022D\u1E4F\u014D\u1E51\u1E53\u014F\u022F\u0231\u00F6\u022B\u1ECF\u0151\u01D2\u020D\u020F\u01A1\u1EDD\u1EDB\u1EE1\u1EDF\u1EE3\u1ECD\u1ED9\u01EB\u01ED\u00F8\u01FF\u0254\uA74B\uA74D\u0275]/g, 'oi': /[\u01A3]/g, 'ou': /[\u0223]/g, 'oo': /[\uA74F]/g, 'p': /[\u0070\u24DF\uFF50\u1E55\u1E57\u01A5\u1D7D\uA751\uA753\uA755]/g, 'q': /[\u0071\u24E0\uFF51\u024B\uA757\uA759]/g, 'r': /[\u0072\u24E1\uFF52\u0155\u1E59\u0159\u0211\u0213\u1E5B\u1E5D\u0157\u1E5F\u024D\u027D\uA75B\uA7A7\uA783]/g, 's': /[\u0073\u24E2\uFF53\u00DF\u015B\u1E65\u015D\u1E61\u0161\u1E67\u1E63\u1E69\u0219\u015F\u023F\uA7A9\uA785\u1E9B]/g, 'ss': /[\u1E9E]/g, 't': /[\u0074\u24E3\uFF54\u1E6B\u1E97\u0165\u1E6D\u021B\u0163\u1E71\u1E6F\u0167\u01AD\u0288\u2C66\uA787]/g, 'tz': /[\uA729]/g, 'u': /[\u0075\u24E4\uFF55\u00F9\u00FA\u00FB\u0169\u1E79\u016B\u1E7B\u016D\u00FC\u01DC\u01D8\u01D6\u01DA\u1EE7\u016F\u0171\u01D4\u0215\u0217\u01B0\u1EEB\u1EE9\u1EEF\u1EED\u1EF1\u1EE5\u1E73\u0173\u1E77\u1E75\u0289]/g, 'v': /[\u0076\u24E5\uFF56\u1E7D\u1E7F\u028B\uA75F\u028C]/g, 'vy': /[\uA761]/g, 'w': /[\u0077\u24E6\uFF57\u1E81\u1E83\u0175\u1E87\u1E85\u1E98\u1E89\u2C73]/g, 'x': /[\u0078\u24E7\uFF58\u1E8B\u1E8D]/g, 'y': /[\u0079\u24E8\uFF59\u1EF3\u00FD\u0177\u1EF9\u0233\u1E8F\u00FF\u1EF7\u1E99\u1EF5\u01B4\u024F\u1EFF]/g, 'z': /[\u007A\u24E9\uFF5A\u017A\u1E91\u017C\u017E\u1E93\u1E95\u01B6\u0225\u0240\u2C6C\uA763]/g, 'A': /[\u0041\u24B6\uFF21\u00C0\u00C1\u00C2\u1EA6\u1EA4\u1EAA\u1EA8\u00C3\u0100\u0102\u1EB0\u1EAE\u1EB4\u1EB2\u0226\u01E0\u00C4\u01DE\u1EA2\u00C5\u01FA\u01CD\u0200\u0202\u1EA0\u1EAC\u1EB6\u1E00\u0104\u023A\u2C6F]/g, 'AA': /[\uA732]/g, 'AE': /[\u00C6\u01FC\u01E2]/g, 'AO': /[\uA734]/g, 'AU': /[\uA736]/g, 'AV': /[\uA738\uA73A]/g, 'AY': /[\uA73C]/g, 'B': /[\u0042\u24B7\uFF22\u1E02\u1E04\u1E06\u0243\u0182\u0181]/g, 'C': /[\u0043\u24B8\uFF23\u0106\u0108\u010A\u010C\u00C7\u1E08\u0187\u023B\uA73E]/g, 'D': /[\u0044\u24B9\uFF24\u1E0A\u010E\u1E0C\u1E10\u1E12\u1E0E\u0110\u018B\u018A\u0189\uA779]/g, 'DZ': /[\u01F1\u01C4]/g, 'Dz': /[\u01F2\u01C5]/g, 'E': /[\u0045\u24BA\uFF25\u00C8\u00C9\u00CA\u1EC0\u1EBE\u1EC4\u1EC2\u1EBC\u0112\u1E14\u1E16\u0114\u0116\u00CB\u1EBA\u011A\u0204\u0206\u1EB8\u1EC6\u0228\u1E1C\u0118\u1E18\u1E1A\u0190\u018E]/g, 'F': /[\u0046\u24BB\uFF26\u1E1E\u0191\uA77B]/g, 'G': /[\u0047\u24BC\uFF27\u01F4\u011C\u1E20\u011E\u0120\u01E6\u0122\u01E4\u0193\uA7A0\uA77D\uA77E]/g, 'H': /[\u0048\u24BD\uFF28\u0124\u1E22\u1E26\u021E\u1E24\u1E28\u1E2A\u0126\u2C67\u2C75\uA78D]/g, 'I': /[\u0049\u24BE\uFF29\u00CC\u00CD\u00CE\u0128\u012A\u012C\u0130\u00CF\u1E2E\u1EC8\u01CF\u0208\u020A\u1ECA\u012E\u1E2C\u0197]/g, 'J': /[\u004A\u24BF\uFF2A\u0134\u0248]/g, 'K': /[\u004B\u24C0\uFF2B\u1E30\u01E8\u1E32\u0136\u1E34\u0198\u2C69\uA740\uA742\uA744\uA7A2]/g, 'L': /[\u004C\u24C1\uFF2C\u013F\u0139\u013D\u1E36\u1E38\u013B\u1E3C\u1E3A\u0141\u023D\u2C62\u2C60\uA748\uA746\uA780]/g, 'LJ': /[\u01C7]/g, 'Lj': /[\u01C8]/g, 'M': /[\u004D\u24C2\uFF2D\u1E3E\u1E40\u1E42\u2C6E\u019C]/g, 'N': /[\u004E\u24C3\uFF2E\u01F8\u0143\u00D1\u1E44\u0147\u1E46\u0145\u1E4A\u1E48\u0220\u019D\uA790\uA7A4]/g, 'NJ': /[\u01CA]/g, 'Nj': /[\u01CB]/g, 'O': /[\u004F\u24C4\uFF2F\u00D2\u00D3\u00D4\u1ED2\u1ED0\u1ED6\u1ED4\u00D5\u1E4C\u022C\u1E4E\u014C\u1E50\u1E52\u014E\u022E\u0230\u00D6\u022A\u1ECE\u0150\u01D1\u020C\u020E\u01A0\u1EDC\u1EDA\u1EE0\u1EDE\u1EE2\u1ECC\u1ED8\u01EA\u01EC\u00D8\u01FE\u0186\u019F\uA74A\uA74C]/g, 'OI': /[\u01A2]/g, 'OO': /[\uA74E]/g, 'OU': /[\u0222]/g, 'P': /[\u0050\u24C5\uFF30\u1E54\u1E56\u01A4\u2C63\uA750\uA752\uA754]/g, 'Q': /[\u0051\u24C6\uFF31\uA756\uA758\u024A]/g, 'R': /[\u0052\u24C7\uFF32\u0154\u1E58\u0158\u0210\u0212\u1E5A\u1E5C\u0156\u1E5E\u024C\u2C64\uA75A\uA7A6\uA782]/g, 'S': /[\u0053\u24C8\uFF33\u015A\u1E64\u015C\u1E60\u0160\u1E66\u1E62\u1E68\u0218\u015E\u2C7E\uA7A8\uA784]/g, 'T': /[\u0054\u24C9\uFF34\u1E6A\u0164\u1E6C\u021A\u0162\u1E70\u1E6E\u0166\u01AC\u01AE\u023E\uA786]/g, 'TZ': /[\uA728]/g, 'U': /[\u0055\u24CA\uFF35\u00D9\u00DA\u00DB\u0168\u1E78\u016A\u1E7A\u016C\u00DC\u01DB\u01D7\u01D5\u01D9\u1EE6\u016E\u0170\u01D3\u0214\u0216\u01AF\u1EEA\u1EE8\u1EEE\u1EEC\u1EF0\u1EE4\u1E72\u0172\u1E76\u1E74\u0244]/g, 'V': /[\u0056\u24CB\uFF36\u1E7C\u1E7E\u01B2\uA75E\u0245]/g, 'VY': /[\uA760]/g, 'W': /[\u0057\u24CC\uFF37\u1E80\u1E82\u0174\u1E86\u1E84\u1E88\u2C72]/g, 'X': /[\u0058\u24CD\uFF38\u1E8A\u1E8C]/g, 'Y': /[\u0059\u24CE\uFF39\u1EF2\u00DD\u0176\u1EF8\u0232\u1E8E\u0178\u1EF6\u1EF4\u01B3\u024E\u1EFE]/g, 'Z': /[\u005A\u24CF\uFF3A\u0179\u1E90\u017B\u017D\u1E92\u1E94\u01B5\u0224\u2C7F\u2C6B\uA762]/g }, isDiacriticsRE = (function() { var re = []; Y.Object.each(DIACRITICS, function(v) { re.push(v.source); }); return re.join("|"); }()), removeDiacritics = function(str) { Y.Object.each(DIACRITICS, function(v, k) { str = str.replace(v, k); }); return str; }; return { removeDiacritics: removeDiacritics, isDiacritics: isDiacriticsRE }; }()); });
/***************************** ACT I: THE SETUP 1. Hat guy 2. Lovers // then let's start escalating... ******************************/ function Stage_Start(self){ // Create Peeps self.world.clearPeeps(); self.world.addBalancedPeeps(20); } function Stage_Hat(self){ // A Hat Guy var hat = new HatPeep(self); self.world.addPeep(hat); // Director self.director.callbacks = { takePhoto: function(d){ // DECLARATIVE d.tryChyron(function(d){ var p = d.photoData; var caught = d.caught({ hat: {_CLASS_:"HatPeep"} }); if(caught.hat){ p.audience = 3; p.caughtHat = caught.hat; d.chyron = "OOH NICE HAT"; return true; } return false; }).otherwise(_chyPeeps); }, movePhoto: function(d){ d.audience_movePhoto(); }, cutToTV: function(d){ // If you did indeed catch a hat peep... var p = d.photoData; if(p.caughtHat){ self.world.addBalancedPeeps(1); // Add with moar! d.audience_cutToTV(function(peep){ peep.wearHat(); }); // make all viewers wear HATS! p.caughtHat.kill(); // Get rid of hat Stage_Lovers(self); // Next stage }else{ d.audience_cutToTV(); } } }; } function Stage_Lovers(self){ // LOVERS var lover1 = new LoverPeep(self); lover1.setType("circle"); var lover2 = new LoverPeep(self); lover2.setType("square"); lover2.follow(lover1); self.world.addPeep(lover1); self.world.addPeep(lover2); // Director self.director.callbacks = { takePhoto: function(d){ // MODULAR & DECLARATIVE d.tryChyron(_chyLovers) .otherwise(_chyHats) .otherwise(_chyPeeps); }, movePhoto: function(d){ d.audience_movePhoto(); }, cutToTV: function(d){ // MODULAR & DECLARATIVE d.tryCut2TV(_cutLovers) .otherwise(_cutHats) .otherwise(_cutPeeps); // And whatever happens, just go to the next stage // ACT II!!! Stage_Screamer(self); } }; } /////////////////////////////////////// /////////////////////////////////////// ////// DECLARATIVE CHYRON MODULES ///// /////////////////////////////////////// /////////////////////////////////////// function _chyLovers(d){ var p = d.photoData; var caught = d.caught({ lover: {_CLASS_:"LoverPeep"} }); if(caught.lover){ if(caught.lover.isEmbarrassed){ d.chyron = "yeah git on outta here"; }else{ p.caughtLovers = true; p.forceChyron = true; d.chyron = "GROSS, GO GET A ROOM"; } return true; } return false; } function _chyHats(d){ var p = d.photoData; var caught = d.caught({ hat: {_CLASS_:"NormalPeep", wearingHat:true} }); if(caught.hat){ p.audience = 1; p.caughtHat = true; d.chyron = "nvm hats aren't cool anymore"; return true; } return false; } function _chyPeeps(d){ var p = d.photoData; if(d.scene.camera.isOverTV(true)){ d.chyron = "A TV... ON TV!"; }else{ var caught = d.caught({ peeps: {_CLASS_:"NormalPeep", returnAll:true}, crickets: {_CLASS_:"Cricket", returnAll:true} }); if(caught.crickets.length>0){ p.CAUGHT_A_CRICKET = true; if(caught.crickets.length==1){ d.chyron = "LIL' CRICKY <3"; }else{ d.chyron = "okay that's too many crickets"; } }else if(caught.peeps.length>0){ if(caught.peeps.length==1){ d.chyron = "just a normal peep"; }else{ d.chyron = "just some normal peeps"; } }else{ p.ITS_NOTHING = true; d.chyron = "WOWWEE, IT'S NOTHING"; } } return true; } /////////////////////////////////////// /////////////////////////////////////// ///// DECLARATIVE CUTTING MODULES ///// /////////////////////////////////////// /////////////////////////////////////// function _cutLovers(d){ var p = d.photoData; if(p.caughtLovers){ // Crickets d.audience_cutToTV(); // MAKE LOVERS EMBARRASSED d.scene.world.peeps.filter(function(peep){ return peep._CLASS_=="LoverPeep"; }).forEach(function(lover){ lover.makeEmbarrassed(); }); return true; }else{ return false; } } function _cutHats(d){ var p = d.photoData; if(p.caughtHat){ // Only get the hat-wearers, make 'em take off the hat. d.audience_cutToTV( function(peep){ peep.takeOffHat(); }, function(peep){ return peep.wearingHat; } ); return true; }else{ // And if not, have them decrease by 1 each time anyway. var hatPeeps = d.scene.world.peeps.slice(0).filter(function(peep){ return peep.wearingHat; }); if(hatPeeps.length>0){ var randomIndex = Math.floor(Math.random()*hatPeeps.length); hatPeeps[randomIndex].takeOffHat(true); } return false; } } function _cutPeeps(d){ d.audience_cutToTV(); return true; }
'use strict'; describe("Divhide.Obj", function () { beforeEach(function () { jasmine.addMatchers(window.JasmineCustomMatchers); }); it("Divhide.Specs.ObjExample", function () { Divhide.Specs.ObjExample(); }); /** * * Tests for Obj.stringify() * */ describe("stringify", function () { /** * * Test toString() with a literal as argument * */ describe("stringify(literal)", function(){ it("String should return a valid string", function () { var val = Divhide.Obj.stringify("Oscar"); expect("\"Oscar\"").toBe(val); }); it("Number should return a valid string", function () { var val = Divhide.Obj.stringify(1); expect(val).toBe("1"); }); it("null should return a valid string", function () { var val = Divhide.Obj.stringify(null); expect(val).toBe("null"); }); it("undefined should return a valid string", function () { var val = Divhide.Obj.stringify(undefined); expect(val).toBe("undefined"); }); }); /** * * Test toString() with an object as the argument * */ describe("stringify(obj)", function(){ it("empty object should return a valid string", function () { var val = Divhide.Obj.stringify({}, { space: 0 }); expect(val).toBe("{}"); }); it("one level object should return a valid string", function () { var val = Divhide.Obj.stringify({ "firstName": "Oscar", "lastName": "Brito" }, { space: 0 }); expect(val) .toBe("{\"firstName\":\"Oscar\",\"lastName\":\"Brito\"}"); }); it("two level object should return a valid string", function () { var val = Divhide.Obj.stringify({ "firstName": { "value": "Oscar" }, "lastName": { "value": "Brito" } }, { space: 0 }); expect(val) .toBe("{\"firstName\":{\"value\":\"Oscar\"},\"lastName\":{\"value\":\"Brito\"}}"); }); it("with identation should return a valid string", function () { var val = Divhide.Obj.stringify({ "other": {}, "firstName": { "value": "Oscar" } }, { space: 2 }); expect(val).toBe("{\n" + " \"other\": {},\n" + " \"firstName\": {\n" + " \"value\": \"Oscar\"\n" + " }\n" + "}"); }); }); /** * * Test toString() with an array as argument * */ describe("stringify(array)", function(){ it("empty array should return a valid string", function () { var val = Divhide.Obj.stringify([], { space: 0 }); expect(val).toBe("[]"); }); it("one level array should return a valid string", function () { var val = Divhide.Obj.stringify([ "one", "two", 3 ], { space: 0 }); expect(val).toBe("[\"one\",\"two\",3]"); }); it("complex array should return a valid string", function () { var val = Divhide.Obj.stringify( ["one", ["two"]], { space: 0 }); expect(val).toBe("[\"one\",[\"two\"]]"); }); it("with identation should return a valid string", function () { var val = Divhide.Obj.stringify([ 1, [], [ 2, 3 ], ], { space: 2 }); expect(val).toBe( "[\n" + " 1,\n" + " [],\n" + " [\n" + " 2,\n" + " 3\n" + " ]\n" + "]"); }); }); /** * * Test toString() with different combination of * arguments. * */ describe("stringify(*)", function(){ it("array with complex combination should return a valid string", function () { var val = Divhide.Obj.stringify([ "one", { "2": "two", "3": "three", 4: [4] }, [ 5 ] ], { space: 0 }); expect(val) .toBe("[\"one\",{\"2\":\"two\",\"3\":\"three\",\"4\":[4]},[5]]"); }); it("object with complex combination should return a valid string", function () { var val = Divhide.Obj.stringify({ 1: 1, 2: [ 2 ], 3: { "value": "3" } }, { space: 0 }); expect(val) .toBe("{\"1\":1,\"2\":[2],\"3\":{\"value\":\"3\"}}"); }); it("array with identation should return a valid string", function () { var val = Divhide.Obj.stringify([ { name: "Oscar", age: 30, tags: [ "tag1", "tag2" ] }, { name: "Filipe", age: 31 }, ], { space: 2 }); expect(val).toBe( "[\n" + " {\n" + " \"name\": \"Oscar\",\n" + " \"age\": 30,\n" + " \"tags\": [\n" + " \"tag1\",\n" + " \"tag2\"\n" + " ]\n" + " },\n" + " {\n" + " \"name\": \"Filipe\",\n" + " \"age\": 31\n" + " }\n" + "]"); }); }); /** * Test stringify() annotations */ describe("annotate", function(){ it("literal should return a valid string", function(){ var val = Divhide.Obj.stringify(1, { space: 2, annotate: function(value, info){ return { before: "-> ", after: " /* A value */" }; } }); expect(val).toBe("-> 1 /* A value */"); }); it("object should return a valid string", function(){ var val = Divhide.Obj.stringify({ name: "Oscar", age: 30 }, { space: 2, annotate: function(value, info){ return { after: (value instanceof Object) ? " /* The one! */" : null }; } }); expect(val).toBe( "{\n" + " \"name\": \"Oscar\",\n" + " \"age\": 30\n" + "} /* The one! */"); }); it("object keys should return a valid string", function(){ var val = Divhide.Obj.stringify({ name: "Oscar", age: 30 }, { space: 2, annotate: function(value, info){ return { before: (value == "Oscar") ? "/* The name */ " : null, after: (value == "Oscar") ? " /* is so cool */" : null }; } }); expect(val).toBe( "{\n" + " \"name\": /* The name */ \"Oscar\", /* is so cool */\n" + " \"age\": 30\n" + "}"); }); it("array should return a valid string", function(){ var val = Divhide.Obj.stringify([{ name: "Oscar", age: 30 }], { space: 2, annotate: function(value, info){ return { after: (value instanceof Array) ? " /* The one! */" : null }; } }); expect(val).toBe( "[\n" + " {\n" + " \"name\": \"Oscar\",\n" + " \"age\": 30\n" + " }\n" + "] /* The one! */"); }); it("array item should return a valid string", function(){ var val = Divhide.Obj.stringify([{ name: "Oscar", age: 30 }], { space: 2, annotate: function(value, info){ return { after: (Divhide.Type.isObject(value)) ? " /* The one! */" : null }; } }); expect(val).toBe( "[\n" + " {\n" + " \"name\": \"Oscar\",\n" + " \"age\": 30\n" + " } /* The one! */\n" + "]"); }); }); }); });
'use strict'; angular.module('app').service('dialogService', [ '$q', function($q) { var remote = require('remote'); var dialog = remote.require('dialog'); function DialogService() {} DialogService.prototype.showOpenDialog = function() { var deferred = $q.defer(); dialog.showOpenDialog(function(fileNames) { return deferred.resolve(fileNames); }); return deferred.promise; }; DialogService.prototype.showSaveDialog = function() { var deferred = $q.defer(); dialog.showSaveDialog(function(fileNames) { return deferred.resolve(fileNames); }); return deferred.promise; }; return new DialogService(); } ]);
angular.module('authService', []) .factory('AuthService', ['$q', '$timeout', '$http', '$rootScope', function ($q, $timeout, $http, $rootScope) { // create user variable var user = null; // return available functions for use in the controllers return ({ isLoggedIn: isLoggedIn, getUserStatus: getUserStatus, login: login, logout: logout, register: register, getRegUsers: getRegUsers, deleteUser: deleteUser }); function isLoggedIn() { return user; } function getUserStatus() { return $http.get('/user/status') // handle success .success(function (data) { user = data.status; }) // handle error .error(function (data) { user = false; }); } function login(username, password) { // create a new instance of deferred var deferred = $q.defer(); // send a post request to the server $http.post('/user/login', {username: username, password: password}) // handle success .success(function (data, status) { if (status === 200 && data.status) { user = true; $rootScope.user = data.user; window.sessionStorage["userInfo"] = JSON.stringify(data.user); $rootScope.userInfo = JSON.parse(window.sessionStorage["userInfo"]); window.sessionStorage["user"] = data.user; deferred.resolve(data.user); } else { user = false; deferred.reject(); } }) // handle error .error(function (data) { user = false; deferred.reject(); }); // return promise object return deferred.promise; } function logout() { // create a new instance of deferred var deferred = $q.defer(); // send a get request to the server $http.get('/user/logout') // handle success .success(function (data) { user = false; deferred.resolve(); }) // handle error .error(function (data) { user = false; deferred.reject(); }); // return promise object return deferred.promise; } function register(regUser) { // create a new instance of deferred var deferred = $q.defer(); // send a post request to the server $http.post('/user/signup', regUser) // handle success .success(function (data, status) { if (status === 200 && data.status) { deferred.resolve(); } else { deferred.reject(); } }) // handle error .error(function (data) { deferred.reject(); }); // return promise object return deferred.promise; } function getRegUsers() { var deferred = $q.defer(); $http.get('/user/allUsers') .success(function (data, status) { if (status === 200) { $rootScope.regUsers = data; deferred.resolve(); } else { deferred.reject(); } }) // handle error .error(function () { deferred.reject(); }); // return promise object return deferred.promise; } function deleteUser(id) { var deferred = $q.defer(); $http.delete('/user/deleteUser', {params: {username: id}}) .success(function (data, status) { if (status === 200) { deferred.resolve(); } }) // handle error .error(function () { deferred.reject(); }); return deferred.promise; } } ] );
(function() { 'use strict'; /** * idHeader * * This component renders the application header. */ angular .module('app.components') .component('idHeader', header()); /** * Internal function that returns the component. * @returns {object} the angular component */ function header() { return { templateUrl: 'app/components/header.component.html', controller: HeaderCtrl, controllerAs: 'vm' }; } /** * Constructor function for the component's controller. * @constructor */ HeaderCtrl.$inject = ['$state', 'eventingService', 'authService']; function HeaderCtrl($state, eventingService, authService) { var vm = this; // lifecycle hooks vm.$onInit = onInit; // scope functions vm.executeSearch = executeSearch; vm.goToIdeas = goToIdeas; vm.goToPeople = goToPeople; vm.goToAccount = goToAccount; vm.logout = logout; vm.clearSearchValue = clearSearchValue; ///////////////////// /** * Initializes the component. */ function onInit() { var currentUser = authService.currentUser(); if (currentUser) { vm.currentUserName = currentUser.firstName + ' ' + currentUser.lastName; } vm.headerVisible = true; vm.searchValue = ''; vm.searchResultsVisible = false; eventingService.registerListener('accountChange', 'header', function(user) { vm.currentUserName = !user ? '' : user.firstName + ' ' + user.lastName; }); } /** * Executes a search. */ function executeSearch() { vm.searchResultsVisible = true; } /** * Navigates to the Ideas view. */ function goToIdeas() { $state.go('ideas'); } /** * Navigates to the People view. */ function goToPeople() { $state.go('people'); } /** * Navigates to the Account view. */ function goToAccount() { $state.go('account'); } /** * Logs the current user out of the application. */ function logout() { authService.logout() .then(function() { $state.go('login'); }); } /** * Clears the search text field. */ function clearSearchValue() { vm.searchValue = ''; } } })();
var files = [ [ "API", "dir_19ea4dbfe8f0e4681f60b9b97f7b5d11.html", "dir_19ea4dbfe8f0e4681f60b9b97f7b5d11" ] ];
/*global angular */ /** * The main controller for the app. The controller: * - retrieves and persists the model via the todoStorage service * - exposes the model to the template and provides event handlers */ angular.module('todomvc') .controller('TodoCtrl', function TodoCtrl($scope, $routeParams, $filter, store) { 'use strict'; var todos = $scope.todos = store.todos; $scope.newTodo = ''; $scope.editedTodo = null; $scope.$watch('todos', function () { $scope.remainingCount = $filter('filter')(todos, { completed: false }).length; $scope.completedCount = todos.length - $scope.remainingCount; $scope.allChecked = !$scope.remainingCount; }, true); // Monitor the current route for changes and adjust the filter accordingly. $scope.$on('$routeChangeSuccess', function () { var status = $scope.status = $routeParams.status || ''; $scope.statusFilter = (status === 'active') ? { completed: false } : (status === 'completed') ? { completed: true } : ''; }); $scope.addTodo = function () { var newTodo = { title: $scope.newTodo.trim(), completed: false }; if (!newTodo.title) { return; } $scope.saving = true; store.insert(newTodo) .then(function success() { $scope.newTodo = ''; }) .finally(function () { $scope.saving = false; }); }; $scope.editTodo = function (todo) { $scope.editedTodo = todo; // Clone the original todo to restore it on demand. $scope.originalTodo = angular.extend({}, todo); }; $scope.saveEdits = function (todo, event) { // Blur events are automatically triggered after the form submit event. // This does some unfortunate logic handling to prevent saving twice. if (event === 'blur' && $scope.saveEvent === 'submit') { $scope.saveEvent = null; return; } $scope.saveEvent = event; if ($scope.reverted) { // Todo edits were reverted-- don't save. $scope.reverted = null; return; } todo.title = todo.title.trim(); if (todo.title === $scope.originalTodo.title) { $scope.editedTodo = null; return; } store[todo.title ? 'put' : 'delete'](todo) .then(function success() {}, function error() { todo.title = $scope.originalTodo.title; }) .finally(function () { $scope.editedTodo = null; }); }; $scope.revertEdits = function (todo) { todos[todos.indexOf(todo)] = $scope.originalTodo; $scope.editedTodo = null; $scope.originalTodo = null; $scope.reverted = true; }; $scope.removeTodo = function (todo) { store.delete(todo); }; $scope.saveTodo = function (todo) { store.put(todo); }; $scope.toggleCompleted = function (todo, completed) { if (angular.isDefined(completed)) { todo.completed = completed; } store.put(todo, todos.indexOf(todo)) .then(function success() {}, function error() { todo.completed = !todo.completed; }); }; $scope.clearCompletedTodos = function () { store.clearCompleted(); }; $scope.markAll = function (completed) { todos.forEach(function (todo) { if (todo.completed !== completed) { $scope.toggleCompleted(todo, completed); } }); }; });
version https://git-lfs.github.com/spec/v1 oid sha256:bdecbb5008fcaa6e28cdb99aada4e0c3dc8dfa6bd53bb4d6e63005c7538ee886 size 30020
// Load required packages var express = require('express'); var triggerPageController = require('../controllers/triggerPage'); // Create our Express router var router = express.Router(); // Create endpoint handlers for trigger pages router.route('/q/:code') .get(triggerPageController.getTriggerPagesQr); router.route('/n/:code') .get(triggerPageController.getTriggerPagesNfc); router.route('/s/:code') .get(triggerPageController.getTriggerPagesShort); module.exports = router;
GridRenderer.prototype.extend( { });
/** * Created by admin on 16/10/11. */ var a=12,b=12,c=12;console.log(a,b,c,'hello')
export default { port: 1989 }
var breadcrumbs=[['-1',"",""],['2',"SOLUTION-WIDE PROPERTIES Reference","topic_0000000000000C16.html"],['655',"Tlece.Recruitment.Entities Namespace","topic_0000000000000265.html"],['1080',"tlece_ProductPurchased Class","topic_00000000000003F3.html"],['1081',"Properties","topic_00000000000003F3_props--.html"],['1094',"ProductId Property","topic_00000000000003F7.html"]];
var mongoose = require('mongoose'); var Post = require('../models/Post').Post; var config = require('../config'); var http = require('http'); var site = ""; var token = ""; var options = { host: 'data.zz.baidu.com', path: '/urls?site=' + site + '&token=' + token, method: 'POST', headers: { 'Accept': '*/*', 'Connection': 'Keep-Alive', 'User-Agent': 'curl/7.12.1 ' } }; var callback = function (res) { var buffers = []; var nread = 0; res.on('data', function (chunk) { buffers.push(chunk); nread += chunk.length; }); res.on('end', function () { console.log(buffers); }); } var req = http.request(options, callback); mongoose.connect(config.db.production); var db = mongoose.connection; db.once('open', function (callback) { Post.find({}, {pid: 1}) .exec(function (err, posts) { var urls = posts.map(function (post) { return 'http://' + config.site.url + '/post/' + post.pid; }); var data = urls.join('\n'); console.log(data,urls.length); req.write(data); req.end(); }); });
const { shallow, mount } = require('enzyme'); const React = require('react'); function Fixture() { return ( <div id="root"> <span id="child">Test</span> </div> ); } describe('toHaveHTML', () => { it('works with `shallow` renders', () => { const wrapper = shallow(<Fixture />); expect(wrapper.find('#child')).toHaveHTML( '<span id="child">Test</span>' ); }); it('works with `mount` renders', () => { const wrapper = mount(<Fixture />); expect(wrapper.find('#child')).toHaveHTML( '<span id="child">Test</span>' ); }); it('normalizes the quotations used', () => { const wrapper = shallow(<Fixture />); expect(wrapper.find('#child')).toHaveHTML( '<span id="child">Test</span>' ); expect(wrapper.find('#child')).toHaveHTML( '<span id=\'child\'>Test</span>' ); }); it('works with with jasmines negation', () => { const wrapper = shallow(<Fixture />); expect(wrapper.find('#child')).not.toHaveHTML('foo'); }); });
function test(chart) { // Set hoverPoint chart.series[0].points[2].onMouseOver(); }
describe("Related Assets", function(){ let project = require('../fixture') let subject = project.documents.at('assets/data-source-spec') it("relates assets across different content collections", function(){ subject.related.data_sources.length.should.equal(2) }) it("provides a related data summary", function(){ subject.relatedData.should.have.property('nested') subject.relatedData.nested.should.have.property('data') subject.relatedData.nested.data.should.have.property('explanation') subject.relatedData.nested.data.explanation.length.should.not.equal(0) }) })
var path = require('path'); var webpack = require('webpack'); var WebpackCleanupPlugin = require("webpack-cleanup-plugin"); module.exports = { entry: './react/index.jsx', output: { path: __dirname + '/www', filename: 'bundle.js' }, module: { loaders: [ { test: /\.scss$/, loaders: ["style", "css", "resolve-url", "sass?sourceMap"] }, { test: /.jsx?$/, loader: 'babel-loader', exclude: /node_modules/, query: { presets: ['es2015', "es2016", "es2017", "react"], plugins: ["transform-class-properties"] } } ] }, plugins: [ new WebpackCleanupPlugin({   exclude: ["index.html"], //Include any important stuff here })   ] }
'use strict'; var yeoman = require('yeoman-generator'); var yosay = require('yosay'); var chalk = require('chalk'); var _ = require('lodash'); module.exports = yeoman.generators.Base.extend({ /** * Constructor * @return {undefined} */ constructor: function () { yeoman.generators.Base.apply(this, arguments); this.option('skip-install', { desc: 'Skips the installation of dependencies', type: Boolean }); }, /** * Prompt the user * @return {undefined} */ prompting: function () { var done = this.async(); this.log('Welcome to ' + chalk.red('uniform') + '. The fullstack form generator tool. Built with love. By developers, for developers.'); var prompts = [{ type: 'input', name: 'configFile', message: 'What\'s the name of your config file?', default: 'uniform.json' }]; this.prompt(prompts, function (answers) { this.uniformConfig = require(this.destinationPath(answers.configFile)); done(); }.bind(this)); }, /** * Writing * @type {Object} */ writing: { /** * package.json * @return {undefined} */ packageJSON: function() { this.template('_package.json', 'package.json'); }, /** * Git * @return {undefined} */ git: function() { this.copy('gitignore', '.gitignore'); }, /** * Bower * @return {undefined} */ bower: function() { this.template('_bower.json', 'bower.json'); this.copy('bowerrc', '.bowerrc'); }, /** * Main app * @return {undefined} */ app: function() { // root level folders this.mkdir('bin'); this.mkdir('public'); this.mkdir('public/components'); this.mkdir('routes'); this.mkdir('views'); // Main route this.template('routes/apiV1.js', 'routes/apiV1.js'); // Node error view this.copy('views/error.jade', 'views/error.jade'); // app files this.copy('bin/www', 'bin/www'); this.copy('app.js', 'app.js'); }, /** * Images * @return {undefined} */ img: function() { this.mkdir('public/img'); }, /** * Javascript * @return {undefined} */ javascript: function() { this.mkdir('public/js'); this.mkdir('public/js/forms'); this.mkdir('public/js/models'); this.mkdir('public/js/routers'); this.mkdir('public/js/views'); // Forms this.copy('public/js/forms/entryform.js', 'public/js/forms/entryform.js'); // Models this.template('public/js/models/_entry.js', 'public/js/models/entry.js'); // Routers this.copy('public/js/routers/default.js', 'public/js/routers/default.js'); // Views this.copy('public/js/views/landingView.js', 'public/js/views/landingView.js'); this.copy('public/js/views/successView.js', 'public/js/views/successView.js'); // Main js file this.copy('public/js/main.js', 'public/js/main.js'); }, /** * [styles description] * @return {[type]} [description] */ styles: function() { this.mkdir('public/css'); this.copy('public/css/main.styl', 'public/css/main.styl'); }, /** * Templates * @return {undefined} */ templates: function() { this.mkdir('public/templates'); this.template('public/templates/landing.hbs', 'public/templates/landing.hbs'); this.template('public/templates/form.hbs', 'public/templates/form.hbs'); this.copy('public/templates/success.hbs', 'public/templates/success.hbs'); }, /** * Dist * @return {undefined} */ dist: function() { // Directories this.mkdir('public/dist'); this.mkdir('public/dist/css'); this.mkdir('public/dist/js'); this.mkdir('public/dist/templates'); }, /** * HTML * @return {undefined} */ html: function() { this.copy('public/index.html', 'public/index.html'); }, /** * Misc files * @return {undefined} */ miscFiles: function() { this.copy('public/.editorconfig', 'public/.editorconfig'); this.copy('public/.gitattributes', 'public/.gitattributes'); this.copy('public/.gitignore', 'public/.gitignore'); this.copy('public/.htaccess', 'public/.htaccess'); this.copy('public/apple-touch-icon.png', 'public/apple-touch-icon.png'); this.copy('public/browserconfig.xml', 'public/browserconfig.xml'); this.copy('public/crossdomain.xml', 'public/crossdomain.xml'); this.copy('public/favicon.ico', 'public/favicon.ico'); this.copy('public/LICENSE.txt', 'public/LICENSE.txt'); this.copy('public/robots.txt', 'public/robots.txt'); this.copy('public/tile-wide.png', 'public/tile-wide.png'); this.copy('public/tile.png', 'public/tile.png'); }, /** * Gulp * @return {undefined} */ gulp: function() { this.copy('gulpfile.js', 'gulpfile.js'); } }, /** * Install Dependencies * @return {undefined} */ install: function() { this.installDependencies({ skipInstall: this.options['skip-install'] }); } });
'use strict' require('./controllers/listCtrl.js'); require('./controllers/loginCtrl.js'); require('./services/pageService.js'); angular.module('app.router', ['ui.router', 'app.list', 'app.login']) .config(configFn); configFn.$inject = ['$locationProvider', '$stateProvider', '$urlRouterProvider']; function configFn($locationProvider, $stateProvider, $urlRouterProvider){ $urlRouterProvider.when('', '/'); $urlRouterProvider.otherwise("/404"); $stateProvider .state('list', { url: "/", template: require('ng-cache!./views/list.html'), // controller: 'listCtrl' }) .state('signin', { url: "/login", template: require('ng-cache!./views/login.html'), // controller: 'loginCtrl' }) .state('404', { url: "/404", template: require('ng-cache!./views/404.html'), controller: function(pageService) { pageService.setTitle('404'); } }); }
/** * Created by josip on 20.1.2017.. */ angular.module('mainModule').config(function($routeProvider, $locationProvider){ $routeProvider .when('/', { templateUrl: '/home/home.view.html', controller: 'homeCtrl', controllerAs: 'vm' }) .when('/register', { templateUrl: '/register/register.view.html', controller: 'registerCtrl', controllerAs: 'vm' }) .when('/login', { templateUrl: '/login/login.view.html', controller: 'loginCtrl', controllerAs: 'vm' }) .when('/profile', { templateUrl: '/profile/profile.view.html', controller: 'profileCtrl', controllerAs: 'vm' }) .when('/forgot-password', { templateUrl: '/forgot-password/forgot.password.view.html', controller: 'forgotPassCtrl', controllerAs: 'vm' }) .when('/measurement',{ templateUrl:'/measurement/measurement.view.html', controller: 'measurementCtrl', controllerAs: 'vm' }) .otherwise({redirectTo: '/'}); // use the HTML5 History API $locationProvider.html5Mode(true); });
import './mc-project-settings.component'; import './project-settings.service';
define(function(require) { 'use strict'; const _ = require('underscore'); const $ = require('jquery'); const __ = require('orotranslation/js/translator'); const BaseView = require('oroui/js/app/views/base/view'); const Confirmation = require('oroui/js/delete-confirmation'); const AttributeFormOptionRowView = BaseView.extend({ tagName: 'tr', events: { 'click .delete-form-option': 'triggerRemove', 'click .edit-form-option': 'triggerEdit' }, options: { template: null, data: { label: null, property_path: null, required: false } }, /** * @inheritDoc */ constructor: function AttributeFormOptionRowView(options) { AttributeFormOptionRowView.__super__.constructor.call(this, options); }, /** * @inheritDoc */ initialize: function(options) { this.options = _.defaults(options || {}, this.options); const template = this.options.template || $('#attribute-form-option-row-template').html(); this.template = _.template(template); }, update: function(data) { this.options.data = data; this.render(); }, triggerEdit: function(e) { e.preventDefault(); this.trigger('editFormOption', this.options.data); }, triggerRemove: function(e) { e.preventDefault(); const confirm = new Confirmation({ content: __('Are you sure you want to delete this field?') }); confirm.on('ok', _.bind(function() { this.trigger('removeFormOption', this.options.data); }, this)); confirm.open(); }, getTemplateData: function() { return this.options.data; } }); return AttributeFormOptionRowView; });
import 'whatwg-fetch'; export default function post(url, data) { return fetch(url, { method: "POST", body: JSON.stringify(data), headers: { "Content-Type": "application/json" }, credentials: "same-origin" }).then(function (response) { response.status //=> number 100–599 response.statusText //=> String response.headers //=> Headers response.url //=> String return response.text() }, function (error) { error.message //=> String }); }
// Write your tests here! // Here is an example. Tinytest.add('Pixedelic Slideshow started', function (test) { test.isNotNull($('#target').camera, 'camera should exist'); test.equal(true, true); });
/** * Created by rg12 on 02/05/2016. */ /** * @desc Add to uib-timepicker to fix timezone issues * @example <uib-timepicker cp-widget-datetimepicker-patch></uib-timepicker> */ (function () { 'use strict'; angular .module('app.widgets') .directive('cpWidgetDatetimepickerPatch', cpWidgetDatetimepickerPatch); function cpWidgetDatetimepickerPatch() { return { restrict: 'A', priority: 1, require: 'ngModel', link: function (scope, element, attrs, ctrl) { ctrl.$formatters.push(function (value) { var date = new Date(value); date = new Date(date.getTime() + (60000 * date.getTimezoneOffset())); return date; }); ctrl.$parsers.push(function (value) { var date = new Date(value.getTime() - (60000 * value.getTimezoneOffset())); return date; }); } }; } })();
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js (function(global) { global.ng = global.ng || {}; global.ng.common = global.ng.common || {}; global.ng.common.locales = global.ng.common.locales || {}; const u = undefined; function plural(n) { let i = Math.floor(Math.abs(n)), v = n.toString().replace(/^[^.]*\.?/, '').length; if (i === 1 && v === 0) return 1; return 5; } root.ng.common.locales['de-be'] = [ 'de-BE', [['AM', 'PM'], u, u], u, [ ['S', 'M', 'D', 'M', 'D', 'F', 'S'], ['So.', 'Mo.', 'Di.', 'Mi.', 'Do.', 'Fr.', 'Sa.'], ['Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag'], ['So.', 'Mo.', 'Di.', 'Mi.', 'Do.', 'Fr.', 'Sa.'] ], [ ['S', 'M', 'D', 'M', 'D', 'F', 'S'], ['So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa'], ['Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag'], ['So.', 'Mo.', 'Di.', 'Mi.', 'Do.', 'Fr.', 'Sa.'] ], [ ['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'], [ 'Jan.', 'Feb.', 'März', 'Apr.', 'Mai', 'Juni', 'Juli', 'Aug.', 'Sept.', 'Okt.', 'Nov.', 'Dez.' ], [ 'Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember' ] ], [ ['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'], ['Jan', 'Feb', 'Mär', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dez'], [ 'Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember' ] ], [['v. Chr.', 'n. Chr.'], u, u], 1, [6, 0], ['dd.MM.yy', 'dd.MM.y', 'd. MMMM y', 'EEEE, d. MMMM y'], ['HH:mm', 'HH:mm:ss', 'HH:mm:ss z', 'HH:mm:ss zzzz'], ['{1}, {0}', u, '{1} \'um\' {0}', u], [',', '.', ';', '%', '+', '-', 'E', '·', '‰', '∞', 'NaN', ':'], ['#,##0.###', '#,##0 %', '#,##0.00 ¤', '#E0'], '€', 'Euro', { 'ATS': ['öS'], 'AUD': ['AU$', '$'], 'BGM': ['BGK'], 'BGO': ['BGJ'], 'CUC': [u, 'Cub$'], 'DEM': ['DM'], 'FKP': [u, 'Fl£'], 'GNF': [u, 'F.G.'], 'KMF': [u, 'FC'], 'RON': [u, 'L'], 'RWF': [u, 'F.Rw'], 'SYP': [], 'THB': ['฿'], 'TWD': ['NT$'], 'XXX': [], 'ZMW': [u, 'K'] }, plural, [ [ ['Mitternacht', 'morgens', 'vorm.', 'mittags', 'nachm.', 'abends', 'nachts'], u, ['Mitternacht', 'morgens', 'vormittags', 'mittags', 'nachmittags', 'abends', 'nachts'] ], [ ['Mitternacht', 'Morgen', 'Vorm.', 'Mittag', 'Nachm.', 'Abend', 'Nacht'], u, ['Mitternacht', 'Morgen', 'Vormittag', 'Mittag', 'Nachmittag', 'Abend', 'Nacht'] ], [ '00:00', ['05:00', '10:00'], ['10:00', '12:00'], ['12:00', '13:00'], ['13:00', '18:00'], ['18:00', '24:00'], ['00:00', '05:00'] ] ] ]; })(typeof globalThis !== 'undefined' && globalThis || typeof global !== 'undefined' && global || typeof window !== 'undefined' && window);
(function() { 'use strict'; function MediaGridDirective($filter, mediaHelper) { function link(scope, el, attr, ctrl) { var itemDefaultHeight = 200; var itemDefaultWidth = 200; var itemMaxWidth = 200; var itemMaxHeight = 200; var itemMinWidth = 125; var itemMinHeight = 125; function activate() { if (scope.itemMaxWidth) { itemMaxWidth = scope.itemMaxWidth; } if (scope.itemMaxHeight) { itemMaxHeight = scope.itemMaxHeight; } if (scope.itemMinWidth) { itemMinWidth = scope.itemMinWidth; } if (scope.itemMinWidth) { itemMinHeight = scope.itemMinHeight; } for (var i = 0; scope.items.length > i; i++) { var item = scope.items[i]; setItemData(item); setOriginalSize(item, itemMaxHeight); } if (scope.items.length > 0) { setFlexValues(scope.items); } } function setItemData(item) { item.isFolder = !mediaHelper.hasFilePropertyType(item); if (!item.isFolder) { item.thumbnail = mediaHelper.resolveFile(item, true); item.image = mediaHelper.resolveFile(item, false); } } function setOriginalSize(item, maxHeight) { //set to a square by default item.width = itemDefaultWidth; item.height = itemDefaultHeight; item.aspectRatio = 1; var widthProp = _.find(item.properties, function(v) { return (v.alias === "umbracoWidth"); }); if (widthProp && widthProp.value) { item.width = parseInt(widthProp.value, 10); if (isNaN(item.width)) { item.width = itemDefaultWidth; } } var heightProp = _.find(item.properties, function(v) { return (v.alias === "umbracoHeight"); }); if (heightProp && heightProp.value) { item.height = parseInt(heightProp.value, 10); if (isNaN(item.height)) { item.height = itemDefaultWidth; } } item.aspectRatio = item.width / item.height; // set max width and height // landscape if (item.aspectRatio >= 1) { if (item.width > itemMaxWidth) { item.width = itemMaxWidth; item.height = itemMaxWidth / item.aspectRatio; } // portrait } else { if (item.height > itemMaxHeight) { item.height = itemMaxHeight; item.width = itemMaxHeight * item.aspectRatio; } } } function setFlexValues(mediaItems) { var flexSortArray = mediaItems; var smallestImageWidth = null; var widestImageAspectRatio = null; // sort array after image width with the widest image first flexSortArray = $filter('orderBy')(flexSortArray, 'width', true); // find widest image aspect ratio widestImageAspectRatio = flexSortArray[0].aspectRatio; // find smallest image width smallestImageWidth = flexSortArray[flexSortArray.length - 1].width; for (var i = 0; flexSortArray.length > i; i++) { var mediaItem = flexSortArray[i]; var flex = 1 / (widestImageAspectRatio / mediaItem.aspectRatio); if (flex === 0) { flex = 1; } var imageMinFlexWidth = smallestImageWidth * flex; var flexStyle = { "flex": flex + " 1 " + imageMinFlexWidth + "px", "max-width": mediaItem.width + "px", "min-width": itemMinWidth + "px", "min-height": itemMinHeight + "px" }; mediaItem.flexStyle = flexStyle; } } scope.clickItem = function(item, $event, $index) { if (scope.onClick) { scope.onClick(item, $event, $index); } }; scope.clickItemName = function(item, $event, $index) { if (scope.onClickName) { scope.onClickName(item, $event, $index); $event.stopPropagation(); } }; scope.hoverItemDetails = function(item, $event, hover) { if (scope.onDetailsHover) { scope.onDetailsHover(item, $event, hover); } }; var unbindItemsWatcher = scope.$watch('items', function(newValue, oldValue) { if (angular.isArray(newValue)) { activate(); } }); scope.$on('$destroy', function() { unbindItemsWatcher(); }); } var directive = { restrict: 'E', replace: true, templateUrl: 'views/components/umb-media-grid.html', scope: { items: '=', onDetailsHover: "=", onClick: '=', onClickName: "=", filterBy: "=", itemMaxWidth: "@", itemMaxHeight: "@", itemMinWidth: "@", itemMinHeight: "@" }, link: link }; return directive; } angular.module('umbraco.directives').directive('umbMediaGrid', MediaGridDirective); })();
'use strict'; // Declare app level module which depends on views, and components var ntApp = angular.module('ntApp', [ //'ngRoute', 'ui.router', 'ntApp.myDesigns', 'ntApp.designDetail', 'ntApp.myInfo', 'ntApp.couponList', 'ntApp.createDesign', 'ntApp.activities', 'ntApp.management', 'ui.bootstrap', 'angularFileUpload', 'angular-carousel', //'ngDragDrop', 'angular-gestures', 'angular-md5' //'ngAnimate' ]); /*ntApp.config(['$routeProvider', function($routeProvider) { //ntApp.registerCtrl = $controllerProvider.register; $routeProvider // .when('/myDesigns', { // templateUrl: 'views/myDesigns.html', // //controller: 'MyDesignsListCtrl' // resolve: controller('myDesigns') // }) // .when('/design/:designId', { // templateUrl: 'views/designDetail.html', // //controller: 'DesignDetailCtrl' // resolve: controller('designDetail') // }) .otherwise({ redirectTo: '/myDesigns' }); }]);*/ ntApp.config(function ($stateProvider, $urlRouterProvider) { $urlRouterProvider.otherwise("myDesigns"); // // Now set up the states $stateProvider .state('myInfo', { url: "/myInfo", templateUrl: 'views/myInfo.html', controller: 'MyInfoCtrl' }) .state('couponList', { url: "/couponList", templateUrl: 'views/couponList.html', controller: 'CouponListCtrl' }) .state('management', { url: "/temp/management", templateUrl: 'views/management.html', controller: 'ManagementControl' }) .state('activities', { url: "/activities", templateUrl: 'views/activities.html', controller: 'ActivitiesControl' }) .state('orderListAuth', { url: '/orderListAuth', template: '<div></div>', controller: function($window, $location) { if (!sTempCode) { $window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + 'wxf26855bd0cda23bd' + '&redirect_uri=' + encodeURIComponent('http://design.weavesfun.com/#/orderList') + '&response_type=code&scope=snsapi_base&state=mine#wechat_redirect'; } } }); });
describe("Fragments", function () { it('replace node with fragment', function () { var node = render( d('div', null, 'Hello', d('div', null, 'World') ), document.body); compare(node.dom, div(text('Hello'), div(text('World')))); node = update(node, d('div', null, d('@', null, 1, 2, 3), 'Boom' )); compare(node.dom, udiv(text(1), text(2), text(3), text('Boom'))); }); it('replace fragment with fragment', function () { var node = render( d('div', null, 'Hello', d('@', null, 1, 2, 3), 'World' ), document.body); compare(node.dom, div(text('Hello'), text(1), text(2), text(3), text('World'))); node = update(node, d('div', null, 'Hello', d('@', null, 4, 5, 6), 'World' )); compare(node.dom, udiv(utext('Hello'), utext(4), utext(5), utext(6), utext('World'))); }); it('replace deep fragment with deep fragment', function () { var node = render( d('div', null, 'Hello', 0, d('@', null, 1, d('@', null, 4, d('@', null, 7, 8), 5), 3), 'World'), document.body); compare(node.dom, div(text('Hello'), text(0), text(1), text(4), text(7), text(8), text(5), text(3), text('World'))); node = update(node, d('div', null, 'Hello', d('@', null, 3, 4), d('@', null, 1, d('@', null, d('@', null, 7, 8), 4, 5), 3), 'World')); compare(node.dom, udiv(utext('Hello'), text(3), text(4), utext(1), text(7), text(8), text(4), utext(5), utext(3), utext('World'))); }); it("replace fragment with node", function () { var node = render( d('div', null, d('@', null, 1, d('@', null, 4, 5, 6), 3 )), document.body); compare(node.dom, div(text(1), text(4), text(5), text(6), text(3))); node = update(node, d('div', null, d('@', null, 1, 2, 3))); compare(node.dom, udiv(utext(1), text(2), utext(3))); }); it("set attrs", function () { var node = render( d('div', null, d('@', {class: 'cls'}, 1, 2)), document.body); compare(node.dom, div(text(1), text(2))); node = update(node, d('div', null, d('@', {class: 'cls'}, 1, 2))); compare(node.dom, udiv(utext(1), utext(2))); }); });
function supports_html5_storage() { try { return 'localStorage' in window && window['localStorage'] !== null; } catch (e) { return false; } } function randomString(length) { var text = ""; var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; for(var i=0; i < length; i++) { text += chars.charAt(Math.floor(Math.random() * chars.length)); } return text; } function register(baseUrl, username, email, password) { var deferred = new $.Deferred(); if (username && email && password) { challenge = randomString(10) encrypted_challenge = sjcl.encrypt(password, challenge) $.when( $.ajax({ type: "POST", url: baseUrl, data: { "username" : username, "email" : email, "challenge" : challenge, "encrypted_challenge" : encrypted_challenge } }) ).done(function() { deferred.resolve("Registration completed"); }).fail(function() { deferred.reject("Registration failed"); }); } else { deferred.reject("Invalid parameters"); } return deferred.promise(); } function login(baseUrl, username, password) { var deferred = new $.Deferred(); if (username && password) { $.when( $.ajax({ type: "GET", url: baseUrl + "?username=" + username, }) ).then(function(data) { return sjcl.decrypt(password, data) }).then(function(challenge) { return $.ajax({ type: "POST", url: baseUrl, data: { "username" : username, "challenge" : challenge, } }) }).then(function(rsa_public) { if (supports_html5_storage()) { localStorage.setItem("rsa_public", rsa_public); } }).done(function(data) { deferred.resolve("Login completed"); }).fail(function() { deferred.reject("Login failed"); }); } else { deferred.reject("Invalid parameters"); } return deferred.promise(); }
(function () { "use strict"; var fs = require("fs"), path = require("path"), os = require("os"), util = require("util"), Stream = require("stream"); var VALUE = 0, ERROR = 1, STREAM = 2, ERRORSTREAM = 3, FULLFILLEDPROMISE = 4; // Create a temporary folder for remembered streams var tmpDir = path.join(os.tmpDir(), Math.random().toString(36)) + '/'; fs.mkdirSync(tmpDir); var tmpCounter = 0; // Empty function var noop = function () {}; // Memoize the specified function function remember(func, options) { if (typeof func !== "function") throw new Error("alzheimer.remember: argument should be a function"); // The memory that will remember the return values var memory = Object.create(null); // Set options var forget = !!(options && options.forget); if (forget && options.forget.after) { var maxAge = options.forget.after; // Sweep the memory in fixed intervals setInterval(function () { // Remove memory cells that are older than allowed var minTimeStamp = Date.now() - maxAge; for (var key in memory) { var memoryCell = memory[key]; if (memoryCell.timestamp <= minTimeStamp) { delete memory[key]; eraseMemoryCell(memoryCell); } } }, 1000); } // Return the memoized function return function (firstArg) { // Fetch the value if it exists in memory var memoryCell = memory[firstArg]; // Determine the value if it doesn't exist in memory yet if (!memoryCell) { // Try to make the cell a regular value try { memoryCell = createMemoryCell(VALUE, func.apply(this, arguments), forget); } // If `func` failed, make the cell an error value catch (error) { memoryCell = createMemoryCell(ERROR, error, forget); } memory[firstArg] = memoryCell; } return getMemoryCellContents(memoryCell); }; } // Extract an actualized result from a memory cell function getMemoryCellContents(memoryCell) { var result = memoryCell.result; // Perform the action based on original function result switch (memoryCell.type) { // Return the result returned by the original function case VALUE: return result; // Throw the error thrown by the original function case ERROR: throw result; // Play back a captured stream case STREAM: // Read the stream from disk, but give it the properties of the original stream var stream = fs.createReadStream(result.file, { encoding: result.encoding }); return PlaceholderStream.call(stream, result.stream); // Play back an erroneous stream case ERRORSTREAM: stream = new PlaceholderStream(result.stream); process.nextTick(stream.emit.bind(stream, "error", result.error)); return stream; // Return a fulfilled promise case FULLFILLEDPROMISE: return result.promise.then(function () { return getMemoryCellContents(result.resultCell); }); } } // Create a memory cell for a function's result function createMemoryCell(type, result, addTimestamp) { // First, create a regular memory cell var memoryCell = { type: type, result: result }; if (addTimestamp) memoryCell.timestamp = Date.now(); // Next, perform specific transformations depending on the result if (type === VALUE) { // If the result is a stream, capture it for later playback if (result instanceof Stream) { // Until the stream is fully captured, shield it off with a temporary placeholder var placeholderStream = new PlaceholderStream(result); memoryCell.result = placeholderStream; // Capture the stream in a file that will be played back later cacheStream(result, function (error, streamFile) { // Make the cell an error value if the original stream errors if (error) { memoryCell.result = { error: error, stream: result }; memoryCell.type = ERRORSTREAM; } // Otherwise, make it a stream cell else { var encoding = result._decoder && result._decoder.encoding; memoryCell.result = { file: streamFile, encoding: encoding, stream: result }; memoryCell.type = STREAM; } // Play back the resulting stream in the placeholder placeholderStream._streamFrom(getMemoryCellContents(memoryCell)); }); } // If the result is a promise, capture its value if (result && typeof(result.then) === "function") { result.then(function (promiseResult) { var resultCell = createMemoryCell(VALUE, promiseResult); memoryCell.type = FULLFILLEDPROMISE; memoryCell.result = { promise: result, resultCell: resultCell }; }); } } // Return the created memory cell return memoryCell; } // Capture the stream in a temporary file and return its name function cacheStream(stream, callback) { var tmpFile = tmpDir + tmpCounter++, tmpStream = fs.createWriteStream(tmpFile); stream.pipe(tmpStream); stream.on("end", callback.bind(null, null, tmpFile)); stream.on("error", callback); } // Clean up the memory cell function eraseMemoryCell(memoryCell) { var result = memoryCell.result; switch (memoryCell.type) { // Delete a cached stream, leaving some time for readers to finish case STREAM: return setTimeout(fs.unlink.bind(fs, result.file), 1000); // Delete the promise's memory cell case FULLFILLEDPROMISE: return eraseMemoryCell(result.resultCell); } } // A stream that serves as a placeholder value until another stream is ready function PlaceholderStream(baseStream) { // Inherit from the base stream, but don't inherit its listeners var originalPrototype = this.__proto__; this.__proto__ = Object.create(baseStream); this._events = {}; // Restore all properties of the original prototype for (var propertyName in originalPrototype) this[propertyName] = originalPrototype[propertyName]; // Imitate the specified stream's behavior by reacting to its stream events this._streamFrom = function (stream) { stream._events = this._events; }; // Return ourself in case we're not called as a constructor return this; } util.inherits(PlaceholderStream, Stream); // Export the alzheimer module module.exports = { remember: remember }; })();
import test from 'ava'; import fn from './'; test('to decimal', t => { t.true(fn(65) === 0.65); t.true(fn(1234.5) === 12.345); t.true(fn(0.1) === 0.001); t.true(fn(12.1245, {digits: 2}) === 0.12); t.true(fn(6158.4256, {digits: 5}) === 61.58426); t.true(fn(1234.5, {digits: 0}) === 12); t.end(); });
// app/routes.js module.exports = function(app, request, Lob) { var googleApiKey = 'AIzaSyAVcJflF_0GpUzioGph0e8edJQeatd-330'; app.get('/', function(req, res) { res.sendfile('./public/index.html'); }); app.get('/api/getreps', function(req, res) { var zip = req.query.zip; var url = 'https://www.googleapis.com/civicinfo/v2/representatives?address='+ zip +'&key=' + googleApiKey request(url, function (error, response, body) { var bodyObj = JSON.parse(body); if (!error && response.statusCode == 200) { var officials = bodyObj.officials; var offices = bodyObj.offices; if(officials && offices) { var resObj = {}; resObj.userCity = bodyObj.normalizedInput.city; resObj.userState = bodyObj.normalizedInput.state; resObj.userZip = bodyObj.normalizedInput.zip; resObj.reps = []; for(var i = 0; i < offices.length; i++) { for(var j = 0; j < offices[i].officialIndices.length; j++) { var officialIndex = offices[i].officialIndices[j]; if(officials[officialIndex].address) { var official = officials[officialIndex]; var rep = {}; rep.officeName = offices[i].name; rep.repName = official.name; rep.address = official.address[0]; rep.photoUrl = official.photoUrl; resObj.reps.push(rep); } } } res.send(resObj); } else { res.send(resObj); } } else { if(bodyObj.error) { res.status(bodyObj.error.code); res.send(bodyObj); } else { res.status(404); res.send(false); } } }); }); app.post('/api/sendletter', function(req, res) { var letter = req.body; Lob.letters.create(letter, function (loberr, lobres) { if(loberr) { console.log('loberr:', loberr); res.status(loberr.status_code); res.send(loberr); } res.send(lobres); }); }); };
import { combineReducers } from 'redux-immutable'; import gluttonousSnake from 'isomerism/reducers/components/game/gluttonousSnake'; export default combineReducers({ gluttonousSnake, });
'use strict'; /** * Removes server error when user updates input */ angular.module('assassinsApp') .directive('mongooseError', function () { return { restrict: 'A', require: 'ngModel', link: function(scope, element, attrs, ngModel) { element.on('keydown', function() { return ngModel.$setValidity('mongoose', true); }); } }; });
import chai from 'chai'; import nock from 'nock'; import path from 'path'; import dota from '../../src/commands/games/dota2'; import { loadFixtures } from '../_helpers'; chai.should(); const FIXTURES = loadFixtures(path.join(__dirname, '../fixtures/dota2/')); describe('dota2', () => { describe('best', () => { it('it should return a list of the top 10 best heroes', done => { function sendMessage(channel, res) { channel.should.equal('test'); res.should.equal(`Okay! Here's the top 10 **statistical** Heroes for **mid**: *1st*. **Shadow Fiend** Presence: __90.74%__ | Winrate: __51.22%__ | KDA: __2.7691__ | GPM: __546.8119__ | XPM: __571.5334__ *2nd*. **Templar Assassin** Presence: __88.29%__ | Winrate: __50.63%__ | KDA: __2.9136__ | GPM: __524.0227__ | XPM: __576.9324__ *3rd*. **Storm Spirit** Presence: __85.77%__ | Winrate: __48.87%__ | KDA: __3.0408__ | GPM: __482.3736__ | XPM: __558.7176__ *4th*. **Tinker** Presence: __84.3%__ | Winrate: __46.21%__ | KDA: __2.9619__ | GPM: __467.0175__ | XPM: __525.773__ *5th*. **Invoker** Presence: __76.37%__ | Winrate: __50.62%__ | KDA: __3.1503__ | GPM: __465.6148__ | XPM: __515.4827__ *6th*. **Queen of Pain** Presence: __71.15%__ | Winrate: __46.43%__ | KDA: __3.3133__ | GPM: __470.747__ | XPM: __528.4107__ *7th*. **Outworld Devourer** Presence: __70.84%__ | Winrate: __48%__ | KDA: __2.5225__ | GPM: __451.1338__ | XPM: __502.5271__ *8th*. **Puck** Presence: __64.24%__ | Winrate: __44.36%__ | KDA: __2.9098__ | GPM: __417.1285__ | XPM: __497.0132__ *9th*. **Death Prophet** Presence: __62.36%__ | Winrate: __49.15%__ | KDA: __2.5247__ | GPM: __452.8678__ | XPM: __514.715__ *10th*. **Zeus** Presence: __61.04%__ | Winrate: __56.12%__ | KDA: __4.1543__ | GPM: __433.3088__ | XPM: __512.4047__`); done(); } nock.cleanAll(); nock('http://www.dotabuff.com') .get('/heroes/lanes?lane=mid') .reply(200, FIXTURES.best); dota.dota2({sendMessage}, {channel: 'test'}, 'best mid'); }); }); describe('build', () => { it('it should return the most popular build for anti-mage', done => { function sendMessage(channel, res) { channel.should.equal('test'); res.should.equal(`You got it! Here's most popular build priorities for **Anti Mage**. R > Q > W > E`); done(); } nock.cleanAll(); nock('http://www.dotabuff.com') .get('/heroes/anti-mage/builds') .reply(200, FIXTURES.build); dota.dota2({sendMessage}, {channel: 'test'}, 'build anti mage'); }); }); describe('counters', () => { it('it should counters for anti-mage', done => { function sendMessage(channel, res) { channel.should.equal('test'); res.should.equal(`Sure! Here's the top 10 **statistical** counters for **Anti Mage** this month: *1st*. **Wraith King** - 56.14% win rate over 590,941 matches. *2nd*. **Zeus** - 55.4% win rate over 482,486 matches. *3rd*. **Medusa** - 54.76% win rate over 267,265 matches. *4th*. **Spectre** - 60.04% win rate over 306,314 matches. *5th*. **Abaddon** - 59.6% win rate over 171,619 matches. *6th*. **Clockwerk** - 48.3% win rate over 164,718 matches. *7th*. **Ancient Apparition** - 49.67% win rate over 196,195 matches. *8th*. **Slark** - 50.93% win rate over 443,573 matches. *9th*. **Undying** - 55.01% win rate over 190,340 matches. *10th*. **Phoenix** - 53.06% win rate over 104,058 matches.`); done(); } nock.cleanAll(); nock('http://www.dotabuff.com') .get('/heroes/anti-mage/matchups') .reply(200, FIXTURES.counters); dota.dota2({sendMessage}, {channel: 'test'}, 'counters anti mage'); }); }); describe('impact', () => { it('it should return the highest impacting heroes', done => { function sendMessage(channel, res) { channel.should.equal('test'); res.should.equal(`Alright! Here's the top 10 Heroes with the biggest impact this month: *1st*. **Spectre** KDA: __3.7913__ | Kills: __9.4035__ | Deaths: __6.9009__ | Assists: __16.76__ *2nd*. **Zeus** KDA: __3.5734__ | Kills: __9.9872__ | Deaths: __7.7636__ | Assists: __17.756__ *3rd*. **Necrophos** KDA: __3.1631__ | Kills: __9.2428__ | Deaths: __7.9451__ | Assists: __15.8888__ *4th*. **Medusa** KDA: __3.0695__ | Kills: __6.1923__ | Deaths: __5.7206__ | Assists: __11.3671__ *5th*. **Weaver** KDA: __3.0651__ | Kills: __9.7294__ | Deaths: __6.8751__ | Assists: __11.3443__ *6th*. **Invoker** KDA: __3.0193__ | Kills: __9.4518__ | Deaths: __7.268__ | Assists: __12.4928__ *7th*. **Wraith King** KDA: __2.9818__ | Kills: __7.5578__ | Deaths: __6.3821__ | Assists: __11.4725__ *8th*. **Abaddon** KDA: __2.8309__ | Kills: __5.9488__ | Deaths: __6.6633__ | Assists: __12.9143__ *9th*. **Riki** KDA: __2.7901__ | Kills: __10.5562__ | Deaths: __7.5115__ | Assists: __10.4022__ *10th*. **Viper** KDA: __2.7874__ | Kills: __10.2064__ | Deaths: __7.8425__ | Assists: __11.6541__`); done(); } nock.cleanAll(); nock('http://www.dotabuff.com') .get('/heroes/impact') .reply(200, FIXTURES.impact); dota.dota2({sendMessage}, {channel: 'test'}, 'impact'); }); }); describe('items', () => { it('it should return the most used items for anti-mage', done => { function sendMessage(channel, res) { channel.should.equal('test'); res.should.equal(`Alright! Here's the top 10 **most used** items for **Anti Mage** this month: *1st*. **Battle Fury** with 49.21% winrate over 4,875,904 matches *2nd*. **Power Treads** with 43.9% winrate over 3,963,102 matches *3rd*. **Manta Style** with 60.2% winrate over 3,691,084 matches *4th*. **Vladmir's Offering** with 54.57% winrate over 2,195,412 matches *5th*. **Abyssal Blade** with 76.77% winrate over 1,386,943 matches *6th*. **Skull Basher** with 52.92% winrate over 1,295,968 matches *7th*. **Town Portal Scroll** with 29.31% winrate over 1,256,926 matches *8th*. **Heart of Tarrasque** with 71.67% winrate over 1,159,192 matches *9th*. **Boots of Travel** with 68.93% winrate over 844,483 matches *10th*. **Butterfly** with 79.96% winrate over 826,125 matches`); done(); } nock.cleanAll(); nock('http://www.dotabuff.com') .get('/heroes/anti-mage/items') .reply(200, FIXTURES.items); dota.dota2({sendMessage}, {channel: 'test'}, 'items anti mage'); }); }); });
'use strict' module.exports = function fooPost(req, res, next) { res.header('name', 'foo'); res.header('method', 'post'); res.send(200); next(); };
/*global document, describe, it, expect, require, window, afterEach */ const jQuery = require('jquery'); require('../../src/browser/place-caret-at-end'); describe('placeCaretAtEnd', () => { 'use strict'; let underTest; afterEach(() => { underTest.remove(); }); it('works on contenteditable divs', () => { underTest = jQuery('<span>').html('some text').appendTo('body'); underTest.placeCaretAtEnd(); const selection = window.getSelection(), range = selection.getRangeAt(0); expect(selection.type).toEqual('Caret'); expect(selection.rangeCount).toEqual(1); range.surroundContents(document.createElement('i')); expect(underTest.html()).toEqual('some text<i></i>'); }); });
module.exports = /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "/dist/"; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ({ /***/ 0: /***/ function(module, exports, __webpack_require__) { module.exports = __webpack_require__(353); /***/ }, /***/ 3: /***/ function(module, exports) { /* globals __VUE_SSR_CONTEXT__ */ // this module is a runtime utility for cleaner component module output and will // be included in the final webpack user bundle module.exports = function normalizeComponent ( rawScriptExports, compiledTemplate, injectStyles, scopeId, moduleIdentifier /* server only */ ) { var esModule var scriptExports = rawScriptExports = rawScriptExports || {} // ES6 modules interop var type = typeof rawScriptExports.default if (type === 'object' || type === 'function') { esModule = rawScriptExports scriptExports = rawScriptExports.default } // Vue.extend constructor export interop var options = typeof scriptExports === 'function' ? scriptExports.options : scriptExports // render functions if (compiledTemplate) { options.render = compiledTemplate.render options.staticRenderFns = compiledTemplate.staticRenderFns } // scopedId if (scopeId) { options._scopeId = scopeId } var hook if (moduleIdentifier) { // server build hook = function (context) { // 2.3 injection context = context || (this.$vnode && this.$vnode.ssrContext) // 2.2 with runInNewContext: true if (!context && typeof __VUE_SSR_CONTEXT__ !== 'undefined') { context = __VUE_SSR_CONTEXT__ } // inject component styles if (injectStyles) { injectStyles.call(this, context) } // register component module identifier for async chunk inferrence if (context && context._registeredComponents) { context._registeredComponents.add(moduleIdentifier) } } // used by ssr in case component is cached and beforeCreate // never gets called options._ssrRegister = hook } else if (injectStyles) { hook = injectStyles } if (hook) { // inject component registration as beforeCreate hook var existing = options.beforeCreate options.beforeCreate = existing ? [].concat(existing, hook) : [hook] } return { esModule: esModule, exports: scriptExports, options: options } } /***/ }, /***/ 13: /***/ function(module, exports) { module.exports = require("element-ui/lib/mixins/emitter"); /***/ }, /***/ 61: /***/ function(module, exports) { module.exports = require("element-ui/lib/locale"); /***/ }, /***/ 85: /***/ function(module, exports) { module.exports = require("element-ui/lib/transitions/collapse-transition"); /***/ }, /***/ 169: /***/ function(module, exports) { module.exports = require("element-ui/lib/utils/merge"); /***/ }, /***/ 307: /***/ function(module, exports) { module.exports = require("element-ui/lib/checkbox"); /***/ }, /***/ 353: /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _tree = __webpack_require__(354); var _tree2 = _interopRequireDefault(_tree); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /* istanbul ignore next */ _tree2.default.install = function (Vue) { Vue.component(_tree2.default.name, _tree2.default); }; exports.default = _tree2.default; /***/ }, /***/ 354: /***/ function(module, exports, __webpack_require__) { var Component = __webpack_require__(3)( /* script */ __webpack_require__(355), /* template */ __webpack_require__(362), /* styles */ null, /* scopeId */ null, /* moduleIdentifier (server only) */ null ) module.exports = Component.exports /***/ }, /***/ 355: /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _treeStore = __webpack_require__(356); var _treeStore2 = _interopRequireDefault(_treeStore); var _locale = __webpack_require__(61); var _emitter = __webpack_require__(13); var _emitter2 = _interopRequireDefault(_emitter); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = { name: 'ElTree', mixins: [_emitter2.default], components: { ElTreeNode: __webpack_require__(359) }, data: function data() { return { store: null, root: null, currentNode: null }; }, props: { data: { type: Array }, emptyText: { type: String, default: function _default() { return (0, _locale.t)('el.tree.emptyText'); } }, nodeKey: String, checkStrictly: Boolean, defaultExpandAll: Boolean, expandOnClickNode: { type: Boolean, default: true }, autoExpandParent: { type: Boolean, default: true }, defaultCheckedKeys: Array, defaultExpandedKeys: Array, renderContent: Function, showCheckbox: { type: Boolean, default: false }, props: { default: function _default() { return { children: 'children', label: 'label', icon: 'icon' }; } }, lazy: { type: Boolean, default: false }, highlightCurrent: Boolean, currentNodeKey: [String, Number], load: Function, filterNodeMethod: Function, accordion: Boolean, indent: { type: Number, default: 16 } }, computed: { children: { set: function set(value) { this.data = value; }, get: function get() { return this.data; } } }, watch: { defaultCheckedKeys: function defaultCheckedKeys(newVal) { this.store.defaultCheckedKeys = newVal; this.store.setDefaultCheckedKey(newVal); }, defaultExpandedKeys: function defaultExpandedKeys(newVal) { this.store.defaultExpandedKeys = newVal; this.store.setDefaultExpandedKeys(newVal); }, currentNodeKey: function currentNodeKey(newVal) { this.store.setCurrentNodeKey(newVal); this.store.currentNodeKey = newVal; }, data: function data(newVal) { this.store.setData(newVal); } }, methods: { filter: function filter(value) { if (!this.filterNodeMethod) throw new Error('[Tree] filterNodeMethod is required when filter'); this.store.filter(value); }, getNodeKey: function getNodeKey(node, index) { var nodeKey = this.nodeKey; if (nodeKey && node) { return node.data[nodeKey]; } return index; }, getCheckedNodes: function getCheckedNodes(leafOnly) { return this.store.getCheckedNodes(leafOnly); }, getCheckedKeys: function getCheckedKeys(leafOnly) { return this.store.getCheckedKeys(leafOnly); }, setCheckedNodes: function setCheckedNodes(nodes, leafOnly) { if (!this.nodeKey) throw new Error('[Tree] nodeKey is required in setCheckedNodes'); this.store.setCheckedNodes(nodes, leafOnly); }, setCheckedKeys: function setCheckedKeys(keys, leafOnly) { if (!this.nodeKey) throw new Error('[Tree] nodeKey is required in setCheckedNodes'); this.store.setCheckedKeys(keys, leafOnly); }, setChecked: function setChecked(data, checked, deep) { this.store.setChecked(data, checked, deep); }, handleNodeExpand: function handleNodeExpand(nodeData, node, instance) { this.broadcast('ElTreeNode', 'tree-node-expand', node); this.$emit('node-expand', nodeData, node, instance); } }, created: function created() { this.isTree = true; this.store = new _treeStore2.default({ key: this.nodeKey, data: this.data, lazy: this.lazy, props: this.props, load: this.load, currentNodeKey: this.currentNodeKey, checkStrictly: this.checkStrictly, defaultCheckedKeys: this.defaultCheckedKeys, defaultExpandedKeys: this.defaultExpandedKeys, autoExpandParent: this.autoExpandParent, defaultExpandAll: this.defaultExpandAll, filterNodeMethod: this.filterNodeMethod }); this.root = this.store.root; } }; // // // // // // // // // // // // // // // // /***/ }, /***/ 356: /***/ function(module, exports, __webpack_require__) { '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 _node = __webpack_require__(357); var _node2 = _interopRequireDefault(_node); var _util = __webpack_require__(358); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var TreeStore = function () { function TreeStore(options) { var _this = this; _classCallCheck(this, TreeStore); this.currentNode = null; this.currentNodeKey = null; for (var option in options) { if (options.hasOwnProperty(option)) { this[option] = options[option]; } } this.nodesMap = {}; this.root = new _node2.default({ data: this.data, store: this }); if (this.lazy && this.load) { var loadFn = this.load; loadFn(this.root, function (data) { _this.root.doCreateChildren(data); _this._initDefaultCheckedNodes(); }); } else { this._initDefaultCheckedNodes(); } } TreeStore.prototype.filter = function filter(value) { var filterNodeMethod = this.filterNodeMethod; var traverse = function traverse(node) { var childNodes = node.root ? node.root.childNodes : node.childNodes; childNodes.forEach(function (child) { child.visible = filterNodeMethod.call(child, value, child.data, child); traverse(child); }); if (!node.visible && childNodes.length) { var allHidden = true; childNodes.forEach(function (child) { if (child.visible) allHidden = false; }); if (node.root) { node.root.visible = allHidden === false; } else { node.visible = allHidden === false; } } if (node.visible && !node.isLeaf) node.expand(); }; traverse(this); }; TreeStore.prototype.setData = function setData(newVal) { var instanceChanged = newVal !== this.root.data; this.root.setData(newVal); if (instanceChanged) { this._initDefaultCheckedNodes(); } }; TreeStore.prototype.getNode = function getNode(data) { var key = (typeof data === 'undefined' ? 'undefined' : _typeof(data)) !== 'object' ? data : (0, _util.getNodeKey)(this.key, data); return this.nodesMap[key]; }; TreeStore.prototype.insertBefore = function insertBefore(data, refData) { var refNode = this.getNode(refData); refNode.parent.insertBefore({ data: data }, refNode); }; TreeStore.prototype.insertAfter = function insertAfter(data, refData) { var refNode = this.getNode(refData); refNode.parent.insertAfter({ data: data }, refNode); }; TreeStore.prototype.remove = function remove(data) { var node = this.getNode(data); if (node) { node.parent.removeChild(node); } }; TreeStore.prototype.append = function append(data, parentData) { var parentNode = parentData ? this.getNode(parentData) : this.root; if (parentNode) { parentNode.insertChild({ data: data }); } }; TreeStore.prototype._initDefaultCheckedNodes = function _initDefaultCheckedNodes() { var _this2 = this; var defaultCheckedKeys = this.defaultCheckedKeys || []; var nodesMap = this.nodesMap; defaultCheckedKeys.forEach(function (checkedKey) { var node = nodesMap[checkedKey]; if (node) { node.setChecked(true, !_this2.checkStrictly); } }); }; TreeStore.prototype._initDefaultCheckedNode = function _initDefaultCheckedNode(node) { var defaultCheckedKeys = this.defaultCheckedKeys || []; if (defaultCheckedKeys.indexOf(node.key) !== -1) { node.setChecked(true, !this.checkStrictly); } }; TreeStore.prototype.setDefaultCheckedKey = function setDefaultCheckedKey(newVal) { if (newVal !== this.defaultCheckedKeys) { this.defaultCheckedKeys = newVal; this._initDefaultCheckedNodes(); } }; TreeStore.prototype.registerNode = function registerNode(node) { var key = this.key; if (!key || !node || !node.data) return; var nodeKey = node.key; if (nodeKey !== undefined) this.nodesMap[node.key] = node; }; TreeStore.prototype.deregisterNode = function deregisterNode(node) { var key = this.key; if (!key || !node || !node.data) return; delete this.nodesMap[node.key]; }; TreeStore.prototype.getCheckedNodes = function getCheckedNodes() { var leafOnly = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; var checkedNodes = []; var traverse = function traverse(node) { var childNodes = node.root ? node.root.childNodes : node.childNodes; childNodes.forEach(function (child) { if (!leafOnly && child.checked || leafOnly && child.isLeaf && child.checked) { checkedNodes.push(child.data); } traverse(child); }); }; traverse(this); return checkedNodes; }; TreeStore.prototype.getCheckedKeys = function getCheckedKeys() { var leafOnly = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; var key = this.key; var allNodes = this._getAllNodes(); var keys = []; allNodes.forEach(function (node) { if (!leafOnly || leafOnly && node.isLeaf) { if (node.checked) { keys.push((node.data || {})[key]); } } }); return keys; }; TreeStore.prototype._getAllNodes = function _getAllNodes() { var allNodes = []; var nodesMap = this.nodesMap; for (var nodeKey in nodesMap) { if (nodesMap.hasOwnProperty(nodeKey)) { allNodes.push(nodesMap[nodeKey]); } } return allNodes; }; TreeStore.prototype._setCheckedKeys = function _setCheckedKeys(key) { var _this3 = this; var leafOnly = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; var checkedKeys = arguments[2]; var allNodes = this._getAllNodes(); allNodes.sort(function (a, b) { return b.level - a.level; }); var keys = Object.keys(checkedKeys); allNodes.forEach(function (node) { var checked = keys.indexOf(node.data[key] + '') > -1; if (!node.isLeaf) { if (!_this3.checkStrictly) { var childNodes = node.childNodes; var all = true; var none = true; for (var i = 0, j = childNodes.length; i < j; i++) { var child = childNodes[i]; if (child.checked !== true || child.indeterminate) { all = false; } if (child.checked !== false || child.indeterminate) { none = false; } } if (all) { node.setChecked(true, !_this3.checkStrictly); } else if (!all && !none) { checked = checked ? true : 'half'; node.setChecked(checked, !_this3.checkStrictly && checked === true); } else if (none) { node.setChecked(checked, !_this3.checkStrictly); } } else { node.setChecked(checked, false); } if (leafOnly) { (function () { node.setChecked(false, false); var traverse = function traverse(node) { var childNodes = node.childNodes; childNodes.forEach(function (child) { if (!child.isLeaf) { child.setChecked(false, false); } traverse(child); }); }; traverse(node); })(); } } else { node.setChecked(checked, false); } }); }; TreeStore.prototype.setCheckedNodes = function setCheckedNodes(array) { var leafOnly = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; var key = this.key; var checkedKeys = {}; array.forEach(function (item) { checkedKeys[(item || {})[key]] = true; }); this._setCheckedKeys(key, leafOnly, checkedKeys); }; TreeStore.prototype.setCheckedKeys = function setCheckedKeys(keys) { var leafOnly = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; this.defaultCheckedKeys = keys; var key = this.key; var checkedKeys = {}; keys.forEach(function (key) { checkedKeys[key] = true; }); this._setCheckedKeys(key, leafOnly, checkedKeys); }; TreeStore.prototype.setDefaultExpandedKeys = function setDefaultExpandedKeys(keys) { var _this4 = this; keys = keys || []; this.defaultExpandedKeys = keys; keys.forEach(function (key) { var node = _this4.getNode(key); if (node) node.expand(null, _this4.autoExpandParent); }); }; TreeStore.prototype.setChecked = function setChecked(data, checked, deep) { var node = this.getNode(data); if (node) { node.setChecked(!!checked, deep); } }; TreeStore.prototype.getCurrentNode = function getCurrentNode() { return this.currentNode; }; TreeStore.prototype.setCurrentNode = function setCurrentNode(node) { this.currentNode = node; }; TreeStore.prototype.setCurrentNodeKey = function setCurrentNodeKey(key) { var node = this.getNode(key); if (node) { this.currentNode = node; } }; return TreeStore; }(); exports.default = TreeStore; ; /***/ }, /***/ 357: /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _merge = __webpack_require__(169); var _merge2 = _interopRequireDefault(_merge); var _util = __webpack_require__(358); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var reInitChecked = function reInitChecked(node) { var siblings = node.childNodes; var all = true; var none = true; for (var i = 0, j = siblings.length; i < j; i++) { var sibling = siblings[i]; if (sibling.checked !== true || sibling.indeterminate) { all = false; } if (sibling.checked !== false || sibling.indeterminate) { none = false; } } if (all) { node.setChecked(true); } else if (!all && !none) { node.setChecked('half'); } else if (none) { node.setChecked(false); } }; var getPropertyFromData = function getPropertyFromData(node, prop) { var props = node.store.props; var data = node.data || {}; var config = props[prop]; if (typeof config === 'function') { return config(data, node); } else if (typeof config === 'string') { return data[config]; } else if (typeof config === 'undefined') { return ''; } }; var nodeIdSeed = 0; var Node = function () { function Node(options) { _classCallCheck(this, Node); this.id = nodeIdSeed++; this.text = null; this.checked = false; this.indeterminate = false; this.data = null; this.expanded = false; this.parent = null; this.visible = true; for (var name in options) { if (options.hasOwnProperty(name)) { this[name] = options[name]; } } // internal this.level = 0; this.loaded = false; this.childNodes = []; this.loading = false; if (this.parent) { this.level = this.parent.level + 1; } var store = this.store; if (!store) { throw new Error('[Node]store is required!'); } store.registerNode(this); var props = store.props; if (props && typeof props.isLeaf !== 'undefined') { var isLeaf = getPropertyFromData(this, 'isLeaf'); if (typeof isLeaf === 'boolean') { this.isLeafByUser = isLeaf; } } if (store.lazy !== true && this.data) { this.setData(this.data); if (store.defaultExpandAll) { this.expanded = true; } } else if (this.level > 0 && store.lazy && store.defaultExpandAll) { this.expand(); } if (!this.data) return; var defaultExpandedKeys = store.defaultExpandedKeys; var key = store.key; if (key && defaultExpandedKeys && defaultExpandedKeys.indexOf(this.key) !== -1) { this.expand(null, store.autoExpandParent); } if (key && store.currentNodeKey && this.key === store.currentNodeKey) { store.currentNode = this; } if (store.lazy) { store._initDefaultCheckedNode(this); } this.updateLeafState(); } Node.prototype.setData = function setData(data) { if (!Array.isArray(data)) { (0, _util.markNodeData)(this, data); } this.data = data; this.childNodes = []; var children = void 0; if (this.level === 0 && this.data instanceof Array) { children = this.data; } else { children = getPropertyFromData(this, 'children') || []; } for (var i = 0, j = children.length; i < j; i++) { this.insertChild({ data: children[i] }); } }; Node.prototype.insertChild = function insertChild(child, index) { if (!child) throw new Error('insertChild error: child is required.'); if (!(child instanceof Node)) { (0, _merge2.default)(child, { parent: this, store: this.store }); child = new Node(child); } child.level = this.level + 1; if (typeof index === 'undefined' || index < 0) { this.childNodes.push(child); } else { this.childNodes.splice(index, 0, child); } this.updateLeafState(); }; Node.prototype.insertBefore = function insertBefore(child, ref) { var index = void 0; if (ref) { index = this.childNodes.indexOf(ref); } this.insertChild(child, index); }; Node.prototype.insertAfter = function insertAfter(child, ref) { var index = void 0; if (ref) { index = this.childNodes.indexOf(ref); if (index !== -1) index += 1; } this.insertChild(child, index); }; Node.prototype.removeChild = function removeChild(child) { var index = this.childNodes.indexOf(child); if (index > -1) { this.store && this.store.deregisterNode(child); child.parent = null; this.childNodes.splice(index, 1); } this.updateLeafState(); }; Node.prototype.removeChildByData = function removeChildByData(data) { var targetNode = null; this.childNodes.forEach(function (node) { if (node.data === data) { targetNode = node; } }); if (targetNode) { this.removeChild(targetNode); } }; Node.prototype.expand = function expand(callback, expandParent) { var _this = this; var done = function done() { if (expandParent) { var parent = _this.parent; while (parent.level > 0) { parent.expanded = true; parent = parent.parent; } } _this.expanded = true; if (callback) callback(); }; if (this.shouldLoadData()) { this.loadData(function (data) { if (data instanceof Array) { done(); } }); } else { done(); } }; Node.prototype.doCreateChildren = function doCreateChildren(array) { var _this2 = this; var defaultProps = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; array.forEach(function (item) { _this2.insertChild((0, _merge2.default)({ data: item }, defaultProps)); }); }; Node.prototype.collapse = function collapse() { this.expanded = false; }; Node.prototype.shouldLoadData = function shouldLoadData() { return this.store.lazy === true && this.store.load && !this.loaded; }; Node.prototype.updateLeafState = function updateLeafState() { if (this.store.lazy === true && this.loaded !== true && typeof this.isLeafByUser !== 'undefined') { this.isLeaf = this.isLeafByUser; return; } var childNodes = this.childNodes; if (!this.store.lazy || this.store.lazy === true && this.loaded === true) { this.isLeaf = !childNodes || childNodes.length === 0; return; } this.isLeaf = false; }; Node.prototype.setChecked = function setChecked(value, deep) { var _this3 = this; this.indeterminate = value === 'half'; this.checked = value === true; var handleDescendants = function handleDescendants() { if (deep) { var childNodes = _this3.childNodes; for (var i = 0, j = childNodes.length; i < j; i++) { var child = childNodes[i]; child.setChecked(value !== false, deep); } } }; if (!this.store.checkStrictly && this.shouldLoadData()) { // Only work on lazy load data. this.loadData(function () { handleDescendants(); }, { checked: value !== false }); } else { handleDescendants(); } var parent = this.parent; if (!parent || parent.level === 0) return; if (!this.store.checkStrictly) { reInitChecked(parent); } }; Node.prototype.getChildren = function getChildren() { // this is data var data = this.data; if (!data) return null; var props = this.store.props; var children = 'children'; if (props) { children = props.children || 'children'; } if (data[children] === undefined) { data[children] = null; } return data[children]; }; Node.prototype.updateChildren = function updateChildren() { var _this4 = this; var newData = this.getChildren() || []; var oldData = this.childNodes.map(function (node) { return node.data; }); var newDataMap = {}; var newNodes = []; newData.forEach(function (item, index) { if (item[_util.NODE_KEY]) { newDataMap[item[_util.NODE_KEY]] = { index: index, data: item }; } else { newNodes.push({ index: index, data: item }); } }); oldData.forEach(function (item) { if (!newDataMap[item[_util.NODE_KEY]]) _this4.removeChildByData(item); }); newNodes.forEach(function (_ref) { var index = _ref.index, data = _ref.data; _this4.insertChild({ data: data }, index); }); this.updateLeafState(); }; Node.prototype.loadData = function loadData(callback) { var _this5 = this; var defaultProps = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; if (this.store.lazy === true && this.store.load && !this.loaded && !this.loading) { this.loading = true; var resolve = function resolve(children) { _this5.loaded = true; _this5.loading = false; _this5.childNodes = []; _this5.doCreateChildren(children, defaultProps); _this5.updateLeafState(); if (callback) { callback.call(_this5, children); } }; this.store.load(this, resolve); } else { if (callback) { callback.call(this); } } }; _createClass(Node, [{ key: 'label', get: function get() { return getPropertyFromData(this, 'label'); } }, { key: 'icon', get: function get() { return getPropertyFromData(this, 'icon'); } }, { key: 'key', get: function get() { var nodeKey = this.store.key; if (this.data) return this.data[nodeKey]; return null; } }]); return Node; }(); exports.default = Node; /***/ }, /***/ 358: /***/ function(module, exports) { 'use strict'; exports.__esModule = true; var NODE_KEY = exports.NODE_KEY = '$treeNodeId'; var markNodeData = exports.markNodeData = function markNodeData(node, data) { if (data[NODE_KEY]) return; Object.defineProperty(data, NODE_KEY, { value: node.id, enumerable: false, configurable: false, writable: false }); }; var getNodeKey = exports.getNodeKey = function getNodeKey(key, data) { if (!key) return data[NODE_KEY]; return data[key]; }; /***/ }, /***/ 359: /***/ function(module, exports, __webpack_require__) { var Component = __webpack_require__(3)( /* script */ __webpack_require__(360), /* template */ __webpack_require__(361), /* styles */ null, /* scopeId */ null, /* moduleIdentifier (server only) */ null ) module.exports = Component.exports /***/ }, /***/ 360: /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _collapseTransition = __webpack_require__(85); var _collapseTransition2 = _interopRequireDefault(_collapseTransition); var _checkbox = __webpack_require__(307); var _checkbox2 = _interopRequireDefault(_checkbox); var _emitter = __webpack_require__(13); var _emitter2 = _interopRequireDefault(_emitter); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = { name: 'ElTreeNode', componentName: 'ElTreeNode', mixins: [_emitter2.default], props: { node: { default: function _default() { return {}; } }, props: {}, renderContent: Function }, components: { ElCollapseTransition: _collapseTransition2.default, ElCheckbox: _checkbox2.default, NodeContent: { props: { node: { required: true } }, render: function render(h) { var parent = this.$parent; var node = this.node; var data = node.data; var store = node.store; return parent.renderContent ? parent.renderContent.call(parent._renderProxy, h, { _self: parent.tree.$vnode.context, node: node, data: data, store: store }) : h( 'span', { 'class': 'el-tree-node__label' }, [this.node.label] ); } } }, data: function data() { return { tree: null, expanded: false, childNodeRendered: false, showCheckbox: false, oldChecked: null, oldIndeterminate: null }; }, watch: { 'node.indeterminate': function nodeIndeterminate(val) { this.handleSelectChange(this.node.checked, val); }, 'node.checked': function nodeChecked(val) { this.handleSelectChange(val, this.node.indeterminate); }, 'node.expanded': function nodeExpanded(val) { this.expanded = val; if (val) { this.childNodeRendered = true; } } }, methods: { getNodeKey: function getNodeKey(node, index) { var nodeKey = this.tree.nodeKey; if (nodeKey && node) { return node.data[nodeKey]; } return index; }, handleSelectChange: function handleSelectChange(checked, indeterminate) { if (this.oldChecked !== checked && this.oldIndeterminate !== indeterminate) { this.tree.$emit('check-change', this.node.data, checked, indeterminate); } this.oldChecked = checked; this.indeterminate = indeterminate; }, handleClick: function handleClick() { var store = this.tree.store; store.setCurrentNode(this.node); this.tree.$emit('current-change', store.currentNode ? store.currentNode.data : null, store.currentNode); this.tree.currentNode = this; if (this.tree.expandOnClickNode) { this.handleExpandIconClick(); } this.tree.$emit('node-click', this.node.data, this.node, this); }, handleExpandIconClick: function handleExpandIconClick() { if (this.node.isLeaf) return; if (this.expanded) { this.tree.$emit('node-collapse', this.node.data, this.node, this); this.node.collapse(); } else { this.node.expand(); this.$emit('node-expand', this.node.data, this.node, this); } }, handleUserClick: function handleUserClick() { if (this.node.indeterminate) { this.node.setChecked(this.node.checked, !this.tree.checkStrictly); } }, handleCheckChange: function handleCheckChange(ev) { if (!this.node.indeterminate) { this.node.setChecked(ev.target.checked, !this.tree.checkStrictly); } }, handleChildNodeExpand: function handleChildNodeExpand(nodeData, node, instance) { this.broadcast('ElTreeNode', 'tree-node-expand', node); this.tree.$emit('node-expand', nodeData, node, instance); } }, created: function created() { var _this = this; var parent = this.$parent; if (parent.isTree) { this.tree = parent; } else { this.tree = parent.tree; } var tree = this.tree; if (!tree) { console.warn('Can not find node\'s tree.'); } var props = tree.props || {}; var childrenKey = props['children'] || 'children'; this.$watch('node.data.' + childrenKey, function () { _this.node.updateChildren(); }); this.showCheckbox = tree.showCheckbox; if (this.node.expanded) { this.expanded = true; this.childNodeRendered = true; } if (this.tree.accordion) { this.$on('tree-node-expand', function (node) { if (_this.node !== node) { _this.node.collapse(); } }); } } }; // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // /***/ }, /***/ 361: /***/ function(module, exports) { module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h; return _c('div', { directives: [{ name: "show", rawName: "v-show", value: (_vm.node.visible), expression: "node.visible" }], staticClass: "el-tree-node", class: { 'is-expanded': _vm.childNodeRendered && _vm.expanded, 'is-current': _vm.tree.store.currentNode === _vm.node, 'is-hidden': !_vm.node.visible }, on: { "click": function($event) { $event.stopPropagation(); _vm.handleClick($event) } } }, [_c('div', { staticClass: "el-tree-node__content", style: ({ 'padding-left': (_vm.node.level - 1) * _vm.tree.indent + 'px' }) }, [_c('span', { staticClass: "el-tree-node__expand-icon", class: { 'is-leaf': _vm.node.isLeaf, expanded: !_vm.node.isLeaf && _vm.expanded }, on: { "click": function($event) { $event.stopPropagation(); _vm.handleExpandIconClick($event) } } }), (_vm.showCheckbox) ? _c('el-checkbox', { attrs: { "indeterminate": _vm.node.indeterminate }, on: { "change": _vm.handleCheckChange }, nativeOn: { "click": function($event) { $event.stopPropagation(); _vm.handleUserClick($event) } }, model: { value: (_vm.node.checked), callback: function($$v) { _vm.node.checked = $$v }, expression: "node.checked" } }) : _vm._e(), (_vm.node.loading) ? _c('span', { staticClass: "el-tree-node__loading-icon el-icon-loading" }) : _vm._e(), _c('node-content', { attrs: { "node": _vm.node } })], 1), _c('el-collapse-transition', [_c('div', { directives: [{ name: "show", rawName: "v-show", value: (_vm.expanded), expression: "expanded" }], staticClass: "el-tree-node__children" }, _vm._l((_vm.node.childNodes), function(child) { return _c('el-tree-node', { key: _vm.getNodeKey(child), attrs: { "render-content": _vm.renderContent, "node": child }, on: { "node-expand": _vm.handleChildNodeExpand } }) }))])], 1) },staticRenderFns: []} /***/ }, /***/ 362: /***/ function(module, exports) { module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h; return _c('div', { staticClass: "el-tree", class: { 'el-tree--highlight-current': _vm.highlightCurrent } }, [_vm._l((_vm.root.childNodes), function(child) { return _c('el-tree-node', { key: _vm.getNodeKey(child), attrs: { "node": child, "props": _vm.props, "render-content": _vm.renderContent }, on: { "node-expand": _vm.handleNodeExpand } }) }), (!_vm.root.childNodes || _vm.root.childNodes.length === 0) ? _c('div', { staticClass: "el-tree__empty-block" }, [_c('span', { staticClass: "el-tree__empty-text" }, [_vm._v(_vm._s(_vm.emptyText))])]) : _vm._e()], 2) },staticRenderFns: []} /***/ } /******/ });
/* * Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved. * * 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. * */ /*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */ /*global define */ define({ /** * Chyby */ // Obecné chyby souboru "GENERIC_ERROR" : "(chyba {0})", "NOT_FOUND_ERR" : "Soubor nenalezen.", "NOT_READABLE_ERR" : "Soubor nelze číst.", "NO_MODIFICATION_ALLOWED_ERR" : "Cílová složka nemůže být změněna.", "NO_MODIFICATION_ALLOWED_ERR_FILE" : "Oprávnění neumožní provádět změny.", "FILE_EXISTS_ERR" : "Soubor již existuje.", "FILE" : "Soubor", "DIRECTORY" : "Složka", // Řetězce chyb projektu "ERROR_LOADING_PROJECT" : "Chyba při otevírání projektu", "OPEN_DIALOG_ERROR" : "Došlo k chybě při zobrazování dialogu Otevřít soubor. (chyba {0})", "REQUEST_NATIVE_FILE_SYSTEM_ERROR" : "Došlo k chybě při načítání adresáře <span class='dialog-filename'>{0}</span>. (chyba {1})", "READ_DIRECTORY_ENTRIES_ERROR" : "Došlo k chybě při načítání obsahu složky <span class='dialog-filename'>{0}</span>. (chyba {1})", // Řetězce chyb otevírání/ukládání souboru "ERROR_OPENING_FILE_TITLE" : "Chyba při otevírání souboru", "ERROR_OPENING_FILE" : "Došlo k chybě při otevírání souboru <span class='dialog-filename'>{0}</span>. {1}", "ERROR_OPENING_FILES" : "Došlo k chybě při otevírání následujících souborů:", "ERROR_RELOADING_FILE_TITLE" : "Chyba při načítání změn z disku", "ERROR_RELOADING_FILE" : "Došlo k chybě při načítání souboru <span class='dialog-filename'>{0}</span>. {1}", "ERROR_SAVING_FILE_TITLE" : "Chyba při ukládání souboru", "ERROR_SAVING_FILE" : "Došlo k chybě při ukládání souboru <span class='dialog-filename'>{0}</span>. {1}", "ERROR_RENAMING_FILE_TITLE" : "Chyba při přejmenování souboru", "ERROR_RENAMING_FILE" : "Došlo k chybě při přejmenování souboru <span class='dialog-filename'>{0}</span>. {1}", "ERROR_DELETING_FILE_TITLE" : "Chyba při mazání souboru", "ERROR_DELETING_FILE" : "Došlo k chybě při mazání souboru <span class='dialog-filename'>{0}</span>. {1}", "INVALID_FILENAME_TITLE" : "Špatné jméno souboru", "INVALID_FILENAME_MESSAGE" : "Jméno souboru nemůže obsahovat znaky: /?*:;{}<>\\|", "FILE_ALREADY_EXISTS" : "Soubor <span class='dialog-filename'>{0}</span> již existuje.", "ERROR_CREATING_FILE_TITLE" : "Chyba při tvorbě souboru", "ERROR_CREATING_FILE" : "Došlo k chybě při vytváření souboru <span class='dialog-filename'>{0}</span>. {1}", // Řetězce chyb aplikace "ERROR_IN_BROWSER_TITLE" : "Ouha! {APP_NAME} ještě neběží v prohlížeči.", "ERROR_IN_BROWSER" : "{APP_NAME} je vytvořen v HTML, ale nyní pracuje jako desktopová aplikace, takže ji můžete použít pro úpravu lokálních souborů. Prosím, použijte shell aplikace v <b>github.com/adobe/brackets-shell</b> repo pro spuštění {APP_NAME}.", // Řetězce chyb indexování souboru "ERROR_MAX_FILES_TITLE" : "Chyba při indexování souborů", "ERROR_MAX_FILES" : "Maximální počet souborů byl indexován. Funkce pro vyhledávání v indexovaných souborech nemusí fungovat správně.", // Řetezce chyb - živý náhled "ERROR_LAUNCHING_BROWSER_TITLE" : "Chyba při spouštění prohlížeče", "ERROR_CANT_FIND_CHROME" : "Google Chrome prohlížeč nebyl nalezen. Je nainstalován?", "ERROR_LAUNCHING_BROWSER" : "Došlo k chybě při spouštění prohlížeče. (chyba {0})", "LIVE_DEVELOPMENT_ERROR_TITLE" : "Živý náhled - chyba", "LIVE_DEVELOPMENT_RELAUNCH_TITLE" : "Připojování k prohlížeči", "LIVE_DEVELOPMENT_ERROR_MESSAGE" : "Aby se mohl živý náhled připojit, je třeba restartovat Chrome s povolenou možností vzdálené ladění. <br /><br /> Chcete restartovat Chrome a povolit vzdálené ladění?", "LIVE_DEV_LOADING_ERROR_MESSAGE" : "Nelze načíst stránku s živým náhledem", "LIVE_DEV_NEED_HTML_MESSAGE" : "Otevřete HTML soubor pro zobrazení v živém náhledu.", "LIVE_DEV_NEED_BASEURL_MESSAGE" : "Pro spuštění živého náhledu se server-side souborem, musíte specifikovat URL pro tento projekt.", "LIVE_DEV_SERVER_NOT_READY_MESSAGE" : "Chyba při spouštění HTTP serveru pro soubory živého náhledu. Prosím, zkuste to znovu.", "LIVE_DEVELOPMENT_INFO_TITLE" : "Vítejte v živém náhledu!", "LIVE_DEVELOPMENT_INFO_MESSAGE" : "Živý náhled připojí {APP_NAME} k vašemu prohlížeči. Spustí náhled HTML souboru, který se aktualizuje pokaždé, kdy editujete svůj kód.<br /><br />V této verzi {APP_NAME}, živý náhled funguje pouze v <strong>Google Chrome</strong> a aktualizuje změny v <strong>CSS souborech</strong>. Změny v HTML nebo JavaScript souborech jsou automaticky načteny, když soubor uložíte.<br /><br />(Tato zpráva se zobrazí pouze jednou.)", "LIVE_DEVELOPMENT_TROUBLESHOOTING" : "Pro více informací navštivte <a href='{0}' title='{0}'>Troubleshooting Live Development connection errors</a>.", "LIVE_DEV_STATUS_TIP_NOT_CONNECTED" : "Živý náhled", "LIVE_DEV_STATUS_TIP_PROGRESS1" : "Živý náhled: Připojování\u2026", "LIVE_DEV_STATUS_TIP_PROGRESS2" : "Živý náhled: Spouštění\u2026", "LIVE_DEV_STATUS_TIP_CONNECTED" : "Zrušit živý náhled", "LIVE_DEV_STATUS_TIP_OUT_OF_SYNC" : "Živý náhled (uložte soubor)", "LIVE_DEV_STATUS_TIP_SYNC_ERROR" : "Živý náhled (neaktualizováno kvůli chybě v syntaxi)", "LIVE_DEV_DETACHED_REPLACED_WITH_DEVTOOLS" : "Živý náhled byl zrušen, protože byly otevřeny vývojářské nástroje prohlížeče", "LIVE_DEV_DETACHED_TARGET_CLOSED" : "Živý náhled byl zrušen, protože dokument byl zavřen v prohlížeči", "LIVE_DEV_NAVIGATED_AWAY" : "Živý náhled byl zrušen, protože prohlížeč přešel na stránku, která není součástí projektu", "LIVE_DEV_CLOSED_UNKNOWN_REASON" : "Živý náhled byl zrušen z neznámého důvodu ({0})", "SAVE_CLOSE_TITLE" : "Uložit změny", "SAVE_CLOSE_MESSAGE" : "Chcete uložit změny v souboru <span class='dialog-filename'>{0}</span>?", "SAVE_CLOSE_MULTI_MESSAGE" : "Chcete uložit změny v následujících souborech?", "EXT_MODIFIED_TITLE" : "Externí změny", "CONFIRM_FOLDER_DELETE_TITLE" : "Potvrdit smazání", "CONFIRM_FOLDER_DELETE" : "Opravdu chcete smazat složku <span class='dialog-filename'>{0}</span>?", "FILE_DELETED_TITLE" : "Soubor smazán", "EXT_MODIFIED_MESSAGE" : "<span class='dialog-filename'>{0}</span> byl změněn, ale neuložené změny se nachází také v {APP_NAME}.<br /><br /> Kterou verzi chcete zachovat?", "EXT_DELETED_MESSAGE" : "<span class='dialog-filename'>{0}</span> byl smazán z disku, ale změny nebyly uloženy v {APP_NAME}.<br /><br />Chcete uložit změny?", // Najít, Nahradit, Nahradit v souborech "SEARCH_REGEXP_INFO" : "Použijte /re/ syntax pro regexp hledání", "FIND_RESULT_COUNT" : "{0} výsledků", "FIND_RESULT_COUNT_SINGLE" : "1 výsledek", "FIND_NO_RESULTS" : "Žádné výsledky", "WITH" : "S", "BUTTON_YES" : "Ano", "BUTTON_NO" : "Ne", "BUTTON_REPLACE_ALL" : "Vše\u2026", "BUTTON_STOP" : "Stop", "BUTTON_REPLACE" : "Nahradit", "BUTTON_NEXT" : "\u25B6", "BUTTON_PREV" : "\u25C0", "BUTTON_NEXT_HINT" : "Další shoda", "BUTTON_PREV_HINT" : "Předchozí shoda", "OPEN_FILE" : "Otevřít soubor", "SAVE_FILE_AS" : "Uložit soubor", "CHOOSE_FOLDER" : "Vybrat složku", "RELEASE_NOTES" : "Poznámky k verzi", "NO_UPDATE_TITLE" : "Vše je aktuální!", "NO_UPDATE_MESSAGE" : "Verze {APP_NAME} je aktuální.", "FIND_REPLACE_TITLE_PART1" : "Nahradit \"", "FIND_REPLACE_TITLE_PART2" : "\" s \"", "FIND_REPLACE_TITLE_PART3" : "\" &mdash; {2} {0} {1}", "FIND_IN_FILES_TITLE_PART1" : "\"", "FIND_IN_FILES_TITLE_PART2" : "\" nalezen", "FIND_IN_FILES_TITLE_PART3" : "&mdash; {0} {1} {2} v {3} {4}", "FIND_IN_FILES_SCOPED" : "v <span class='dialog-filename'>{0}</span>", "FIND_IN_FILES_NO_SCOPE" : "v projektu", "FIND_IN_FILES_FILE" : "souboru", "FIND_IN_FILES_FILES" : "souborech", "FIND_IN_FILES_MATCH" : "výsledek", "FIND_IN_FILES_MATCHES" : "výsledků", "FIND_IN_FILES_MORE_THAN" : "více než ", "FIND_IN_FILES_PAGING" : "{0}&mdash;{1}", "FIND_IN_FILES_FILE_PATH" : "Soubor: <span class='dialog-filename'>{0}</span>", "ERROR_FETCHING_UPDATE_INFO_TITLE" : "Chyba při získávání informací o aktualizaci", "ERROR_FETCHING_UPDATE_INFO_MSG" : "Nelze získat aktualizace. Ujistěte se, že máte připojení na internet a zkuste to znovu.", /** * Správce projektu */ "PROJECT_LOADING" : "Načítání\u2026", "UNTITLED" : "Nový", "WORKING_FILES" : "Pracovní soubory", /** * Jména kláves */ "KEYBOARD_CTRL" : "Ctrl", "KEYBOARD_SHIFT" : "Shift", "KEYBOARD_SPACE" : "Space", /** * Řetezce příkazového řádku */ "STATUSBAR_SELECTION_CH_SINGULAR" : " \u2014 Vybrán {0} sloupec", "STATUSBAR_SELECTION_CH_PLURAL" : " \u2014 Vybrány {0} sloupce", "STATUSBAR_SELECTION_LINE_SINGULAR" : " \u2014 Vybrán {0} řádek", "STATUSBAR_SELECTION_LINE_PLURAL" : " \u2014 Vybrány {0} řádky", "STATUSBAR_CURSOR_POSITION" : "Řádek {0}, Sloupec {1}", "STATUSBAR_INDENT_TOOLTIP_SPACES" : "Přepnout odsazení na mezery", "STATUSBAR_INDENT_TOOLTIP_TABS" : "Přepnout odsazení na tabulátory", "STATUSBAR_INDENT_SIZE_TOOLTIP_SPACES" : "Změnit počet mezer použitých pro odsazení", "STATUSBAR_INDENT_SIZE_TOOLTIP_TABS" : "Změnit šířku tabulátoru", "STATUSBAR_SPACES" : "Mezery:", "STATUSBAR_TAB_SIZE" : "Velikost tabulátoru:", "STATUSBAR_LINE_COUNT_SINGULAR" : "Řádek: {0}", "STATUSBAR_LINE_COUNT_PLURAL" : "Řádky: {0}", // CodeInspection: chyby/varování "ERRORS_PANEL_TITLE" : "{0} chyby", "SINGLE_ERROR" : "1 {0} chyba", "MULTIPLE_ERRORS" : "{1} {0} chyby", "NO_ERRORS" : "Žádné {0} chyby - dobrá práce!", "LINT_DISABLED" : "Lintování je vypnuto", "NO_LINT_AVAILABLE" : "Žádný linter není dostupný pro {0}", "NOTHING_TO_LINT" : "Nic k lintování", /** * Příkazy */ // Příkazy menu Soubor "FILE_MENU" : "Soubor", "CMD_FILE_NEW_UNTITLED" : "Nový", "CMD_FILE_NEW" : "Nový soubor", "CMD_FILE_NEW_FOLDER" : "Nová složka", "CMD_FILE_OPEN" : "Otevřít\u2026", "CMD_ADD_TO_WORKING_SET" : "Přidat k pracovní sadě", "CMD_OPEN_DROPPED_FILES" : "Otevřít opuštěné soubory", "CMD_OPEN_FOLDER" : "Otevřít složku\u2026", "CMD_FILE_CLOSE" : "Zavřít", "CMD_FILE_CLOSE_ALL" : "Zavřít vše", "CMD_FILE_CLOSE_LIST" : "Zavřít seznam", "CMD_FILE_CLOSE_OTHERS" : "Zavřít ostatní", "CMD_FILE_CLOSE_ABOVE" : "Zavřít ostatní výše", "CMD_FILE_CLOSE_BELOW" : "Zavřít ostatní níže", "CMD_FILE_SAVE" : "Uložit", "CMD_FILE_SAVE_ALL" : "Uložit vše", "CMD_FILE_SAVE_AS" : "Uložit jako\u2026", "CMD_LIVE_FILE_PREVIEW" : "Živý náhled", "CMD_LIVE_HIGHLIGHT" : "Živé zvýraznění", "CMD_PROJECT_SETTINGS" : "Nastavení projektu\u2026", "CMD_FILE_RENAME" : "Přejmenovat", "CMD_FILE_DELETE" : "Smazat", "CMD_INSTALL_EXTENSION" : "Instalovat doplňky\u2026", "CMD_EXTENSION_MANAGER" : "Správce doplňků\u2026", "CMD_FILE_REFRESH" : "Obnovit", "CMD_QUIT" : "Konec", // Použito v souborovém menu Windows "CMD_EXIT" : "Konec", // Příkazy menu Edit "EDIT_MENU" : "Úpravy", "CMD_UNDO" : "Zpět", "CMD_REDO" : "Znovu", "CMD_CUT" : "Vyjmout", "CMD_COPY" : "Kopírovat", "CMD_PASTE" : "Vložit", "CMD_SELECT_ALL" : "Vybrat vše", "CMD_SELECT_LINE" : "Vybrat řádek", "CMD_FIND" : "Najít", "CMD_FIND_IN_FILES" : "Najít v souborech", "CMD_FIND_IN_SUBTREE" : "Najít v\u2026", "CMD_FIND_NEXT" : "Najít další", "CMD_FIND_PREVIOUS" : "Najít předchozí", "CMD_REPLACE" : "Nahradit", "CMD_INDENT" : "Odsadit", "CMD_UNINDENT" : "Vrátit odsazení", "CMD_DUPLICATE" : "Duplikovat", "CMD_DELETE_LINES" : "Smazat řádek", "CMD_COMMENT" : "Řádkový komentář", "CMD_BLOCK_COMMENT" : "Blokový komentář", "CMD_LINE_UP" : "Posunout řádek nahoru", "CMD_LINE_DOWN" : "Posunout řádek dolů", "CMD_OPEN_LINE_ABOVE" : "O řádek výše", "CMD_OPEN_LINE_BELOW" : "O řádek níže", "CMD_TOGGLE_CLOSE_BRACKETS" : "Uzavírat závorky", "CMD_SHOW_CODE_HINTS" : "Zobrazit nápovědu", // Příkazy menu Zobrazit "VIEW_MENU" : "Zobrazit", "CMD_HIDE_SIDEBAR" : "Skrýt boční menu", "CMD_SHOW_SIDEBAR" : "Zobrazit boční menu", "CMD_INCREASE_FONT_SIZE" : "Zvětšit velikost písma", "CMD_DECREASE_FONT_SIZE" : "Zmenšit velikost písma", "CMD_RESTORE_FONT_SIZE" : "Obnovit velikost písma", "CMD_SCROLL_LINE_UP" : "Posunout o řádek nahoru", "CMD_SCROLL_LINE_DOWN" : "Posunout o řádek dolů", "CMD_TOGGLE_LINE_NUMBERS" : "Čísla řádků", "CMD_TOGGLE_ACTIVE_LINE" : "Zvýraznit aktivní řádek", "CMD_TOGGLE_WORD_WRAP" : "Zalomit řádky", "CMD_VIEW_TOGGLE_INSPECTION" : "Lint soubory při uložení", "CMD_SORT_WORKINGSET_BY_ADDED" : "Řadit podle data", "CMD_SORT_WORKINGSET_BY_NAME" : "Řadit podle jména", "CMD_SORT_WORKINGSET_BY_TYPE" : "Řadit podle typu", "CMD_SORT_WORKINGSET_AUTO" : "Automatické řazení", // Příkazy menu Navigace "NAVIGATE_MENU" : "Navigace", "CMD_QUICK_OPEN" : "Rychle otevřít", "CMD_GOTO_LINE" : "Přejít na řádek", "CMD_GOTO_DEFINITION" : "Přejít na funkci", "CMD_GOTO_FIRST_PROBLEM" : "Přejít na první chybu/varování", "CMD_TOGGLE_QUICK_EDIT" : "Rychlá úprava", "CMD_TOGGLE_QUICK_DOCS" : "Rychlá dokumentace", "CMD_QUICK_EDIT_PREV_MATCH" : "Předchozí shoda", "CMD_QUICK_EDIT_NEXT_MATCH" : "Další shoda", "CMD_CSS_QUICK_EDIT_NEW_RULE" : "Nové pravidlo", "CMD_NEXT_DOC" : "Další dokument", "CMD_PREV_DOC" : "Předchozí dokument", "CMD_SHOW_IN_TREE" : "Zobrazit stromovou strukturu", "CMD_SHOW_IN_OS" : "Zobrazit v OS", // Příkazy menu nápověda "HELP_MENU" : "Nápověda", "CMD_CHECK_FOR_UPDATE" : "Zkontrolovat aktualizace", "CMD_HOW_TO_USE_BRACKETS" : "Jak používat {APP_NAME}", "CMD_FORUM" : "{APP_NAME} fórum", "CMD_RELEASE_NOTES" : "Poznámky k verzi", "CMD_REPORT_AN_ISSUE" : "Nahlásit problém", "CMD_SHOW_EXTENSIONS_FOLDER" : "Zobrazit složku s doplňky", "CMD_TWITTER" : "{TWITTER_NAME} - Twitter", "CMD_ABOUT" : "O aplikaci {APP_TITLE}", // Řetězce pro main-view.html "EXPERIMENTAL_BUILD" : "experimentální verze", "DEVELOPMENT_BUILD" : "vývojová verze", "OK" : "OK", "DONT_SAVE" : "Neukládat", "SAVE" : "Uložit", "CANCEL" : "Zrušit", "DELETE" : "Smazat", "RELOAD_FROM_DISK" : "Načíst z disku", "KEEP_CHANGES_IN_EDITOR" : "Ponechat změny v editoru", "CLOSE_DONT_SAVE" : "Zavřít (neukládat)", "RELAUNCH_CHROME" : "Restartovat Chrome", "ABOUT" : "O aplikaci", "CLOSE" : "Zavřít", "ABOUT_TEXT_LINE1" : "sprint {VERSION_MINOR} {BUILD_TYPE} {VERSION}", "ABOUT_TEXT_LINE3" : "Oznámení, podmínky týkající se software třetích stran jsou umístěny na <a href='{ADOBE_THIRD_PARTY}'>{ADOBE_THIRD_PARTY}</a> a začleněny prostřednictvím odkazu zde.", "ABOUT_TEXT_LINE4" : "Dokumentace a zdrojový kód na <a href='https://github.com/adobe/brackets/'>https://github.com/adobe/brackets/</a>.", "ABOUT_TEXT_LINE5" : "Vytvořeno s \u2764 a pomocí JavaScript těmito lidmi:", "ABOUT_TEXT_LINE6" : "Mnoho lidí (ale momentálně máme problém s načítáním dat).", "ABOUT_TEXT_WEB_PLATFORM_DOCS" : "Web Platform Docs a Web Platform logo využívají licenci Creative Commons Attribution, <a href='{WEB_PLATFORM_DOCS_LICENSE}'>CC-BY 3.0 Unported</a>.", "UPDATE_NOTIFICATION_TOOLTIP" : "Je dostupná nová verze {APP_NAME} ! Klikněte zde pro více informací.", "UPDATE_AVAILABLE_TITLE" : "Dostupná aktualizace", "UPDATE_MESSAGE" : "Nová verze {APP_NAME} je dostupná. Seznam některých vylepšení:", "GET_IT_NOW" : "Stáhnout!", "PROJECT_SETTINGS_TITLE" : "Nastavení projektu: {0}", "PROJECT_SETTING_BASE_URL" : "Živý náhled URL", "PROJECT_SETTING_BASE_URL_HINT" : "(nechte prázdné pro URL souboru)", "BASEURL_ERROR_INVALID_PROTOCOL" : "{0} protokol není podporován živým náhledem&mdash;prosím, použijte http: nebo https: .", "BASEURL_ERROR_SEARCH_DISALLOWED" : "URL nemůže obsahovat výrazy pro hledání jako \"{0}\".", "BASEURL_ERROR_HASH_DISALLOWED" : "URL nemůže obsahovat znaky jako \"{0}\".", "BASEURL_ERROR_INVALID_CHAR" : "Zvláštní znaky jako '{0}' musí být %-enkódovány.", "BASEURL_ERROR_UNKNOWN_ERROR" : "Neznámá chyba při zpracování URL", // CSS Quick Edit "BUTTON_NEW_RULE" : "Nové pravidlo", // Řetězce pro správce doplňků "INSTALL" : "Instalovat", "UPDATE" : "Aktualizovat", "REMOVE" : "Odstranit", "OVERWRITE" : "Přepsat", "CANT_REMOVE_DEV" : "Doplněk v \"dev\" složce musí být smazán manuálně.", "CANT_UPDATE" : "Aktualizace není kompatibilní s touto verzí {APP_NAME}.", "INSTALL_EXTENSION_TITLE" : "Instalovat doplněk", "UPDATE_EXTENSION_TITLE" : "Aktualizovat doplněk", "INSTALL_EXTENSION_LABEL" : "URL adresa doplňku", "INSTALL_EXTENSION_HINT" : "URL adresa zip archivu nebo GitHub repozitáře", "INSTALLING_FROM" : "Instalace doplňku z {0}\u2026", "INSTALL_SUCCEEDED" : "Instalace byla úspěšná!", "INSTALL_FAILED" : "Instalace se nezdařila.", "CANCELING_INSTALL" : "Rušení instalace\u2026", "CANCELING_HUNG" : "Rušení instalace trvá dlouho. Mohlo dojít k interní chybě.", "INSTALL_CANCELED" : "Instalace zrušena.", // Tyto musí odpovídat chybovým hlášením v ExtensionsDomain.Errors.* : "INVALID_ZIP_FILE" : "Stažený soubor není platný zip soubor.", "INVALID_PACKAGE_JSON" : "Package.json balíček není platný (chyba byla: {0}).", "MISSING_PACKAGE_NAME" : "Package.json balíček nespecifikuje jméno souboru.", "BAD_PACKAGE_NAME" : "{0} je neplatné jméno balíčku.", "MISSING_PACKAGE_VERSION" : "Package.json balíček nespecifikuje verzi souboru.", "INVALID_VERSION_NUMBER" : "Balíček verze ({0}) je neplatný.", "INVALID_BRACKETS_VERSION" : "Řetězec kompatibility {{0}} pro Brackets je neplatný.", "DISALLOWED_WORDS" : "Slova {{1}} nejsou povolena v {{0}} poli.", "API_NOT_COMPATIBLE" : "Doplněk není kompatibilní s touto verzi Brackets. Naleznete jej ve složce disabled extensions.", "MISSING_MAIN" : "Balíček neobsahuje soubor main.js.", "EXTENSION_ALREADY_INSTALLED" : "Instalace tohoto balíčku přepíše již nainstalovaný doplněk. Chcete přepsat starý doplněk?", "EXTENSION_SAME_VERSION" : "Tento balíček je stejná verze jako ta, kterou již máte nainstalovanou. Chcete přepsat existující doplněk?", "EXTENSION_OLDER_VERSION" : "Tento balíček je verze {0}, která je starší než současně nainstalovaná verze ({1}). Chcete přepsat existující doplněk?", "DOWNLOAD_ID_IN_USE" : "Interní chyba: ID stahování se již používá.", "NO_SERVER_RESPONSE" : "Nelze se připojit na server.", "BAD_HTTP_STATUS" : "Soubor nebyl nalezen (HTTP {0}).", "CANNOT_WRITE_TEMP" : "Nelze uložit do dočasných souborů.", "ERROR_LOADING" : "Při spuštění doplňku došlo k chybě.", "MALFORMED_URL" : "URL adresa je neplatná. Ujistěte se, že jste adresu zadali správně.", "UNSUPPORTED_PROTOCOL" : "URL adresa musí být http nebo https.", "UNKNOWN_ERROR" : "Neznámá chyba.", // Pro NOT_FOUND_ERR, vyhledejte obecné řetězce výše "EXTENSION_MANAGER_TITLE" : "Správce doplňků", "EXTENSION_MANAGER_ERROR_LOAD" : "Nelze získat přístup k registru doplňků. Prosím, zkuste to znovu později.", "INSTALL_FROM_URL" : "Instalovat z URL\u2026", "EXTENSION_AUTHOR" : "Autor", "EXTENSION_DATE" : "Datum", "EXTENSION_INCOMPATIBLE_NEWER" : "Tento doplněk požaduje novější verzi {APP_NAME}.", "EXTENSION_INCOMPATIBLE_OLDER" : "Tento doplněk funguje pouze ve starší verzi {APP_NAME}.", "EXTENSION_LATEST_INCOMPATIBLE_NEWER" : "Verze {0} tohoto doplňku vyžaduje novější verzi {APP_NAME}. Můžete si ale nainstalovat dřívější verzi {1}.", "EXTENSION_LATEST_INCOMPATIBLE_OLDER" : "Verze {0} tohoto doplňku funguje pouze se starší verzí {APP_NAME}. Můžete si ale nainstalovat dřívější verzi {1}.", "EXTENSION_NO_DESCRIPTION" : "Bez popisu", "EXTENSION_MORE_INFO" : "Více informací...", "EXTENSION_ERROR" : "Chyba doplňku", "EXTENSION_KEYWORDS" : "Klíčová slova", "EXTENSION_INSTALLED" : "Nainstalováno", "EXTENSION_UPDATE_INSTALLED" : "Aktualizace doplňku byla stažena a bude nainstalována při ukončení aplikace {APP_NAME}.", "EXTENSION_SEARCH_PLACEHOLDER" : "Hledat", "EXTENSION_MORE_INFO_LINK" : "Více", "BROWSE_EXTENSIONS" : "Procházet doplňky", "EXTENSION_MANAGER_REMOVE" : "Odstranit doplněk", "EXTENSION_MANAGER_REMOVE_ERROR" : "Chyba při odstraňování jednoho nebo více doplňků: {{0}}. {APP_NAME} bude stále ukončen.", "EXTENSION_MANAGER_UPDATE" : "Aktualizovat doplněk", "EXTENSION_MANAGER_UPDATE_ERROR" : "Nelze aktualizovat jeden nebo více doplňků: {0}. Aplikace {APP_NAME} bude ukončena.", "MARKED_FOR_REMOVAL" : "Označeno pro odstranění", "UNDO_REMOVE" : "Zpět", "MARKED_FOR_UPDATE" : "Označeno pro aktualizaci", "UNDO_UPDATE" : "Zpět", "CHANGE_AND_QUIT_TITLE" : "Změnit doplněk", "CHANGE_AND_QUIT_MESSAGE" : "Pro aktualizaci nebo odstranění označených doplňků musíte ukončit a restartovat aplikaci {APP_NAME}. Budete vyzváni k uložení změn.", "REMOVE_AND_QUIT" : "Odstranit doplňky a ukončit program", "CHANGE_AND_QUIT" : "Změnit doplňky a ukončit program", "UPDATE_AND_QUIT" : "Aktualizovat doplňky a ukončit program", "EXTENSION_NOT_INSTALLED" : "Doplněk {{0}} nemohl být odstraněn, protože nebyl nainstalován.", "NO_EXTENSIONS" : "Žádný doplněk ještě nebyl nainstalován.<br />Klikněte na tlačítko Instalovat z URL pro zahájení instalace.", "NO_EXTENSION_MATCHES" : "Žádný doplněk neodpovídá hledání.", "REGISTRY_SANITY_CHECK_WARNING" : "Buďte opatrní při instalaci doplňků z neznámých zdrojů.", "EXTENSIONS_INSTALLED_TITLE" : "Nainstalované", "EXTENSIONS_AVAILABLE_TITLE" : "Dostupné", "EXTENSIONS_UPDATES_TITLE" : "Aktualizace", "INLINE_EDITOR_NO_MATCHES" : "Žádné dostupné shody.", "CSS_QUICK_EDIT_NO_MATCHES" : "Neexistují žádná CSS pravidla odpovídající vašemu výběru.<br> Pro vytvoření pravidla klikněte na \"Nové pravidlo\".", "CSS_QUICK_EDIT_NO_STYLESHEETS" : "Neexistují žádné soubory s kaskádovými styly ve vašem projektu.<br>Vytvořte nový soubor pro přidání CSS pravidel.", /** * Jména jednotek */ "UNIT_PIXELS" : "pixely", // extensions/default/DebugCommands "DEBUG_MENU" : "Nástroje", "CMD_SHOW_DEV_TOOLS" : "Zobrazit nástroje pro vývojáře", "CMD_REFRESH_WINDOW" : "Restartovat {APP_NAME}", "CMD_NEW_BRACKETS_WINDOW" : "Nové okno {APP_NAME}", "CMD_SWITCH_LANGUAGE" : "Změnit jazyk", "CMD_RUN_UNIT_TESTS" : "Spustit testy", "CMD_SHOW_PERF_DATA" : "Zobrazit údaje o výkonnosti", "CMD_ENABLE_NODE_DEBUGGER" : "Povolit Node Debugger", "CMD_LOG_NODE_STATE" : "Uložit stav Node do konzole", "CMD_RESTART_NODE" : "Restartovat Node", "LANGUAGE_TITLE" : "Změnit jazyk", "LANGUAGE_MESSAGE" : "Prosím, vyberte jazyk ze seznamu:", "LANGUAGE_SUBMIT" : "Restartovat {APP_NAME}", "LANGUAGE_CANCEL" : "Zrušit", "LANGUAGE_SYSTEM_DEFAULT" : "Výchozí", /** * Jazyky */ "LOCALE_CS" : "Česky", "LOCALE_DE" : "Německy", "LOCALE_EN" : "Anglicky", "LOCALE_ES" : "Španělsky", "LOCALE_FR" : "Francouzsky", "LOCALE_IT" : "Italsky", "LOCALE_JA" : "Japonsky", "LOCALE_NB" : "Norsky", "LOCALE_PL" : "Polsky", "LOCALE_PT_BR" : "Portugalsky, Brazílie", "LOCALE_PT_PT" : "Portugalsky", "LOCALE_RU" : "Rusky", "LOCALE_SK" : "Slovensky", "LOCALE_SR" : "Srbština", "LOCALE_SV" : "Švédsky", "LOCALE_TR" : "Turecky", "LOCALE_FI" : "Finsky", "LOCALE_ZH_CN" : "Čínsky", "LOCALE_HU" : "Maďarsky", // extensions/default/InlineTimingFunctionEditor "INLINE_TIMING_EDITOR_TIME" : "Doba", "INLINE_TIMING_EDITOR_PROGRESSION" : "Postup", // extensions/default/InlineColorEditor "COLOR_EDITOR_CURRENT_COLOR_SWATCH_TIP" : "Současná barva", "COLOR_EDITOR_ORIGINAL_COLOR_SWATCH_TIP" : "Původní barva", "COLOR_EDITOR_RGBA_BUTTON_TIP" : "RGBa formát", "COLOR_EDITOR_HEX_BUTTON_TIP" : "Hex formát", "COLOR_EDITOR_HSLA_BUTTON_TIP" : "HSLa formát", "COLOR_EDITOR_USED_COLOR_TIP_SINGULAR" : "{0} (použito {1} krát)", "COLOR_EDITOR_USED_COLOR_TIP_PLURAL" : "{0} (použito {1} krát)", // extensions/default/JavaScriptCodeHints "CMD_JUMPTO_DEFINITION" : "Přejít na definici", "CMD_SHOW_PARAMETER_HINT" : "Zobrazit nápovědu parametru", "NO_ARGUMENTS" : "<žádné parametry>", // extensions/default/JSLint "JSLINT_NAME" : "JSLint", // extensions/default/QuickView "CMD_ENABLE_QUICK_VIEW" : "Rychlý náhled", // extensions/default/RecentProjects "CMD_TOGGLE_RECENT_PROJECTS" : "Nedávné projekty", // extensions/default/WebPlatformDocs "DOCS_MORE_LINK" : "Více" });
import store from '../store' import { mapState } from 'vuex' import { Scroller, Example } from 'components' export default { name: 'Main', store, computed: mapState({ name: state => state.name }), render() { const { name } = this return ( <Scroller> <Example name={ name } /> </Scroller> ) } }
export { default as invocationsRoute } from './invocations/index.js' export { default as invokeAsyncRoute } from './invoke-async/index.js'
const {capitalize} = require('../capitalize'); const {expect} = require('chai'); describe('capitalize() Capitalizes the first letter of a string', function() { it('should capitalize the first letter of a string', function(){ expect(capitalize("github")).to.equal("Github") }) })
/** * @file Defines the on-render callback and the event handler for MD Tabs. * @author Derek Gransaull <[email protected]> * @copyright DGTLife, LLC 2017 */ import { Template } from 'meteor/templating'; import { currentTab, initializeTabGroup, handleClickOnTab } from '../../api/md-tabs-api.js'; import './md-tabs.jade'; // On-render callback for MD Tabs. Template.md_tabs.onRendered( function onRenderedTabs() { /* * Initialize the tab group based on its template configuration, if it has * not already been initialized (e.g. by restoreTabs) */ if (!currentTab.get(this.data.id)) { initializeTabGroup(this.firstNode); } } ); // Event handler for MD Tabs. Template.md_tabs.events({ 'click .md-tab'(event) { handleClickOnTab(event.currentTarget); } });
/* * Copyright (c) 2013-2016 Chukong Technologies Inc. * * 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. */ 'use strict'; /** * @type {Object} * @name jsb.AssetsManager * jsb.AssetsManager is the native AssetsManager for your game resources or scripts. * please refer to this document to know how to use it: http://www.cocos2d-x.org/docs/manual/framework/html5/v3/assets-manager/en * Only available in JSB */ jsb.AssetsManager = cc.AssetsManager; /** * @type {Object} * @name jsb.Manifest * please refer to this document to know how to use it: http://www.cocos2d-x.org/docs/manual/framework/html5/v3/assets-manager/en * Only available in JSB */ jsb.Manifest = cc.Manifest; /** * @type {Object} * @name jsb.EventListenerAssetsManager * jsb.EventListenerAssetsManager is the native event listener for AssetsManager. * please refer to this document to know how to use it: http://www.cocos2d-x.org/docs/manual/framework/html5/v3/assets-manager/en * Only available in JSB */ jsb.EventListenerAssetsManager = cc.EventListenerAssetsManager; /** * @type {Object} * @name jsb.EventAssetsManager * jsb.EventAssetsManager is the native event for AssetsManager. * please refer to this document to know how to use it: http://www.cocos2d-x.org/docs/manual/framework/html5/v3/assets-manager/en * Only available in JSB */ jsb.EventAssetsManager = cc.EventAssetsManager; jsb.AssetsManager.State = { UNINITED : 0, UNCHECKED : 1, PREDOWNLOAD_VERSION : 2, DOWNLOADING_VERSION : 3, VERSION_LOADED : 4, PREDOWNLOAD_MANIFEST : 5, DOWNLOADING_MANIFEST : 6, MANIFEST_LOADED : 7, NEED_UPDATE : 8, READY_TO_UPDATE : 9, UPDATING : 10, UNZIPPING : 11, UP_TO_DATE : 12, FAIL_TO_UPDATE : 13 } jsb.EventListenerAssetsManager.prototype._ctor = function(assetsManager, callback) { callback !== undefined && this.init(assetsManager, callback); }; jsb.Manifest.DownloadState = { UNSTARTED: 0, DOWNLOADING: 1, SUCCESSED: 2, UNMARKED: 3 }; jsb.EventAssetsManager.ERROR_NO_LOCAL_MANIFEST = 0; jsb.EventAssetsManager.ERROR_DOWNLOAD_MANIFEST = 1; jsb.EventAssetsManager.ERROR_PARSE_MANIFEST = 2; jsb.EventAssetsManager.NEW_VERSION_FOUND = 3; jsb.EventAssetsManager.ALREADY_UP_TO_DATE = 4; jsb.EventAssetsManager.UPDATE_PROGRESSION = 5; jsb.EventAssetsManager.ASSET_UPDATED = 6; jsb.EventAssetsManager.ERROR_UPDATING = 7; jsb.EventAssetsManager.UPDATE_FINISHED = 8; jsb.EventAssetsManager.UPDATE_FAILED = 9; jsb.EventAssetsManager.ERROR_DECOMPRESS = 10; /** * @constant * @type Number */ cc.KEYBOARD_RETURNTYPE_DEFAULT = 0; /** * @constant * @type Number */ cc.KEYBOARD_RETURNTYPE_DONE = 1; /** * @constant * @type Number */ cc.KEYBOARD_RETURNTYPE_SEND = 2; /** * @constant * @type Number */ cc.KEYBOARD_RETURNTYPE_SEARCH = 3; /** * @constant * @type Number */ cc.KEYBOARD_RETURNTYPE_GO = 4; /** * The EditBox::InputMode defines the type of text that the user is allowed * to enter. * @constant * @type Number */ cc.EDITBOX_INPUT_MODE_ANY = 0; /** * The user is allowed to enter an e-mail address. * @constant * @type Number */ cc.EDITBOX_INPUT_MODE_EMAILADDR = 1; /** * The user is allowed to enter an integer value. * @constant * @type Number */ cc.EDITBOX_INPUT_MODE_NUMERIC = 2; /** * The user is allowed to enter a phone number. * @constant * @type Number */ cc.EDITBOX_INPUT_MODE_PHONENUMBER = 3; /** * The user is allowed to enter a URL. * @constant * @type Number */ cc.EDITBOX_INPUT_MODE_URL = 4; /** * The user is allowed to enter a real number value. * This extends kEditBoxInputModeNumeric by allowing a decimal point. * @constant * @type Number */ cc.EDITBOX_INPUT_MODE_DECIMAL = 5; /** * The user is allowed to enter any text, except for line breaks. * @constant * @type Number */ cc.EDITBOX_INPUT_MODE_SINGLELINE = 6; /** * Indicates that the text entered is confidential data that should be * obscured whenever possible. This implies EDIT_BOX_INPUT_FLAG_SENSITIVE. * @constant * @type Number */ cc.EDITBOX_INPUT_FLAG_PASSWORD = 0; /** * Indicates that the text entered is sensitive data that the * implementation must never store into a dictionary or table for use * in predictive, auto-completing, or other accelerated input schemes. * A credit card number is an example of sensitive data. * @constant * @type Number */ cc.EDITBOX_INPUT_FLAG_SENSITIVE = 1; /** * This flag is a hint to the implementation that during text editing, * the initial letter of each word should be capitalized. * @constant * @type Number */ cc.EDITBOX_INPUT_FLAG_INITIAL_CAPS_WORD = 2; /** * This flag is a hint to the implementation that during text editing, * the initial letter of each sentence should be capitalized. * @constant * @type Number */ cc.EDITBOX_INPUT_FLAG_INITIAL_CAPS_SENTENCE = 3; /** * Capitalize all characters automatically. * @constant * @type Number */ cc.EDITBOX_INPUT_FLAG_INITIAL_CAPS_ALL_CHARACTERS = 4;
/** * This file is part of the Unit.js testing framework. * * (c) Nicolas Tallefourtane <[email protected]> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code * or visit {@link http://unitjs.com|Unit.js}. * * @author Nicolas Tallefourtane <[email protected]> */ 'use strict'; var RawCommonApi = require('../common_api'), // constructor rawAssertions = require('../assertions'), // object _ = require('noder.io')._ ; /** * Expose all assertions * @type {function} * @param {mixed} actual Actual value tested * @return {Object} The current asserter */ module.exports = function BoolAsserter(actual) { // actual value tested this.actual = actual; // assertions with the current context var assertions = rawAssertions.call(this, actual); // Build the common API with the current context var CommonApi = RawCommonApi.bind(this); var commonApi = new CommonApi(); // provides the common API in the current asserter for (var method in commonApi) { this[method] = commonApi[method]; } // assert the type assertions.isBool(this.actual); // provides the assertions to the current asserter var useAssertions = ['isTrue', 'isNotTrue', 'isFalse', 'isNotFalse']; var asserterAssertions = _.pick(assertions, useAssertions); for (var method in asserterAssertions) { this[method] = asserterAssertions[method]; } // return this asserter return this; };
"use strict"; var React = require("react"); var MainView = require("../views/MainView"); var MainElement = document.getElementById("main"); var socket = require("socket.io-client")(); var Store = require("../views/Store"); var omit = require("lodash/object/omit"); socket.on("initialize", function (data) { Store.league = data.league; Store.adp = data.adp; var i = 0, players = data.players, total = players.length; for (; i < total; ++i) { Store.players[players[i].id] = omit(players[i], ["_id", "id"]); } var franchises = data.league.franchises.franchise; total = franchises.length; i = 0; for (; i < total; ++i) { Store.franchises[franchises[i].id] = omit(franchises[i], ["_id", "id"]); } var handleClick = function handleClick(event, callback) { console.log("deeper click"); var typeStr = event.target.getAttribute("data-target"); socket.emit("client-pull", typeStr, callback); }; React.render(React.createElement(MainView, { onClick: handleClick }), MainElement); }); socket.on("data-change", function (data) { console.log("data-change:", data); });
'use strict'; module.exports = { name: 'base', configure: function(config) { config.addCommand(require('./SwitchTextTypeCommand')); config.addCommand(require('./UndoCommand')); config.addCommand(require('./RedoCommand')); config.addTool(require('./UndoTool')); config.addTool(require('./RedoTool')); config.addTool(require('./SwitchTextTypeTool')); // Icons config.addIcon('undo', { 'fontawesome': 'fa-undo' }); config.addIcon('redo', { 'fontawesome': 'fa-repeat' }); config.addIcon('edit', { 'fontawesome': 'fa-cog' }); config.addIcon('delete', { 'fontawesome': 'fa-times' }); config.addIcon('expand', { 'fontawesome': 'fa-arrows-h' }); config.addIcon('truncate', { 'fontawesome': 'fa-arrows-h' }); // Labels config.addLabel('undo', { en: 'Undo', de: 'Rückgängig' }); config.addLabel('redo', { en: 'Redo', de: 'Wiederherstellen' }); config.addLabel('container-selection', { en: 'Container', de: 'Container' }); config.addLabel('container', { en: 'Container', de: 'Container' }); config.addLabel('insert-container', { en: 'Insert Container', de: 'Container einfügen' }); } };
'use strict'; angular.module('core').controller('ShortBreakController', ['$scope', '$interval', 'timer', function ($scope, $interval, timer) { var initialTime = 300000; $scope.currentTime = initialTime; $scope.startTimer = function() { timer.start($scope); }; $scope.stopTimer = function() { timer.stop($scope); }; $scope.resetTimer = function() { timer.reset($scope, initialTime); }; $scope.returnToWorkMessage = function() { return 1 === 1; }; } ]);
var dest = './public'; var src = './src'; module.exports = { browserSync: { server: { // Serve up our build folder baseDir: dest }, open: false, https: false }, sass: { src: [ src + '/assets/css/*.{sass,scss}', src + '/assets/css/**/*.{sass,scss}', src + '/assets/css/**/**/*.{sass,scss}' ], dest: dest + '/css', settings: { // indentedSyntax: true, // Enable .sass syntax! imagePath: 'images' // Used by the image-url helper } }, browserify: { // A separate bundle will be generated for each // bundle config in the list below bundleConfigs: [/*{ entries: src + '/javascript/global.coffee', dest: dest, outputName: 'global.js', // Additional file extentions to make optional extensions: ['.coffee', '.hbs'], // list of modules to make require-able externally require: [ 'jquery', 'backbone/node_modules/underscore' ] // See https://github.com/greypants/gulp-starter/issues/87 for note about // why this is 'backbone/node_modules/underscore' and not 'underscore' }, */{ entries: [ src + '/app/app.module.js' ], dest: dest + '/js', outputName: 'app.js', // list of externally available modules to exclude from the bundle external: [ 'jquery', 'underscore' ] }] }, moveAssets: { src: [ src + '/*.html', src + '/app/**/**/*.html', src + '/assets/libs/*' ], dest: dest }, templateCache: { src: src, dest: dest }, jshint: { src: [ src + '/app/*.js', src + '/app/**/*.js', src + '/app/**/**/*.js', src + '/app/**/**/**/*.js' ] } };
/*jslint browser: true */ /*global require, app: true, $, Backbone, window, document */ require([ 'router' ], function () { 'use strict'; });
// ## Globals /*global $:true*/ var $ = require('gulp-load-plugins')({rename: {'gulp-jade-php': 'jade' }}); var argv = require('yargs').argv; var browserSync = require('browser-sync'); var gulp = require('gulp'); var lazypipe = require('lazypipe'); var merge = require('merge-stream'); var runSequence = require('run-sequence'); // See https://github.com/austinpray/asset-builder var manifest = require('asset-builder')('./assets/manifest.json'); // `path` - Paths to base asset directories. With trailing slashes. // - `path.source` - Path to the source files. Default: `assets/` // - `path.dist` - Path to the build directory. Default: `dist/` var path = manifest.paths; // `config` - Store arbitrary configuration values here. var config = manifest.config || {}; // `globs` - These ultimately end up in their respective `gulp.src`. // - `globs.js` - Array of asset-builder JS dependency objects. Example: // ``` // {type: 'js', name: 'main.js', globs: []} // ``` // - `globs.css` - Array of asset-builder CSS dependency objects. Example: // ``` // {type: 'css', name: 'main.css', globs: []} // ``` // - `globs.fonts` - Array of font path globs. // - `globs.images` - Array of image path globs. // - `globs.bower` - Array of all the main Bower files. var globs = manifest.globs; // `project` - paths to first-party assets. // - `project.js` - Array of first-party JS assets. // - `project.css` - Array of first-party CSS assets. var project = manifest.getProjectGlobs(); // CLI options var enabled = { // Enable static asset revisioning when `--production` rev: argv.production, // Disable source maps when `--production` maps: !argv.production, // Fail styles task on error when `--production` failStyleTask: argv.production }; // Path to the compiled assets manifest in the dist directory var revManifest = path.dist + 'assets.json'; // ## Reusable Pipelines // See https://github.com/OverZealous/lazypipe // ### CSS processing pipeline // Example // ``` // gulp.src(cssFiles) // .pipe(cssTasks('main.css') // .pipe(gulp.dest(path.dist + 'styles')) // ``` var cssTasks = function(filename) { return lazypipe() .pipe(function() { return $.if(!enabled.failStyleTask, $.plumber()); }) .pipe(function() { return $.if(enabled.maps, $.sourcemaps.init()); }) .pipe(function() { return $.if('*.less', $.less()); }) .pipe(function() { return $.if('*.scss', $.sass({ outputStyle: 'nested', // libsass doesn't support expanded yet precision: 10, includePaths: ['.'], errLogToConsole: !enabled.failStyleTask })); }) .pipe($.concat, filename) .pipe($.autoprefixer, { browsers: [ 'last 2 versions', 'ie 8', 'ie 9', 'android 2.3', 'android 4', 'opera 12' ] }) .pipe($.minifyCss) .pipe(function() { return $.if(enabled.rev, $.rev()); }) .pipe(function() { return $.if(enabled.maps, $.sourcemaps.write('.')); })(); }; // ### JS processing pipeline // Example // ``` // gulp.src(jsFiles) // .pipe(jsTasks('main.js') // .pipe(gulp.dest(path.dist + 'scripts')) // ``` var jsTasks = function(filename) { return lazypipe() .pipe(function() { return $.if(enabled.maps, $.sourcemaps.init()); }) .pipe($.concat, filename) .pipe($.uglify) .pipe(function() { return $.if(enabled.rev, $.rev()); }) .pipe(function() { return $.if(enabled.maps, $.sourcemaps.write('.')); })(); }; // ### Write to rev manifest // If there are any revved files then write them to the rev manifest. // See https://github.com/sindresorhus/gulp-rev var writeToManifest = function(directory) { return lazypipe() .pipe(gulp.dest, path.dist + directory) .pipe(function() { return $.if('**/*.{js,css}', browserSync.reload({stream:true})); }) .pipe($.rev.manifest, revManifest, { base: path.dist, merge: true }) .pipe(gulp.dest, path.dist)(); }; // ## Gulp tasks // Run `gulp -T` for a task summary // ### Styles // `gulp styles` - Compiles, combines, and optimizes Bower CSS and project CSS. // By default this task will only log a warning if a precompiler error is // raised. If the `--production` flag is set: this task will fail outright. gulp.task('styles', ['wiredep'], function() { var merged = merge(); manifest.forEachDependency('css', function(dep) { var cssTasksInstance = cssTasks(dep.name); if (!enabled.failStyleTask) { cssTasksInstance.on('error', function(err) { console.error(err.message); this.emit('end'); }); } merged.add(gulp.src(dep.globs, {base: 'styles'}) .pipe(cssTasksInstance)); }); return merged .pipe(writeToManifest('styles')); }); // ### Scripts // `gulp scripts` - Runs JSHint then compiles, combines, and optimizes Bower JS // and project JS. gulp.task('scripts', ['jshint'], function() { var merged = merge(); manifest.forEachDependency('js', function(dep) { merged.add( gulp.src(dep.globs, {base: 'scripts'}) .pipe(jsTasks(dep.name)) ); }); return merged .pipe(writeToManifest('scripts')); }); // ### Fonts // `gulp fonts` - Grabs all the fonts and outputs them in a flattened directory // structure. See: https://github.com/armed/gulp-flatten gulp.task('fonts', function() { return gulp.src(globs.fonts) .pipe($.flatten()) .pipe(gulp.dest(path.dist + 'fonts')); }); // ### Images // `gulp images` - Run lossless compression on all the images. gulp.task('images', function() { return gulp.src(globs.images) .pipe($.imagemin({ progressive: true, interlaced: true, svgoPlugins: [{removeUnknownsAndDefaults: false}] })) .pipe(gulp.dest(path.dist + 'images')); }); // ### JSHint // `gulp jshint` - Lints configuration JSON and project JS. gulp.task('jshint', function() { return gulp.src([ 'bower.json', 'gulpfile.js' ].concat(project.js)) .pipe($.jshint()) .pipe($.jshint.reporter('jshint-stylish')) .pipe($.jshint.reporter('fail')); }); // ### Jade Templates // be careful - these views will overwrite the defaults in the root // gulp.task('jade', function() { // gulp.src('./assets/views/**/*.jade') // .pipe($.jade({ pretty : true })) // .on('error', function(err) { // console.error(err.message); // this.emit('end'); // }) // .pipe(gulp.dest('.')) // ; // }); // ### Clean // `gulp clean` - Deletes the build folder entirely. gulp.task('clean', require('del').bind(null, [path.dist])); // ### Watch // `gulp watch` - Use BrowserSync to proxy your dev server and synchronize code // changes across devices. Specify the hostname of your dev server at // `manifest.config.devUrl`. When a modification is made to an asset, run the // build step for that asset and inject the changes into the page. // See: http://www.browsersync.io gulp.task('watch', function() { browserSync({ proxy: config.devUrl, snippetOptions: { whitelist: ['/wp-admin/admin-ajax.php'], blacklist: ['/wp-admin/**'] } }); // gulp.watch([path.source + 'views/**/*'], ['jade']); gulp.watch([path.source + 'styles/**/*'], ['styles']); gulp.watch([path.source + 'scripts/**/*'], ['jshint', 'scripts']); gulp.watch([path.source + 'fonts/**/*'], ['fonts']); gulp.watch([path.source + 'images/**/*'], ['images']); gulp.watch(['bower.json', 'assets/manifest.json'], ['build']); gulp.watch('**/*.php', function() { browserSync.reload(); }); }); // ### Build // `gulp build` - Run all the build tasks but don't clean up beforehand. // Generally you should be running `gulp` instead of `gulp build`. gulp.task('build', function(callback) { runSequence('styles', 'scripts', ['fonts', 'images'], callback); }); // ### Wiredep // `gulp wiredep` - Automatically inject Less and Sass Bower dependencies. See // https://github.com/taptapship/wiredep gulp.task('wiredep', function() { var wiredep = require('wiredep').stream; return gulp.src(project.css) .pipe(wiredep()) .pipe($.changed(path.source + 'styles', { hasChanged: $.changed.compareSha1Digest })) .pipe(gulp.dest(path.source + 'styles')); }); // ### Gulp // `gulp` - Run a complete build. To compile for production run `gulp --production`. gulp.task('default', ['clean'], function() { gulp.start('build'); });
// run `node syncSchemaDocs.js` from the lib folder to update/add the schema docs that we specify here // note the relative path to nano module from where this doc is stored. // currently this script requires the context docs to already exist in couchdb // if creating/defining a brand new schema doc - use futon or curl to create an otherwise empty doc with the needed "_id" first. var nano = require('../node_modules/nano')('http://127.0.0.1:5984'); var db = nano.use('patterns'); // specifies the blank json to be sent when GETing /patterns/new var newPatternSchema = { "_id": "patternSchema", "doctype": "schema", "int_id": null, "name": "", "pic": {"b64encoding": "", "filename": "" }, "author": [{ "ORCID": "", "name": "" }], "context": "", "problem": "", "force": [{ "name": "", "description": "", "pic": { "b64encoding": "", "filename": "" } } ], "solution": "", "rationale": "", "diagram": { "b64encoding": "", "filename": "" }, "evidence": [ {} ], }; var alpaca = { "_id": "alpaca", "schema": { "title": "Create a new Pattern!", "type": "object", "properties": { "title": { "type": "string", "title": "Title" }, "image": { "type": "string", "title": "Select an image to upload..." } } } }; //schema for vaidating POST to new or PUT to /prototype var validationSchema = { "_id": "newPatternValidationSchema", "doctype": "schema", "$schema": "http://json-schema.org/schema#", "title": "New pattern validation schema", "type": "object", "items": { "type": "object", "properties": { "doctype":{ "type": "string" }, "name": { "type": "string" }, "pic": { "type": "object" }, "author": { "type": "array" }, "context": { "type": "string" }, "problem": { "type": "string" }, "force": { "type": "array" }, "solution": { "type": "string" }, "rationale": { "type": "string" }, "diagram": { "type": "object" }, "evidence": { "type": "array" } }, "required": ["doctype", "name", "pic", "author", "context", "problem", "force", "solution", "rationale", "diagram", "evidence"] } }; var schemaDocs = [newPatternSchema, validationSchema, alpaca]; //note this function uses an Immediately Invoked Function expression to // allow async call-back funtions to close properly within the // for loop. see // http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example/19323214#19323214 // http://learn.jquery.com/javascript-101/functions/#immediately-invoked-function-expression-iife // http://en.wikipedia.org/wiki/Immediately-invoked_function_expression function syncDocs() { for (var x = 0; x < schemaDocs.length; x++) { //IIFE - anon function will be called on each iteration of the for loop // we pass in the value of for loop x as index within the anon funct (function(index){ //we copy the contents of the JSON objects specified above into the temp var doc here var doc = JSON.parse(JSON.stringify(schemaDocs[index])); //retreive the doc from couch db db.get(doc['_id'], function(err, body){ if(!err){ //if OK, set/create temp doc "_rev" field to match current db rev doc['_rev'] = body['_rev']; //write the doc db.insert(doc, function(err, body){ console.log(body); }) } else{ // if the db.get fails console.log(err); } //console.log("doc id is "+doc['_id']+" and doc rev is set to "+doc['_rev']); }) })(x); // we send the for loop iterator x to the (IIFE) anon function above, where it is defined as 'index' // see IIFE links above } } syncDocs();
const ESCAPES = { u: (flags) => { flags.lowercaseNext = false flags.uppercaseNext = true }, l: (flags) => { flags.uppercaseNext = false flags.lowercaseNext = true }, U: (flags) => { flags.lowercaseAll = false flags.uppercaseAll = true }, L: (flags) => { flags.uppercaseAll = false flags.lowercaseAll = true }, E: (flags) => { flags.uppercaseAll = false flags.lowercaseAll = false }, r: (flags, result) => { result.push('\\r') }, n: (flags, result) => { result.push('\\n') }, $: (flags, result) => { result.push('$') } } function transformText (str, flags) { if (flags.uppercaseAll) { return str.toUpperCase() } else if (flags.lowercaseAll) { return str.toLowerCase() } else if (flags.uppercaseNext) { flags.uppercaseNext = false return str.replace(/^./, s => s.toUpperCase()) } else if (flags.lowercaseNext) { return str.replace(/^./, s => s.toLowerCase()) } return str } class Insertion { constructor ({ range, substitution, references }) { this.range = range this.substitution = substitution this.references = references if (substitution) { if (substitution.replace === undefined) { substitution.replace = '' } this.replacer = this.makeReplacer(substitution.replace) } } isTransformation () { return !!this.substitution } makeReplacer (replace) { return function replacer (...match) { let flags = { uppercaseAll: false, lowercaseAll: false, uppercaseNext: false, lowercaseNext: false } replace = [...replace] let result = [] replace.forEach(token => { if (typeof token === 'string') { result.push(transformText(token, flags)) } else if (token.escape) { ESCAPES[token.escape](flags, result) } else if (token.backreference) { let transformed = transformText(match[token.backreference], flags) result.push(transformed) } }) return result.join('') } } transform (input) { let { substitution } = this if (!substitution) { return input } return input.replace(substitution.find, this.replacer) } } module.exports = Insertion
// @ag-grid-community/react v25.1.0 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); //# sourceMappingURL=interfaces.js.map
/* Copyright (c) 2009-2011, Dan "Ducky" Little & GeoMOOSE.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ dojo.require('dojo.fx'); dojo.require('dijit.layout.BorderContainer'); dojo.require('dijit.layout.TabContainer'); dojo.require('dojox.widget.Standby'); dojo.registerModulePath('GeoMOOSE', '../../../geomoose/GeoMOOSE'); dojo.require('GeoMOOSE.Popup'); dojo.require('GeoMOOSE.Application'); dojo.require('GeoMOOSE.Handler.Box'); dojo.require('GeoMOOSE.Handler.MeasurePath'); dojo.require('GeoMOOSE.Control.Measure'); dojo.require('GeoMOOSE.Control.DeleteFeature'); dojo.require('GeoMOOSE.Dialog.AttributeEditor'); dojo.require('GeoMOOSE.Dialog.Download'); dojo.require('GeoMOOSE.MapSource'); dojo.require('GeoMOOSE.MapSource.Vector'); dojo.require('GeoMOOSE.MapSource.Vector.WFS'); dojo.require('GeoMOOSE.MapSource.WMS'); dojo.require('GeoMOOSE.MapSource.MapServer'); dojo.require('GeoMOOSE.MapSource.TMS'); dojo.require('GeoMOOSE.MapSource.XYZ'); dojo.require('GeoMOOSE.MapSource.Google'); dojo.require('GeoMOOSE.MapSource.AGS'); dojo.require('GeoMOOSE.Tab'); dojo.require('GeoMOOSE.Tab.Service'); dojo.require('GeoMOOSE.Tab.Catalog'); dojo.require('GeoMOOSE.Tab.Catalog.LayerControl'); dojo.require('GeoMOOSE.Tab.Catalog.LayerControl.Activate'); dojo.require('GeoMOOSE.Tab.Catalog.LayerControl.Popups'); dojo.require('GeoMOOSE.Tab.Catalog.LayerControl.Up'); dojo.require('GeoMOOSE.Tab.Catalog.LayerControl.Fade'); dojo.require('GeoMOOSE.Tab.Catalog.LayerControl.Legend'); dojo.require('GeoMOOSE.ServiceManager'); dojo.require('GeoMOOSE.UI.Toolbar'); dojo.require('GeoMOOSE.Layout.Default'); dojo.require('GeoMOOSE.UI.CoordinateDisplay'); dojo.require('GeoMOOSE.UI.ScaleJumper'); dojo.require('GeoMOOSE.UI.ZoomTo'); dojo.require('GeoMOOSE.UI.LinksBar'); dojo.require('GeoMOOSE.Tool.MeasureArea');
angular .module('platoon.event', []) .controller('EventController', ['$scope', '$location', '$filter', function($scope, $location, $filter) { $scope.eventTypes = [{ label: 'Private', type: 'private' },{ label: 'Company', type: 'company' },{ label: 'Wedding', type: 'wedding' },{ label: 'Student', type: 'student' } ]; $scope.add = {}; $scope.add.djs = { djs: [], add: function(dj) { $scope.$evalAsync(function() { $scope.add.djs.djs.push(dj); $scope.add.djs.current = ''; }.bind(this)); }, remove: function(event) { var target = $(event.target).find(':selected'); if (target.length > 0 && event.which === 8 || event.which === 46) { event.preventDefault(); event.stopPropagation(); var dj = target.html(); for (var i = 0; i < this.djs.length; i++) { if (this.djs[i] == dj) { this.djs.splice(i, 1); break; } } } }, engine: { name: 'djs', source: new Bloodhound({ queryTokenizer: Bloodhound.tokenizers.whitespace, datumTokenizer: Bloodhound.tokenizers.whitespace, local: ['Max', 'Arvid', 'Roshan', 'Amanda', 'Robin'] }) } }; $scope.add.type = $scope.eventTypes[0].type; $scope.add.phone = ''; $scope.add.layout = 'standard'; $scope.$watch(function() { return $scope.add.phone; }, function(val) { if (val != null) $scope.add.phone = $filter('phoneNumber')(val); }); }]);
/* © Copyright Adam Aharony (a.k.a. Cringy Adam) All rights reserved Twitter: @AdamAharony, Discord: @Cringy Adam#4611 */ exports.run = (client, message, args) => { message.delete(); message.channel.send('', { embed: { author: { name: client.user.username }, color: 0x008AF3, title: "CringyBot Selfbot edition info:", description: 'This selfbot is made by Adam Aharony (bot origionally from @XeliteXirish (a.k.a. Cringy Adam).\n(Twitter: @AdamAharony)\nAiming to make the discord experience much better.\nSpecial thanks to Jayden#5395 for helping me with some commands.', timestamp: new Date(), footer: { text: 'CringyBot Selfbot edition', icon_url: client.user.avatarURL } } }); };
'use strict'; /** * This contains a promisified confirmation question */ module.exports = function(kbox) { // Npm modules var inquirer = require('inquirer'); // Kbox modules var Promise = require('bluebird'); /* * Make sure the user wants to proceed with the install/update */ return function(state) { // Set up our confirmation question var confirm = { type: 'confirm', name: 'doit', message: 'Install all the magic and get this party started?', when: function(answers) { return !state.nonInteractive; } }; // Kick off a promise for this return new Promise(function(resolve) { return inquirer.prompt([confirm], function(answers) { // Log our answers state.log.debug('USER INPUT => ' + JSON.stringify(answers)); // Return our answers return resolve(answers); }); }); }; };
import React from 'react'; import {withStyles} from '@material-ui/core/styles'; import Popover from '@material-ui/core/Popover'; import {VisualQueryManager, PastebinContext} from './Pastebin'; import GraphicalQuery from '../components/GraphicalQuery'; const animationId = `scr-a-graphicalHighlight-${Date.now()}`; const styles = theme => ({ '@global': { [`@keyframes ${animationId}`]: { '0%': {borderWidth: '1px'}, '100%': {borderWidth: '2px'}, }, }, element: { border: `1px solid ${theme.palette.secondary.main}`, }, popoverPaper: { marginLeft: -2, marginTop: -2, overflow: 'auto', maxWidth: 'unset', maxHeight: 'unset', background: 'transparent', }, popover: { // restricts backdrop from being modal width: 0, height: 0, }, anchor: { backgroundColor: 'transparent', position: 'absolute', width: 0, height: 0, borderTop: '5px solid transparent', borderBottom: '5px solid transparent', borderLeft: `5px solid ${theme.palette.secondary.main}`, }, }); let visualIdentifier = () => []; export const getVisualIdsFromRefs = (refsArray) => { return visualIdentifier(refsArray); }; class GraphicalMapper extends React.Component { addOverlay(elt, containerRef, handleChangeGraphicalLocator, isSelected, key) { if (!this.vContainer) { return; } const overlays = []; const clientRect = containerRef.current.getBoundingClientRect(); const containerOffsetTopPos = clientRect.y; const containerOffsetLeftPos = clientRect.x; const rects = elt.getClientRects(); for (let i = 0; i < rects.length; i++) { const rect = rects[i]; const tableRectDiv = document.createElement('div'); tableRectDiv.style.overflow = elt.style.overflow || 'unset'; tableRectDiv.style.position = 'absolute'; tableRectDiv.style.border = '1px dashed darkorange'; if (isSelected) { tableRectDiv.style.animation = `${animationId} 1s 1s infinite`; tableRectDiv.style.border = '1px solid darkorange'; } const scrollTop = document.documentElement.scrollTop || document.body.scrollTop; const scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft; tableRectDiv.style.margin = tableRectDiv.style.padding = '0'; tableRectDiv.style.top = (containerOffsetTopPos + rect.top + scrollTop) + 'px'; tableRectDiv.style.left = (containerOffsetLeftPos + rect.left + scrollLeft) + 'px'; // we want rect.width to be the border width, so content width is 2px less. tableRectDiv.style.width = (rect.width - 2) + 'px'; tableRectDiv.style.height = (rect.height - 2) + 'px'; tableRectDiv.onclick = handleChangeGraphicalLocator; this.vContainer.appendChild(tableRectDiv); // document.body.appendChild(tableRectDiv); overlays.push({ overlay: tableRectDiv, reactKey: `${tableRectDiv.style.top}:${ tableRectDiv.style.left }:${tableRectDiv.style.width}:${tableRectDiv.style.height}:${key}` }); } return overlays; } getVisualIdsFromRefs = (refsArray) => { if (refsArray && refsArray.map && this.props && this.props.visualElements) { return refsArray.map(ref => this.props.visualElements.indexOf(ref)).filter(e => e >= 0); } else { return []; } }; componentDidMount() { visualIdentifier = this.getVisualIdsFromRefs; } componentWillMount() { visualIdentifier = () => []; } render() { const { classes, bundle, isGraphicalLocatorActive, visualElements, containerRef, handleChangeGraphicalLocator, searchState } = this.props; const locatedEls = []; if (isGraphicalLocatorActive) { if (this.vContainer) { document.body.removeChild(this.vContainer); this.vContainer = null; } this.vContainer = document.createElement('div'); document.body.appendChild(this.vContainer); visualElements.forEach((IframeAnchorEl, key) => { if (IframeAnchorEl.tagName === 'STYLE') { return; } const isSelected = searchState.visualQuery && searchState.visualQuery.find(el => el === IframeAnchorEl); const anchorEls = this .addOverlay( IframeAnchorEl, containerRef, handleChangeGraphicalLocator, isSelected, key ); if (!anchorEls[0]) { return; } this.anchors = this.anchors || []; this.visualEls = this.visualEls || []; VisualQueryManager.visualElements = this.visualEls; this.anchors.push(anchorEls); this.visualEls.push(IframeAnchorEl); const anchorEl = anchorEls[0].overlay; const reactKey = anchorEls[0].reactKey; locatedEls.push(<Popover key={reactKey} className={classes.popover} classes={{ paper: classes.popoverPaper, }} modal={null} hideBackdrop={true} disableBackdropClick={true} disableAutoFocus={true} disableEnforceFocus={true} open={true} anchorEl={anchorEl} onClose={this.handleClose} elevation={0} anchorOrigin={{ vertical: 'bottom', horizontal: 'right', }} transformOrigin={{ vertical: 'top', horizontal: 'left', }} > <div className={classes.anchor}/> <GraphicalQuery outputRefs={[IframeAnchorEl]} visualIds={[key]} selected={!!isSelected} /> </Popover>); }); } else { if (this.vContainer) { document.body.removeChild(this.vContainer); this.vContainer = null; } if (searchState.visualQuery && searchState.visualQuery.length) { if (this.vContainer) { document.body.removeChild(this.vContainer); this.vContainer = null; } this.vContainer = document.createElement('div'); document.body.appendChild(this.vContainer); visualElements.forEach((IframeAnchorEl, key) => { if (IframeAnchorEl.tagName === 'STYLE' || !searchState.visualQuery.includes(IframeAnchorEl)) { return; } const isSelected = searchState.visualQuery && searchState.visualQuery.find(el => el === IframeAnchorEl); const anchorEls = this .addOverlay( IframeAnchorEl, containerRef, handleChangeGraphicalLocator, isSelected, key ); if (!anchorEls[0]) { return; } this.anchors = this.anchors || []; this.visualEls = this.visualEls || []; this.anchors.push(anchorEls); this.visualEls.push(IframeAnchorEl); const anchorEl = anchorEls[0].overlay; const reactKey = anchorEls[0].reactKey; locatedEls.push(<Popover key={reactKey} className={classes.popover} classes={{ paper: classes.popoverPaper, }} modal={null} hideBackdrop={true} disableBackdropClick={true} disableAutoFocus={true} disableEnforceFocus={true} open={true} anchorEl={anchorEl} onClose={this.handleClose} elevation={0} anchorOrigin={{ vertical: 'bottom', horizontal: 'right', }} transformOrigin={{ vertical: 'top', horizontal: 'left', }} > <div className={classes.anchor}/> <GraphicalQuery outputRefs={[IframeAnchorEl]} visualIds={[key]} selected={!!isSelected} /> </Popover>); }); } else { if (this.vContainer) { document.body.removeChild(this.vContainer); this.vContainer = null; } } } return <React.Fragment>{locatedEls}</React.Fragment>; } } const GraphicalMapperWithContext = props => ( <PastebinContext.Consumer> {(context) => { return <GraphicalMapper {...props} {...context}/> }} </PastebinContext.Consumer> ); export default withStyles(styles)(GraphicalMapperWithContext);
/** * butterItemFilterField is a jQuery plugin that filters html element with the css class <code>filterable-item</code>. * It is applied to the search field.<br/> * If no filter text is entered, then all filterable-items are displayed. Else the search field value is matched against <b>all</b> text contained by a filterable-item. * * How to use: * jQuery("#someInputSelector").butterItemFilterField(); * * Author: Yann Massard */ (function ($) { var delay = (function () { var timer = 0; return function (callback, ms) { clearTimeout(timer); timer = setTimeout(callback, ms); }; })(); // extend jQuery -------------------------------------------------------------------- $.fn.butterItemFilterField = function (filterableItemContainerSelector) { return this.each(function () { var $this = $(this); $this.keyup(function () { delay(function () { var filterValue = $this.val(); // find container again every time, because it could have been rerendered. var $filterableItemContainer; if (filterableItemContainerSelector) { $filterableItemContainer = $(filterableItemContainerSelector); } else { var containerSelector = $this.attr('data-filterable-item-container'); $filterableItemContainer = $(containerSelector); } var filterableItems = $filterableItemContainer.find('.filterable-item'); filterableItems.each(function (i, elem) { var $filterableItem = $(elem); if ($filterableItem.is(':containsIgnoreCase(' + filterValue + ')')) { $filterableItem.removeAttr("hidden"); $filterableItem.highlight(filterValue); } else { $filterableItem.attr("hidden", "hidden"); } }); }, 300); }); }); }; }(jQuery)); (function ($) { $.expr[":"].containsIgnoreCase = $.expr.createPseudo(function (arg) { return function (elem) { return !arg || $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0; }; }); }(jQuery));
var translations = { 'Mostri spaziali': { en: 'Space monsters', }, 'Dettagli': { en: 'Details', }, 'Testa': { en: 'Head', }, 'Occhi': { en: 'Eyes', }, 'Naso': { en: 'Nose', }, 'Bocca': { en: 'Mouth', }, 'Orecchie': { en: 'Ears', }, 'Fantasmatico': { en: 'InHideum', }, 'Allegro': { en: 'Happy', }, 'Orribile': { en: 'Franken', }, 'Schifoso': { en: 'Zombus', }, 'Bizzarro': { en: 'Wackus', }, 'Smorfioso': { en: 'Vegitas', }, 'Spiritato': { en: 'Spritem', }, 'Crea un mostro a caso': { en: 'Create a random monster', }, 'Come si chiama?': { en: 'What\'s his name?', }, 'Mostro numero': { en: 'Monster number', }, 'Stampa per giocare': { en: 'Print to play', }, 'Maggiori info su code.org': { en: 'More info on code.org', }, 'Lingua': { en: 'Language', } };
// Fuzzy utility 'use strict'; var filter = require('array-filter'); var fuzzy = function(items, key) { return function (query) { query = query.toLowerCase(); var re = new RegExp(query, 'i'); return filter(items, function(item) { return re.test(item[key]); }); }; }; module.exports = fuzzy;
'use strict'; /* jshint ignore:start */ /** * This code was generated by * \ / _ _ _| _ _ * | (_)\/(_)(_|\/| |(/_ v1.0.0 * / / */ /* jshint ignore:end */ var _ = require('lodash'); /* jshint ignore:line */ var AssistantList = require('./understand/assistant').AssistantList; var Version = require('../../base/Version'); /* jshint ignore:line */ /* jshint ignore:start */ /** * Initialize the Understand version of Preview * * @constructor Twilio.Preview.Understand * * @property {Twilio.Preview.Understand.AssistantList} assistants - * assistants resource * * @param {Twilio.Preview} domain - The twilio domain */ /* jshint ignore:end */ function Understand(domain) { Version.prototype.constructor.call(this, domain, 'understand'); // Resources this._assistants = undefined; } _.extend(Understand.prototype, Version.prototype); Understand.prototype.constructor = Understand; Object.defineProperty(Understand.prototype, 'assistants', { get: function() { this._assistants = this._assistants || new AssistantList(this); return this._assistants; } }); module.exports = Understand;
/* Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang( 'font', 'sv', { fontSize: { label: 'Storlek', voiceLabel: 'Teckenstorlek', panelTitle: 'Teckenstorlek' }, label: 'Typsnitt', panelTitle: 'Typsnitt', voiceLabel: 'Typsnitt' } );
function ConnectionList(){ this.client = {}; this.add = function(id, value){ if( id ) this.client[id] = value; else throw "Não da pra adicionar um valor [ " + id + " ] ao dicionario hash;"; } this.remove = function(id){ delete this.client[id]; } this.clear = function(){ delete this.client; this.client = {}; } this.length = function(){ return Object.keys( this.client ).length; } this.get = function(id){ return this.client[id]; } this.find = function(id){ if (this.client[id] == undefined) return false else return true; } this.getAll = function(){ return Object.values(this.client); } this.broadcast = function(evt, msg){ for (var key in this.client) { this.client[key].socket.emit(evt, msg); } } this.getData = function(id){ return this.client[id].data; } this.getAllData = function(evt, msg){ var array = []; for (var key in this.client) { array.push( this.client[key].data ); } return array; } this.getAllDataObj = function(evt, msg){ var obj = {}; for (var key in this.client) { obj[key] = this.client[key].data; } return obj; } this.clone = function(){ var list = new ConnectionList(); for (var key in this.client) { list.add( key, this.client[key] ); } return list; } } module.exports = ConnectionList;
// Generated by CoffeeScript 1.3.3 (function() { var MAXSAMPLES, Point, STAGE_LOBBY, STAGE_PLAYING, baseObject, button, calcAvgTick, canvas, delta, difficulty, enemy, explosion, initialize, lastScore, lasttime, lives, missile, missileFired, mouseDown, mouseX, mouseY, nextspawn, objectlist, origin, point, samples, score, spawnthink, stage, startButton, think, tickindex, ticklist, ticksum, time, toremove, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; MAXSAMPLES = 100; samples = 0; tickindex = 0; ticksum = 0; ticklist = []; calcAvgTick = function(newtick) { ticklist[tickindex] = ticklist[tickindex] || 0; ticksum -= ticklist[tickindex]; ticksum += newtick; ticklist[tickindex] = newtick; tickindex++; if (tickindex === MAXSAMPLES) { tickindex = 0; } if (samples < MAXSAMPLES) { samples++; return 0; } return ticksum / MAXSAMPLES; }; canvas = $("#canvas"); mouseX = 0; mouseY = 0; mouseDown = false; time = (new Date()).getTime(); lasttime = time; delta = 0; objectlist = []; toremove = []; difficulty = 0; score = 0; lives = 3; lastScore = null; STAGE_LOBBY = 0; STAGE_PLAYING = 1; stage = STAGE_LOBBY; Point = (function() { function Point(x, y) { this.x = x; this.y = y; } Point.prototype.add = function(b) { return new Point(this.x + b.x, this.y + b.y); }; Point.prototype.sub = function(b) { return new Point(this.x - b.x, this.y - b.y); }; Point.prototype.mul = function(b) { if (typeof b === "number") { return new Point(this.x * b, this.y * b); } else { return new Point(this.x * b.x, this.y * b.y); } }; Point.prototype.div = function(b) { if (typeof b === "number") { return new Point(this.x / b, this.y / b); } else { return new Point(this.x / b.x, this.y / b.y); } }; Point.prototype.distance = function(b) { return Math.sqrt(Math.pow(b.x - this.x, 2) + Math.pow(b.y - this.y, 2)); }; Point.prototype.norm = function() { return this.div(this.distance(origin)); }; return Point; })(); point = function(x, y) { return new Point(x, y); }; origin = point(0, 0); Math.rand = function(a, b) { var c; c = a; if (b > a) { c = b; b = a; } return b + Math.round(Math.random() * (c - b)); }; Math.randD = function(a, b) { var c; c = a; if (b > a) { c = b; b = a; } return b + Math.random() * (c - b); }; baseObject = (function() { function baseObject() { objectlist.push(this); this.timestamp = time; this.initialize(); } baseObject.prototype.initialize = function() {}; baseObject.prototype.think = function() {}; baseObject.prototype.render = function() { return canvas.drawArc({ fillStyle: "black", x: this.x, y: this.y, radius: 4 }); }; baseObject.prototype.remove = function() { if (toremove.indexOf(this) < 0) { return toremove.push(this); } }; baseObject.prototype._remove = function() { objectlist.splice(objectlist.indexOf(this), 1); return delete this; }; baseObject.prototype.x = 0; baseObject.prototype.y = 0; baseObject.prototype.setPos = function(point, b) { if (typeof point === "object") { this.x = point.x; return this.y = point.y; } else { this.x = point; return this.y = b; } }; baseObject.prototype.getPos = function() { return point(this.x, this.y); }; return baseObject; })(); enemy = (function(_super) { __extends(enemy, _super); function enemy() { return enemy.__super__.constructor.apply(this, arguments); } enemy.prototype.speed = 0.05; enemy.prototype.initialize = function() { return this.speed = 0.05 + difficulty / 100; }; enemy.prototype.isEnemy = true; enemy.prototype.setOrigin = function(origin) { this.origin = origin; return this.setPos(origin); }; enemy.prototype.setTarget = function(target) { return this.target = target; }; enemy.prototype.think = function() { var pos, z; pos = this.getPos().add((this.target.sub(this.getPos())).norm().mul(delta * this.speed)); this.setPos(pos); if (delta * this.speed > this.getPos().distance(this.target)) { z = new explosion; z.setPos(this.getPos()); this.remove(); lives--; if (lives < 1) { lastScore = score; return initialize(); } } }; enemy.prototype.render = function() { canvas.drawLine({ strokeStyle: "silver", strokeWidth: 1, x1: this.x, y1: this.y, x2: this.origin.x, y2: this.origin.y }); return enemy.__super__.render.apply(this, arguments); }; return enemy; })(baseObject); missileFired = false; missile = (function(_super) { __extends(missile, _super); function missile() { return missile.__super__.constructor.apply(this, arguments); } missile.prototype.speed = 0.15; missile.prototype.initialize = function() { return this.speed = 0.15 + difficulty / 75; }; missile.prototype.setTarget = function(target) { return this.target = target; }; missile.prototype.think = function() { var pos, z; pos = this.getPos().add((this.target.sub(this.getPos())).norm().mul(delta * this.speed)); this.setPos(pos); if (delta * this.speed > this.getPos().distance(this.target)) { z = new explosion; z.radius = 500; z.setPos(this.getPos()); missileFired = false; return this.remove(); } }; return missile; })(baseObject); explosion = (function(_super) { __extends(explosion, _super); function explosion() { return explosion.__super__.constructor.apply(this, arguments); } explosion.prototype.radius = 250; explosion.prototype.initialize = function() {}; explosion.prototype.think = function() { var e, z, _i, _len; for (_i = 0, _len = objectlist.length; _i < _len; _i++) { e = objectlist[_i]; if (e.isEnemy != null) { if (e.getPos().distance(this.getPos()) <= (time - this.timestamp) / 10) { z = new explosion; z.setPos(e.getPos()); e.remove(); score++; } } } if ((time - this.timestamp) > this.radius) { return this.remove(); } }; explosion.prototype.render = function() { var a; a = Math.round(255 * (time - this.timestamp) / this.radius); return canvas.drawArc({ strokeStyle: "rgb(255 , " + a + ", " + a + ")", strokeWidth: 2, x: this.x, y: this.y, radius: (time - this.timestamp) / 10 }); }; return explosion; })(baseObject); button = (function(_super) { __extends(button, _super); function button() { return button.__super__.constructor.apply(this, arguments); } button.prototype.speed = 0.05; button.prototype.hovered = false; button.prototype.width = 100; button.prototype.height = 100; button.prototype.lastMouseDown = false; button.prototype.clicking = false; button.prototype.text = 'Nothing'; button.prototype.initialize = function() {}; button.prototype.setText = function(text) { return this.text = text; }; button.prototype.remove = function() { return button.__super__.remove.apply(this, arguments); }; button.prototype.think = function() { this.hovered = !(mouseX < this.x || mouseY < this.y || mouseX > this.x + this.width || mouseY > this.y + this.height); if (this.hovered) { canvas.css('cursor', 'pointer'); } else { canvas.css('cursor', 'auto'); } if (this.hovered && mouseDown && !this.lastMouseDown) { this.clicking = true; } if (!mouseDown) { if (this.clicking && this.hovered) { this.onclick(); } this.clicking = false; } return this.lastMouseDown = mouseDown; }; button.prototype.onclick = function() { return canvas.css('cursor', 'auto'); }; button.prototype.render = function() { var fill; fill = "#555555"; if (this.hovered) { fill = "#888888"; if (mouseDown) { fill = "#333333"; } } return canvas.drawRect({ fillStyle: fill, x: this.x, y: this.y, width: this.width, height: this.height, fromCenter: false }).drawText({ fillStyle: "#FFF", x: this.x + this.width / 2, y: this.y + this.height / 2, font: "14px sans-serif", text: this.text, fromCenter: true }); }; return button; })(baseObject); think = function() { var object, text, _i, _j, _k, _len, _len1, _len2; time = (new Date()).getTime(); delta = time - lasttime; lasttime = time; for (_i = 0, _len = objectlist.length; _i < _len; _i++) { object = objectlist[_i]; if (object != null) { object.think(); } } canvas.clearCanvas(); for (_j = 0, _len1 = objectlist.length; _j < _len1; _j++) { object = objectlist[_j]; object.render(); } for (_k = 0, _len2 = toremove.length; _k < _len2; _k++) { object = toremove[_k]; object._remove(); } if (stage === STAGE_PLAYING) { canvas.drawText({ fillStyle: "#000", x: 200, y: 10, font: "12px Arial, sans-serif", text: "Lives: " + lives }).drawText({ fillStyle: "#000", x: 100, y: 10, font: "12px Arial, sans-serif", text: "Score: " + score }).drawRect({ fillStyle: "#000", x: 0, y: 350, width: 400, height: 50, fromCenter: false }); difficulty += delta / 10000; spawnthink(); } else { canvas.drawText({ fillStyle: "#000", x: 200, y: 10, font: "16px Arial, sans-serif", text: "Defend the Earth from asteroids!" }).drawText({ fillStyle: "#000", x: 200, y: 26, font: "12px Arial, sans-serif", text: "Use the left mouse button and shoot down the asteroids" }).drawText({ fillStyle: "#000", x: 200, y: 39, font: "12px Arial, sans-serif", text: "before they fall!" }); if (lastScore !== null) { text = "Uh, you scored " + lastScore + " points..."; if (lastScore > 5) { text = "Cool, you scored " + lastScore + " points..."; } if (lastScore > 10) { text = "Whoa! You scored " + lastScore + " points!"; } if (lastScore > 25) { text = "Awesome! You scored " + lastScore + " points!"; } if (lastScore > 50) { text = "HOLY SHIT! You scored " + lastScore + " points!"; } if (lastScore > 100) { text = "you gotta be cheating now; " + lastScore + " points?"; } canvas.drawText({ fillStyle: "#000", weight: "bold", x: 200, y: 100, font: "18px Arial, sans-serif", text: text }); } } return toremove = []; }; nextspawn = 0; spawnthink = function() { var e, _ref; if (time > nextspawn) { nextspawn = time + 2000 - ((_ref = difficulty > 7.5) != null ? _ref : { 1500: difficulty * 200 }); e = new enemy(); e.setTarget(point(Math.rand(0, 400), 350)); return e.setOrigin(point(Math.rand(0, 400), -10)); } }; setInterval(think, 0); canvas.mousemove(function(e) { mouseX = e.offsetX; return mouseY = e.offsetY; }).click(function(e) { var z; if (stage === STAGE_PLAYING) { if (!missileFired) { z = new missile(); z.setTarget(point(e.offsetX, e.offsetY)); z.setPos(point(200, 350)); return missileFired = true; } } }).mousedown(function(e) { console.log(e.offsetX); mouseX = e.offsetX; mouseDown = true; return think(); }).mouseup(function(e) { mouseY = e.offsetY; mouseDown = false; return think(); }); startButton = null; initialize = function() { nextspawn = 0; objectlist = []; toremove = []; stage = STAGE_LOBBY; startButton = new button(); startButton.setText("Play"); startButton.setPos(point(150, 150)); startButton.onclick = function() { stage = STAGE_PLAYING; startButton.remove(); return canvas.css('cursor', 'auto'); }; difficulty = 0; score = 0; lives = 3; return missileFired = false; }; initialize(); }).call(this);
import React from 'react'; const Footer = () => ( <div className="col s12 home-inner footer" > <div className="inner-content center m-auto"> <p> Copyright &copy; 2017 Andela24 News - All rights reserved </p> </div> </div> ); export default Footer;
import chai, { expect } from 'chai' import chaiHttp from 'chai-http' import server from '../src/index' import Query from '../src/query' import { url } from '../src/resources' chai.use(chaiHttp) export default (done) => { Query.create({title: 'Task', completed: true}) .then((task) => { task.title = 'Tarefa Alterada' chai.request(server.info.uri) .put(url) .send(task) .end((err, res) => { expect(res).to.have.status(200) expect(res.body).to.not.be.null expect(res.body).to.have.property('title') expect(res.body.title).to.equal('Tarefa Alterada') done() }) }) .error((err) => { done(err) }) }
/** @module ember @submodule ember-htmlbars */ /** An HTMLBars AST transformation that replaces all instances of ```handlebars {{#with foo.bar as bar}} {{/with}} ``` with ```handlebars {{#with foo.bar keywordName="bar"}} {{/with}} ``` @private @class TransformWithAsToHash */ function TransformWithAsToHash() { // set later within HTMLBars to the syntax package this.syntax = null; } /** @private @method transform @param {AST} The AST to be transformed. */ TransformWithAsToHash.prototype.transform = function TransformWithAsToHash_transform(ast) { var pluginContext = this; var walker = new pluginContext.syntax.Walker(); var b = pluginContext.syntax.builders; walker.visit(ast, function(node) { if (pluginContext.validate(node)) { var removedParams = node.sexpr.params.splice(1, 2); var keyword = removedParams[1].original; // TODO: This may not be necessary. if (!node.sexpr.hash) { node.sexpr.hash = b.hash(); } node.sexpr.hash.pairs.push(b.pair( 'keywordName', b.string(keyword) )); } }); return ast; }; TransformWithAsToHash.prototype.validate = function TransformWithAsToHash_validate(node) { return node.type === 'BlockStatement' && node.sexpr.path.original === 'with' && node.sexpr.params.length === 3 && node.sexpr.params[1].type === 'PathExpression' && node.sexpr.params[1].original === 'as'; }; export default TransformWithAsToHash;
var clientElasticsearch = require("../../../Elasticsearch/ElasticsearchClient"); var ElasticsearchParser = require("../../../Elasticsearch/ElasticsearchParser"); var Q = require('q'); var getSuggestions=function(){ return clientElasticsearch.search({ "index":"source", "type":"zabbix_host", "body":{ "query" : { "term": { "haveMapping" : false} }, "fields" : ["id","hostname"] }, "from":0, "size":999999999, "scroll" : "1m" }).then(function(body){ // Récuparation de la recherche en liste return ElasticsearchParser.loadFromBodyFields(body); }).then(function(results){ var retour=[]; results.forEach(function(host){ retour.push({ "response_id" : host.id, "response_label" : host.hostname, "target": [ { "label" : host.hostname } ] }); }); return retour; }); } module.exports = getSuggestions;