code
stringlengths
2
1.05M
version https://git-lfs.github.com/spec/v1 oid sha256:49c54ee863855e8fa7d43bdb5142596122609269a2e98c9a92e10dffcda1376d size 65177
'use strict'; var util = require('util'); var GtReq = require('../GtReq'); var BaseTemplate = require('./BaseTemplate'); function IncTemplate(options) { BaseTemplate.call(this, options); options = util._extend({ transmissionContent: '', incAppId: '' }, options); util._extend(this, options); } util.inherits(IncTemplate, BaseTemplate); IncTemplate.prototype.getActionChain = function() { var actionChain1 = new GtReq.ActionChain({ actionId: 1, type: GtReq.ActionChain.Type.Goto, next: 10030 }); var appStartUp = new GtReq.AppStartUp({ android: '', symbia: '', ios: '' }); // 启动app // Start the app var actionChain2 = new GtReq.ActionChain({ actionId: 10030, type: GtReq.ActionChain.Type.startapp, appid: this.incAppId, autostart: 1 === this.transmissionType, appstartupid: appStartUp, failedAction: 100, next: 100 }); // 结束 // Finish var actionChain3 = new GtReq.ActionChain({ actionId: 100, type: GtReq.ActionChain.Type.eoa }); var actionChains = [actionChain1, actionChain2, actionChain3]; return actionChains; }; IncTemplate.prototype.getTransmissionContent = function() { return this.transmissionContent; }; IncTemplate.prototype.getPushType = function() { return 'TransmissionMsg'; }; /** * 设置 透传消息类型 1:收到通知立即启动应用 2:收到通知不启动应用 * Set direct display message type 1:Start the app once gets notification. 2:Not to start the app once gets notification * @param transmissionType */ IncTemplate.prototype.setTransmissionType = function(transmissionType) { this.transmissionType = transmissionType; return this; }; IncTemplate.prototype.setTransmissionContent = function(transmissionContent) { this.transmissionContent = transmissionContent; return this; }; IncTemplate.prototype.setIncAppId = function(incAppId) { this.incAppId = incAppId; return this; }; module.exports = IncTemplate;
/** * @module ember-paper */ import Ember from 'ember'; import RippleMixin from '../mixins/ripple-mixin'; import ProxyMixin from 'ember-paper/mixins/proxy-mixin'; const { get, set, isEmpty, computed, run, Component } = Ember; /** * @class PaperItem * @extends Ember.Component * @uses ProxyMixin * @uses RippleMixin */ export default Component.extend(RippleMixin, ProxyMixin, { tagName: 'md-list-item', // Ripple Overrides rippleContainerSelector: '.md-no-style', center: false, dimBackground: true, outline: false, classNameBindings: ['shouldBeClickable:md-clickable', 'hasProxiedComponent:md-proxy-focus'], attributeBindings: ['role', 'tabindex'], role: 'listitem', tabindex: '-1', hasProxiedComponent: computed.bool('proxiedComponents.length'), hasPrimaryAction: computed.notEmpty('onClick'), hasSecondaryAction: computed('secondaryItem', 'onClick', function() { let secondaryItem = get(this, 'secondaryItem'); if (!isEmpty(secondaryItem)) { let hasClickAction = get(secondaryItem, 'onClick'); let hasChangeAction = get(secondaryItem, 'onChange'); return hasClickAction || hasChangeAction; } else { return false; } }), secondaryItem: computed('proxiedComponents.[]', function() { let proxiedComponents = get(this, 'proxiedComponents'); return proxiedComponents.find((component)=> { return get(component, 'isSecondary'); }); }), shouldBeClickable: computed.or('proxiedComponents.length', 'onClick'), click(ev) { this.get('proxiedComponents').forEach((component)=> { if (component.processProxy && !get(component, 'disabled') && (get(component, 'bubbles') | !get(this, 'hasPrimaryAction'))) { component.processProxy(); } }); this.sendAction('onClick', ev); }, setupProxiedComponent() { let tEl = this.$(); let proxiedComponents = get(this, 'proxiedComponents'); proxiedComponents.forEach((component)=> { let isProxyHandlerSet = get(component, 'isProxyHandlerSet'); // we run init only once for each component. if (!isProxyHandlerSet) { // Allow proxied component to propagate ripple hammer event if (!get(component, 'onClick') && !get(component, 'propagateRipple')) { set(component, 'propagateRipple', true); } // ripple let el = component.$(); set(this, 'mouseActive', false); el.on('mousedown', ()=> { set(this, 'mouseActive', true); run.later(()=> { set(this, 'mouseActive', false); }, 100); }); el.on('focus', ()=> { if (!get(this, 'mouseActive')) { tEl.addClass('md-focused'); } el.on('blur', function proxyOnBlur() { tEl.removeClass('md-focused'); el.off('blur', proxyOnBlur); }); }); // If we don't have primary action then // no need to bubble if (!get(this, 'hasPrimaryAction')) { let bubbles = get(component, 'bubbles'); if (isEmpty(bubbles)) { set(component, 'bubbles', false); } } else if (get(proxiedComponents, 'length')) { // primary action exists. Make sure child // that has separate action won't bubble. proxiedComponents.forEach((component)=> { let hasClickAction = get(component, 'onClick'); let hasChangeAction = get(component, 'onChange'); if (hasClickAction || hasChangeAction) { let bubbles = get(component, 'bubbles'); if (isEmpty(bubbles)) { set(component, 'bubbles', false); } } }); } // Init complete. We don't want it to run again // for that particular component. set(component, 'isProxyHandlerSet', true); } }); } });
/*jshint unused:false */ var dojoConfig = { async: 1, cacheBust: 0, 'routing-map': { pathPrefix: '', layers: {} }, packages: [ { name: 'oe_dojo', location: '..' } ] };
/** * Generate a function that accepts a variable number of arguments as the last * function argument. * * @param {Function} fn * @return {Function} */ module.exports = function (fn) { var count = Math.max(fn.length - 1, 0); return function () { var args = new Array(count); var index = 0; // https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments for (; index < count; index++) { args[index] = arguments[index]; } var variadic = args[count] = []; for (; index < arguments.length; index++) { variadic.push(arguments[index]); } return fn.apply(this, args); }; };
function char2int(c) { return c.charCodeAt(0); } var hexD = [ '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' ]; hexD = ['0'].concat(hexD); function hex(number) { var str = ""; str = hexD[number&0xf] + str str = hexD[(number>>=4)&0xf] + str ; str = hexD[(number>>=4)&0xf] + str ; str = hexD[(number>>=4)&0xf] + str ; return str; } function hex2(number) { var str = ""; str = hexD[number&0xf] + str str = hexD[(number>>=4)&0xf] + str ; return str; } function fromRunLenCodes(runLenArray, bitm) { bitm = bitm || []; var bit = runLenArray[0]; var runLenIdx = 1, bitIdx = 0; var runLen = 0; while (runLenIdx < runLenArray.length) { runLen = runLenArray[runLenIdx]; while (runLen--) { while ((INTBITLEN * (bitm.length)) < bitIdx) bitm.push(0); if (bit) bitm[bitIdx >> D_INTBITLEN] |= (1 << (M_INTBITLEN & bitIdx)); bitIdx++ ; } runLenIdx++ ; bit ^= 1; } return (bitm); } function arguments_or_eval(l) { switch ( l ) { case 'arguments': case 'eval': return true; } return false; }; var has = Object.prototype.hasOwnProperty; function fromcode(codePoint ) { if ( codePoint <= 0xFFFF) return String.fromCharCode(codePoint) ; return String.fromCharCode(((codePoint-0x10000 )>>10)+0x0D800, ((codePoint-0x10000 )&(1024-1))+0x0DC00); } function core(n) { return n.type === PAREN ? n.expr : n; }; function toNum (n) { return (n >= CH_0 && n <= CH_9) ? n - CH_0 : (n <= CH_f && n >= CH_a) ? 10 + n - CH_a : (n >= CH_A && n <= CH_F) ? 10 + n - CH_A : -1; };
import { getTransitionNames, getAvailableTransitionNames, getTransitionStylesName } from 'frontend/transitions'; describe('getTransitionNames', () => { it('returns array of names', () => { const result = getTransitionNames(); expect(result).toContain('scroll'); expect(result).toContain('fade'); }); }); describe('getAvailableTransitions', () => { it('offers fade transitions if section and previous section both have full height', () => { const section = {fullHeight: true}; const previousSection = {fullHeight: true}; const result = getAvailableTransitionNames(section, previousSection); expect(result).toContain('fade'); expect(result).toContain('fadeBg'); }); it('does not offer fade transitions if section does not have full height', () => { const section = {}; const previousSection = {fullHeight: true}; const result = getAvailableTransitionNames(section, previousSection); expect(result).toContain('scroll'); expect(result).not.toContain('fade'); expect(result).not.toContain('fadeBg'); }); it('does not offer fade transitions if previous section does not have full height', () => { const section = {fullHeight: true}; const previousSection = {}; const result = getAvailableTransitionNames(section, previousSection); expect(result).toContain('scroll'); expect(result).not.toContain('fade'); expect(result).not.toContain('fadeBg'); }); }); describe('getTransitionStylesName', () => { it('uses fadeIn if both section and previous section have fullHeight', () => { const previousSection = {fullHeight: true, transition: 'scroll'}; const section = {fullHeight: true, transition: 'fade'}; const nextSection = {transition: 'scroll'}; const result = getTransitionStylesName(section, previousSection, nextSection); expect(result).toBe('fadeInScrollOut'); }); it('falls back to scrollIn if previous section does not have fullHeight', () => { const previousSection = {transition: 'scroll'}; const section = {fullHeight: true, transition: 'fade'}; const nextSection = {fullHeight: true, transition: 'scroll'}; const result = getTransitionStylesName(section, previousSection, nextSection); expect(result).toBe('scrollInScrollOut'); }); it('falls back to scrollIn if section does not have fullHeight', () => { const previousSection = {fullHeight: true, transition: 'scroll'}; const section = {transition: 'fade'}; const nextSection = {fullHeight: true, transition: 'scroll'}; const result = getTransitionStylesName(section, previousSection, nextSection); expect(result).toBe('scrollInScrollOut'); }); it('falls back to scrollIn if previous is missing', () => { const section = {transition: 'fade'}; const nextSection = {fullHeight: true, transition: 'scroll'}; const result = getTransitionStylesName(section, null, nextSection); expect(result).toBe('scrollInScrollOut'); }); it('uses fadeOut if both section and next section have fullHeight', () => { const previousSection = {transition: 'scroll'}; const section = {fullHeight: true, transition: 'reveal'}; const nextSection = {fullHeight: true, transition: 'fade'}; const result = getTransitionStylesName(section, previousSection, nextSection); expect(result).toBe('revealFadeOut'); }); it('falls back to scrollOut if next section does not have fullHeight', () => { const previousSection = {transition: 'scroll'}; const section = {fullHeight: true, transition: 'reveal'}; const nextSection = {transition: 'fade'}; const result = getTransitionStylesName(section, previousSection, nextSection); expect(result).toBe('revealScrollOut'); }); it('falls back to scrollOut if section does not have fullHeight', () => { const previousSection = {transition: 'scroll'}; const section = {transition: 'reveal'}; const nextSection = {fullHeight: true, transition: 'fade'}; const result = getTransitionStylesName(section, previousSection, nextSection); expect(result).toBe('revealScrollOut'); }); it('falls back to scrollOut if next section is missing', () => { const previousSection = {transition: 'scroll'}; const section = {transition: 'reveal'}; const result = getTransitionStylesName(section, previousSection, null); expect(result).toBe('revealScrollOut'); }); });
/* * Created for OpenROV: www.openrov.com * Author: Dominik * Date: 06/03/12 * * Description: * This file acts as a mock implementation for the camera module. It reads jpg files from a directory and returns them. * * License * This work is licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported License. * To view a copy of this license, visit http://creativecommons.org/licenses/by-sa/3.0/ or send a * letter to Creative Commons, 444 Castro Street, Suite 900, Mountain View, California, 94041, USA. * */ var EventEmitter = require('events').EventEmitter, fs = require('fs'), path = require('path'), CONFIG = require('./config'), logger = require('./logger').create(CONFIG); var FirmwareInstaller = function () { var installer = new EventEmitter(); installer.installfromsource = function () { installer.install(''); }; installer.unpack = function (filename) { setTimeout(function () { installer.emit('firmwareinstaller-unpacked', 'some directory'); }, 2000); }; installer.compile = function (directory) { setTimeout(function () { installer.emit('firmwareinstaller-output', 'Stated compiling\n'); }, 500); setTimeout(function () { installer.emit('firmwareinstaller-output', 'Do compiling\n'); }, 1000); setTimeout(function () { installer.emit('firmwareinstaller-compilled', directory); }, 2000); }; installer.upload = function (directory) { setTimeout(function () { installer.emit('firmwareinstaller-uploaded', directory); }, 2000); }; installer.install = function (filename) { installer.unpack(filename); setTimeout(installer.compile, 2000); setTimeout(installer.upload, 4000); }; return installer; }; module.exports = FirmwareInstaller;
module.exports = function (config) { config.set({ basePath: './', files: [ 'www/lib/**/*.js', 'www/**/*.js' ], preprocessors: { 'www/app.js': 'coverage', 'www/**/*.js': 'sourcemap' }, autoWatch: true, frameworks: [ 'jasmine' ], browsers: ['Chrome', 'Safari'], plugins: [ 'karma-chrome-launcher', 'karma-coverage', 'karma-jasmine', 'karma-safari-launcher', 'karma-spec-reporter', 'karma-sourcemap-loader' ], logLevel: 'warn', loggers: [ {type: 'console'} ], reporters: ['spec', 'coverage'], coverageReporter: { dir: 'coverage/', reporters: [ {type: 'html', subdir: 'html'}, {type: 'text', subdir: '.', file: 'coverage.txt'}, {type: 'json', subdir: '.', file: 'coverage-karma.json'}, {type: 'text-summary'} ] } }); };
(this => {});
angular.module('App') .controller('AppController', function($scope, $http, URL) { $http.get(URL, {headers: {"X-Requested-With" : "XMLHttpRequest"}}) .success(function (response) {$scope.examples = response.examples;}); });
// Эти данные получаются с помощью метода cars_by_order var result = { // Базовые данные carModel: "INFINITI FX5 PREMIUM", num: "т607ау190", vin: "JN1TANS50U0005180", body: "", // Номер кузова year: "2007", engineDisp: "3498", // Объем двигателя engineHp: "280", // Мощность (л.с.) // Пробег автомобиля // Максимальный пробег в КМ milleage: "106000", // Массив пробегов milleageArr: [ { year: "07-09-2012", milleage: "106000" } ], // Проверка контрольного символа VIN isVinOk: true, // Документы об участии в ДТП docs: [ { link: "http://cdn.adaperio.ru/data%2F%D0%BE100%D1%80%D1%81197.pdf", link_thumbnail: "" } ], // Данные об участии в ДТП dtps: [ { date: "17.04.2014", type: "Наезд на препятствие", damage: "" } ], // История регистрационных действий за последние 5 лет regData: { Category: "В", Displacement: "3498", // Приоритет отдаётся полю engineDisp EngineNumber: "129547С", MarkaRus: "ИНФИНИТИ FХ35 РRЕМIUМ", MaxWeight: "2530", NettoWeight: "2080", Power: "280", // Приоритет отдаётся полю engineHp // 1 - левый руль // 2 - правый руль SteeringWheelPlacement: "1", Year: "2007" // Приоритет отдаётся полю year codeOfTechOperation: "", arr: [ { // Недокументированное поле area: "142960", // 1 - Юридическое лицо // 2 - Физическое лицо categoryOfOwner: "2", city: "УЗУНОВО С.", // 11 - 'Первичная регистрация'; // 12 - 'Регистрация снятого с учета ТС'; // 41 - 'Замена государственного регистрационного знака'; // 42 - 'Выдача дубликата регистрационного документа'; // 43 - 'Выдача (замена) паспорта ТС'; // 44 - 'Замена номерного агрегата, цвета, изменение конструкции ТС'; // 45 - 'Изменение Ф.И.О. (наименования) владельца'; // 46 - 'Изменение места жительства (юридического адреса) владельца в пределах территории обслуживания регистрационным пунктом'; // 47 - 'Наличие запретов и ограничений'; // 48 - 'Снятие запретов и ограничений'; // 51 - 'Коррекция иных реквизитов'; // 52 - 'Выдача акта технического осмотра'; // 53 - 'Проведение ГТО'; // 54 - 'Постоянная регистрация ТС по окончанию временной'; // 91 - 'Изменение собственника по наследству с заменой государственных регистрационных знаков'; // 92 - 'Изменение собственника по наследству с сохранением государственных регистрационных знаков за новым собственником (наследником)'; // 93 - 'Изменение собственника по сделкам, произведенным в любой форме (купля-продажа, дарение, др.) с заменой государственных регистрационных знаков'; // 94 - 'Изменение собственника по сделкам, произведенным в любой форме с сохранением государственных регистрационных знаков'; codeOfTechOperation: "16", dateOfFirstRegistration: "01.01.0001", dateOfLastOperation: "15.12.2009", oblast: "Московская область", okrug: "Центральный", region: "СЕРЕБРЯНО-ПРУДСКИЙ", street: "-" } ] }, // Использование автомобиля в качестве такси taxiData: [ { name: "Инфинити", owner: "Проташков Александр Владимирович", started: "14.01.2011", end: "14.01.2012" } ], // Информация о розыске транспортного средства, в федеральной информационной системе МВД России gibddWanted: false, // Информация о наложении ограничений в федеральной информационной системе МВД России gibddRestricted: true, restrictedArr: [ { dateadd: "08.08.2014", dateogr: "08.08.2014", divid: "040", //1 - 'Судебные органы'; //2 - 'Судебный пристав'; //3 - 'Таможенные органы'; //4 - 'Органы социальной защиты'; //5 - 'Нотарус'; //6 - 'Органы внутренних дел или иные правоохранительные органы'; //7 - 'Органы внутренних дел или иные правоохранительные органы (прочие)'; divtype: "6", gid: "43#000075178", ogrkod: "1", regid: "1133", regname: "Кировская область", tsmodel: "INFINIТI FХ-35 РRЕМIUМ", tsyear: "2007" } ], // Информация о нахождении в залоге у банков // Завершилась ли проверка залогов успешно reestrGotResult: true, reestrResult: [ { // Дата регистрации уведомления о залоге RegDate: '', // Залогодержатели Mortgagees: '', // Дата договора date: '', // Срок исполнения обязательства end: '' } ], // Проверка истории CARFAX carfax: { fullLink: "http://cdn.adaperio.ru/some_link", history: { accident: false, totalLoss: false, structuralDamage: false, airbagDeployment: false, odometrCheck: false, manufacturerRecall: false, warantyVoid: true }, owners: [ { lastMilleage: 137680, // Км. ownership: "43 мес.", state: "Louisiana", yearPurchased: "2001" } ] }, // Проверка истории на аукционах auctions: [ { damage: [ "Передняя часть" ], date: "", odometr: "12298", photos: [ "http://img.copartimages.com//website/data/pix/20110517/17605611_1X.JPG" ], } ], // Данные таможни customs: { country: "ЯПОНИЯ", date: "15.09.2008", model: "Infiniti FX5", odometer: "", price: "574719" // таможенная стоимость в рублях }, // Комплектация equip: { make: "Nissan", model: "[S50] INFINITIFX45/35 ", series: "", year: "07/2007", engine: "[VQ35DE] VQ35DE TYPE ENGINE", bodyType: "[W] WAGON ", color: "[KH3] BLACK ", interiorColor: "[G] BLACK ", transmission: "[AT] AUTOMATIC TRANSMISSION ", year: "07/2007", manufacturedAt: "", // Произведено month: "", // Месяц engineCode: "", // Код двигателя transmissionCode: "", // Код трансммиссии transmission2: "", // Трансммиссия (дополнительно) internalsCode: "", // Код отделки roofColor: "", // Цвет крыши typeCode: "", // Код catalysis: "", // Катализатор panzer: "", // Бронирование steeringWheel: "", // Руль gearbox: "", // Коробка передач made: "", // Изготовление marking: "", // Обозначение manuf: "", // Сборка factory: "", // Завод изготовитель trim: "", // Комплектация trimCode: "", // Комплектация (код) drive: "", // Привод region: "", // Регион modelCode: "", // Код модели manufPeriod: "", // Период производства engineDisp: "", // Объем fuelType: "", // Вид топлива country: "", // Страна происхождения modelYear: "", // Модельный год seats: "", // Тип сидений doorStyle: "", // Стиль дверей classification: "", // Класификация susp: "", // Подвеска options: "", // Опции optionsArr: [ { code: "", desc: "" } ] }, // Ремонтные работы (по расчетам страховой компании) repairs: { vin: "JN1TANS50U0005180", make: "INFINITI [R] [47]", year: "", engine: "", color: "", engineDisp: "" hp: "", repairs: [ { date: "02.08.2011", items: [ { changed: true, paint: false, partlyChanged: false, partlyRepaired: false, repaired: false, title: "КРЕПЛ БАМПЕРА П62030-1CA0A" } ] } ] } };
module.exports = { // mock开发配置 'GET /login?$user&$password': { ok: { code: 100, msg: 'ok', data: { a: 1, b: 2 } }, fail: { code: 200, msg: 'fail' } }, 'POST /signup?$user&$password': { ok: { code: 100, msg: 'ok', data: { a: 1, b: 2 } }, fail: { code: 200, msg: 'fail' } } }
/* eslint-env mocha */ /* global expect, testContext */ /* eslint-disable prefer-arrow-callback, no-unused-expressions */ import factory from 'src/test/factories' import {resetDB, runGraphQLMutation, useFixture} from 'src/test/helpers' import {Cycle} from 'src/server/services/dataService' import {COMPLETE, PRACTICE} from 'src/common/models/cycle' import fields from '../index' describe(testContext(__filename), function () { useFixture.buildOneQuestionSurvey() useFixture.buildSurvey() beforeEach(resetDB) beforeEach(async function () { await this.buildSurvey() this.user = await factory.build('user', {id: this.project.memberIds[0]}) this.respondentId = this.project.memberIds[0] this.invokeAPI = function () { const responses = this.project.memberIds.slice(1).map(memberId => ({ values: [{subjectId: memberId, value: 'foo'}], questionId: this.surveyQuestion.id, surveyId: this.survey.id, respondentId: this.respondentId, })) return runGraphQLMutation( `mutation($responses: [SurveyResponseInput]!) { saveRetrospectiveSurveyResponses(responses: $responses) { createdIds } }`, fields, {responses}, {currentUser: this.user}, ) } }) it('returns new response ids for all responses created in REFLECTION state', function () { return this.invokeAPI() .then(result => result.data.saveRetrospectiveSurveyResponses.createdIds) .then(createdIds => expect(createdIds).have.length(this.project.memberIds.length - 1)) }) it('returns new response ids for all responses created in COMPLETE state', async function () { await Cycle.get(this.cycleId).updateWithTimestamp({state: COMPLETE}) return this.invokeAPI() .then(result => result.data.saveRetrospectiveSurveyResponses.createdIds) .then(createdIds => expect(createdIds).have.length(this.project.memberIds.length - 1)) }) it('returns an error when in PRACTICE state', async function () { await Cycle.get(this.cycleId).updateWithTimestamp({state: PRACTICE}) return expect(this.invokeAPI()) .to.be.rejectedWith(/cycle is in the PRACTICE state/) }) })
'use strict'; let path = require('path'); let ModuleInitializer = require('../../tools/ModuleInitializer'); class CommandHandlerInitializer extends ModuleInitializer { constructor(repositories, buses, options) { super(options); this._repositories = repositories; this._buses = buses; } createModule(module) { let handler = require(module)(this._repositories, this._buses); let command = path.basename(module).replace('Handler.js', ''); this._buses.command.register(command, handler); } moduleSuffix() { return 'CommandHandler'; } } module.exports = CommandHandlerInitializer;
// numeral.js // version : 1.4.8 // author : Adam Draper // license : MIT // http://adamwdraper.github.com/Numeral-js/ (function () { /************************************ Constants ************************************/ var numeral, VERSION = '1.4.8', // internal storage for language config files languages = {}, currentLanguage = 'en', zeroFormat = null, // check for nodeJS hasModule = (typeof module !== 'undefined' && module.exports); /************************************ Constructors ************************************/ // Numeral prototype object function Numeral (number) { this._n = number; } /** * Implementation of toFixed() that treats floats more like decimals * * Fixes binary rounding issues (eg. (0.615).toFixed(2) === '0.61') that present * problems for accounting- and finance-related software. */ function toFixed (value, precision, optionals) { var power = Math.pow(10, precision), output; // Multiply up by precision, round accurately, then divide and use native toFixed(): output = (Math.round(value * power) / power).toFixed(precision); if (optionals) { var optionalsRegExp = new RegExp('0{1,' + optionals + '}$'); output = output.replace(optionalsRegExp, ''); } return output; } /************************************ Formatting ************************************/ // determine what type of formatting we need to do function formatNumeral (n, format) { var output; // figure out what kind of format we are dealing with if (format.indexOf('$') > -1) { // currency!!!!! output = formatCurrency(n, format); } else if (format.indexOf('%') > -1) { // percentage output = formatPercentage(n, format); } else if (format.indexOf(':') > -1) { // time output = formatTime(n, format); } else { // plain ol' numbers or bytes output = formatNumber(n, format); } // return string return output; } // revert to number function unformatNumeral (n, string) { if (string.indexOf(':') > -1) { n._n = unformatTime(string); } else { if (string === zeroFormat) { n._n = 0; } else { var stringOriginal = string; if (languages[currentLanguage].delimiters.decimal !== '.') { string = string.replace(/\./g,'').replace(languages[currentLanguage].delimiters.decimal, '.'); } // see if abbreviations are there so that we can multiply to the correct number var thousandRegExp = new RegExp(languages[currentLanguage].abbreviations.thousand + '(?:\\)|(\\' + languages[currentLanguage].currency.symbol + ')?(?:\\))?)?$'), millionRegExp = new RegExp(languages[currentLanguage].abbreviations.million + '(?:\\)|(\\' + languages[currentLanguage].currency.symbol + ')?(?:\\))?)?$'), billionRegExp = new RegExp(languages[currentLanguage].abbreviations.billion + '(?:\\)|(\\' + languages[currentLanguage].currency.symbol + ')?(?:\\))?)?$'), trillionRegExp = new RegExp(languages[currentLanguage].abbreviations.trillion + '(?:\\)|(\\' + languages[currentLanguage].currency.symbol + ')?(?:\\))?)?$'); // see if bytes are there so that we can multiply to the correct number var prefixes = ['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'], bytesMultiplier = false; for (var power = 0; power <= prefixes.length; power++) { bytesMultiplier = (string.indexOf(prefixes[power]) > -1) ? Math.pow(1024, power + 1) : false; if (bytesMultiplier) { break; } } // do some math to create our number n._n = ((bytesMultiplier) ? bytesMultiplier : 1) * ((stringOriginal.match(thousandRegExp)) ? Math.pow(10, 3) : 1) * ((stringOriginal.match(millionRegExp)) ? Math.pow(10, 6) : 1) * ((stringOriginal.match(billionRegExp)) ? Math.pow(10, 9) : 1) * ((stringOriginal.match(trillionRegExp)) ? Math.pow(10, 12) : 1) * ((string.indexOf('%') > -1) ? 0.01 : 1) * Number(((string.indexOf('(') > -1) ? '-' : '') + string.replace(/[^0-9\.-]+/g, '')); // round if we are talking about bytes n._n = (bytesMultiplier) ? Math.ceil(n._n) : n._n; } } return n._n; } function formatCurrency (n, format) { var prependSymbol = (format.indexOf('$') <= 1) ? true : false; // remove $ for the moment var space = ''; // check for space before or after currency if (format.indexOf(' $') > -1) { space = ' '; format = format.replace(' $', ''); } else if (format.indexOf('$ ') > -1) { space = ' '; format = format.replace('$ ', ''); } else { format = format.replace('$', ''); } // format the number var output = formatNumeral(n, format); // position the symbol if (prependSymbol) { if (output.indexOf('(') > -1 || output.indexOf('-') > -1) { output = output.split(''); output.splice(1, 0, languages[currentLanguage].currency.symbol + space); output = output.join(''); } else { output = languages[currentLanguage].currency.symbol + space + output; } } else { if (output.indexOf(')') > -1) { output = output.split(''); output.splice(-1, 0, space + languages[currentLanguage].currency.symbol); output = output.join(''); } else { output = output + space + languages[currentLanguage].currency.symbol; } } return output; } function formatPercentage (n, format) { var space = ''; // check for space before % if (format.indexOf(' %') > -1) { space = ' '; format = format.replace(' %', ''); } else { format = format.replace('%', ''); } n._n = n._n * 100; var output = formatNumeral(n, format); if (output.indexOf(')') > -1 ) { output = output.split(''); output.splice(-1, 0, space + '%'); output = output.join(''); } else { output = output + space + '%'; } return output; } function formatTime (n, format) { var hours = Math.floor(n._n/60/60), minutes = Math.floor((n._n - (hours * 60 * 60))/60), seconds = Math.round(n._n - (hours * 60 * 60) - (minutes * 60)); return hours + ':' + ((minutes < 10) ? '0' + minutes : minutes) + ':' + ((seconds < 10) ? '0' + seconds : seconds); } function unformatTime (string) { var timeArray = string.split(':'), seconds = 0; // turn hours and minutes into seconds and add them all up if (timeArray.length === 3) { // hours seconds = seconds + (Number(timeArray[0]) * 60 * 60); // minutes seconds = seconds + (Number(timeArray[1]) * 60); // seconds seconds = seconds + Number(timeArray[2]); } else if (timeArray.lenght === 2) { // minutes seconds = seconds + (Number(timeArray[0]) * 60); // seconds seconds = seconds + Number(timeArray[1]); } return Number(seconds); } function formatNumber (n, format) { var negP = false, optDec = false, abbr = '', bytes = '', ord = '', abs = Math.abs(n._n); // check if number is zero and a custom zero format has been set if (n._n === 0 && zeroFormat !== null) { return zeroFormat; } else { // see if we should use parentheses for negative number if (format.indexOf('(') > -1) { negP = true; format = format.slice(1, -1); } // see if abbreviation is wanted if (format.indexOf('a') > -1) { // check for space before abbreviation if (format.indexOf(' a') > -1) { abbr = ' '; format = format.replace(' a', ''); } else { format = format.replace('a', ''); } if (abs >= Math.pow(10, 12)) { // trillion abbr = abbr + languages[currentLanguage].abbreviations.trillion; n._n = n._n / Math.pow(10, 12); } else if (abs < Math.pow(10, 12) && abs >= Math.pow(10, 9)) { // billion abbr = abbr + languages[currentLanguage].abbreviations.billion; n._n = n._n / Math.pow(10, 9); } else if (abs < Math.pow(10, 9) && abs >= Math.pow(10, 6)) { // million abbr = abbr + languages[currentLanguage].abbreviations.million; n._n = n._n / Math.pow(10, 6); } else if (abs < Math.pow(10, 6) && abs >= Math.pow(10, 3)) { // thousand abbr = abbr + languages[currentLanguage].abbreviations.thousand; n._n = n._n / Math.pow(10, 3); } } // see if we are formatting bytes if (format.indexOf('b') > -1) { // check for space before if (format.indexOf(' b') > -1) { bytes = ' '; format = format.replace(' b', ''); } else { format = format.replace('b', ''); } var prefixes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'], min, max; for (var power = 0; power <= prefixes.length; power++) { min = Math.pow(1024, power); max = Math.pow(1024, power+1); if (n._n >= min && n._n < max) { bytes = bytes + prefixes[power]; if (min > 0) { n._n = n._n / min; } break; } } } // see if ordinal is wanted if (format.indexOf('o') > -1) { // check for space before if (format.indexOf(' o') > -1) { ord = ' '; format = format.replace(' o', ''); } else { format = format.replace('o', ''); } ord = ord + languages[currentLanguage].ordinal(n._n); } if (format.indexOf('[.]') > -1) { optDec = true; format = format.replace('[.]', '.'); } var w = n._n.toString().split('.')[0], precision = format.split('.')[1], thousands = format.indexOf(','), d = '', neg = false; if (precision) { if (precision.indexOf('[') > -1) { precision = precision.replace(']', ''); precision = precision.split('['); d = toFixed(n._n, (precision[0].length + precision[1].length), precision[1].length); } else { d = toFixed(n._n, precision.length); } w = d.split('.')[0]; if (d.split('.')[1].length) { d = languages[currentLanguage].delimiters.decimal + d.split('.')[1]; } else { d = ''; } if (optDec && Number(d.slice(1)) === 0) { d = ''; } } else { w = toFixed(n._n, null); } // format number if (w.indexOf('-') > -1) { w = w.slice(1); neg = true; } if (thousands > -1) { w = w.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1' + languages[currentLanguage].delimiters.thousands); } if (format.indexOf('.') === 0) { w = ''; } return ((negP && neg) ? '(' : '') + ((!negP && neg) ? '-' : '') + w + d + ((ord) ? ord : '') + ((abbr) ? abbr : '') + ((bytes) ? bytes : '') + ((negP && neg) ? ')' : ''); } } /************************************ Top Level Functions ************************************/ numeral = function (input) { if (numeral.isNumeral(input)) { input = input.value(); } else if (!Number(input)) { input = 0; } return new Numeral(Number(input)); }; // version number numeral.version = VERSION; // compare numeral object numeral.isNumeral = function (obj) { return obj instanceof Numeral; }; // This function will load languages and then set the global language. If // no arguments are passed in, it will simply return the current global // language key. numeral.language = function (key, values) { if (!key) { return currentLanguage; } if (key && !values) { if(!languages[key]) { throw new Error('Unknown language : ' + key); } currentLanguage = key; } if (values || !languages[key]) { loadLanguage(key, values); } return numeral; }; numeral.language('en', { delimiters: { thousands: ',', decimal: '.' }, abbreviations: { thousand: 'k', million: 'm', billion: 'b', trillion: 't' }, ordinal: function (number) { var b = number % 10; return (~~ (number % 100 / 10) === 1) ? 'th' : (b === 1) ? 'st' : (b === 2) ? 'nd' : (b === 3) ? 'rd' : 'th'; }, currency: { symbol: '$' } }); numeral.zeroFormat = function (format) { if (typeof(format) === 'string') { zeroFormat = format; } else { zeroFormat = null; } }; /************************************ Helpers ************************************/ function loadLanguage(key, values) { languages[key] = values; } /************************************ Numeral Prototype ************************************/ numeral.fn = Numeral.prototype = { clone : function () { return numeral(this); }, format : function (inputString) { return formatNumeral(this, inputString ? inputString : numeral.defaultFormat); }, unformat : function (inputString) { return unformatNumeral(this, inputString ? inputString : numeral.defaultFormat); }, value : function () { return this._n; }, valueOf : function () { return this._n; }, set : function (value) { this._n = Number(value); return this; }, add : function (value) { this._n = this._n + Number(value); return this; }, subtract : function (value) { this._n = this._n - Number(value); return this; }, multiply : function (value) { this._n = this._n * Number(value); return this; }, divide : function (value) { this._n = this._n / Number(value); return this; }, difference : function (value) { var difference = this._n - Number(value); if (difference < 0) { difference = -difference; } return difference; } }; /************************************ Exposing Numeral ************************************/ // CommonJS module is defined if (hasModule) { module.exports = numeral; } /*global ender:false */ if (typeof ender === 'undefined') { // here, `this` means `window` in the browser, or `global` on the server // add `numeral` as a global object via a string identifier, // for Closure Compiler 'advanced' mode this['numeral'] = numeral; } /*global define:false */ if (typeof define === 'function' && define.amd) { define([], function () { return numeral; }); } }).call(this);
import _Set from './internal/_Set.js'; import _curry2 from './internal/_curry2.js'; /** * Returns a new list containing only one copy of each element in the original * list, based upon the value returned by applying the supplied function to * each list element. Prefers the first item if the supplied function produces * the same value on two items. [`R.equals`](#equals) is used for comparison. * * @func * @memberOf R * @since v0.16.0 * @category List * @sig (a -> b) -> [a] -> [a] * @param {Function} fn A function used to produce a value to use during comparisons. * @param {Array} list The array to consider. * @return {Array} The list of unique items. * @example * * R.uniqBy(Math.abs, [-1, -5, 2, 10, 1, 2]); //=> [-1, -5, 2, 10] */ var uniqBy = _curry2(function uniqBy(fn, list) { var set = new _Set(); var result = []; var idx = 0; var appliedItem, item; while (idx < list.length) { item = list[idx]; appliedItem = fn(item); if (set.add(appliedItem)) { result.push(item); } idx += 1; } return result; }); export default uniqBy;
/** * index.js * * The purpose of this module is to provide user model classes * corresponding to DTOs used by the GoomY API. * * Created on: 2015-12-05 * * Author: Eléonore d'Agostino (paranoodle) * Author: Karim Ghozlani (gweezer7) * Author: Yassin Kammoun (yibnl) */ module.exports = { User: function(id) { this.id = id; }, UserSummary: function(id, href, badgeCount, pointCount) { this.id = id; this.href = href; this.badgeCount = badgeCount; this.pointCount = pointCount; }, UserDetails: function(id, href, badgeCount, pointCount, awards) { this.id = id; this.href = href; this.badgeCount = badgeCount; this.pointCount = pointCount; this.awards = awards; } };
/** @member {boolean} Seemple.Array#renderIfPossible @importance 3 @summary The ``renderIfPossible`` property cancels the array rendering if it equals ``false`` @see {@link Seemple.Array#itemRenderer} @example class MyArray extends Seemple.Array { get renderIfPossible() { return false; } // ... }); */
const Constraint = Jymfony.Component.Validator.Constraint; /** * @memberOf Jymfony.Component.Validator.Constraints */ export default class Choice extends Constraint { /** * @inheritdoc */ static getErrorName(errorCode) { switch (errorCode) { case __self.NO_SUCH_CHOICE_ERROR: return 'NO_SUCH_CHOICE_ERROR'; case __self.TOO_FEW_ERROR: return 'TOO_FEW_ERROR'; case __self.TOO_MANY_ERROR: return 'TOO_MANY_ERROR'; } return Constraint.getErrorName(errorCode); } __construct(options = null) { this.choices = undefined; this.callback = undefined; this.multiple = false; this.min = undefined; this.max = undefined; this.message = 'The value you selected is not a valid choice.'; this.multipleMessage = 'One or more of the given values is invalid.'; this.minMessage = 'You must select at least {{ limit }} choice.|You must select at least {{ limit }} choices.'; this.maxMessage = 'You must select at most {{ limit }} choice.|You must select at most {{ limit }} choices.'; return super.__construct(options); } /** * @inheritdoc */ get defaultOption() { return 'choices'; } } Object.defineProperties(Choice, { NO_SUCH_CHOICE_ERROR: { value: '8e179f1b-97aa-4560-a02f-2a8b42e49df7', writable: false }, TOO_FEW_ERROR: { value: '11edd7eb-5872-4b6e-9f12-89923999fd0e', writable: false }, TOO_MANY_ERROR: { value: '9bd98e49-211c-433f-8630-fd1c2d0f08c3', writable: false }, });
'use strict'; const common = require('../common'); const assert = require('assert'); const async_hooks = require('async_hooks'); const initHooks = require('./init-hooks'); // Verify that if there is no registered hook, then those invalid parameters // won't be checked. assert.doesNotThrow(() => async_hooks.emitInit()); const expectedId = async_hooks.newUid(); const expectedTriggerId = async_hooks.newUid(); const expectedType = 'test_emit_init_type'; const expectedResource = { key: 'test_emit_init_resource' }; const hooks1 = initHooks({ oninit: common.mustCall((id, type, triggerAsyncId, resource) => { assert.strictEqual(id, expectedId); assert.strictEqual(type, expectedType); assert.strictEqual(triggerAsyncId, expectedTriggerId); assert.strictEqual(resource.key, expectedResource.key); }) }); hooks1.enable(); assert.throws(() => async_hooks.emitInit(), /^RangeError: asyncId must be an unsigned integer$/); assert.throws(() => async_hooks.emitInit(expectedId), /^TypeError: type must be a string with length > 0$/); assert.throws(() => async_hooks.emitInit(expectedId, expectedType, -1), /^RangeError: triggerAsyncId must be an unsigned integer$/); async_hooks.emitInit(expectedId, expectedType, expectedTriggerId, expectedResource); hooks1.disable(); initHooks({ oninit: common.mustCall((id, type, triggerAsyncId, resource) => { assert.strictEqual(id, expectedId); assert.strictEqual(type, expectedType); assert.notStrictEqual(triggerAsyncId, expectedTriggerId); assert.strictEqual(resource.key, expectedResource.key); }) }).enable(); async_hooks.emitInit(expectedId, expectedType, null, expectedResource);
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M21 6h-7.59l3.29-3.29L16 2l-4 4-4-4-.71.71L10.59 6H3c-1.1 0-2 .89-2 2v12c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V8c0-1.11-.9-2-2-2zm0 14H3V8h18v12zM9 10v8l7-4z" /> , 'LiveTv');
'use strict'; module.exports = function setup(options, imports) { // forget to provide E1, that nobody is consuming return { // E1: function() {}, E2: function() {} }; }
/* _/ _/_/ _/_/_/_/_/ _/ _/ _/ _/ _/_/ _/ _/ _/_/_/ _/_/_/ _/ _/ _/_/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/_/ _/ _/ _/_/ _/_/_/ _/_/_/ _/ _/ _/ _/ Created by David Kaneda <http://www.davidkaneda.com> Documentation and issue tracking on Google Code <http://code.google.com/p/jqtouch/> Special thanks to Jonathan Stark <http://jonathanstark.com/> and pinch/zoom <http://www.pinchzoom.com/> (c) 2009 by jQTouch project members. See LICENSE.txt for license. activityIndicator - Daniel J. Pinter - DataZombies Based on http://starkravingcoder.blogspot.com/2007/09/canvas-loading-indicator.html Object Properties (all properties are set in the canvas tag): animating is the object in motion? Use object methods to change - true/false - Default = false barHeight height of the bars in px - Default = 5 barWidth width of the bars in px - Default = 2 color uses canvas's style attribute to set the bar color - in rgb() - Default = 0, 0, 0 (black) direction the direction the object rotates - counterclockwise/clockwise - Default = clockwise innerRadius radius of the hole in the middle in px - Default = 5 numberOfBars how many bars the object has - Default = 12 speed how fast the object rotates - larger numbers are slower - Default = 50 xPos x-position on canvas in px - Default = center of canvas yPos y-position on canvas in px - Default = middle of canvas Object Methods: start() begins the object's rotation stop() ends the object's rotation Object Instantiation: var aiGreenStar = new activityIndicator($('#GreenStar')); Bind Object to Events via jQuery: $('#page1').bind('pageAnimationStart', function (e, data) {if (data.direction === 'in'){aiGreenStar.start();}}); $('#page').bind('pageAnimationEnd', function (e, data) {if (data.direction === 'out'){aiGreenStar.stop();}}); Canvas tag with Object's ID: This displays an green asterisk-like (*) activityIndicator in the top left corner of a 100 x 250 canvas. <canvas id="GreenStar" height="100" width="250" barHeight="10" barWidth="3" style="color:rgb(0,255,0);" direction="counterclockwise" innerRadius="5" numberOfBars="6" speed="50" xPos="30" yPos="45"></canvas> */ function activityIndicator(canvas) { var animating = false; var barHeight = $(canvas).attr('barHeight') - 0; var barWidth = $(canvas).attr('barWidth') - 0; var color = $(canvas).css('color'); var context = $(canvas).get(0).getContext('2d'); var direction = $(canvas).attr('direction'); var innerRadius = $(canvas).attr('innerRadius') - 0; var numberOfBars = $(canvas).attr('numberOfBars') - 0; var speed = $(canvas).attr('speed') - 0; var xPos = $(canvas).attr('xPos') - 0; var yPos = $(canvas).attr('yPos') - 0; var offset = 0; if (isNaN(barHeight)) {barHeight = 5;} if (isNaN(barWidth)) {barWidth = 2;} var a = color.indexOf('(') + 1; var b = a; if (a !== -1) { if (color.substr(0, 4) === 'rgb('){ b = color.lastIndexOf(')') - a; } else if (color.substr(0, 5) === 'rgba(') { b = color.lastIndexOf(',') - a; } color = b > a ? color.substr(a, b) + ', ' : '0, 0, 0, '; } else { color = '0, 0, 0, '; } switch (direction){ case 'counterclockwise': direction = -1; break; case 'clockwise': default: direction = 1; break; } if (isNaN(innerRadius)) {innerRadius = 5;} if (isNaN(numberOfBars)) {numberOfBars = 12;} if (isNaN(speed)) {speed = 50;} if (isNaN(xPos)) {xPos = $(canvas).attr('width') / 2;} if (isNaN(yPos)) {yPos = $(canvas).attr('height') / 2;} function clear() {context.clearRect(0, 0, context.canvas.clientWidth, context.canvas.clientHeight);}; function draw(offset) { clear(); context.save(); context.translate(xPos, yPos); for (var i = 0; i < numberOfBars; i++) { var angle = 2 * ((offset + i) % numberOfBars) * Math.PI / numberOfBars; context.save(); context.translate((innerRadius * Math.sin(-angle)), (innerRadius * Math.cos(-angle))); context.rotate(angle); context.fillStyle = 'rgba(' + color + (numberOfBars + 1 - i) / (numberOfBars + 1) + ')'; context.fillRect(-barWidth / 2, 0, barWidth, barHeight); context.restore(); } context.restore(); }; function animate() { if (!animating) {return;}; offset = (offset + direction) % numberOfBars; draw(offset); setTimeout(animate, speed); }; function start(){ animating = true; animate(); }; function stop(){ animating = false; clear(); }; return { start: start, stop: stop }; };
export {default} from 'koenig-editor/components/koenig-menu-content';
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M9 4v4c-1.1 0-2-.9-2-2s.9-2 2-2m8-2H9C6.79 2 5 3.79 5 6s1.79 4 4 4v5h2V4h2v11h2V4h2V2zm0 12v3H5v2h12v3l4-4-4-4z" /></g></React.Fragment> , 'FormatTextdirectionLToROutlined');
var exphbs = require('express-handlebars');
version https://git-lfs.github.com/spec/v1 oid sha256:d1b4f8dc9d9f4ae479ea4896a2bc244b2d51382eb978009a23c65d2d9ff28f9f size 5749
var expect = require('chai').expect, Model = require('../lib/model'); describe('attribute initial state', function () { var ModelClass, NestedClass; before(function () { NestedClass = Model.inherit({ attributes: { a: Model.attributeTypes.String.inherit({ default: 'a' }) } }); ModelClass = Model.inherit({ attributes: { a: Model.attributeTypes.String.inherit({ default: 'a' }), nested: Model.attributeTypes.Model(NestedClass), collection: Model.attributeTypes.ModelsList(NestedClass) } }); }); describe('isSet', function () { it('should be false if attribute was not set', function () { var model = new ModelClass(); expect(model.isSet('a')).to.be.equal(false); }); it('should be false if attribute was initialized with null value', function () { var model = new ModelClass({a: null}); expect(model.isSet('a')).to.be.equal(false); }); it('should be true if attribute was set when inited', function () { var model = new ModelClass({ a: 'a' }); expect(model.isSet('a')).to.be.equal(true); }); it('should be true if attribute was set', function () { var model = new ModelClass(); model.set('a', true); expect(model.isSet('a')).to.be.equal(true); }); it('should be false after set and revert', function () { var model = new ModelClass(); model.set('a', true); model.revert(); expect(model.isSet('a')).to.be.equal(false); }); it('should be true after set, commit and revert', function () { var model = new ModelClass(); model.set('a', true); model.revert(); expect(model.isSet('a')).to.be.equal(false); }); }); describe('unset', function () { it('should change value to default', function () { var model = new ModelClass({ a: 'a-1' }); model.unset('a'); expect(model.get('a')).to.be.equal('a'); }); it('should make isSet to be false', function () { var model = new ModelClass({ a: 'a-1' }); model.unset('a'); expect(model.isSet('a')).to.be.equal(false); }); it('should emit change', function (done) { var model = new ModelClass({ a: 'a-1' }); model.ready().then(function () { model.on('change:a', function () { done(); }); model.unset('a'); }).done(); }); }); describe('set', function () { it('should unset when setting null', function () { var model = new ModelClass({ a: 'a-1' }); model.set('a', null); expect(model.get('a')).to.be.equal('a'); }); }); });
if (typeof(console) == "undefined") { console = {}; } if (typeof(console.log) == "undefined") { console.log = function() { return 0; }; }; String.prototype.capitalize = function() { return this.charAt(0).toUpperCase() + this.slice(1); }; if(typeof jQuery !== "undefined") jQuery.support.placeholder = (function () { var i = document.createElement('input'); return 'placeholder' in i; })();
import { RELOAD_WEBVIEW, WEBVIEW_ERROR } from '../../middlewares/Webviews/types'; import { ADD_ACCOUNT, REMOVE_ACCOUNT, TOGGLE_SIDEBAR, TOGGLE_SIDEBAR_ITEM_POSITION, UPDATE_SETTINGS, UPDATE_UNREAD_EMAILS } from './types'; const initialState = { accounts: [], settings: { darkTheme: false, hideSidebar: false, useProtonMailBeta: false, }, webviewStatuses: {}, }; export default (state = initialState, action) => { switch (action.type) { case ADD_ACCOUNT: return { ...state, accounts: [ ...state.accounts, action.account, ], }; case REMOVE_ACCOUNT: return { ...state, accounts: state.accounts.filter(a => a.username !== action.username), }; case TOGGLE_SIDEBAR: return { ...state, settings: { ...state.settings, hideSidebar: !state.settings.hideSidebar, } }; case TOGGLE_SIDEBAR_ITEM_POSITION: { const accounts = [...state.accounts]; accounts.splice(action.to, 0, ...accounts.splice(action.from, 1)); return { ...state, accounts }; } case UPDATE_SETTINGS: return { ...state, settings: { ...state.settings, [action.key]: action.value, }, }; case RELOAD_WEBVIEW: return { ...state, webviewStatuses: { ...state.webviewStatuses, [action.name]: {}, }, }; case WEBVIEW_ERROR: return { ...state, webviewStatuses: { ...state.webviewStatuses, [action.name]: { error: action.error, }, }, }; case UPDATE_UNREAD_EMAILS: return { ...state, accounts: state.accounts .map(a => a.username === action.username ? ({ ...a, unreadEmails: action.unreadEmails }) : a) }; } return state; };
/** * The main AWS namespace */ var AWS = { util: require('./util') }; /** * @api private * @!macro [new] nobrowser * @note This feature is not supported in the browser environment of the SDK. */ var _hidden = {}; _hidden.toString(); // hack to parse macro module.exports = AWS; AWS.util.update(AWS, { /** * @constant */ VERSION: '2.2.9', /** * @api private */ Signers: {}, /** * @api private */ Protocol: { Json: require('./protocol/json'), Query: require('./protocol/query'), Rest: require('./protocol/rest'), RestJson: require('./protocol/rest_json'), RestXml: require('./protocol/rest_xml') }, /** * @api private */ XML: { Builder: require('./xml/builder'), Parser: null // conditionally set based on environment }, /** * @api private */ JSON: { Builder: require('./json/builder'), Parser: require('./json/parser') }, /** * @api private */ Model: { Api: require('./model/api'), Operation: require('./model/operation'), Shape: require('./model/shape'), Paginator: require('./model/paginator'), ResourceWaiter: require('./model/resource_waiter') }, util: require('./util'), /** * @api private */ apiLoader: function() { throw new Error('No API loader set'); } }); require('./service'); require('./credentials'); require('./credentials/credential_provider_chain'); require('./credentials/temporary_credentials'); require('./credentials/web_identity_credentials'); require('./credentials/cognito_identity_credentials'); require('./credentials/saml_credentials'); require('./config'); require('./http'); require('./sequential_executor'); require('./event_listeners'); require('./request'); require('./response'); require('./resource_waiter'); require('./signers/request_signer'); require('./param_validator'); /** * @readonly * @return [AWS.SequentialExecutor] a collection of global event listeners that * are attached to every sent request. * @see AWS.Request AWS.Request for a list of events to listen for * @example Logging the time taken to send a request * AWS.events.on('send', function startSend(resp) { * resp.startTime = new Date().getTime(); * }).on('complete', function calculateTime(resp) { * var time = (new Date().getTime() - resp.startTime) / 1000; * console.log('Request took ' + time + ' seconds'); * }); * * new AWS.S3().listBuckets(); // prints 'Request took 0.285 seconds' */ AWS.events = new AWS.SequentialExecutor();
"use strict"; module.exports = function (app) { app.route('/book') .get(function (req, res) { res.send('Get a random book'); }) .post(function (req, res) { res.send('Add a book'); }) .put(function (req, res) { res.send('Update the book'); }); }
if(typeof cptable === 'undefined') cptable = {}; cptable[29001] = (function(){ var d = "ΈΉΊΌΎ°◘○◙♂♀♪♬☼▶◀↕‼¶§£Ώ↑↓→←Ë↔▲▼ !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùΑÖÜøαØάΒáíóúñÑβΓγΔδΕεέΖζΗηή│ªÁÂÀΘθ║╗╝ΙΪ┐└º¡¿─΄ãÃ╚╔ιίϊ═ΐΚκΛÊλΜμÍΝν┘┌ΞξΟοόÓßÔΠõÕπΡρÚΣςσΤτΥΫυύϋΰΦφΧχΨ·ψΩωώ", e = {}; for(var i=0;i!=d.length;++i) if(d.charCodeAt(i) !== 0xFFFD)e[d[i]] = i; return {"enc": e, "dec": d.split("") }; })();
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); 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 _reactIconBase = require('react-icon-base'); var _reactIconBase2 = _interopRequireDefault(_reactIconBase); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var FaCny = function FaCny(props) { return _react2.default.createElement( _reactIconBase2.default, _extends({ viewBox: '0 0 40 40' }, props), _react2.default.createElement( 'g', null, _react2.default.createElement('path', { d: 'm22 34.3h-3.9q-0.3 0-0.5-0.2t-0.2-0.5v-7.4h-6.4q-0.3 0-0.5-0.2t-0.2-0.5v-2.3q0-0.3 0.2-0.5t0.5-0.2h6.4v-1.9h-6.4q-0.3 0-0.5-0.2t-0.2-0.5v-2.4q0-0.2 0.2-0.5t0.5-0.2h4.8l-7.2-12.9q-0.2-0.3 0-0.7 0.2-0.3 0.6-0.3h4.3q0.5 0 0.7 0.4l4.8 9.4q0.4 0.9 1.2 2.8 0.3-0.5 0.7-1.5t0.6-1.3l4.3-9.4q0.2-0.4 0.6-0.4h4.3q0.4 0 0.6 0.3 0.2 0.3 0 0.7l-7 12.9h4.8q0.3 0 0.5 0.2t0.3 0.5v2.4q0 0.3-0.3 0.5t-0.5 0.2h-6.4v1.9h6.4q0.3 0 0.5 0.2t0.3 0.5v2.3q0 0.3-0.3 0.5t-0.5 0.2h-6.4v7.4q0 0.3-0.2 0.5t-0.5 0.2z' }) ) ); }; exports.default = FaCny; module.exports = exports['default'];
'use strict'; /*global ActiveXObject:true*/ var defaults = require('./../defaults'); var utils = require('./../utils'); var buildUrl = require('./../helpers/buildUrl'); var cookies = require('./../helpers/cookies'); var parseHeaders = require('./../helpers/parseHeaders'); var transformData = require('./../helpers/transformData'); var urlIsSameOrigin = require('./../helpers/urlIsSameOrigin'); module.exports = function xhrAdapter(resolve, reject, config) { // Transform request data var data = transformData( config.data, config.headers, config.transformRequest ); // Merge headers var requestHeaders = utils.merge( defaults.headers.common, defaults.headers[config.method] || {}, config.headers || {} ); if (utils.isFormData(data)) { delete requestHeaders['Content-Type']; // Let the browser set it } // Create the request var request = new (XMLHttpRequest || ActiveXObject)('Microsoft.XMLHTTP'); request.open(config.method.toUpperCase(), buildUrl(config.url, config.params), true); // Set the request timeout in MS request.timeout = config.timeout; // Listen for ready state request.onreadystatechange = function () { if (request && request.readyState === 4) { // Prepare the response var responseHeaders = parseHeaders(request.getAllResponseHeaders()); var responseData = ['text', ''].indexOf(config.responseType || '') !== -1 ? request.responseText : request.response; var response = { data: transformData( responseData, responseHeaders, config.transformResponse ), status: request.status, statusText: request.statusText, headers: responseHeaders, config: config }; // Resolve or reject the Promise based on the status (request.status >= 200 && request.status < 300 ? resolve : reject)(response); // Clean up request request = null; } }; // Add xsrf header var xsrfValue = urlIsSameOrigin(config.url) ? cookies.read(config.xsrfCookieName || defaults.xsrfCookieName) : undefined; if (xsrfValue) { requestHeaders[config.xsrfHeaderName || defaults.xsrfHeaderName] = xsrfValue; } // Add headers to the request utils.forEach(requestHeaders, function (val, key) { // Remove Content-Type if data is undefined if (!data && key.toLowerCase() === 'content-type') { delete requestHeaders[key]; } // Otherwise add header to the request else { request.setRequestHeader(key, val); } }); // Add withCredentials to request if needed if (config.withCredentials) { request.withCredentials = true; } // Add responseType to request if needed if (config.responseType) { try { request.responseType = config.responseType; } catch (e) { if (request.responseType !== 'json') { throw e; } } } if (utils.isArrayBuffer(data)) { data = new DataView(data); } // Send the request request.send(data); };
angular.module('teamform-manage_team-app', ['firebase']) .controller('ManageTeamCtrl', ['$scope', '$firebaseObject', '$firebaseArray', function($scope, $firebaseObject, $firebaseArray) { initalizeFirebase(); var teamleader; firebase.auth().onAuthStateChanged(function(user) { if (user) { var userPath = "/user/" + user.uid; var userref = firebase.database().ref(userPath); userref.on("value", function(snapshot) { console.log(snapshot.val()); teamleader = snapshot.val().name; console.log(teamleader); }, function (errorObject) { console.log("The read failed: " + errorObject.code); }); } else {} }); $scope.teaminfo = {TeamLeader:"", Description:"", Forward:"", Midfield:"", LeftBack:"", RightBack:"", Goalkeeper:""}; $scope.input = {teamLeader: teamleader, forward:"", midfield:"", leftBack:"", rightBack:"", goalkeeper:""}; $scope.teamtaginfo = {Pass_and_move:"", Give_and_go:"", The_long_through_ball:"", Triangular_movement:"", Swapping_of_the_wing_man:"", Strong_side_overloads:"", The_zone_defence:"", Depth_considerations:"", The_man_to_man_defence:""}; $scope.teamtaginput = {pass_and_move:0, give_and_go:0, the_long_through_ball:0, triangular_movement:0, swapping_of_the_wing_man:0, strong_side_overloads:0, the_zone_defence:0, depth_considerations:0, the_man_to_man_defence:0}; var eventName, teamName; eventName = getURLParameter("q"); teamName = getURLParameter("tn"); var eventPath ="/event/" + eventName +"/param"; var eventref = firebase.database().ref(eventPath); var current_team; eventref.once("value",function(snapshot) { console.log(snapshot.val()); current_team = snapshot.val().No_of_Team; current_team = current_team +1; console.log(current_team); eventref.update( { 'No_of_Team' : current_team } ); }, function (errorObject) { console.log("The read failed: " + errorObject.code); }); var ref, refPath; $scope.EventName = eventName; $scope.TeamName = teamName; var teamtaginit = "NULL"; $scope.TeamTag = teamtaginit; //Get The team info refPath = "/event/" + eventName + "/team/" + teamName; ref = firebase.database().ref(refPath); $scope.teaminfo = $firebaseObject(ref); ref.set({ TeamName: teamName, TeamTag: "NULL", TeamLeader: "", Description:"", Forward:"", Midfield:"", LeftBack:"", RightBack:"", GoalKeeper:"", NumMembers: 0 }); $scope.teaminfo.$loaded() .then( function(data) { // Fill in some initial values when the DB entry doesn't exist // Enable the UI when the data is successfully loaded and synchornized //$('#manage_team_page_controller').show(); $scope.teaminfo.TeamLeader = $scope.input.teamLeader; $scope.teaminfo.Description = $scope.input.description; $scope.teaminfo.Forward = $scope.input.forward; $scope.teaminfo.Midfield = $scope.input.midfield; $scope.teaminfo.LeftBack = $scope.input.leftBack; $scope.teaminfo.RightBack = $scope.input.rightBack; $scope.teaminfo.Goalkeeper = $scope.input.goalkeeper; }) .catch(function(error) { // Database connection error handling... //console.error("Error:", error); }); //Get the team tag info var tagRef, tagRefPath; tagRefPath = "/event/" + eventName + "/team/" + teamName + "/tag"; tagRef = firebase.database().ref(tagRefPath); $scope.teamtaginfo = $firebaseObject(tagRef); tagRef.set({ Pass_and_move:"", Give_and_go:"", The_long_through_ball:"", Triangular_movement:"", Swapping_of_the_wing_man:"", Strong_side_overloads:"", The_zone_defence:"", Depth_considerations:"", The_man_to_man_defence:"" }) $scope.teamtaginfo.$loaded() .then( function(data) { /* $scope.teamtaginfo.Pass_and_move = $scope.teamtaginput.pass_and_move; $scope.teamtaginfo.Give_and_go = $scope.teamtaginput.give_and_go; $scope.teamtaginfo.The_long_through_ball = $scope.teamtaginput.the_long_through_ball; $scope.teamtaginfo.Triangular_movement = $scope.teamtaginput.triangular_movement; $scope.teamtaginfo.Swapping_of_the_wing_man = $scope.teamtaginput.swapping_of_the_wing_man; $scope.teamtaginfo.Strong_side_overloads = $scope.teamtaginput.strong_side_overloads; $scope.teamtaginfo.The_zone_defence = $scope.teamtaginput.the_zone_defence; $scope.teamtaginfo.Depth_considerations = $scope.teamtaginput.depth_considerations; $scope.teamtaginfo.The_man_to_man_defence = $scope.teamtaginput.the_man_to_man_defence; */ $scope.teamtaginfo.Pass_and_move = 0; $scope.teamtaginfo.Give_and_go = 0; $scope.teamtaginfo.The_long_through_ball = 0; $scope.teamtaginfo.Triangular_movement = 0; $scope.teamtaginfo.Swapping_of_the_wing_man = 0; $scope.teamtaginfo.Strong_side_overloads = 0; $scope.teamtaginfo.The_zone_defence = 0; $scope.teamtaginfo.Depth_considerations = 0; $scope.teamtaginfo.The_man_to_man_defence = 0; }) .catch(function(error) { }); $scope.saveFunc = function() { $scope.teaminfo.$save(); $scope.teamtaginfo.$save(); // Finally, go back to the front-end window.location.href= "team.html?q=" + eventName +"&tn=" + teamName; } $scope.processRequest = function(r) { //$scope.test = "processRequest: " + r; if ( $scope.param.teamMembers.indexOf(r) < 0 && $scope.param.teamMembers.length < $scope.param.currentTeamSize ) { // Not exists, and the current number of team member is less than the preferred team size $scope.param.teamMembers.push(r); $scope.saveFunc(); $scope.saveFuncTeamTag(); } } $scope.removeMember = function(member) { var index = $scope.param.teamMembers.indexOf(member); if ( index > -1 ) { $scope.param.teamMembers.splice(index, 1); // remove that item $scope.saveFunc(); $scope.saveFuncTeamTag(); } } } ]);
import m from 'mithril'; import prop from 'mithril/stream'; import h from '../h'; import _ from 'underscore'; const EnterKey = 13; const innerFieldInput = { oninit: function(vnode) { const inputState = { value: vnode.attrs.inputValue, setValue: function(value) { value = (''+value).replace(/[^0-9]*/g, ''); value = Math.abs(parseInt(value)); inputState.value(value); } } vnode.state = { inputState }; }, view: function({state, attrs}) { const defaultInputOptions = { onchange: m.withAttr('value', state.inputState.setValue), value: state.inputState.value(), onkeyup: (e) => { if (e.keyCode == EnterKey) attrs.onsetValue(); state.inputState.setValue(e.target.value) } }; let inputExtraProps = ''; if ('min' in attrs) inputExtraProps += `[min='${attrs.min}']`; if ('max' in attrs) inputExtraProps += `[max='${attrs.max}']`; if ('placeholder' in attrs) inputExtraProps += `[placeholder='${attrs.placeholder}']`; else inputExtraProps += `[placeholder=' ']`; return attrs.shouldRenderInnerFieldLabel ? m(`input.text-field.positive.w-input[type='number']${inputExtraProps}`, defaultInputOptions) : m('.w-row', [ m('.text-field.positive.prefix.no-hover.w-col.w-col-3.w-col-small-3.w-col-tiny-3', m('.fontsize-smallest.fontcolor-secondary.u-text-center', attrs.label) ), m('.w-col.w-col-9.w-col-small-9.w-col-tiny-9', m(`input.text-field.postfix.positive.w-input[type='number']${inputExtraProps}`, defaultInputOptions) ) ]); } } const filterDropdownNumberRange = { oninit: function (vnode) { const firstValue = prop(0), secondValue = prop(0), clearFieldValues = () => { firstValue(0), secondValue(0) }, getNumericValue = (value) => isNaN(value) ? 0 : value, getLowerValue = () => getNumericValue(firstValue()), getHigherValue = () => getNumericValue(secondValue()), renderPlaceholder = () => { const lowerValue = getLowerValue(), higherValue = getHigherValue(); let placeholder = vnode.attrs.value_change_placeholder; if (higherValue !== 0) placeholder = vnode.attrs.value_change_both_placeholder; if (lowerValue !== 0) { placeholder = placeholder.replace('#V1', lowerValue); } else { placeholder = placeholder.replace('#V1', vnode.attrs.init_lower_value); } if (higherValue !== 0) { placeholder = placeholder.replace('#V2', higherValue); } else { placeholder = placeholder.replace('#V2', vnode.attrs.init_higher_value); } return placeholder; }, showDropdown = h.toggleProp(false, true); vnode.state = { firstValue, secondValue, clearFieldValues, getLowerValue, getHigherValue, renderPlaceholder, showDropdown }; }, view: function ({state, attrs}) { const dropdownOptions = {}; const shouldRenderInnerFieldLabel = !!!attrs.inner_field_label; const applyValueToFilter = () => { const higherValue = state.getHigherValue() * attrs.value_multiplier; const lowerValue = state.getLowerValue() * attrs.value_multiplier; attrs.vm.gte(lowerValue); attrs.vm.lte(higherValue); attrs.onapply(); state.showDropdown.toggle(); }; if ('dropdown_inline_style' in attrs) { dropdownOptions.style = attrs.dropdown_inline_style; } return m(attrs.wrapper_class, [ m('.fontsize-smaller.u-text-center', attrs.label), m('div', { style: {'z-index' : '1'} }, [ m('select.w-select.text-field.positive', { style: { 'margin-bottom' : '0px' }, onmousedown: function(e) { e.preventDefault(); if (attrs.selectable() !== attrs.index && state.showDropdown()) state.showDropdown.toggle(); attrs.selectable(attrs.index); state.showDropdown.toggle(); } }, [ m('option', { value: '' }, state.renderPlaceholder()) ]), ((state.showDropdown() && attrs.selectable() == attrs.index) ? m('nav.dropdown-list.dropdown-list-medium.card', dropdownOptions, [ m('.u-marginbottom-20.w-row', [ m('.w-col.w-col-5.w-col-small-5.w-col-tiny-5', m(innerFieldInput, { shouldRenderInnerFieldLabel, inputValue: state.firstValue, placeholder: attrs.inner_field_placeholder, label: attrs.inner_field_label, min: attrs.min, onsetValue: applyValueToFilter }) ), m('.w-col.w-col-2.w-col-small-2.w-col-tiny-2', m('.fontsize-smaller.u-text-center.u-margintop-10', 'a' ) ), m('.w-col.w-col-5.w-col-small-5.w-col-tiny-5', m(innerFieldInput, { shouldRenderInnerFieldLabel, inputValue: state.secondValue, placeholder: ' ', label: attrs.inner_field_label, min: attrs.min, onsetValue: applyValueToFilter }) ) ]), m('a.fontsize-smaller.fontweight-semibold.alt-link.u-right[href=\'#\']', { onclick: applyValueToFilter }, 'Aplicar'), m('a.fontsize-smaller.link-hidden[href=\'#\']', { onclick: () => { state.clearFieldValues(); applyValueToFilter(); } }, 'Limpar') ]) : '') ]) ]); } } export default filterDropdownNumberRange;
import { expect } from 'chai'; import React from 'react'; import { Provider } from 'react-redux'; import { mount } from 'enzyme'; import fakeStore from './fakeStore'; import CreateRecipe from '../../client/components/CreateRecipe.js'; describe('<CreateRecipe />', () => { let wrapper; before('render CreateRecipe', () => { wrapper = mount( <Provider store={fakeStore}> <CreateRecipe /> </Provider>); }); it('renders without problems', () => { expect(wrapper.find(CreateRecipe)).to.have.length(1); }); it('can dispatch changes to React state', () => { const titleField = wrapper.find('[name="title"]'); const event1 = { target: { value: 'cat', name: 'title' } }; titleField.simulate('change', event1); expect(titleField.prop('value')).to.equal('cat'); const yieldField = wrapper.find('[name="yield"]'); const event2 = { target: { value: 15, name: 'yield' } }; yieldField.simulate('change', event2); expect(yieldField.prop('value')).to.equal(15); }); });
/*! jQuery UI - v1.10.3 - 2013-09-04 * http://jqueryui.com * Copyright 2013 jQuery Foundation and other contributors; Licensed MIT */ jQuery(function(t){t.datepicker.regional.da={closeText:"Luk",prevText:"&#x3C;Forrige",nextText:"Næste&#x3E;",currentText:"Idag",monthNames:["Januar","Februar","Marts","April","Maj","Juni","Juli","August","September","Oktober","November","December"],monthNamesShort:["Jan","Feb","Mar","Apr","Maj","Jun","Jul","Aug","Sep","Okt","Nov","Dec"],dayNames:["Søndag","Mandag","Tirsdag","Onsdag","Torsdag","Fredag","Lørdag"],dayNamesShort:["Søn","Man","Tir","Ons","Tor","Fre","Lør"],dayNamesMin:["Sø","Ma","Ti","On","To","Fr","Lø"],weekHeader:"Uge",dateFormat:"dd-mm-yy",firstDay:1,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},t.datepicker.setDefaults(t.datepicker.regional.da)});
window.codeforcesOptions = []; window.codeforcesOptions.subscribeServerUrl = "http://pubsub.codeforces.com:85/sub";
"use strict"; var FilterDispatcher = require("../dispatcher/filter_dispatcher"); module.exports = { changeDate: function changeDate(key, date) { var pos = arguments.length <= 2 || arguments[2] === undefined ? "start" : arguments[2]; FilterDispatcher.handleChangeDate({ type: "CHANGE_DATE", date: date, key: key, pos: pos }); }, checkFilter: function checkFilter(filterBy, id, value) { FilterDispatcher.handleCheckFilter({ type: "CHECK_FILTER", filterBy: filterBy, id: id, value: value }); }, changeKey: function changeKey(data) { FilterDispatcher.handleKeyUpdate({ type: "CHANGE_KEY", data: data }); }, fetchFilters: function fetchFilters(api) { FilterDispatcher.handleFetchFilters({ type: "FETCH", api: api }); }, receiveAll: function receiveAll(data) { FilterDispatcher.handleServerAction({ type: "RECEIVE_DATA", data: data }); }, selectFilter: function selectFilter(filterBy, id) { FilterDispatcher.handleSelectFilter({ type: "SELECT_FILTER", filterBy: filterBy, id: id }); }, setKeys: function setKeys(data) { FilterDispatcher.setAllKeysUpdate({ type: "SET_KEYS", data: data }); }, setTab: function setTab(tab) { FilterDispatcher.setTab({ type: "SET_TAB", tab: tab }); } }; //# sourceMappingURL=filter_actions.js.map
/*jshint jquery:true, devel:true */ (function (n64js) {'use strict'; var kDebugTLB = 0; var kDebugDynarec = 0; var kEnableDynarec = true; var hitCounts = {}; var fragmentMap = {}; var fragmentInvalidationEvents = []; var kHotFragmentThreshold = 500; var accurateCountUpdating = false; var COUNTER_INCREMENT_PER_OP = 1; var k1Shift32 = 4294967296.0; var UT_VEC = 0x80000000; var XUT_VEC = 0x80000080; var ECC_VEC = 0x80000100; var E_VEC = 0x80000180; var SR_IE = 0x00000001; var SR_EXL = 0x00000002; var SR_ERL = 0x00000004; var SR_KSU_KER = 0x00000000; var SR_KSU_SUP = 0x00000008; var SR_KSU_USR = 0x00000010; var SR_KSU_MASK = 0x00000018; var SR_UX = 0x00000020; var SR_SX = 0x00000040; var SR_KX = 0x00000080; var SR_IBIT1 = 0x00000100; var SR_IBIT2 = 0x00000200; var SR_IBIT3 = 0x00000400; var SR_IBIT4 = 0x00000800; var SR_IBIT5 = 0x00001000; var SR_IBIT6 = 0x00002000; var SR_IBIT7 = 0x00004000; var SR_IBIT8 = 0x00008000; var SR_IMASK0 = 0x0000ff00; var SR_IMASK1 = 0x0000fe00; var SR_IMASK2 = 0x0000fc00; var SR_IMASK3 = 0x0000f800; var SR_IMASK4 = 0x0000f000; var SR_IMASK5 = 0x0000e000; var SR_IMASK6 = 0x0000c000; var SR_IMASK7 = 0x00008000; var SR_IMASK8 = 0x00000000; var SR_IMASK = 0x0000ff00; var SR_DE = 0x00010000; var SR_CE = 0x00020000; var SR_CH = 0x00040000; var SR_SR = 0x00100000; var SR_TS = 0x00200000; var SR_BEV = 0x00400000; var SR_ITS = 0x01000000; var SR_RE = 0x02000000; var SR_FR = 0x04000000; var SR_RP = 0x08000000; var SR_CU0 = 0x10000000; var SR_CU1 = 0x20000000; var SR_CU2 = 0x40000000; var SR_CU3 = 0x80000000; var SR_CUMASK = 0xf0000000; var CAUSE_BD_BIT = 31; // NB: Closure Compiler doesn't like 32 bit constants. var CAUSE_BD = 0x80000000; var CAUSE_CEMASK = 0x30000000; var CAUSE_CESHIFT = 28; var CAUSE_SW1 = 0x00000100; var CAUSE_SW2 = 0x00000200; var CAUSE_IP3 = 0x00000400; var CAUSE_IP4 = 0x00000800; var CAUSE_IP5 = 0x00001000; var CAUSE_IP6 = 0x00002000; var CAUSE_IP7 = 0x00004000; var CAUSE_IP8 = 0x00008000; var CAUSE_IPMASK = 0x0000FF00; var CAUSE_IPSHIFT = 8; var CAUSE_EXCMASK = 0x0000007C; var CAUSE_EXCSHIFT = 2; var EXC_INT = 0; var EXC_MOD = 4; var EXC_RMISS = 8; var EXC_WMISS = 12; var EXC_RADE = 16; var EXC_WADE = 20; var EXC_IBE = 24; var EXC_DBE = 28; var EXC_SYSCALL = 32; var EXC_BREAK = 36; var EXC_II = 40; var EXC_CPU = 44; var EXC_OV = 48; var EXC_TRAP = 52; var EXC_VCEI = 56; var EXC_FPE = 60; var EXC_WATCH = 92; var EXC_VCED = 124; var FPCSR_RM_RN = 0x00000000; var FPCSR_RM_RZ = 0x00000001; var FPCSR_RM_RP = 0x00000002; var FPCSR_RM_RM = 0x00000003; var FPCSR_FI = 0x00000004; var FPCSR_FU = 0x00000008; var FPCSR_FO = 0x00000010; var FPCSR_FZ = 0x00000020; var FPCSR_FV = 0x00000040; var FPCSR_EI = 0x00000080; var FPCSR_EU = 0x00000100; var FPCSR_EO = 0x00000200; var FPCSR_EZ = 0x00000400; var FPCSR_EV = 0x00000800; var FPCSR_CI = 0x00001000; var FPCSR_CU = 0x00002000; var FPCSR_CO = 0x00004000; var FPCSR_CZ = 0x00008000; var FPCSR_CV = 0x00010000; var FPCSR_CE = 0x00020000; var FPCSR_C = 0x00800000; var FPCSR_FS = 0x01000000; var FPCSR_RM_MASK = 0x00000003; var TLBHI_VPN2MASK = 0xffffe000; var TLBHI_VPN2MASK_NEG= 0x00001fff; var TLBHI_VPN2SHIFT = 13; var TLBHI_PIDMASK = 0xff; var TLBHI_PIDSHIFT = 0; var TLBHI_NPID = 255; var TLBLO_PFNMASK = 0x3fffffc0; var TLBLO_PFNSHIFT = 6; var TLBLO_CACHMASK = 0x38; var TLBLO_CACHSHIFT = 3; var TLBLO_UNCACHED = 0x10; var TLBLO_NONCOHRNT = 0x18; var TLBLO_EXLWR = 0x28; var TLBLO_D = 0x4; var TLBLO_V = 0x2; var TLBLO_G = 0x1; var TLBINX_PROBE = 0x80000000; var TLBINX_INXMASK = 0x3f; var TLBINX_INXSHIFT = 0; var TLBRAND_RANDMASK = 0x3f; var TLBRAND_RANDSHIFT = 0; var TLBWIRED_WIREDMASK = 0x3f; var TLBCTXT_BASEMASK = 0xff800000; var TLBCTXT_BASESHIFT = 23; var TLBCTXT_BASEBITS = 9; var TLBCTXT_VPNMASK = 0x7ffff0; var TLBCTXT_VPNSHIFT = 4; var TLBPGMASK_4K = 0x00000000; var TLBPGMASK_16K = 0x00006000; var TLBPGMASK_64K = 0x0001e000; var TLBPGMASK_256K = 0x0007e000; var TLBPGMASK_1M = 0x001fe000; var TLBPGMASK_4M = 0x007fe000; var TLBPGMASK_16M = 0x01ffe000; var kStuffToDoHalt = 1<<0; var kStuffToDoCheckInterrupts = 1<<1; var kStuffToDoBreakout = 1<<2; var kVIIntrCycles = 62500; var kEventVbl = 0; var kEventCompare = 1; var kEventRunForCycles = 2; n64js.getHi32 = function (v) { // >>32 just seems to no-op? Argh. return Math.floor( v / k1Shift32 ); }; function TLBEntry() { this.pagemask = 0; this.hi = 0; this.pfne = 0; this.pfno = 0; this.mask = 0; this.global = 0; } TLBEntry.prototype.update = function(index, pagemask, hi, entrylo0, entrylo1) { if (kDebugTLB) { n64js.log('TLB update: index=' + index + ', pagemask=' + n64js.toString32(pagemask) + ', entryhi=' + n64js.toString32(hi) + ', entrylo0=' + n64js.toString32(entrylo0) + ', entrylo1=' + n64js.toString32(entrylo1) ); switch (pagemask) { case TLBPGMASK_4K: n64js.log(' 4k Pagesize'); break; case TLBPGMASK_16K: n64js.log(' 16k Pagesize'); break; case TLBPGMASK_64K: n64js.log(' 64k Pagesize'); break; case TLBPGMASK_256K: n64js.log(' 256k Pagesize'); break; case TLBPGMASK_1M: n64js.log(' 1M Pagesize'); break; case TLBPGMASK_4M: n64js.log(' 4M Pagesize'); break; case TLBPGMASK_16M: n64js.log(' 16M Pagesize'); break; default: n64js.log(' Unknown Pagesize'); break; } } this.pagemask = pagemask; this.hi = hi; this.pfne = entrylo0; this.pfno = entrylo1; this.global = (entrylo0 & entrylo1 & TLBLO_G); this.mask = pagemask | TLBHI_VPN2MASK_NEG; this.mask2 = this.mask>>>1; this.vpnmask = (~this.mask)>>>0; this.vpn2mask = this.vpnmask>>>1; this.addrcheck = (hi & this.vpnmask)>>>0; this.pfnehi = (this.pfne << TLBLO_PFNSHIFT) & this.vpn2mask; this.pfnohi = (this.pfno << TLBLO_PFNSHIFT) & this.vpn2mask; switch (this.pagemask) { case TLBPGMASK_4K: this.checkbit = 0x00001000; break; case TLBPGMASK_16K: this.checkbit = 0x00004000; break; case TLBPGMASK_64K: this.checkbit = 0x00010000; break; case TLBPGMASK_256K: this.checkbit = 0x00040000; break; case TLBPGMASK_1M: this.checkbit = 0x00100000; break; case TLBPGMASK_4M: this.checkbit = 0x00400000; break; case TLBPGMASK_16M: this.checkbit = 0x01000000; break; default: // shouldn't happen! this.checkbit = 0; break; } }; function CPU0() { this.opsExecuted = 0; // Approximate... this.ram = undefined; // bound to in reset n64js.getRamU8Array(); this.gprLoMem = new ArrayBuffer(32*4); this.gprHiMem = new ArrayBuffer(32*4); this.gprLoBytes = new Uint8Array(this.gprLoMem); // Used to help form addresses without causing deopts or generating HeapNumbers. this.gprLo = new Uint32Array(this.gprLoMem); this.gprHi = new Uint32Array(this.gprHiMem); this.gprLo_signed = new Int32Array(this.gprLoMem); this.gprHi_signed = new Int32Array(this.gprHiMem); this.controlMem = new ArrayBuffer(32*4); this.control = new Uint32Array(this.controlMem); this.control_signed = new Int32Array(this.controlMem); this.pc = 0; this.delayPC = 0; this.nextPC = 0; // Set to the next expected PC before an op executes. Ops can update this to change control flow without branch delay (e.g. likely branches, ERET) this.branchTarget = 0; // Set to indicate a branch has been taken. Sets the delayPC for the subsequent op. this.stuffToDo = 0; // used to flag r4300 to cease execution this.events = []; this.multHiMem = new ArrayBuffer(2*4); this.multLoMem = new ArrayBuffer(2*4); this.multHi = new Uint32Array(this.multHiMem); this.multLo = new Uint32Array(this.multLoMem); this.multHi_signed = new Int32Array(this.multHiMem); this.multLo_signed = new Int32Array(this.multLoMem); this.tlbEntries = []; for (var i = 0; i < 32; ++i) { this.tlbEntries.push(new TLBEntry()); } // General purpose register constants this.kRegister_r0 = 0x00; this.kRegister_at = 0x01; this.kRegister_v0 = 0x02; this.kRegister_v1 = 0x03; this.kRegister_a0 = 0x04; this.kRegister_a1 = 0x05; this.kRegister_a2 = 0x06; this.kRegister_a3 = 0x07; this.kRegister_t0 = 0x08; this.kRegister_t1 = 0x09; this.kRegister_t2 = 0x0a; this.kRegister_t3 = 0x0b; this.kRegister_t4 = 0x0c; this.kRegister_t5 = 0x0d; this.kRegister_t6 = 0x0e; this.kRegister_t7 = 0x0f; this.kRegister_s0 = 0x10; this.kRegister_s1 = 0x11; this.kRegister_s2 = 0x12; this.kRegister_s3 = 0x13; this.kRegister_s4 = 0x14; this.kRegister_s5 = 0x15; this.kRegister_s6 = 0x16; this.kRegister_s7 = 0x17; this.kRegister_t8 = 0x18; this.kRegister_t9 = 0x19; this.kRegister_k0 = 0x1a; this.kRegister_k1 = 0x1b; this.kRegister_gp = 0x1c; this.kRegister_sp = 0x1d; this.kRegister_s8 = 0x1e; this.kRegister_ra = 0x1f; // Control register constants this.kControlIndex = 0; this.kControlRand = 1; this.kControlEntryLo0 = 2; this.kControlEntryLo1 = 3; this.kControlContext = 4; this.kControlPageMask = 5; this.kControlWired = 6; //... this.kControlBadVAddr = 8; this.kControlCount = 9; this.kControlEntryHi = 10; this.kControlCompare = 11; this.kControlSR = 12; this.kControlCause = 13; this.kControlEPC = 14; this.kControlPRId = 15; this.kControlConfig = 16; this.kControlLLAddr = 17; this.kControlWatchLo = 18; this.kControlWatchHi = 19; //... this.kControlECC = 26; this.kControlCacheErr = 27; this.kControlTagLo = 28; this.kControlTagHi = 29; this.kControlErrorEPC = 30; } CPU0.prototype.getCount = function() { return this.control[this.kControlCount]; }; CPU0.prototype.getGPR_s64 = function (r) { return (this.gprHi_signed[r] * k1Shift32) + this.gprLo[r]; }; CPU0.prototype.getGPR_u64 = function (r) { return (this.gprHi[r] * k1Shift32) + this.gprLo[r]; }; CPU0.prototype.setGPR_s64 = function (r, v) { this.gprHi_signed[r] = Math.floor( v / k1Shift32 ); this.gprLo_signed[r] = v; }; CPU0.prototype.reset = function () { var i; hitCounts = {}; fragmentMap = {}; fragmentInvalidationEvents = []; this.ram = n64js.getRamU8Array(); for (i = 0; i < 32; ++i) { this.gprLo[i] = 0; this.gprHi[i] = 0; this.control[i] = 0; } for (i = 0; i < 32; ++i) { this.tlbEntries[i].update(i, 0, 0x80000000, 0, 0); } this.pc = 0; this.delayPC = 0; this.nextPC = 0; this.branchTarget = 0; this.stuffToDo = 0; this.events = []; this.multLo[0] = this.multLo[1] = 0; this.multHi[0] = this.multHi[1] = 0; this.control[this.kControlRand] = 32-1; this.control[this.kControlSR] = 0x70400004; this.control[this.kControlConfig] = 0x0006e463; this.addEvent(kEventVbl, kVIIntrCycles); }; CPU0.prototype.breakExecution = function () { this.stuffToDo |= kStuffToDoHalt; }; CPU0.prototype.speedHack = function () { var next_instruction = n64js.readMemoryInternal32(this.pc + 4); if (next_instruction === 0) { if (this.events.length > 0) { // Ignore the kEventRunForCycles event var run_countdown = 0; if (this.events[0].type === kEventRunForCycles && this.events.length > 1) { run_countdown += this.events[0].countdown; this.events.splice(0,1); } var to_skip = run_countdown + this.events[0].countdown - 1; //n64js.log('speedhack: skipping ' + to_skip + ' cycles'); this.control[this.kControlCount] += to_skip; this.events[0].countdown = 1; // Re-add the kEventRunForCycles event if (run_countdown) { this.addEvent(kEventRunForCycles, run_countdown); } } else { n64js.log('no events'); } } else { //n64js.log('next instruction does something'); } }; CPU0.prototype.updateCause3 = function () { if (n64js.miInterruptsUnmasked()) { this.control[this.kControlCause] |= CAUSE_IP3; if (this.checkForUnmaskedInterrupts()) { this.stuffToDo |= kStuffToDoCheckInterrupts; } } else { this.control[this.kControlCause] &= ~CAUSE_IP3; } checkCauseIP3Consistent(); }; CPU0.prototype.setSR = function (value) { var old_value = this.control[this.kControlSR]; if ((old_value & SR_FR) !== (value & SR_FR)) { n64js.log('Changing FPU to ' + ((value & SR_FR) ? '64bit' : '32bit' )); } this.control[this.kControlSR] = value; setCop1Enable( (value & SR_CU1) !== 0 ); if (this.checkForUnmaskedInterrupts()) { this.stuffToDo |= kStuffToDoCheckInterrupts; } }; CPU0.prototype.checkForUnmaskedInterrupts = function () { var sr = this.control[this.kControlSR]; // Ensure ERL/EXL are clear and IE is set if ((sr & (SR_EXL | SR_ERL | SR_IE)) === SR_IE) { // Check if interrupts are actually pending, and wanted var cause = this.control[this.kControlCause]; if ((sr & cause & CAUSE_IPMASK) !== 0) { return true; } } return false; }; CPU0.prototype.throwTLBException = function (address, exc_code, vec) { this.control[this.kControlBadVAddr] = address; this.control[this.kControlContext] &= 0xff800000; this.control[this.kControlContext] |= ((address >>> 13) << 4); this.control[this.kControlEntryHi] &= 0x00001fff; this.control[this.kControlEntryHi] |= (address & 0xfffffe000); // XXXX check we're not inside exception handler before snuffing CAUSE reg? this.setException( CAUSE_EXCMASK, exc_code ); this.nextPC = vec; }; CPU0.prototype.throwTLBReadMiss = function (address) { this.throwTLBException(address, EXC_RMISS, UT_VEC); }; CPU0.prototype.throwTLBWriteMiss = function (address) { this.throwTLBException(address, EXC_WMISS, UT_VEC); }; CPU0.prototype.throwTLBReadInvalid = function (address) { this.throwTLBException(address, EXC_RMISS, E_VEC); }; CPU0.prototype.throwTLBWriteInvalid = function (address) { this.throwTLBException(address, EXC_WMISS, E_VEC); }; CPU0.prototype.throwCop1Unusable = function () { // XXXX check we're not inside exception handler before snuffing CAUSE reg? this.setException( CAUSE_EXCMASK|CAUSE_CEMASK, EXC_CPU | 0x10000000 ); this.nextPC = E_VEC; }; CPU0.prototype.handleInterrupt = function () { if (this.checkForUnmaskedInterrupts()) { this.setException( CAUSE_EXCMASK, EXC_INT ); // this is handled outside of the main dispatch loop, so need to update pc directly this.pc = E_VEC; this.delayPC = 0; } else { n64js.assert(false, "Was expecting an unmasked interrupt - something wrong with kStuffToDoCheckInterrupts?"); } }; CPU0.prototype.setException = function (mask, exception) { this.control[this.kControlCause] &= ~mask; this.control[this.kControlCause] |= exception; this.control[this.kControlSR] |= SR_EXL; this.control[this.kControlEPC] = this.pc; var bd_mask = (1<<CAUSE_BD_BIT); if (this.delayPC) { this.control[this.kControlCause] |= bd_mask; this.control[this.kControlEPC] -= 4; } else { this.control[this.kControlCause] &= ~bd_mask; } }; CPU0.prototype.setCompare = function (value) { this.control[this.kControlCause] &= ~CAUSE_IP8; if (value === this.control[this.kControlCompare]) { // just clear the IP8 flag } else { if (value !== 0) { var count = this.control[this.kControlCount]; if (value > count) { var delta = value - count; this.removeEventsOfType(kEventCompare); this.addEvent(kEventCompare, delta); } else { n64js.warn('setCompare underflow - was' + n64js.toString32(count) + ', setting to ' + value); } } } this.control[this.kControlCompare] = value; }; function Event(type, countdown) { this.type = type; this.countdown = countdown; } Event.prototype.getName = function () { switch(this.type) { case kEventVbl: return 'Vbl'; case kEventCompare: return 'Compare'; case kEventRunForCycles: return 'Run'; } return '?'; }; CPU0.prototype.addEvent = function(type, countdown) { n64js.assert( countdown >0, "Countdown is invalid" ); for (var i = 0; i < this.events.length; ++i) { var event = this.events[i]; if (countdown <= event.countdown) { event.countdown -= countdown; this.events.splice(i, 0, new Event(type, countdown)); return; } countdown -= event.countdown; } this.events.push(new Event(type, countdown)); }; CPU0.prototype.removeEventsOfType = function (type) { var count = 0; for (var i = 0; i < this.events.length; ++i) { count += this.events[i].countdown; if (this.events[i].type == type) { // Add this countdown on to the subsequent event if ((i+1) < this.events.length) { this.events[i+1].countdown += this.events[i].countdown; } this.events.splice(i, 1); return count; } } // Not found. return -1; }; CPU0.prototype.hasEvent = function(type) { for (var i = 0; i < this.events.length; ++i) { if (this.events[i].type == type) { return true; } } return false; }; CPU0.prototype.getRandom = function () { var wired = this.control[this.kControlWired] & 0x1f; var random = Math.floor(Math.random() * (32-wired)) + wired; var sync = n64js.getSyncFlow(); if (sync) { random = sync.reflect32(random); } n64js.assert(random >= wired && random <= 31, "Ooops - random should be in range " + wired + "..31, but got " + random); return random; }; CPU0.prototype.setTLB = function (cpu, index) { var pagemask = cpu.control[cpu.kControlPageMask]; var entryhi = cpu.control[cpu.kControlEntryHi]; var entrylo1 = cpu.control[cpu.kControlEntryLo1]; var entrylo0 = cpu.control[cpu.kControlEntryLo0]; cpu.tlbEntries[index].update(index, pagemask, entryhi, entrylo0, entrylo1); }; CPU0.prototype.tlbWriteIndex = function () { this.setTLB(this, this.control[this.kControlIndex] & 0x1f); }; CPU0.prototype.tlbWriteRandom = function () { this.setTLB(this, this.getRandom()); }; CPU0.prototype.tlbRead = function () { var index = this.control[this.kControlIndex] & 0x1f; var tlb = this.tlbEntries[index]; this.control[this.kControlPageMask] = tlb.mask; this.control[this.kControlEntryHi ] = tlb.hi; this.control[this.kControlEntryLo0] = tlb.pfne | tlb.global; this.control[this.kControlEntryLo1] = tlb.pfno | tlb.global; if (kDebugTLB) { n64js.log('TLB Read Index ' + n64js.toString8(index) + '.'); n64js.log(' PageMask: ' + n64js.toString32(this.control[this.kControlPageMask])); n64js.log(' EntryHi: ' + n64js.toString32(this.control[this.kControlEntryHi])); n64js.log(' EntryLo0: ' + n64js.toString32(this.control[this.kControlEntryLo0])); n64js.log(' EntryLo1: ' + n64js.toString32(this.control[this.kControlEntryLo1])); } }; CPU0.prototype.tlbProbe = function () { var entryhi = this.control[this.kControlEntryHi]; var entryhi_vpn2 = entryhi & TLBHI_VPN2MASK; var entryhi_pid = entryhi & TLBHI_PIDMASK; for (var i = 0; i < 32; ++i) { var tlb = this.tlbEntries[i]; if ( (tlb.hi & TLBHI_VPN2MASK) === entryhi_vpn2) { if (((tlb.hi & TLBHI_PIDMASK) === entryhi_pid) || tlb.global) { if (kDebugTLB) { n64js.log('TLB Probe. EntryHi:' + n64js.toString32(entryhi) + '. Found matching TLB entry - ' + n64js.toString8(i)); } this.control[this.kControlIndex] = i; return; } } } if (kDebugTLB) { n64js.log('TLB Probe. EntryHi:' + n64js.toString32(entryhi) + ". Didn't find matching entry"); } this.control[this.kControlIndex] = TLBINX_PROBE; }; CPU0.prototype.tlbFindEntry = function (address) { for(var count = 0; count < 32; ++count) { // NB should put mru cache here var i = count; var tlb = this.tlbEntries[i]; if ((address & tlb.vpnmask) === tlb.addrcheck) { if (!tlb.global) { var ehi = this.control[this.kControlEntryHi]; if ((tlb.hi & TLBHI_PIDMASK) !== (ehi & TLBHI_PIDMASK) ) { // Entries ASID must match continue; } } return tlb; } } return null; }; CPU0.prototype.translateReadInternal = function (address) { var tlb = this.tlbFindEntry(address); if (tlb) { var valid; var physical_addr; if (address & tlb.checkbit) { valid = (tlb.pfno & TLBLO_V) !== 0; physical_addr = tlb.pfnohi | (address & tlb.mask2); } else { valid = (tlb.pfne & TLBLO_V) !== 0; physical_addr = tlb.pfnehi | (address & tlb.mask2); } if (valid) return physical_addr; return 0; } return 0; }; function TLBException(address) { this.address = address; } CPU0.prototype.translateRead = function (address) { var tlb = this.tlbFindEntry(address); if (tlb) { var valid; var physical_addr; if (address & tlb.checkbit) { valid = (tlb.pfno & TLBLO_V) !== 0; physical_addr = tlb.pfnohi | (address & tlb.mask2); } else { valid = (tlb.pfne & TLBLO_V) !== 0; physical_addr = tlb.pfnehi | (address & tlb.mask2); } if (valid) return physical_addr; this.throwTLBReadInvalid(address); throw new TLBException(address); } this.throwTLBReadMiss(address); throw new TLBException(address); }; CPU0.prototype.translateWrite = function (address) { var tlb = this.tlbFindEntry(address); if (tlb) { var valid; var physical_addr; if (address & tlb.checkbit) { valid = (tlb.pfno & TLBLO_V) !== 0; physical_addr = tlb.pfnohi | (address & tlb.mask2); } else { valid = (tlb.pfne & TLBLO_V) !== 0; physical_addr = tlb.pfnehi | (address & tlb.mask2); } if (valid) return physical_addr; this.throwTLBWriteInvalid(address); throw new TLBException(address); } this.throwTLBWriteMiss(address); throw new TLBException(address); }; function CPU1() { this.control = new Uint32Array(32); this.mem = new ArrayBuffer(32 * 4); // 32 32-bit regs this.float32 = new Float32Array(this.mem); this.float64 = new Float64Array(this.mem); this.int32 = new Int32Array(this.mem); this.uint32 = new Uint32Array(this.mem); this.reset = function () { for (var i = 0; i < 32; ++i) { this.control[i] = 0; this.int32[i] = 0; } this.control[0] = 0x00000511; }; this.setCondition = function (v) { if (v) this.control[31] |= FPCSR_C; else this.control[31] &= ~FPCSR_C; }; this.store_64 = function (i, lo, hi) { this.int32[i+0] = lo; this.int32[i+1] = hi; }; this.load_f64 = function (i) { return this.float64[i>>1]; }; this.load_s64_as_double = function (i) { return (this.int32[i+1] * k1Shift32) + this.int32[i]; }; this.store_float_as_long = function (i, v) { this.int32[i ] = v & 0xffffffff; this.int32[i+1] = Math.floor( v / k1Shift32 ); }; this.store_f64 = function (i, v) { this.float64[i>>1] = v; }; } // Expose the cpu state var cpu0 = new CPU0(); var cpu1 = new CPU1(); n64js.cpu0 = cpu0; n64js.cpu1 = cpu1; function fd(i) { return (i>>> 6)&0x1f; } function fs(i) { return (i>>>11)&0x1f; } function ft(i) { return (i>>>16)&0x1f; } function copop(i) { return (i>>>21)&0x1f; } function offset(i) { return ((i&0xffff)<<16)>>16; } function sa(i) { return (i>>> 6)&0x1f; } function rd(i) { return (i>>>11)&0x1f; } function rt(i) { return (i>>>16)&0x1f; } function rs(i) { return (i>>>21)&0x1f; } function op(i) { return (i>>>26)&0x1f; } function tlbop(i) { return i&0x3f; } function cop1_func(i) { return i&0x3f; } function cop1_bc(i) { return (i>>>16)&0x3; } function target(i) { return (i )&0x3ffffff; } function imm(i) { return (i )&0xffff; } function imms(i) { return ((i&0xffff)<<16)>>16; } // treat immediate value as signed function base(i) { return (i>>>21)&0x1f; } function memaddr(i) { return cpu0.gprLo[base(i)] + imms(i); } function branchAddress(pc,i) { return ((pc+4) + (offset(i)*4))>>>0; } //function branchAddress(pc,i) { return (((pc>>>2)+1) + offset(i))<<2; } // NB: convoluted calculation to avoid >>>0 (deopt) function jumpAddress(pc,i) { return ((pc&0xf0000000) | (target(i)*4))>>>0; } function performBranch(new_pc) { //if (new_pc < 0) { // n64js.log('Oops, branching to negative address: ' + new_pc); // throw 'Oops, branching to negative address: ' + new_pc; //} cpu0.branchTarget = new_pc; } function setSignExtend(r,v) { cpu0.gprLo[r] = v; cpu0.gprHi_signed[r] = v >> 31; } function setZeroExtend(r, v) { cpu0.gprLo[r] = v; cpu0.gprHi_signed[r] = 0; } function setHiLoSignExtend(arr, v) { arr[0] = v; arr[1] = v >> 31; } function setHiLoZeroExtend(arr, v) { arr[0] = v; arr[1] = 0; } function genSrcRegLo(i) { if (i === 0) return '0'; return 'rlo[' + i + ']'; } function genSrcRegHi(i) { if (i === 0) return '0'; return 'rhi[' + i + ']'; } // // Memory access routines. // // These are out of line so that the >>>0 doesn't cause a shift-i deopt in the body of the calling function function lwu_slow(addr) { return n64js.readMemoryU32(addr>>>0); } function lhu_slow(addr) { return n64js.readMemoryU16(addr>>>0); } function lbu_slow(addr) { return n64js.readMemoryU8( addr>>>0); } function lw_slow(addr) { return n64js.readMemoryS32(addr>>>0); } function lh_slow(addr) { return n64js.readMemoryS16(addr>>>0); } function lb_slow(addr) { return n64js.readMemoryS8( addr>>>0); } function sw_slow(addr, value) { n64js.writeMemory32(addr>>>0, value); } function sh_slow(addr, value) { n64js.writeMemory16(addr>>>0, value); } function sb_slow(addr, value) { n64js.writeMemory8( addr>>>0, value); } n64js.load_u8 = function (ram, addr) { if (addr < -2139095040) { var phys = (addr + 0x80000000) | 0; // NB: or with zero ensures we return an SMI if possible. return ram[phys]; } return lbu_slow(addr); }; n64js.load_s8 = function (ram, addr) { if (addr < -2139095040) { var phys = (addr + 0x80000000) | 0; // NB: or with zero ensures we return an SMI if possible. return (ram[phys] << 24) >> 24; } return lb_slow(addr); }; n64js.load_u16 = function (ram, addr) { if (addr < -2139095040) { var phys = (addr + 0x80000000) | 0; // NB: or with zero ensures we return an SMI if possible. return (ram[phys] << 8) | ram[phys+1]; } return lhu_slow(addr); }; n64js.load_s16 = function (ram, addr) { if (addr < -2139095040) { var phys = (addr + 0x80000000) | 0; // NB: or with zero ensures we return an SMI if possible. return ((ram[phys] << 24) | (ram[phys+1] << 16)) >> 16; } return lh_slow(addr); }; n64js.load_u32 = function (ram, addr) { if (addr < -2139095040) { var phys = (addr + 0x80000000) | 0; // NB: or with zero ensures we return an SMI if possible. return ((ram[phys] << 24) | (ram[phys+1] << 16) | (ram[phys+2] << 8) | ram[phys+3]) >>> 0; } return lwu_slow(addr); }; n64js.load_s32 = function (ram, addr) { if (addr < -2139095040) { var phys = (addr + 0x80000000) | 0; // NB: or with zero ensures we return an SMI if possible. return ((ram[phys] << 24) | (ram[phys+1] << 16) | (ram[phys+2] << 8) | ram[phys+3]) | 0; } return lw_slow(addr); }; n64js.store_8 = function (ram, addr, value) { if (addr < -2139095040) { var phys = (addr + 0x80000000) | 0; // NB: or with zero ensures we return an SMI if possible. ram[phys] = value; } else { sb_slow(addr, value); } }; n64js.store_16 = function (ram, addr, value) { if (addr < -2139095040) { var phys = (addr + 0x80000000) | 0; // NB: or with zero ensures we return an SMI if possible. ram[phys ] = value >> 8; ram[phys+1] = value; } else { sh_slow(addr, value); } }; n64js.store_32 = function (ram, addr, value) { if (addr < -2139095040) { var phys = (addr + 0x80000000) | 0; // NB: or with zero ensures we return an SMI if possible. ram[phys+0] = value >> 24; ram[phys+1] = value >> 16; ram[phys+2] = value >> 8; ram[phys+3] = value; } else { sw_slow(addr, value); } }; n64js.store_64 = function (ram, addr, value_lo, value_hi) { if (addr < -2139095040) { var phys = (addr + 0x80000000) | 0; // NB: or with zero ensures we return an SMI if possible. ram[phys+0] = value_hi >> 24; ram[phys+1] = value_hi >> 16; ram[phys+2] = value_hi >> 8; ram[phys+3] = value_hi; ram[phys+4] = value_lo >> 24; ram[phys+5] = value_lo >> 16; ram[phys+6] = value_lo >> 8; ram[phys+7] = value_lo; } else { sw_slow(addr, value_hi); sw_slow(addr + 4, value_lo); } }; function unimplemented(pc,i) { var r = n64js.disassembleOp(pc,i); var e = 'Unimplemented op ' + n64js.toString32(i) + ' : ' + r.disassembly; n64js.log(e); throw e; } function executeUnknown(i) { throw 'Unknown op: ' + n64js.toString32(cpu0.pc) + ', ' + n64js.toString32(i); } function BreakpointException() { } function executeBreakpoint(i) { // NB: throw here so that we don't execute the op. throw new BreakpointException(); } function generateShiftImmediate(ctx, op) { // Handle NOP for SLL if (ctx.instruction === 0) return generateNOPBoilerplate('/*NOP*/', ctx); var d = ctx.instr_rd(); var t = ctx.instr_rt(); var shift = ctx.instr_sa(); var impl = ''; impl += 'var result = ' + genSrcRegLo(t) + ' ' + op + ' ' + shift + ';\n'; impl += 'rlo[' + d + '] = result;\n'; impl += 'rhi[' + d + '] = result >> 31;\n'; return generateTrivialOpBoilerplate(impl, ctx); } function generateSLL(ctx) { return generateShiftImmediate(ctx, '<<'); } function executeSLL(i) { // NOP if (i === 0) return; var d = rd(i); var t = rt(i); var shift = sa(i); var result = cpu0.gprLo_signed[t] << shift; cpu0.gprLo_signed[d] = result; cpu0.gprHi_signed[d] = result >> 31; // sign extend } function generateSRL(ctx) { return generateShiftImmediate(ctx, '>>>'); } function executeSRL(i) { var d = rd(i); var t = rt(i); var shift = sa(i); var result = cpu0.gprLo_signed[t] >>> shift; cpu0.gprLo_signed[d] = result; cpu0.gprHi_signed[d] = result >> 31; // sign extend } function generateSRA(ctx) { return generateShiftImmediate(ctx, '>>'); } function executeSRA(i) { var d = rd(i); var t = rt(i); var shift = sa(i); var result = cpu0.gprLo_signed[t] >> shift; cpu0.gprLo_signed[d] = result; cpu0.gprHi_signed[d] = result >> 31; // sign extend } function generateShiftVariable(ctx, op) { var d = ctx.instr_rd(); var s = ctx.instr_rs(); var t = ctx.instr_rt(); var impl = ''; impl += 'var result = ' + genSrcRegLo(t) + ' ' + op + ' (' + genSrcRegLo(s) + ' & 0x1f);\n'; impl += 'rlo[' + d + '] = result;\n'; impl += 'rhi[' + d + '] = result >> 31;\n'; return generateTrivialOpBoilerplate(impl, ctx); } function generateSLLV(ctx) { return generateShiftVariable(ctx, '<<'); } function executeSLLV(i) { var d = rd(i); var s = rs(i); var t = rt(i); var result = cpu0.gprLo_signed[t] << (cpu0.gprLo_signed[s] & 0x1f); cpu0.gprLo_signed[d] = result; cpu0.gprHi_signed[d] = result >> 31; // sign extend } function generateSRLV(ctx) { return generateShiftVariable(ctx, '>>>'); } function executeSRLV(i) { var d = rd(i); var s = rs(i); var t = rt(i); var result = cpu0.gprLo_signed[t] >>> (cpu0.gprLo_signed[s] & 0x1f); cpu0.gprLo_signed[d] = result; cpu0.gprHi_signed[d] = result >> 31; // sign extend } function generateSRAV(ctx) { return generateShiftVariable(ctx, '>>'); } function executeSRAV(i) { var d = rd(i); var s = rs(i); var t = rt(i); var result = cpu0.gprLo_signed[t] >> (cpu0.gprLo_signed[s] & 0x1f); cpu0.gprLo_signed[d] = result; cpu0.gprHi_signed[d] = result >> 31; // sign extend } function executeDSLLV(i) { var d = rd(i); var t = rt(i); var s = rs(i); var shift = cpu0.gprLo[s] & 0x3f; var lo = cpu0.gprLo[t]; var hi = cpu0.gprHi[t]; if (shift < 32) { var nshift = 32-shift; cpu0.gprLo[d] = (lo<<shift); cpu0.gprHi[d] = (hi<<shift) | (lo>>>nshift); } else { cpu0.gprLo_signed[d] = 0; cpu0.gprHi_signed[d] = lo << (shift - 32); } } function executeDSRLV(i) { var d = rd(i); var t = rt(i); var s = rs(i); var shift = cpu0.gprLo[s] & 0x3f; var lo = cpu0.gprLo[t]; var hi = cpu0.gprHi[t]; if (shift < 32) { var nshift = 32-shift; cpu0.gprLo[d] = (lo>>>shift) | (hi<<nshift); cpu0.gprHi[d] = (hi>>>shift); } else { cpu0.gprLo[d] = hi >>> (shift - 32); cpu0.gprHi_signed[d] = 0; } } function executeDSRAV(i) { var d = rd(i); var t = rt(i); var s = rs(i); var shift = cpu0.gprLo[s] & 0x3f; var lo = cpu0.gprLo[t]; var hi = cpu0.gprHi_signed[t]; if (shift < 32) { var nshift = 32-shift; cpu0.gprLo[d] = (lo>>>shift) | (hi<<nshift); cpu0.gprHi[d] = (hi>>shift); } else { var olo = hi >> (shift - 32); cpu0.gprLo_signed[d] = olo; cpu0.gprHi_signed[d] = olo >> 31; } } function executeDSLL(i) { var d = rd(i); var t = rt(i); var shift = sa(i); var nshift = 32-shift; var lo = cpu0.gprLo[t]; var hi = cpu0.gprHi[t]; cpu0.gprLo[d] = (lo<<shift); cpu0.gprHi[d] = (hi<<shift) | (lo>>>nshift); } function executeDSLL32(i) { var d = rd(i); cpu0.gprLo_signed[d] = 0; cpu0.gprHi_signed[d] = cpu0.gprLo[rt(i)] << sa(i); } function executeDSRL(i) { var d = rd(i); var t = rt(i); var shift = sa(i); var nshift = 32-shift; var lo = cpu0.gprLo[t]; var hi = cpu0.gprHi[t]; cpu0.gprLo[d] = (lo>>>shift) | (hi<<nshift); cpu0.gprHi[d] = (hi>>>shift); } function executeDSRL32(i) { var d = rd(i); cpu0.gprLo[d] = cpu0.gprHi[rt(i)] >>> sa(i); cpu0.gprHi_signed[d] = 0; } function executeDSRA(i) { var d = rd(i); var t = rt(i); var shift = sa(i); var nshift = 32-shift; var lo = cpu0.gprLo[t]; var hi = cpu0.gprHi_signed[t]; cpu0.gprLo[d] = (lo>>>shift) | (hi<<nshift); cpu0.gprHi[d] = (hi>>shift); } function executeDSRA32(i) { var d = rd(i); var olo = cpu0.gprHi_signed[rt(i)] >> sa(i); cpu0.gprLo_signed[d] = olo; cpu0.gprHi_signed[d] = olo >> 31; } function executeSYSCALL(i) { unimplemented(cpu0.pc,i); } function executeBREAK(i) { unimplemented(cpu0.pc,i); } function executeSYNC(i) { unimplemented(cpu0.pc,i); } function generateMFHI(ctx) { var d = ctx.instr_rd(); var impl = ''; impl += 'rlo[' + d + '] = c.multHi_signed[0];\n'; impl += 'rhi[' + d + '] = c.multHi_signed[1];\n'; return generateTrivialOpBoilerplate(impl, ctx); } function executeMFHI(i) { var d = rd(i); cpu0.gprLo_signed[d] = cpu0.multHi_signed[0]; cpu0.gprHi_signed[d] = cpu0.multHi_signed[1]; } function generateMFLO(ctx) { var d = ctx.instr_rd(); var impl = ''; impl += 'rlo[' + d + '] = c.multLo_signed[0];\n'; impl += 'rhi[' + d + '] = c.multLo_signed[1];\n'; return generateTrivialOpBoilerplate(impl, ctx); } function executeMFLO(i) { var d = rd(i); cpu0.gprLo_signed[d] = cpu0.multLo_signed[0]; cpu0.gprHi_signed[d] = cpu0.multLo_signed[1]; } function generateMTHI(ctx) { var s = ctx.instr_rs(); var impl = ''; impl += 'c.multHi_signed[0] = rlo[' + s + '];\n'; impl += 'c.multHi_signed[1] = rhi[' + s + '];\n'; return generateTrivialOpBoilerplate(impl, ctx); } function executeMTHI(i) { var s = rs(i); cpu0.multHi_signed[0] = cpu0.gprLo_signed[s]; cpu0.multHi_signed[1] = cpu0.gprHi_signed[s]; } function generateMTLO(ctx) { var s = ctx.instr_rs(); var impl = ''; impl += 'c.multLo_signed[0] = rlo[' + s + '];\n'; impl += 'c.multLo_signed[1] = rhi[' + s + '];\n'; return generateTrivialOpBoilerplate(impl, ctx); } function executeMTLO(i) { var s = rs(i); cpu0.multLo_signed[0] = cpu0.gprLo_signed[s]; cpu0.multLo_signed[1] = cpu0.gprHi_signed[s]; } function generateMULT(ctx) { var d = ctx.instr_rd(); var s = ctx.instr_rs(); var t = ctx.instr_rt(); var impl = ''; impl += 'var result = ' + genSrcRegLo(s) + ' * ' + genSrcRegLo(t) + ';\n'; impl += 'var result_lo = result & 0xffffffff;\n'; impl += 'var result_hi = n64js.getHi32(result);\n'; impl += 'c.multLo[0] = result_lo;\n'; impl += 'c.multLo[1] = result_lo >> 31;\n'; impl += 'c.multHi[0] = result_hi;\n'; impl += 'c.multHi[1] = result_hi >> 31;\n'; return generateTrivialOpBoilerplate(impl, ctx); } function executeMULT(i) { var result = cpu0.gprLo_signed[rs(i)] * cpu0.gprLo_signed[rt(i)]; var lo = result & 0xffffffff; var hi = n64js.getHi32(result); cpu0.multLo[0] = lo; cpu0.multLo[1] = lo >> 31; cpu0.multHi[0] = hi; cpu0.multHi[1] = hi >> 31; } function generateMULTU(ctx) { var d = ctx.instr_rd(); var s = ctx.instr_rs(); var t = ctx.instr_rt(); var impl = ''; impl += 'var result = c.gprLo[' + s + '] * c.gprLo[' + t + '];\n'; impl += 'var result_lo = result & 0xffffffff;\n'; impl += 'var result_hi = n64js.getHi32(result);\n'; impl += 'c.multLo[0] = result_lo;\n'; impl += 'c.multLo[1] = result_lo >> 31;\n'; impl += 'c.multHi[0] = result_hi;\n'; impl += 'c.multHi[1] = result_hi >> 31;\n'; return generateTrivialOpBoilerplate(impl, ctx); } function executeMULTU(i) { var result = cpu0.gprLo[rs(i)] * cpu0.gprLo[rt(i)]; var lo = result & 0xffffffff; var hi = n64js.getHi32(result); cpu0.multLo[0] = lo; cpu0.multLo[1] = lo >> 31; cpu0.multHi[0] = hi; cpu0.multHi[1] = hi >> 31; } function executeDMULT(i) { var result = cpu0.getGPR_s64(rs(i)) * cpu0.getGPR_s64(rt(i)); cpu0.multLo[0] = result & 0xffffffff; cpu0.multLo[1] = n64js.getHi32(result); cpu0.multHi_signed[0] = 0; cpu0.multHi_signed[1] = 0; } function executeDMULTU(i) { var result = cpu0.getGPR_u64(rs(i)) * cpu0.getGPR_u64(rt(i)); cpu0.multLo[0] = result & 0xffffffff; cpu0.multLo[1] = n64js.getHi32(result); cpu0.multHi_signed[0] = 0; cpu0.multHi_signed[1] = 0; } function executeDIV(i) { var dividend = cpu0.gprLo_signed[rs(i)]; var divisor = cpu0.gprLo_signed[rt(i)]; if (divisor) { setHiLoSignExtend( cpu0.multLo, Math.floor(dividend / divisor) ); setHiLoSignExtend( cpu0.multHi, dividend % divisor ); } } function executeDIVU(i) { var dividend = cpu0.gprLo[rs(i)]; var divisor = cpu0.gprLo[rt(i)]; if (divisor) { setHiLoSignExtend( cpu0.multLo, Math.floor(dividend / divisor) ); setHiLoSignExtend( cpu0.multHi, dividend % divisor ); } } function executeDDIV(i) { var s = rs(i); var t = rt(i); if ((cpu0.gprHi[s] + (cpu0.gprLo[s] >>> 31) + cpu0.gprHi[t] + (cpu0.gprLo[t] >>> 31)) !== 0) { // FIXME: seems ok if dividend/divisor fit in mantissa of double... var dividend = cpu0.getGPR_s64(s); var divisor = cpu0.getGPR_s64(t); if (divisor) { setHiLoZeroExtend( cpu0.multLo, Math.floor(dividend / divisor) ); setHiLoZeroExtend( cpu0.multHi, dividend % divisor ); } } else { var dividend = cpu0.gprLo_signed[s]; var divisor = cpu0.gprLo_signed[t]; if (divisor) { setHiLoSignExtend( cpu0.multLo, Math.floor(dividend / divisor) ); setHiLoSignExtend( cpu0.multHi, dividend % divisor ); } } } function executeDDIVU(i) { var s = rs(i); var t = rt(i); if ((cpu0.gprHi[s] | cpu0.gprHi[t]) !== 0) { // FIXME: seems ok if dividend/divisor fit in mantissa of double... var dividend = cpu0.getGPR_u64(s); var divisor = cpu0.getGPR_u64(t); if (divisor) { setHiLoZeroExtend( cpu0.multLo, Math.floor(dividend / divisor) ); setHiLoZeroExtend( cpu0.multHi, dividend % divisor ); } } else { var dividend = cpu0.gprLo[s]; var divisor = cpu0.gprLo[t]; if (divisor) { setHiLoZeroExtend( cpu0.multLo, Math.floor(dividend / divisor) ); setHiLoZeroExtend( cpu0.multHi, dividend % divisor ); } } } function generateTrivialArithmetic(ctx, op) { var d = ctx.instr_rd(); var s = ctx.instr_rs(); var t = ctx.instr_rt(); var impl = ''; impl += 'var result = ' + genSrcRegLo(s) + ' ' + op + ' ' + genSrcRegLo(t) + ';\n'; impl += 'rlo[' + d + '] = result;\n'; impl += 'rhi[' + d + '] = result >> 31;\n'; return generateTrivialOpBoilerplate(impl, ctx); } function generateTrivialLogical(ctx, op) { var d = ctx.instr_rd(); var s = ctx.instr_rs(); var t = ctx.instr_rt(); var impl = ''; impl += 'rlo[' + d + '] = ' + genSrcRegLo(s) + ' ' + op + ' ' + genSrcRegLo(t) + ';\n'; impl += 'rhi[' + d + '] = ' + genSrcRegHi(s) + ' ' + op + ' ' + genSrcRegHi(t) + ';\n'; return generateTrivialOpBoilerplate(impl, ctx); } function generateADD(ctx) { return generateTrivialArithmetic(ctx, '+'); } function executeADD(i) { var d = rd(i); var s = rs(i); var t = rt(i); var result = cpu0.gprLo_signed[s] + cpu0.gprLo_signed[t]; cpu0.gprLo_signed[d] = result; cpu0.gprHi_signed[d] = result >> 31; } function generateADDU(ctx) { return generateTrivialArithmetic(ctx, '+'); } function executeADDU(i) { var d = rd(i); var s = rs(i); var t = rt(i); var result = cpu0.gprLo_signed[s] + cpu0.gprLo_signed[t]; cpu0.gprLo_signed[d] = result; cpu0.gprHi_signed[d] = result >> 31; } function generateSUB(ctx) { return generateTrivialArithmetic(ctx, '-'); } function executeSUB(i) { var d = rd(i); var s = rs(i); var t = rt(i); var result = cpu0.gprLo_signed[s] - cpu0.gprLo_signed[t]; cpu0.gprLo_signed[d] = result; cpu0.gprHi_signed[d] = result >> 31; } function generateSUBU(ctx) { return generateTrivialArithmetic(ctx, '-'); } function executeSUBU(i) { var d = rd(i); var s = rs(i); var t = rt(i); var result = cpu0.gprLo_signed[s] - cpu0.gprLo_signed[t]; cpu0.gprLo_signed[d] = result; cpu0.gprHi_signed[d] = result >> 31; } function generateAND(ctx) { return generateTrivialLogical(ctx, '&'); } function executeAND(i) { var d = rd(i); var s = rs(i); var t = rt(i); cpu0.gprHi_signed[d] = cpu0.gprHi_signed[s] & cpu0.gprHi_signed[t]; cpu0.gprLo_signed[d] = cpu0.gprLo_signed[s] & cpu0.gprLo_signed[t]; } function generateOR(ctx) { var d = ctx.instr_rd(); var s = ctx.instr_rs(); var t = ctx.instr_rt(); // OR is used to implement CLEAR and MOV if (t === 0) { var impl = ''; impl += 'rlo[' + d + '] = ' + genSrcRegLo(s) + ';\n'; impl += 'rhi[' + d + '] = ' + genSrcRegHi(s) + ';\n'; return generateTrivialOpBoilerplate(impl, ctx); } return generateTrivialLogical(ctx, '|'); } function executeOR(i) { var d = rd(i); var s = rs(i); var t = rt(i); cpu0.gprHi_signed[d] = cpu0.gprHi_signed[s] | cpu0.gprHi_signed[t]; cpu0.gprLo_signed[d] = cpu0.gprLo_signed[s] | cpu0.gprLo_signed[t]; } function generateXOR(ctx) { return generateTrivialLogical(ctx, '^'); } function executeXOR(i) { var d = rd(i); var s = rs(i); var t = rt(i); cpu0.gprHi_signed[d] = cpu0.gprHi_signed[s] ^ cpu0.gprHi_signed[t]; cpu0.gprLo_signed[d] = cpu0.gprLo_signed[s] ^ cpu0.gprLo_signed[t]; } function generateNOR(ctx) { var d = ctx.instr_rd(); var s = ctx.instr_rs(); var t = ctx.instr_rt(); var impl = ''; impl += 'rhi[' + d + '] = ~(' + genSrcRegHi(s) + ' | ' + genSrcRegHi(t) + ');\n'; impl += 'rlo[' + d + '] = ~(' + genSrcRegLo(s) + ' | ' + genSrcRegLo(t) + ');\n'; return generateTrivialOpBoilerplate(impl, ctx); } function executeNOR(i) { var d = rd(i); var s = rs(i); var t = rt(i); cpu0.gprHi_signed[d] = ~(cpu0.gprHi_signed[s] | cpu0.gprHi_signed[t]); cpu0.gprLo_signed[d] = ~(cpu0.gprLo_signed[s] | cpu0.gprLo_signed[t]); } function generateSLT(ctx) { var d = ctx.instr_rd(); var s = ctx.instr_rs(); var t = ctx.instr_rt(); var impl = ''; impl += 'var r = 0;\n'; impl += 'if (' + genSrcRegHi(s) + ' < ' + genSrcRegHi(t) + ') {\n'; impl += ' r = 1;\n'; impl += '} else if (' + genSrcRegHi(s) + ' === ' + genSrcRegHi(t) + ') {\n'; impl += ' r = (c.gprLo[' + s + '] < c.gprLo[' + t + ']) ? 1 : 0;\n'; impl += '}\n'; impl += 'rlo[' + d + '] = r;\n'; impl += 'rhi[' + d + '] = 0;\n'; return generateTrivialOpBoilerplate(impl, ctx); } function executeSLT(i) { var d = rd(i); var s = rs(i); var t = rt(i); var r = 0; if (cpu0.gprHi_signed[s] < cpu0.gprHi_signed[t]) { r = 1; } else if (cpu0.gprHi_signed[s] === cpu0.gprHi_signed[t]) { r = (cpu0.gprLo[s] < cpu0.gprLo[t]) ? 1 : 0; } cpu0.gprLo_signed[d] = r; cpu0.gprHi_signed[d] = 0; } function generateSLTU(ctx) { var d = ctx.instr_rd(); var s = ctx.instr_rs(); var t = ctx.instr_rt(); var impl = ''; impl += 'var r = 0;\n'; impl += 'if (c.gprHi[' + s + '] < c.gprHi[' + t + '] ||\n'; impl += ' (' + genSrcRegHi(s) + ' === ' + genSrcRegHi(t) + ' && c.gprLo[' + s + '] < c.gprLo[' + t + '])) {\n'; impl += ' r = 1;\n'; impl += '}\n'; impl += 'rlo[' + d + '] = r;\n'; impl += 'rhi[' + d + '] = 0;\n'; return generateTrivialOpBoilerplate(impl, ctx); } function executeSLTU(i) { var d = rd(i); var s = rs(i); var t = rt(i); var r = 0; if (cpu0.gprHi[s] < cpu0.gprHi[t] || (cpu0.gprHi_signed[s] === cpu0.gprHi_signed[t] && cpu0.gprLo[s] < cpu0.gprLo[t])) { // NB signed cmps avoid deopts r = 1; } cpu0.gprLo_signed[d] = r; cpu0.gprHi_signed[d] = 0; } function executeDADD(i) { cpu0.setGPR_s64(rd(i), cpu0.getGPR_s64(rs(i)) + cpu0.getGPR_s64(rt(i))); // NB: identical to DADDU, but should throw exception on overflow } function executeDADDU(i) { cpu0.setGPR_s64(rd(i), cpu0.getGPR_s64(rs(i)) + cpu0.getGPR_s64(rt(i))); } function executeDSUB(i) { cpu0.setGPR_s64(rd(i), cpu0.getGPR_s64(rs(i)) - cpu0.getGPR_s64(rt(i))); // NB: identical to DSUBU, but should throw exception on overflow } function executeDSUBU(i) { cpu0.setGPR_s64(rd(i), cpu0.getGPR_s64(rs(i)) - cpu0.getGPR_s64(rt(i))); } function executeTGE(i) { unimplemented(cpu0.pc,i); } function executeTGEU(i) { unimplemented(cpu0.pc,i); } function executeTLT(i) { unimplemented(cpu0.pc,i); } function executeTLTU(i) { unimplemented(cpu0.pc,i); } function executeTEQ(i) { unimplemented(cpu0.pc,i); } function executeTNE(i) { unimplemented(cpu0.pc,i); } function executeMFC0(i) { var control_reg = fs(i); // Check consistency if (control_reg === cpu0.kControlCause) { checkCauseIP3Consistent(); } if (control_reg === cpu0.kControlRand) { setZeroExtend( rt(i), cpu0.getRandom() ); } else { setZeroExtend( rt(i), cpu0.control[control_reg] ); } } function generateMTC0(ctx) { var s = ctx.instr_fs(); if (s === cpu0.kControlSR) { ctx.fragment.cop1statusKnown = false; } var impl = ''; impl += 'n64js.executeMTC0(' + n64js.toString32(ctx.instruction) + ');\n'; return generateGenericOpBoilerplate(impl, ctx); } function executeMTC0(i) { var control_reg = fs(i); var new_value = cpu0.gprLo[rt(i)]; switch (control_reg) { case cpu0.kControlContext: n64js.log('Setting Context register to ' + n64js.toString32(new_value) ); cpu0.control[cpu0.kControlContext] = new_value; break; case cpu0.kControlWired: n64js.log('Setting Wired register to ' + n64js.toString32(new_value) ); // Set to top limit on write to wired cpu0.control[cpu0.kControlRand] = 31; cpu0.control[cpu0.kControlWired] = new_value; break; case cpu0.kControlRand: case cpu0.kControlBadVAddr: case cpu0.kControlPRId: case cpu0.kControlCacheErr: // All these registers are read-only n64js.log('Attempted write to read-only cpu0 control register. ' + n64js.toString32(new_value) + ' --> ' + n64js.cop0ControlRegisterNames[control_reg] ); break; case cpu0.kControlCause: n64js.log('Setting cause register to ' + n64js.toString32(new_value) ); n64js.check(new_value === 0, 'Should only write 0 to Cause register.'); cpu0.control[cpu0.kControlCause] &= ~0x300; cpu0.control[cpu0.kControlCause] |= (new_value & 0x300); break; case cpu0.kControlSR: cpu0.setSR(new_value); break; case cpu0.kControlCount: cpu0.control[cpu0.kControlCount] = new_value; break; case cpu0.kControlCompare: cpu0.setCompare(new_value); break; case cpu0.kControlEPC: case cpu0.kControlEntryHi: case cpu0.kControlEntryLo0: case cpu0.kControlEntryLo1: case cpu0.kControlIndex: case cpu0.kControlPageMask: case cpu0.kControlTagLo: case cpu0.kControlTagHi: cpu0.control[control_reg] = new_value; break; default: cpu0.control[control_reg] = new_value; n64js.log('Write to cpu0 control register. ' + n64js.toString32(new_value) + ' --> ' + n64js.cop0ControlRegisterNames[control_reg] ); break; } } function executeTLB(i) { switch(tlbop(i)) { case 0x01: cpu0.tlbRead(); return; case 0x02: cpu0.tlbWriteIndex(); return; case 0x06: cpu0.tlbWriteRandom(); return; case 0x08: cpu0.tlbProbe(); return; case 0x18: executeERET(i); return; } executeUnknown(i); } function executeERET(i) { if (cpu0.control[cpu0.kControlSR] & SR_ERL) { cpu0.nextPC = cpu0.control[cpu0.kControlErrorEPC]; cpu0.control[cpu0.kControlSR] &= ~SR_ERL; n64js.log('ERET from error trap - ' + cpu0.nextPC); } else { cpu0.nextPC = cpu0.control[cpu0.kControlEPC]; cpu0.control[cpu0.kControlSR] &= ~SR_EXL; //n64js.log('ERET from interrupt/exception ' + cpu0.nextPC); } } function executeTGEI(i) { unimplemented(cpu0.pc,i); } function executeTGEIU(i) { unimplemented(cpu0.pc,i); } function executeTLTI(i) { unimplemented(cpu0.pc,i); } function executeTLTIU(i) { unimplemented(cpu0.pc,i); } function executeTEQI(i) { unimplemented(cpu0.pc,i); } function executeTNEI(i) { unimplemented(cpu0.pc,i); } // Jump function generateJ(ctx) { var addr = jumpAddress(ctx.pc, ctx.instruction); var impl = 'c.delayPC = ' + n64js.toString32(addr) + ';\n'; return generateBranchOpBoilerplate(impl, ctx, false); } function executeJ(i) { performBranch( jumpAddress(cpu0.pc,i) ); } function generateJAL(ctx) { var addr = jumpAddress(ctx.pc, ctx.instruction); var ra = ctx.pc + 8; var ra_hi = (ra & 0x80000000) ? -1 : 0; var impl = ''; impl += 'c.delayPC = ' + n64js.toString32(addr) + ';\n'; impl += 'rlo[' + cpu0.kRegister_ra + '] = ' + n64js.toString32(ra) + ';\n'; impl += 'rhi[' + cpu0.kRegister_ra + '] = ' + ra_hi + ';\n'; return generateBranchOpBoilerplate(impl, ctx, false); } function executeJAL(i) { setSignExtend(cpu0.kRegister_ra, cpu0.pc + 8); performBranch( jumpAddress(cpu0.pc,i) ); } function generateJALR(ctx) { var s = ctx.instr_rs(); var d = ctx.instr_rd(); var ra = ctx.pc + 8; var ra_hi = (ra & 0x80000000) ? -1 : 0; var impl = ''; impl += 'c.delayPC = c.gprLo[' + s + '];\n'; // NB needs to be unsigned impl += 'rlo[' + d + '] = ' + n64js.toString32(ra) + ';\n'; impl += 'rhi[' + d + '] = ' + ra_hi + ';\n'; return generateBranchOpBoilerplate(impl, ctx, false); } function executeJALR(i) { var new_pc = cpu0.gprLo[rs(i)]; setSignExtend(rd(i), cpu0.pc + 8); performBranch( new_pc ); } function generateJR(ctx) { var impl = 'c.delayPC = c.gprLo[' + ctx.instr_rs() + '];\n'; // NB needs to be unsigned return generateBranchOpBoilerplate(impl, ctx, false); } function executeJR(i) { performBranch( cpu0.gprLo[rs(i)] ); } function generateBEQ(ctx) { var s = ctx.instr_rs(); var t = ctx.instr_rt(); var off = ctx.instr_offset(); var addr = branchAddress(ctx.pc, ctx.instruction); var impl = ''; if (s === t) { if (off === -1) { impl += 'c.speedHack();\n'; ctx.bailOut = true; } impl += 'c.delayPC = ' + n64js.toString32(addr) + ';\n'; } else { impl += 'if (' + genSrcRegHi(s) + ' === ' + genSrcRegHi(t) + ' &&\n'; impl += ' ' + genSrcRegLo(s) + ' === ' + genSrcRegLo(t) + ' ) {\n'; if (off === -1) { impl += ' c.speedHack();\n'; ctx.bailOut = true; } impl += ' c.delayPC = ' + n64js.toString32(addr) + ';\n'; impl += '}\n'; } return generateBranchOpBoilerplate(impl, ctx, false); } function executeBEQ(i) { var s = rs(i); var t = rt(i); if (cpu0.gprHi_signed[s] === cpu0.gprHi_signed[t] && cpu0.gprLo_signed[s] === cpu0.gprLo_signed[t] ) { if (offset(i) === -1 ) cpu0.speedHack(); performBranch( branchAddress(cpu0.pc,i) ); } } function generateBEQL(ctx) { var s = ctx.instr_rs(); var t = ctx.instr_rt(); var off = ctx.instr_offset(); var addr = branchAddress(ctx.pc, ctx.instruction); var impl = ''; impl += 'if (' + genSrcRegHi(s) + ' === ' + genSrcRegHi(t) + ' &&\n'; impl += ' ' + genSrcRegLo(s) + ' === ' + genSrcRegLo(t) + ' ) {\n'; impl += ' c.delayPC = ' + n64js.toString32(addr) + ';\n'; impl += '} else {\n'; impl += ' c.nextPC += 4;\n'; impl += '}\n'; return generateBranchOpBoilerplate(impl, ctx, true /* might_adjust_next_pc*/); } function executeBEQL(i) { var s = rs(i); var t = rt(i); if (cpu0.gprHi_signed[s] === cpu0.gprHi_signed[t] && cpu0.gprLo_signed[s] === cpu0.gprLo_signed[t] ) { performBranch( branchAddress(cpu0.pc,i) ); } else { cpu0.nextPC += 4; // skip the next instruction } } function generateBNE(ctx) { var s = ctx.instr_rs(); var t = ctx.instr_rt(); var off = ctx.instr_offset(); var addr = branchAddress(ctx.pc, ctx.instruction); var impl = ''; impl += 'if (' + genSrcRegHi(s) + ' !== ' + genSrcRegHi(t) + ' ||\n'; impl += ' ' + genSrcRegLo(s) + ' !== ' + genSrcRegLo(t) + ' ) {\n'; if (off === -1) { impl += ' c.speedHack();\n'; ctx.bailOut = true; } impl += ' c.delayPC = ' + n64js.toString32(addr) + ';\n'; impl += '}\n'; return generateBranchOpBoilerplate(impl, ctx, false); } function executeBNE(i) { var s = rs(i); var t = rt(i); if (cpu0.gprHi_signed[s] !== cpu0.gprHi_signed[t] || cpu0.gprLo_signed[s] !== cpu0.gprLo_signed[t] ) { // NB: if imms(i) == -1 then this is a branch to self/busywait performBranch( branchAddress(cpu0.pc,i) ); } } function generateBNEL(ctx) { var s = ctx.instr_rs(); var t = ctx.instr_rt(); var off = ctx.instr_offset(); var addr = branchAddress(ctx.pc, ctx.instruction); var impl = ''; impl += 'if (' + genSrcRegHi(s) + ' !== ' + genSrcRegHi(t) + ' ||\n'; impl += ' ' + genSrcRegLo(s) + ' !== ' + genSrcRegLo(t) + ' ) {\n'; impl += ' c.delayPC = ' + n64js.toString32(addr) + ';\n'; impl += '} else {\n'; impl += ' c.nextPC += 4;\n'; impl += '}\n'; return generateBranchOpBoilerplate(impl, ctx, true /* might_adjust_next_pc*/); } function executeBNEL(i) { var s = rs(i); var t = rt(i); if (cpu0.gprHi_signed[s] !== cpu0.gprHi_signed[t] || cpu0.gprLo_signed[s] !== cpu0.gprLo_signed[t] ) { performBranch( branchAddress(cpu0.pc,i) ); } else { cpu0.nextPC += 4; // skip the next instruction } } // Branch Less Than or Equal To Zero function generateBLEZ(ctx) { var s = ctx.instr_rs(); var addr = branchAddress(ctx.pc, ctx.instruction); var impl = ''; impl += 'if ( ' + genSrcRegHi(s) + ' < 0 ||\n'; impl += ' (' + genSrcRegHi(s) + ' === 0 && ' + genSrcRegLo(s) + ' === 0) ) {\n'; impl += ' c.delayPC = ' + n64js.toString32(addr) + ';\n'; impl += '}\n'; return generateBranchOpBoilerplate(impl, ctx, false); } function executeBLEZ(i) { var s = rs(i); if ( cpu0.gprHi_signed[s] < 0 || (cpu0.gprHi_signed[s] === 0 && cpu0.gprLo_signed[s] === 0) ) { performBranch( branchAddress(cpu0.pc,i) ); } } function executeBLEZL(i) { var s = rs(i); // NB: if rs == r0 then this branch is always taken if ( cpu0.gprHi_signed[s] < 0 || (cpu0.gprHi_signed[s] === 0 && cpu0.gprLo_signed[s] === 0) ) { performBranch( branchAddress(cpu0.pc,i) ); } else { cpu0.nextPC += 4; // skip the next instruction } } // Branch Greater Than Zero function generateBGTZ(ctx) { var s = ctx.instr_rs(); var addr = branchAddress(ctx.pc, ctx.instruction); var impl = ''; impl += 'if ( ' + genSrcRegHi(s) + ' >= 0 &&\n'; impl += ' (' + genSrcRegHi(s) + ' !== 0 || ' + genSrcRegLo(s) + ' !== 0) ) {\n'; impl += ' c.delayPC = ' + n64js.toString32(addr) + ';\n'; impl += '}\n'; return generateBranchOpBoilerplate(impl, ctx, false); } function executeBGTZ(i) { var s = rs(i); if ( cpu0.gprHi_signed[s] >= 0 && (cpu0.gprHi_signed[s] !== 0 || cpu0.gprLo_signed[s] !== 0) ) { performBranch( branchAddress(cpu0.pc,i) ); } } function executeBGTZL(i) { var s = rs(i); if ( cpu0.gprHi_signed[s] >= 0 && (cpu0.gprHi_signed[s] !== 0 || cpu0.gprLo_signed[s] !== 0) ) { performBranch( branchAddress(cpu0.pc,i) ); } else { cpu0.nextPC += 4; // skip the next instruction } } // Branch Less Than Zero function generateBLTZ(ctx) { var s = ctx.instr_rs(); var addr = branchAddress(ctx.pc, ctx.instruction); var impl = ''; impl += 'if (' + genSrcRegHi(s) + ' < 0) {\n'; impl += ' c.delayPC = ' + n64js.toString32(addr) + ';\n'; impl += '}\n'; return generateBranchOpBoilerplate(impl, ctx, false); } function executeBLTZ(i) { if (cpu0.gprHi_signed[rs(i)] < 0) { performBranch( branchAddress(cpu0.pc,i) ); } } function generateBLTZL(ctx) { var s = ctx.instr_rs(); var addr = branchAddress(ctx.pc, ctx.instruction); var impl = ''; impl += 'if (' + genSrcRegHi(s) + ' < 0) {\n'; impl += ' c.delayPC = ' + n64js.toString32(addr) + ';\n'; impl += '} else {\n'; impl += ' c.nextPC += 4;\n'; impl += '}\n'; return generateBranchOpBoilerplate(impl, ctx, true /* might_adjust_next_pc*/); } function executeBLTZL(i) { if (cpu0.gprHi_signed[rs(i)] < 0) { performBranch( branchAddress(cpu0.pc,i) ); } else { cpu0.nextPC += 4; // skip the next instruction } } function executeBLTZAL(i) { setSignExtend(cpu0.kRegister_ra, cpu0.pc + 8); if (cpu0.gprHi_signed[rs(i)] < 0) { performBranch( branchAddress(cpu0.pc,i) ); } } function executeBLTZALL(i) { setSignExtend(cpu0.kRegister_ra, cpu0.pc + 8); if (cpu0.gprHi_signed[rs(i)] < 0) { performBranch( branchAddress(cpu0.pc,i) ); } else { cpu0.nextPC += 4; // skip the next instruction } } // Branch Greater Than Zero function generateBGEZ(ctx) { var s = ctx.instr_rs(); var addr = branchAddress(ctx.pc, ctx.instruction); var impl = ''; impl += 'if (' + genSrcRegHi(s) + ' >= 0) {\n'; impl += ' c.delayPC = ' + n64js.toString32(addr) + ';\n'; impl += '}\n'; return generateBranchOpBoilerplate(impl, ctx, false); } function executeBGEZ(i) { if (cpu0.gprHi_signed[rs(i)] >= 0) { performBranch( branchAddress(cpu0.pc,i) ); } } function generateBGEZL(ctx) { var s = ctx.instr_rs(); var addr = branchAddress(ctx.pc, ctx.instruction); var impl = ''; impl += 'if (' + genSrcRegHi(s) + ' >= 0) {\n'; impl += ' c.delayPC = ' + n64js.toString32(addr) + ';\n'; impl += '} else {\n'; impl += ' c.nextPC += 4;\n'; impl += '}\n'; return generateBranchOpBoilerplate(impl, ctx, true /* might_adjust_next_pc*/); } function executeBGEZL(i) { if (cpu0.gprHi_signed[rs(i)] >= 0) { performBranch( branchAddress(cpu0.pc,i) ); } else { cpu0.nextPC += 4; // skip the next instruction } } function executeBGEZAL(i) { setSignExtend(cpu0.kRegister_ra, cpu0.pc + 8); if (cpu0.gprHi_signed[rs(i)] >= 0) { performBranch( branchAddress(cpu0.pc,i) ); } } function executeBGEZALL(i) { setSignExtend(cpu0.kRegister_ra, cpu0.pc + 8); if (cpu0.gprHi_signed[rs(i)] >= 0) { performBranch( branchAddress(cpu0.pc,i) ); } else { cpu0.nextPC += 4; // skip the next instruction } } function generateADDI(ctx) { var s = ctx.instr_rs(); var t = ctx.instr_rt(); var impl = ''; impl += 'var result = ' + genSrcRegLo(s) + ' + ' + imms(ctx.instruction) + ';\n'; impl += 'rlo[' + t + '] = result;\n'; impl += 'rhi[' + t + '] = result >> 31;\n'; return generateTrivialOpBoilerplate(impl, ctx); } function executeADDI(i) { var s = rs(i); var t = rt(i); var result = cpu0.gprLo_signed[s] + imms(i); cpu0.gprLo_signed[t] = result; cpu0.gprHi_signed[t] = result >> 31; } function generateADDIU(ctx) { var s = ctx.instr_rs(); var t = ctx.instr_rt(); var impl = ''; impl += 'var result = ' + genSrcRegLo(s) + ' + ' + imms(ctx.instruction) + ';\n'; impl += 'rlo[' + t + '] = result;\n'; impl += 'rhi[' + t + '] = result >> 31;\n'; return generateTrivialOpBoilerplate(impl, ctx); } function executeADDIU(i) { var s = rs(i); var t = rt(i); var result = cpu0.gprLo_signed[s] + imms(i); cpu0.gprLo_signed[t] = result; cpu0.gprHi_signed[t] = result >> 31; } function executeDADDI(i) { cpu0.setGPR_s64(rt(i), cpu0.getGPR_s64(rs(i)) + imms(i)); } function executeDADDIU(i) { cpu0.setGPR_s64(rt(i), cpu0.getGPR_s64(rs(i)) + imms(i)); } function generateSLTI(ctx) { var s = ctx.instr_rs(); var t = ctx.instr_rt(); var immediate = imms(ctx.instruction); var imm_hi = immediate >> 31; var imm_unsigned = immediate >>> 0; var impl = ''; impl += 'if (' + genSrcRegHi(s) + ' === ' + imm_hi + ') {\n'; impl += ' rlo[' + t + '] = (c.gprLo[' + s +'] < ' + imm_unsigned + ') ? 1 : 0;\n'; impl += '} else {\n'; impl += ' rlo[' + t + '] = (' + genSrcRegHi(s) + ' < ' + imm_hi + ') ? 1 : 0;\n'; impl += '}\n'; impl += 'rhi[' + t + '] = 0;\n'; return generateTrivialOpBoilerplate(impl, ctx); } function executeSLTI(i) { var s = rs(i); var t = rt(i); var immediate = imms(i); var imm_hi = immediate >> 31; var s_hi = cpu0.gprHi_signed[s]; if (s_hi === imm_hi) { cpu0.gprLo_signed[t] = (cpu0.gprLo[s] < (immediate>>>0)) ? 1 : 0; // NB signed compare } else { cpu0.gprLo_signed[t] = (s_hi < imm_hi) ? 1 : 0; } cpu0.gprHi_signed[t] = 0; } function generateSLTIU(ctx) { var s = ctx.instr_rs(); var t = ctx.instr_rt(); var immediate = imms(ctx.instruction); var imm_hi = immediate >> 31; var imm_unsigned = immediate >>> 0; var impl = ''; impl += 'if (' + genSrcRegHi(s) + ' === ' + imm_hi + ') {\n'; impl += ' rlo[' + t + '] = (c.gprLo[' + s +'] < ' + imm_unsigned + ') ? 1 : 0;\n'; impl += '} else {\n'; impl += ' rlo[' + t + '] = ((' + genSrcRegHi(s) + '>>>0) < (' + (imm_hi>>>0) + ')) ? 1 : 0;\n'; impl += '}\n'; impl += 'rhi[' + t + '] = 0;\n'; return generateTrivialOpBoilerplate(impl, ctx); } function executeSLTIU(i) { var s = rs(i); var t = rt(i); // NB: immediate value is still sign-extended, but treated as unsigned var immediate = imms(i); var imm_hi = immediate >> 31; var s_hi = cpu0.gprHi_signed[s]; if (s_hi === imm_hi) { cpu0.gprLo[t] = (cpu0.gprLo[s] < (immediate>>>0)) ? 1 : 0; } else { cpu0.gprLo[t] = ((s_hi>>>0) < (imm_hi>>>0)) ? 1 : 0; } cpu0.gprHi[t] = 0; } function generateANDI(ctx) { var s = ctx.instr_rs(); var t = ctx.instr_rt(); var impl = ''; impl += 'rlo[' + t + '] = ' + genSrcRegLo(s) + ' & ' + imm(ctx.instruction) + ';\n'; impl += 'rhi[' + t + '] = 0;\n'; return generateTrivialOpBoilerplate(impl, ctx); } function executeANDI(i) { var s = rs(i); var t = rt(i); cpu0.gprLo_signed[t] = cpu0.gprLo_signed[s] & imm(i); cpu0.gprHi_signed[t] = 0; // always 0, as sign extended immediate value is always 0 } function generateORI(ctx) { var s = ctx.instr_rs(); var t = ctx.instr_rt(); var impl = ''; impl += 'rlo[' + t + '] = ' + genSrcRegLo(s) + ' | ' + imm(ctx.instruction) + ';\n'; if (s !== t) impl += 'rhi[' + t + '] = ' + genSrcRegHi(s) + ';\n'; return generateTrivialOpBoilerplate(impl, ctx); } function executeORI(i) { var s = rs(i); var t = rt(i); cpu0.gprLo_signed[t] = cpu0.gprLo_signed[s] | imm(i); cpu0.gprHi_signed[t] = cpu0.gprHi_signed[s]; } function generateXORI(ctx) { var s = ctx.instr_rs(); var t = ctx.instr_rt(); var impl = ''; impl += 'rlo[' + t + '] = ' + genSrcRegLo(s) + ' ^ ' + imm(ctx.instruction) + ';\n'; if (s !== t) impl += 'rhi[' + t + '] = ' + genSrcRegHi(s) + ';\n'; return generateTrivialOpBoilerplate(impl, ctx); } function executeXORI(i) { // High 32 bits are always unchanged, as sign extended immediate value is always 0 var s = rs(i); var t = rt(i); cpu0.gprLo_signed[t] = cpu0.gprLo_signed[s] ^ imm(i); cpu0.gprHi_signed[t] = cpu0.gprHi_signed[s]; } function generateLUI(ctx) { var t = ctx.instr_rt(); var value_lo = imms(ctx.instruction) << 16; var value_hi = (value_lo < 0) ? -1 : 0; var impl = ''; impl += 'rlo[' + t +'] = ' + value_lo + ';\n'; impl += 'rhi[' + t +'] = ' + value_hi + ';\n'; return generateTrivialOpBoilerplate(impl, ctx); } function executeLUI(i) { var t = rt(i); var value = imms(i) << 16; cpu0.gprLo_signed[t] = value; cpu0.gprHi_signed[t] = value >> 31; } function generateLB(ctx) { var t = ctx.instr_rt(); var b = ctx.instr_base(); var o = ctx.instr_imms(); var impl = ''; impl += 'var value = n64js.load_s8(ram, ' + genSrcRegLo(b) + ' + ' + o + ');\n'; impl += 'rlo[' + t + '] = value;\n'; impl += 'rhi[' + t + '] = value >> 31;\n'; return generateMemoryAccessBoilerplate(impl, ctx); } function executeLB(i) { var t = rt(i); var b = base(i); var o = imms(i); var value = n64js.load_s8(cpu0.ram, cpu0.gprLo_signed[b] + o); cpu0.gprLo_signed[t] = value; cpu0.gprHi_signed[t] = value >> 31; } function generateLBU(ctx) { var t = ctx.instr_rt(); var b = ctx.instr_base(); var o = ctx.instr_imms(); var impl = ''; impl += 'rlo[' + t + '] = n64js.load_u8(ram, ' + genSrcRegLo(b) + ' + ' + o + ');\n'; impl += 'rhi[' + t + '] = 0;\n'; return generateMemoryAccessBoilerplate(impl, ctx); } function executeLBU(i) { var t = rt(i); var b = base(i); var o = imms(i); cpu0.gprLo_signed[t] = n64js.load_u8(cpu0.ram, cpu0.gprLo_signed[b] + o); cpu0.gprHi_signed[t] = 0; } function generateLH(ctx) { var t = ctx.instr_rt(); var b = ctx.instr_base(); var o = ctx.instr_imms(); var impl = ''; impl += 'var value = n64js.load_s16(ram, ' + genSrcRegLo(b) + ' + ' + o + ');\n'; impl += 'rlo[' + t + '] = value;\n'; impl += 'rhi[' + t + '] = value >> 31;\n'; return generateMemoryAccessBoilerplate(impl, ctx); } function executeLH(i) { var t = rt(i); var b = base(i); var o = imms(i); var value = n64js.load_s16(cpu0.ram, cpu0.gprLo_signed[b] + o); cpu0.gprLo_signed[t] = value; cpu0.gprHi_signed[t] = value >> 31; } function generateLHU(ctx) { var t = ctx.instr_rt(); var b = ctx.instr_base(); var o = ctx.instr_imms(); var impl = ''; impl += 'rlo[' + t + '] = n64js.load_u16(ram, ' + genSrcRegLo(b) + ' + ' + o + ');\n'; impl += 'rhi[' + t + '] = 0;\n'; return generateMemoryAccessBoilerplate(impl, ctx); } function executeLHU(i) { var t = rt(i); var b = base(i); var o = imms(i); cpu0.gprLo_signed[t] = n64js.load_u16(cpu0.ram, cpu0.gprLo_signed[b] + o); cpu0.gprHi_signed[t] = 0; } function generateLW(ctx) { var t = ctx.instr_rt(); var b = ctx.instr_base(); var o = ctx.instr_imms(); // SF2049 requires this, apparently if (t === 0) return generateNOPBoilerplate('/*load to r0!*/', ctx); var impl = ''; impl += 'var value = n64js.load_s32(ram, ' + genSrcRegLo(b) + ' + ' + o + ');\n'; impl += 'rlo[' + t + '] = value;\n'; impl += 'rhi[' + t + '] = value >> 31;\n'; return generateMemoryAccessBoilerplate(impl, ctx); } function executeLW(i) { var t = rt(i); var b = base(i); var o = imms(i); // SF2049 requires this, apparently if (t === 0) return; var value = n64js.load_s32(cpu0.ram, cpu0.gprLo_signed[b] + o); cpu0.gprLo_signed[t] = value; cpu0.gprHi_signed[t] = value >> 31; } function generateLWU(ctx) { var t = ctx.instr_rt(); var b = ctx.instr_base(); var o = ctx.instr_imms(); var impl = ''; impl += 'rlo[' + t + '] = n64js.load_u32(ram, ' + genSrcRegLo(b) + ' + ' + o + ');\n'; impl += 'rhi[' + t + '] = 0;\n'; return generateMemoryAccessBoilerplate(impl, ctx); } function executeLWU(i) { var t = rt(i); var b = base(i); var o = imms(i); cpu0.gprLo_signed[t] = n64js.load_u32(cpu0.ram, cpu0.gprLo_signed[b] + o); cpu0.gprHi_signed[t] = 0; } function generateLD(ctx) { var t = ctx.instr_rt(); var b = ctx.instr_base(); var o = ctx.instr_imms(); var impl = ''; impl += 'var addr = ' + genSrcRegLo(b) + ' + ' + o + ';\n'; impl += 'if (addr < -2139095040) {\n'; impl += ' var phys = (addr + 0x80000000) | 0;\n'; impl += ' rhi[' + t + '] = ((ram[phys ] << 24) | (ram[phys+1] << 16) | (ram[phys+2] << 8) | ram[phys+3]);\n'; impl += ' rlo[' + t + '] = ((ram[phys+4] << 24) | (ram[phys+5] << 16) | (ram[phys+6] << 8) | ram[phys+7]);\n'; impl += '} else {\n'; impl += ' rhi[' + t + '] = lw_slow(addr);\n'; impl += ' rlo[' + t + '] = lw_slow(addr + 4);\n'; impl += '}\n'; return generateMemoryAccessBoilerplate(impl, ctx); } function executeLD(i) { var t = rt(i); var b = base(i); var o = imms(i); var addr = cpu0.gprLo_signed[b] + o; if (addr < -2139095040) { var phys = (addr + 0x80000000) | 0; // NB: or with zero ensures we return an SMI if possible. var ram = cpu0.ram; cpu0.gprHi_signed[t] = ((ram[phys ] << 24) | (ram[phys+1] << 16) | (ram[phys+2] << 8) | ram[phys+3]) | 0; cpu0.gprLo_signed[t] = ((ram[phys+4] << 24) | (ram[phys+5] << 16) | (ram[phys+6] << 8) | ram[phys+7]) | 0; } else { cpu0.gprHi_signed[t] = lw_slow(addr); cpu0.gprLo_signed[t] = lw_slow(addr + 4); } } function generateLWC1(ctx) { var t = ctx.instr_ft(); var b = ctx.instr_base(); var o = ctx.instr_imms(); ctx.fragment.usesCop1 = true; var impl = 'cpu1.int32[' + t + '] = n64js.load_s32(ram, ' + genSrcRegLo(b) + ' + ' + o + ');\n'; return generateMemoryAccessBoilerplate(impl, ctx); } // FIXME: needs to check Cop1Enabled - thanks Salvy! function executeLWC1(i) { var t = ft(i); var b = base(i); var o = imms(i); cpu1.int32[t] = n64js.load_s32(cpu0.ram, cpu0.gprLo_signed[b] + o); } function generateLDC1(ctx){ var t = ctx.instr_ft(); var b = ctx.instr_base(); var o = ctx.instr_imms(); ctx.fragment.usesCop1 = true; var impl = ''; impl += 'var value_lo;\n'; impl += 'var value_hi;\n'; impl += 'var addr = ' + genSrcRegLo(b) + ' + ' + o + ';\n'; impl += 'if (addr < -2139095040) {\n'; impl += ' var phys = (addr + 0x80000000) | 0;\n'; impl += ' value_hi = ((ram[phys ] << 24) | (ram[phys+1] << 16) | (ram[phys+2] << 8) | ram[phys+3]) | 0;\n'; // FIXME: |0 needed? impl += ' value_lo = ((ram[phys+4] << 24) | (ram[phys+5] << 16) | (ram[phys+6] << 8) | ram[phys+7]) | 0;\n'; impl += '} else {\n'; impl += ' value_hi = lw_slow(addr);\n'; impl += ' value_lo = lw_slow(addr + 4);\n'; impl += '}\n'; impl += 'cpu1.store_64(' + t + ', value_lo, value_hi);\n'; return generateMemoryAccessBoilerplate(impl, ctx); } // FIXME: needs to check Cop1Enabled - thanks Salvy! function executeLDC1(i) { var t = ft(i); var b = base(i); var o = imms(i); var addr = cpu0.gprLo_signed[b] + o; var value_lo; var value_hi; if (addr < -2139095040) { var phys = (addr + 0x80000000) | 0; // NB: or with zero ensures we return an SMI if possible. var ram = cpu0.ram; value_hi = ((ram[phys ] << 24) | (ram[phys+1] << 16) | (ram[phys+2] << 8) | ram[phys+3]) | 0; value_lo = ((ram[phys+4] << 24) | (ram[phys+5] << 16) | (ram[phys+6] << 8) | ram[phys+7]) | 0; } else { value_hi = lw_slow(addr); value_lo = lw_slow(addr + 4); } cpu1.store_64( t, value_lo, value_hi ); } function executeLDC2(i) { unimplemented(cpu0.pc,i); } function executeLWL(i) { var address = memaddr(i)>>>0; var address_aligned = (address & ~3)>>>0; var memory = n64js.readMemoryU32(address_aligned); var reg = cpu0.gprLo[rt(i)]; var value; switch(address % 4) { case 0: value = memory; break; case 1: value = (reg & 0x000000ff) | (memory << 8); break; case 2: value = (reg & 0x0000ffff) | (memory << 16); break; default: value = (reg & 0x00ffffff) | (memory << 24); break; } setSignExtend( rt(i), value ); } function executeLWR(i) { var address = memaddr(i)>>>0; var address_aligned = (address & ~3)>>>0; var memory = n64js.readMemoryU32(address_aligned); var reg = cpu0.gprLo[rt(i)]; var value; switch(address % 4) { case 0: value = (reg & 0xffffff00) | (memory >>> 24); break; case 1: value = (reg & 0xffff0000) | (memory >>> 16); break; case 2: value = (reg & 0xff000000) | (memory >>> 8); break; default: value = memory; break; } setSignExtend( rt(i), value ); } function executeLDL(i) { unimplemented(cpu0.pc,i); } function executeLDR(i) { unimplemented(cpu0.pc,i); } function generateSB(ctx) { var t = ctx.instr_rt(); var b = ctx.instr_base(); var o = ctx.instr_imms(); var impl = ''; impl += 'n64js.store_8(ram, ' + genSrcRegLo(b) + ' + ' + o + ', ' + genSrcRegLo(t) + ');\n'; return generateMemoryAccessBoilerplate(impl, ctx); } function executeSB(i) { var t = rt(i); var b = base(i); var o = imms(i); n64js.store_8(cpu0.ram, cpu0.gprLo_signed[b] + o, cpu0.gprLo_signed[t] /*& 0xff*/); } function generateSH(ctx) { var t = ctx.instr_rt(); var b = ctx.instr_base(); var o = ctx.instr_imms(); var impl = ''; impl += 'n64js.store_16(ram, ' + genSrcRegLo(b) + ' + ' + o + ', ' + genSrcRegLo(t) + ');\n'; return generateMemoryAccessBoilerplate(impl, ctx); } function executeSH(i) { var t = rt(i); var b = base(i); var o = imms(i); n64js.store_16(cpu0.ram, cpu0.gprLo_signed[b] + o, cpu0.gprLo_signed[t] /*& 0xffff*/); } function generateSW(ctx) { var t = ctx.instr_rt(); var b = ctx.instr_base(); var o = ctx.instr_imms(); var impl = ''; impl += 'n64js.store_32(ram, ' + genSrcRegLo(b) + ' + ' + o + ', ' + genSrcRegLo(t) + ');\n'; return generateMemoryAccessBoilerplate(impl, ctx); } function executeSW(i) { var t = rt(i); var b = base(i); var o = imms(i); n64js.store_32(cpu0.ram, cpu0.gprLo_signed[b] + o, cpu0.gprLo_signed[t]); } function generateSD(ctx) { var t = ctx.instr_rt(); var b = ctx.instr_base(); var o = ctx.instr_imms(); var impl = ''; impl += 'var addr = ' + genSrcRegLo(b) + ' + ' + o + ';\n'; impl += 'n64js.store_64(ram, addr, ' + genSrcRegLo(t) + ',' + genSrcRegHi(t) + ');\n'; return generateMemoryAccessBoilerplate(impl, ctx); } function executeSD(i) { var t = rt(i); var b = base(i); var o = imms(i); var addr = cpu0.gprLo_signed[b] + o; n64js.store_64(cpu0.ram, addr, cpu0.gprLo_signed[t], cpu0.gprHi_signed[t]); } function generateSWC1(ctx) { var t = ctx.instr_ft(); var b = ctx.instr_base(); var o = ctx.instr_imms(); ctx.fragment.usesCop1 = true; // FIXME: can avoid cpuStuffToDo if we're writing to ram var impl = ''; impl += 'n64js.store_32(ram, ' + genSrcRegLo(b) + ' + ' + o + ', cpu1.int32[' + t + ']);\n'; return generateMemoryAccessBoilerplate(impl, ctx); } // FIXME: needs to check Cop1Enabled - thanks Salvy! function executeSWC1(i) { var t = ft(i); var b = base(i); var o = imms(i); n64js.store_32(cpu0.ram, cpu0.gprLo_signed[b] + o, cpu1.int32[t]); } function generateSDC1(ctx) { var t = ctx.instr_ft(); var b = ctx.instr_base(); var o = ctx.instr_imms(); var hi = t+1; ctx.fragment.usesCop1 = true; // FIXME: can avoid cpuStuffToDo if we're writing to ram var impl = ''; impl += 'var addr = ' + genSrcRegLo(b) + ' + ' + o + ';\n'; impl += 'n64js.store_64(ram, addr, cpu1.int32[' + t + '], cpu1.int32[' + hi + ']);\n'; return generateMemoryAccessBoilerplate(impl, ctx); } // FIXME: needs to check Cop1Enabled - thanks Salvy! function executeSDC1(i) { var t = ft(i); var b = base(i); var o = imms(i); // FIXME: this can do a single check that the address is in ram var addr = cpu0.gprLo_signed[b] + o; n64js.store_64(cpu0.ram, addr, cpu1.int32[t], cpu1.int32[t+1]); } function executeSDC2(i) { unimplemented(cpu0.pc,i); } function executeSWL(i) { var address = memaddr(i); var address_aligned = (address & ~3)>>>0; var memory = n64js.readMemoryU32(address_aligned); var reg = cpu0.gprLo[rt(i)]; var value; switch(address % 4) { case 0: value = reg; break; case 1: value = (memory & 0xff000000) | (reg >>> 8); break; case 2: value = (memory & 0xffff0000) | (reg >>> 16); break; default: value = (memory & 0xffffff00) | (reg >>> 24); break; } n64js.writeMemory32( address_aligned, value ); } function executeSWR(i) { var address = memaddr(i); var address_aligned = (address & ~3)>>>0; var memory = n64js.readMemoryU32(address_aligned); var reg = cpu0.gprLo[rt(i)]; var value; switch(address % 4) { case 0: value = (memory & 0x00ffffff) | (reg << 24); break; case 1: value = (memory & 0x0000ffff) | (reg << 16); break; case 2: value = (memory & 0x000000ff) | (reg << 8); break; default: value = reg; break; } n64js.writeMemory32( address_aligned, value ); } function executeSDL(i) { unimplemented(cpu0.pc,i); } function executeSDR(i) { unimplemented(cpu0.pc,i); } function generateCACHE(ctx) { var b = ctx.instr_base(); var o = ctx.instr_imms(); var cache_op = ctx.instr_rt(); var cache = (cache_op ) & 0x3; var action = (cache_op >>> 2) & 0x7; if(cache === 0 && (action === 0 || action === 4)) { var impl = ''; impl += 'var addr = ' + genSrcRegLo(b) + ' + ' + o + ';\n'; impl += "n64js.invalidateICacheEntry(addr);\n"; return generateTrivialOpBoilerplate(impl, ctx); } else { return generateNOPBoilerplate('/*ignored CACHE*/', ctx); } } function executeCACHE(i) { var cache_op = rt(i); var cache = (cache_op ) & 0x3; var action = (cache_op >>> 2) & 0x7; if(cache === 0 && (action === 0 || action === 4)) { // NB: only bother generating address if we handle the instruction - memaddr deopts like crazy var address = memaddr(i); n64js.invalidateICacheEntry(address); } } function executeLL(i) { unimplemented(cpu0.pc,i); } function executeLLD(i) { unimplemented(cpu0.pc,i); } function executeSC(i) { unimplemented(cpu0.pc,i); } function executeSCD(i) { unimplemented(cpu0.pc,i); } function generateMFC1Stub(ctx) { var t = ctx.instr_rt(); var s = ctx.instr_fs(); ctx.fragment.usesCop1 = true; ctx.isTrivial = true; var impl = ''; impl += 'var result = cpu1.int32[' + s + '];\n'; impl += 'rlo[' + t + '] = result;\n'; impl += 'rhi[' + t + '] = result >> 31;\n'; return impl; } function executeMFC1(i) { var t = rt(i); var s = fs(i); var result = cpu1.int32[s]; cpu0.gprLo_signed[t] = result; cpu0.gprHi_signed[t] = result >> 31; } function generateDMFC1Stub(ctx) { var t = ctx.instr_rt(); var s = ctx.instr_fs(); var hi = s+1; ctx.fragment.usesCop1 = true; ctx.isTrivial = true; var impl = ''; impl += 'rlo[' + t + '] = cpu1.int32[' + s + '];\n'; impl += 'rhi[' + t + '] = cpu1.int32[' + hi + '];\n'; return impl; } function executeDMFC1(i) { var t = rt(i); var s = fs(i); cpu0.gprLo_signed[t] = cpu1.int32[s]; cpu0.gprHi_signed[t] = cpu1.int32[s+1]; } function generateMTC1Stub(ctx) { var s = ctx.instr_fs(); var t = ctx.instr_rt(); ctx.fragment.usesCop1 = true; ctx.isTrivial = true; return 'cpu1.int32[' + s + '] = rlo[' + t + '];\n'; } function executeMTC1(i) { cpu1.int32[fs(i)] = cpu0.gprLo_signed[rt(i)]; } function generateDMTC1Stub(ctx) { var s = ctx.instr_fs(); var t = ctx.instr_rt(); var hi = s+1; ctx.fragment.usesCop1 = true; ctx.isTrivial = true; var impl = ''; impl += 'cpu1.int32[' + s + '] = rlo[' + t + '];\n'; impl += 'cpu1.int32[' + hi + '] = rhi[' + t + '];\n'; return impl; } function executeDMTC1(i) { var s = fs(i); var t = rt(i); cpu1.int32[s+0] = cpu0.gprLo_signed[t]; cpu1.int32[s+1] = cpu0.gprHi_signed[t]; } function generateCFC1Stub(ctx) { var s = ctx.instr_fs(); var t = ctx.instr_rt(); ctx.fragment.usesCop1 = true; ctx.isTrivial = true; var impl = ''; switch(s) { case 0: case 31: impl += 'var value = cpu1.control[' + s + '];\n'; impl += 'rlo[' + t + '] = value;\n'; impl += 'rhi[' + t + '] = value >> 31;\n'; return impl; } return '/*CFC1 invalid reg*/\n'; } function executeCFC1(i) { var s = fs(i); var t = rt(i); switch(s) { case 0: case 31: var value = cpu1.control[s]; cpu0.gprLo_signed[t] = value; cpu0.gprHi_signed[t] = value >> 31; break; } } function generateCTC1Stub(ctx) { var s = ctx.instr_fs(); var t = ctx.instr_rt(); ctx.fragment.usesCop1 = true; ctx.isTrivial = true; if (s === 31) { return 'cpu1.control[' + s + '] = rlo[' + t + '];\n'; } return '/*CTC1 invalid reg*/\n'; } function executeCTC1(i) { var s = fs(i); var t = rt(i); if (s === 31) { var v = cpu0.gprLo[t]; // switch (v & FPCSR_RM_MASK) { // case FPCSR_RM_RN: n64js.log('cop1 - setting round near'); break; // case FPCSR_RM_RZ: n64js.log('cop1 - setting round zero'); break; // case FPCSR_RM_RP: n64js.log('cop1 - setting round ceil'); break; // case FPCSR_RM_RM: n64js.log('cop1 - setting round floor'); break; // } cpu1.control[s] = v; } } function generateBCInstrStub(ctx) { var i = ctx.instruction; n64js.assert( ((i>>>18)&0x7) === 0, "cc bit is not 0" ); var condition = (i&0x10000) !== 0; var likely = (i&0x20000) !== 0; var target = branchAddress(ctx.pc, i); ctx.fragment.usesCop1 = true; ctx.isTrivial = false; // NB: not trivial - branches! var impl = ''; var test = condition ? '!==' : '==='; impl += 'if ((cpu1.control[31] & FPCSR_C) ' + test + ' 0) {\n'; impl += ' c.branchTarget = ' + n64js.toString32(target) + ';\n'; if (likely) { impl += '} else {\n'; impl += ' c.nextPC += 4;\n'; } impl += '}\n'; return impl; } function executeBCInstr(i) { n64js.assert( ((i>>>18)&0x7) === 0, "cc bit is not 0" ); var condition = (i&0x10000) !== 0; var likely = (i&0x20000) !== 0; var cc = (cpu1.control[31] & FPCSR_C) !== 0; if (cc === condition) { performBranch( branchAddress(cpu0.pc, i) ); } else { if (likely) { cpu0.nextPC += 4; // skip the next instruction } } } n64js.trunc = function (x) { if (x < 0) return Math.ceil(x); else return Math.floor(x); }; n64js.convert = function (x) { switch(cpu1.control[31] & FPCSR_RM_MASK) { case FPCSR_RM_RN: return Math.round(x); case FPCSR_RM_RZ: return n64js.trunc(x); case FPCSR_RM_RP: return Math.ceil(x); case FPCSR_RM_RM: return Math.floor(x); } n64js.assert('unknown rounding mode'); }; function generateFloatCompare(op) { var impl = ''; impl += 'var cc = false;\n'; impl += 'if (isNaN(fs+ft)) {\n'; if (op&0x8) { impl += ' n64js.halt("should raise Invalid Operation here.");\n'; } if (op&0x1) { impl += ' cc = true;\n'; } impl += '} else {\n'; if (op&0x4) { impl += ' cc |= fs < ft;\n'; } if (op&0x2) { impl += ' cc |= fs == ft;\n'; } impl += '}\n'; impl += 'if (cc) { cpu1.control[31] |= FPCSR_C; } else { cpu1.control[31] &= ~FPCSR_C; }\n'; return impl; } function handleFloatCompare(op, fs, ft) { var c = false; if (isNaN(fs+ft)) { if (op&0x8) { n64js.halt('Should raise Invalid Operation here.'); } if (op&0x1) c = true; } else { if (op&0x4) c |= fs < ft; if (op&0x2) c |= fs == ft; // unordered is false here } cpu1.setCondition(c); } function generateSInstrStub(ctx) { var s = ctx.instr_fs(); var t = ctx.instr_ft(); var d = ctx.instr_fd(); ctx.fragment.usesCop1 = true; ctx.isTrivial = true; var op = cop1_func(ctx.instruction); if (op < 0x30) { switch(op) { case 0x00: return 'cpu1.float32[' + d + '] = cpu1.float32[' + s + '] + cpu1.float32[' + t + '];\n'; case 0x01: return 'cpu1.float32[' + d + '] = cpu1.float32[' + s + '] - cpu1.float32[' + t + '];\n'; case 0x02: return 'cpu1.float32[' + d + '] = cpu1.float32[' + s + '] * cpu1.float32[' + t + '];\n'; case 0x03: return 'cpu1.float32[' + d + '] = cpu1.float32[' + s + '] / cpu1.float32[' + t + '];\n'; case 0x04: return 'cpu1.float32[' + d + '] = Math.sqrt( cpu1.float32[' + s + '] );\n'; case 0x05: return 'cpu1.float32[' + d + '] = Math.abs( cpu1.float32[' + s + '] );\n'; case 0x06: return 'cpu1.float32[' + d + '] = cpu1.float32[' + s + '];\n'; case 0x07: return 'cpu1.float32[' + d + '] = -cpu1.float32[' + s + '];\n'; case 0x08: /* 'ROUND.L.'*/ return 'cpu1.store_float_as_long(' + d + ', Math.round( cpu1.float32[' + s + ']));\n'; case 0x09: /* 'TRUNC.L.'*/ return 'cpu1.store_float_as_long(' + d + ', n64js.trunc( cpu1.float32[' + s + ']));\n'; case 0x0a: /* 'CEIL.L.'*/ return 'cpu1.store_float_as_long(' + d + ', Math.ceil( cpu1.float32[' + s + ']));\n'; case 0x0b: /* 'FLOOR.L.'*/ return 'cpu1.store_float_as_long(' + d + ', Math.floor( cpu1.float32[' + s + ']));\n'; case 0x0c: /* 'ROUND.W.'*/ return 'cpu1.int32[' + d + '] = Math.round( cpu1.float32[' + s + '] );\n'; // TODO: check this case 0x0d: /* 'TRUNC.W.'*/ return 'cpu1.int32[' + d + '] = n64js.trunc( cpu1.float32[' + s + '] );\n'; case 0x0e: /* 'CEIL.W.'*/ return 'cpu1.int32[' + d + '] = Math.ceil( cpu1.float32[' + s + '] );\n'; case 0x0f: /* 'FLOOR.W.'*/ return 'cpu1.int32[' + d + '] = Math.floor( cpu1.float32[' + s + '] );\n'; case 0x20: /* 'CVT.S' */ break; case 0x21: /* 'CVT.D' */ return 'cpu1.store_f64( ' + d + ', cpu1.float32[' + s + '] );\n'; case 0x24: /* 'CVT.W' */ return 'cpu1.int32[' + d + '] = n64js.convert( cpu1.float32[' + s + '] );\n'; case 0x25: /* 'CVT.L' */ break; } return 'unimplemented(' + n64js.toString32(ctx.pc) + ',' + n64js.toString32(ctx.instruction) + ');\n'; } // It's a compare instruction var impl = ''; impl += 'var fs = cpu1.float32[' + s + '];\n'; impl += 'var ft = cpu1.float32[' + t + '];\n'; impl += generateFloatCompare(op); return impl; } function executeSInstr(i) { var s = fs(i); var t = ft(i); var d = fd(i); var op = cop1_func(i); if (op < 0x30) { switch(op) { case 0x00: cpu1.float32[d] = cpu1.float32[s] + cpu1.float32[t]; return; case 0x01: cpu1.float32[d] = cpu1.float32[s] - cpu1.float32[t]; return; case 0x02: cpu1.float32[d] = cpu1.float32[s] * cpu1.float32[t]; return; case 0x03: cpu1.float32[d] = cpu1.float32[s] / cpu1.float32[t]; return; case 0x04: cpu1.float32[d] = Math.sqrt( cpu1.float32[s] ); return; case 0x05: cpu1.float32[d] = Math.abs( cpu1.float32[s] ); return; case 0x06: cpu1.float32[d] = cpu1.float32[s]; return; case 0x07: cpu1.float32[d] = -cpu1.float32[s]; return; case 0x08: /* 'ROUND.L.'*/ cpu1.store_float_as_long(d, Math.round( cpu1.float32[s] )); return; case 0x09: /* 'TRUNC.L.'*/ cpu1.store_float_as_long(d, n64js.trunc( cpu1.float32[s] )); return; case 0x0a: /* 'CEIL.L.'*/ cpu1.store_float_as_long(d, Math.ceil( cpu1.float32[s] )); return; case 0x0b: /* 'FLOOR.L.'*/ cpu1.store_float_as_long(d, Math.floor( cpu1.float32[s] )); return; case 0x0c: /* 'ROUND.W.'*/ cpu1.int32[d] = Math.round( cpu1.float32[s] )|0; return; // TODO: check this case 0x0d: /* 'TRUNC.W.'*/ cpu1.int32[d] = n64js.trunc( cpu1.float32[s] )|0; return; case 0x0e: /* 'CEIL.W.'*/ cpu1.int32[d] = Math.ceil( cpu1.float32[s] )|0; return; case 0x0f: /* 'FLOOR.W.'*/ cpu1.int32[d] = Math.floor( cpu1.float32[s] )|0; return; case 0x20: /* 'CVT.S' */ unimplemented(cpu0.pc,i); return; case 0x21: /* 'CVT.D' */ cpu1.store_f64( d, cpu1.float32[s] ); return; case 0x24: /* 'CVT.W' */ cpu1.int32[d] = n64js.convert( cpu1.float32[s] )|0; return; case 0x25: /* 'CVT.L' */ unimplemented(cpu0.pc,i); return; } unimplemented(cpu0.pc,i); } else { var _s = cpu1.float32[s]; var _t = cpu1.float32[t]; handleFloatCompare(op, _s, _t); } } function generateDInstrStub(ctx) { var s = ctx.instr_fs(); var t = ctx.instr_ft(); var d = ctx.instr_fd(); ctx.fragment.usesCop1 = true; ctx.isTrivial = true; var op = cop1_func(ctx.instruction); if (op < 0x30) { switch(op) { case 0x00: return 'cpu1.store_f64( ' + d + ', cpu1.load_f64( ' + s + ' ) + cpu1.load_f64( ' + t + ' ) );\n'; case 0x01: return 'cpu1.store_f64( ' + d + ', cpu1.load_f64( ' + s + ' ) - cpu1.load_f64( ' + t + ' ) );\n'; case 0x02: return 'cpu1.store_f64( ' + d + ', cpu1.load_f64( ' + s + ' ) * cpu1.load_f64( ' + t + ' ) );\n'; case 0x03: return 'cpu1.store_f64( ' + d + ', cpu1.load_f64( ' + s + ' ) / cpu1.load_f64( ' + t + ' ) );\n'; case 0x04: return 'cpu1.store_f64( ' + d + ', Math.sqrt( cpu1.load_f64( ' + s + ' ) ) );\n'; case 0x05: return 'cpu1.store_f64( ' + d + ', Math.abs( cpu1.load_f64( ' + s + ' ) ) );\n'; case 0x06: return 'cpu1.store_f64( ' + d + ', cpu1.load_f64( ' + s + ' ) );\n'; case 0x07: return 'cpu1.store_f64( ' + d + ', -cpu1.load_f64( ' + s + ' ) );\n'; case 0x08: /* 'ROUND.L.'*/ return 'cpu1.store_float_as_long(' + d + ', Math.round( cpu1.load_f64( ' + s + ' )));\n'; case 0x09: /* 'TRUNC.L.'*/ return 'cpu1.store_float_as_long(' + d + ', n64js.trunc( cpu1.load_f64( ' + s + ' )));\n'; case 0x0a: /* 'CEIL.L.'*/ return 'cpu1.store_float_as_long(' + d + ', Math.ceil( cpu1.load_f64( ' + s + ' )));\n'; case 0x0b: /* 'FLOOR.L.'*/ return 'cpu1.store_float_as_long(' + d + ', Math.floor( cpu1.load_f64( ' + s + ' )));\n'; case 0x0c: /* 'ROUND.W.'*/ return 'cpu1.int32[' + d + '] = Math.round( cpu1.load_f64( ' + s + ' ) ) | 0;\n'; // TODO: check this case 0x0d: /* 'TRUNC.W.'*/ return 'cpu1.int32[' + d + '] = n64js.trunc( cpu1.load_f64( ' + s + ' ) ) | 0;\n'; case 0x0e: /* 'CEIL.W.'*/ return 'cpu1.int32[' + d + '] = Math.ceil( cpu1.load_f64( ' + s + ' ) ) | 0;\n'; case 0x0f: /* 'FLOOR.W.'*/ return 'cpu1.int32[' + d + '] = Math.floor( cpu1.load_f64( ' + s + ' ) ) | 0;\n'; case 0x20: /* 'CVT.S' */ return 'cpu1.float32[' + d + '] = cpu1.load_f64( ' + s + ' );\n'; case 0x21: /* 'CVT.D' */ break; case 0x24: /* 'CVT.W' */ return 'cpu1.int32[' + d + '] = n64js.convert( cpu1.load_f64( ' + s + ' ) ) | 0;\n'; case 0x25: /* 'CVT.L' */ break; } return 'unimplemented(' + n64js.toString32(ctx.pc) + ',' + n64js.toString32(ctx.instruction) + ');\n'; } // It's a compare instruction var impl = ''; impl += 'var fs = cpu1.load_f64(' + s + ');\n'; impl += 'var ft = cpu1.load_f64(' + t + ');\n'; impl += generateFloatCompare(op); return impl; } function executeDInstr(i) { var s = fs(i); var t = ft(i); var d = fd(i); var op = cop1_func(i); if (op < 0x30) { switch(op) { case 0x00: cpu1.store_f64( d, cpu1.load_f64( s ) + cpu1.load_f64( t ) ); return; case 0x01: cpu1.store_f64( d, cpu1.load_f64( s ) - cpu1.load_f64( t ) ); return; case 0x02: cpu1.store_f64( d, cpu1.load_f64( s ) * cpu1.load_f64( t ) ); return; case 0x03: cpu1.store_f64( d, cpu1.load_f64( s ) / cpu1.load_f64( t ) ); return; case 0x04: cpu1.store_f64( d, Math.sqrt( cpu1.load_f64( s ) ) ); return; case 0x05: cpu1.store_f64( d, Math.abs( cpu1.load_f64( s ) ) ); return; case 0x06: cpu1.store_f64( d, cpu1.load_f64( s ) ); return; case 0x07: cpu1.store_f64( d, -cpu1.load_f64( s ) ); return; case 0x08: /* 'ROUND.L.'*/ cpu1.store_float_as_long(d, Math.round( cpu1.load_f64( s ) )); return; case 0x09: /* 'TRUNC.L.'*/ cpu1.store_float_as_long(d, n64js.trunc( cpu1.load_f64( s ) )); return; case 0x0a: /* 'CEIL.L.'*/ cpu1.store_float_as_long(d, Math.ceil( cpu1.load_f64( s ) )); return; case 0x0b: /* 'FLOOR.L.'*/ cpu1.store_float_as_long(d, Math.floor( cpu1.load_f64( s ) )); return; case 0x0c: /* 'ROUND.W.'*/ cpu1.int32[d] = Math.round( cpu1.load_f64( s ) ) | 0; return; // TODO: check this case 0x0d: /* 'TRUNC.W.'*/ cpu1.int32[d] = n64js.trunc( cpu1.load_f64( s ) ) | 0; return; case 0x0e: /* 'CEIL.W.'*/ cpu1.int32[d] = Math.ceil( cpu1.load_f64( s ) ) | 0; return; case 0x0f: /* 'FLOOR.W.'*/ cpu1.int32[d] = Math.floor( cpu1.load_f64( s ) ) | 0; return; case 0x20: /* 'CVT.S' */ cpu1.float32[d] = cpu1.load_f64( s ); return; case 0x21: /* 'CVT.D' */ unimplemented(cpu0.pc,i); return; case 0x24: /* 'CVT.W' */ cpu1.int32[d] = n64js.convert( cpu1.load_f64( s ) ) | 0; return; case 0x25: /* 'CVT.L' */ unimplemented(cpu0.pc,i); return; } unimplemented(cpu0.pc,i); } else { var _s = cpu1.load_f64( s ); var _t = cpu1.load_f64( t ); handleFloatCompare(op, _s, _t); } } function generateWInstrStub(ctx) { var s = ctx.instr_fs(); var d = ctx.instr_fd(); ctx.fragment.usesCop1 = true; ctx.isTrivial = true; switch(cop1_func(ctx.instruction)) { case 0x20: /* 'CVT.S' */ return 'cpu1.float32[' + d + '] = cpu1.int32[' + s + '];\n'; case 0x21: /* 'CVT.D' */ return 'cpu1.store_f64(' + d + ', cpu1.int32[' + s + ']);\n'; } return 'unimplemented(' + n64js.toString32(ctx.pc) + ',' + n64js.toString32(ctx.instruction) + ');\n'; } function executeWInstr(i) { var s = fs(i); var d = fd(i); switch(cop1_func(i)) { case 0x20: cpu1.float32[d] = cpu1.int32[s]; return; case 0x21: cpu1.store_f64(d, cpu1.int32[s]); return; } unimplemented(cpu0.pc,i); } function generateLInstrStub(ctx) { var s = ctx.instr_fs(); var d = ctx.instr_fd(); ctx.fragment.usesCop1 = true; ctx.isTrivial = true; switch(cop1_func(ctx.instruction)) { case 0x20: /* 'CVT.S' */ return 'cpu1.float32[' + d + '] = cpu1.load_s64_as_double(' + s + ');\n'; case 0x21: /* 'CVT.D' */ return 'cpu1.store_f64(' + d + ', cpu1.load_s64_as_double(' + s + ') );\n'; } return 'unimplemented(' + n64js.toString32(ctx.pc) + ',' + n64js.toString32(ctx.instruction) + ');\n'; } function executeLInstr(i) { var s = fs(i); var d = fd(i); switch(cop1_func(i)) { case 0x20: /* 'CVT.S' */ cpu1.float32[d] = cpu1.load_s64_as_double(s); return; case 0x21: /* 'CVT.D' */ cpu1.store_f64(d, cpu1.load_s64_as_double(s)); return; } unimplemented(cpu0.pc,i); } var specialTable = [ executeSLL, executeUnknown, executeSRL, executeSRA, executeSLLV, executeUnknown, executeSRLV, executeSRAV, executeJR, executeJALR, executeUnknown, executeUnknown, executeSYSCALL, executeBREAK, executeUnknown, executeSYNC, executeMFHI, executeMTHI, executeMFLO, executeMTLO, executeDSLLV, executeUnknown, executeDSRLV, executeDSRAV, executeMULT, executeMULTU, executeDIV, executeDIVU, executeDMULT, executeDMULTU, executeDDIV, executeDDIVU, executeADD, executeADDU, executeSUB, executeSUBU, executeAND, executeOR, executeXOR, executeNOR, executeUnknown, executeUnknown, executeSLT, executeSLTU, executeDADD, executeDADDU, executeDSUB, executeDSUBU, executeTGE, executeTGEU, executeTLT, executeTLTU, executeTEQ, executeUnknown, executeTNE, executeUnknown, executeDSLL, executeUnknown, executeDSRL, executeDSRA, executeDSLL32, executeUnknown, executeDSRL32, executeDSRA32 ]; if (specialTable.length != 64) { throw "Oops, didn't build the special table correctly"; } n64js.executeUnknown = executeUnknown; function executeSpecial(i) { var fn = i & 0x3f; specialTable[fn](i); } var cop0Table = [ executeMFC0, executeUnknown, executeUnknown, executeUnknown, executeMTC0, executeUnknown, executeUnknown, executeUnknown, executeUnknown, executeUnknown, executeUnknown, executeUnknown, executeUnknown, executeUnknown, executeUnknown, executeUnknown, executeTLB, executeUnknown, executeUnknown, executeUnknown, executeUnknown, executeUnknown, executeUnknown, executeUnknown, executeUnknown, executeUnknown, executeUnknown, executeUnknown, executeUnknown, executeUnknown, executeUnknown, executeUnknown ]; if (cop0Table.length != 32) { throw "Oops, didn't build the cop0 table correctly"; } var cop0TableGen = [ 'executeMFC0', 'executeUnknown', 'executeUnknown', 'executeUnknown', generateMTC0, 'executeUnknown', 'executeUnknown', 'executeUnknown', 'executeUnknown', 'executeUnknown', 'executeUnknown', 'executeUnknown', 'executeUnknown', 'executeUnknown', 'executeUnknown', 'executeUnknown', 'executeTLB', 'executeUnknown', 'executeUnknown', 'executeUnknown', 'executeUnknown', 'executeUnknown', 'executeUnknown', 'executeUnknown', 'executeUnknown', 'executeUnknown', 'executeUnknown', 'executeUnknown', 'executeUnknown', 'executeUnknown', 'executeUnknown', 'executeUnknown' ]; if (cop0TableGen.length != 32) { throw "Oops, didn't build the cop0 table correctly"; } // Expose all the functions that we don't yet generate n64js.executeMFC0 = executeMFC0; n64js.executeMTC0 = executeMTC0; // There's a generateMTC0, but it calls through to the interpreter n64js.executeTLB = executeTLB; function executeCop0(i) { var fmt = (i >>> 21) & 0x1f; cop0Table[fmt](i); } var cop1Table = [ executeMFC1, executeDMFC1, executeCFC1, executeUnknown, executeMTC1, executeDMTC1, executeCTC1, executeUnknown, executeBCInstr, executeUnknown, executeUnknown, executeUnknown, executeUnknown, executeUnknown, executeUnknown, executeUnknown, executeSInstr, executeDInstr, executeUnknown, executeUnknown, executeWInstr, executeLInstr, executeUnknown, executeUnknown, executeUnknown, executeUnknown, executeUnknown, executeUnknown, executeUnknown, executeUnknown, executeUnknown, executeUnknown ]; if (cop1Table.length != 32) { throw "Oops, didn't build the cop1 table correctly"; } var cop1TableGen = [ generateMFC1Stub, generateDMFC1Stub, generateCFC1Stub, 'executeUnknown', generateMTC1Stub, generateDMTC1Stub, generateCTC1Stub, 'executeUnknown', generateBCInstrStub, 'executeUnknown', 'executeUnknown', 'executeUnknown', 'executeUnknown', 'executeUnknown', 'executeUnknown', 'executeUnknown', generateSInstrStub, generateDInstrStub, 'executeUnknown', 'executeUnknown', generateWInstrStub, generateLInstrStub, 'executeUnknown', 'executeUnknown', 'executeUnknown', 'executeUnknown', 'executeUnknown', 'executeUnknown', 'executeUnknown', 'executeUnknown', 'executeUnknown', 'executeUnknown' ]; if (cop1TableGen.length != 32) { throw "Oops, didn't build the cop1 gen table correctly"; } function generateCop1(ctx) { var fmt = (ctx.instruction >>> 21) & 0x1f; var fn = cop1TableGen[fmt]; var op_impl; if (typeof fn === 'string') { //n64js.log(fn); op_impl = 'n64js.' + fn + '(' + n64js.toString32(ctx.instruction) + ');\n'; } else { op_impl = fn(ctx); } var impl = ''; ctx.fragment.usesCop1 = true; if (ctx.fragment.cop1statusKnown) { // Assert that cop1 is enabled impl += ctx.genAssert('(c.control[12] & SR_CU1) !== 0', 'cop1 should be enabled'); impl += op_impl; } else { impl += 'if( (c.control[12] & SR_CU1) === 0 ) {\n'; impl += ' executeCop1_disabled(' + n64js.toString32(ctx.instruction) + ');\n'; impl += '} else {\n'; impl += ' ' + op_impl; impl += '}\n'; ctx.isTrivial = false; // Not trivial! ctx.fragment.cop1statusKnown = true; return generateGenericOpBoilerplate(impl, ctx); // Ensure we generate full boilerplate here, even for trivial ops } if (ctx.isTrivial) { return generateTrivialOpBoilerplate(impl, ctx); } return generateGenericOpBoilerplate(impl, ctx); } function executeCop1(i) { //n64js.assert( (cpu0.control[cpu0.kControlSR] & SR_CU1) !== 0, "SR_CU1 in inconsistent state" ); var fmt = (i >>> 21) & 0x1f; cop1Table[fmt](i); } function executeCop1_disabled(i) { n64js.log('Thread accessing cop1 for first time, throwing cop1 unusable exception'); n64js.assert( (cpu0.control[cpu0.kControlSR] & SR_CU1) === 0, "SR_CU1 in inconsistent state" ); cpu0.throwCop1Unusable(); } function setCop1Enable(enable) { simpleTable[0x11] = enable ? executeCop1 : executeCop1_disabled; } var regImmTable = [ executeBLTZ, executeBGEZ, executeBLTZL, executeBGEZL, executeUnknown, executeUnknown, executeUnknown, executeUnknown, executeTGEI, executeTGEIU, executeTLTI, executeTLTIU, executeTEQI, executeUnknown, executeTNEI, executeUnknown, executeBLTZAL, executeBGEZAL, executeBLTZALL, executeBGEZALL, executeUnknown, executeUnknown, executeUnknown, executeUnknown, executeUnknown, executeUnknown, executeUnknown, executeUnknown, executeUnknown, executeUnknown, executeUnknown, executeUnknown ]; if (regImmTable.length != 32) { throw "Oops, didn't build the regimm table correctly"; } function executeRegImm(i) { var rt = (i >>> 16) & 0x1f; return regImmTable[rt](i); } var simpleTable = [ executeSpecial, executeRegImm, executeJ, executeJAL, executeBEQ, executeBNE, executeBLEZ, executeBGTZ, executeADDI, executeADDIU, executeSLTI, executeSLTIU, executeANDI, executeORI, executeXORI, executeLUI, executeCop0, executeCop1_disabled, executeUnknown, executeUnknown, executeBEQL, executeBNEL, executeBLEZL, executeBGTZL, executeDADDI, executeDADDIU, executeLDL, executeLDR, executeUnknown, executeUnknown, executeUnknown, executeUnknown, executeLB, executeLH, executeLWL, executeLW, executeLBU, executeLHU, executeLWR, executeLWU, executeSB, executeSH, executeSWL, executeSW, executeSDL, executeSDR, executeSWR, executeCACHE, executeLL, executeLWC1, executeUnknown, executeUnknown, executeLLD, executeLDC1, executeLDC2, executeLD, executeSC, executeSWC1, executeBreakpoint, executeUnknown, executeSCD, executeSDC1, executeSDC2, executeSD ]; if (simpleTable.length != 64) { throw "Oops, didn't build the simple table correctly"; } function executeOp(i) { var opcode = (i >>> 26) & 0x3f; return simpleTable[opcode](i); } var specialTableGen = [ generateSLL, 'executeUnknown', generateSRL, generateSRA, generateSLLV, 'executeUnknown', generateSRLV, generateSRAV, generateJR, generateJALR, 'executeUnknown', 'executeUnknown', 'executeSYSCALL', 'executeBREAK', 'executeUnknown', 'executeSYNC', generateMFHI, generateMTHI, generateMFLO, generateMTLO, 'executeDSLLV', 'executeUnknown', 'executeDSRLV', 'executeDSRAV', generateMULT, generateMULTU, 'executeDIV', 'executeDIVU', 'executeDMULT', 'executeDMULTU', 'executeDDIV', 'executeDDIVU', generateADD, generateADDU, generateSUB, generateSUBU, generateAND, generateOR, generateXOR, generateNOR, 'executeUnknown', 'executeUnknown', generateSLT, generateSLTU, 'executeDADD', 'executeDADDU', 'executeDSUB', 'executeDSUBU', 'executeTGE', 'executeTGEU', 'executeTLT', 'executeTLTU', 'executeTEQ', 'executeUnknown', 'executeTNE', 'executeUnknown', 'executeDSLL', 'executeUnknown', 'executeDSRL', 'executeDSRA', 'executeDSLL32', 'executeUnknown', 'executeDSRL32', 'executeDSRA32' ]; if (specialTableGen.length != 64) { throw "Oops, didn't build the special gen table correctly"; } // Expose all the functions that we don't yet generate n64js.executeSYSCALL = executeSYSCALL; n64js.executeBREAK = executeBREAK; n64js.executeSYNC = executeSYNC; n64js.executeDSLLV = executeDSLLV; n64js.executeDSRLV = executeDSRLV; n64js.executeDSRAV = executeDSRAV; n64js.executeDIV = executeDIV; n64js.executeDIVU = executeDIVU; n64js.executeDMULT = executeDMULT; n64js.executeDMULTU = executeDMULTU; n64js.executeDDIV = executeDDIV; n64js.executeDDIVU = executeDDIVU; n64js.executeDADD = executeDADD; n64js.executeDADDU = executeDADDU; n64js.executeDSUB = executeDSUB; n64js.executeDSUBU = executeDSUBU; n64js.executeTGE = executeTGE; n64js.executeTGEU = executeTGEU; n64js.executeTLT = executeTLT; n64js.executeTLTU = executeTLTU; n64js.executeTEQ = executeTEQ; n64js.executeTNE = executeTNE; n64js.executeDSLL = executeDSLL; n64js.executeDSRL = executeDSRL; n64js.executeDSRA = executeDSRA; n64js.executeDSLL32 = executeDSLL32; n64js.executeDSRL32 = executeDSRL32; n64js.executeDSRA32 = executeDSRA32; var regImmTableGen = [ generateBLTZ, generateBGEZ, generateBLTZL, generateBGEZL, 'executeUnknown', 'executeUnknown', 'executeUnknown', 'executeUnknown', 'executeTGEI', 'executeTGEIU', 'executeTLTI', 'executeTLTIU', 'executeTEQI', 'executeUnknown', 'executeTNEI', 'executeUnknown', 'executeBLTZAL', 'executeBGEZAL', 'executeBLTZALL', 'executeBGEZALL', 'executeUnknown', 'executeUnknown', 'executeUnknown', 'executeUnknown', 'executeUnknown', 'executeUnknown', 'executeUnknown', 'executeUnknown', 'executeUnknown', 'executeUnknown', 'executeUnknown', 'executeUnknown' ]; if (regImmTableGen.length != 32) { throw "Oops, didn't build the regimm gen table correctly"; } // Expose all the functions that we don't yet generate n64js.executeTGEI = executeTGEI; n64js.executeTGEIU = executeTGEIU; n64js.executeTLTI = executeTLTI; n64js.executeTLTIU = executeTLTIU; n64js.executeTEQI = executeTEQI; n64js.executeTNEI = executeTNEI; n64js.executeBLTZAL = executeBLTZAL; n64js.executeBGEZAL = executeBGEZAL; n64js.executeBLTZALL = executeBLTZALL; n64js.executeBGEZALL = executeBGEZALL; var simpleTableGen = [ generateSpecial, generateRegImm, generateJ, generateJAL, generateBEQ, generateBNE, generateBLEZ, generateBGTZ, generateADDI, generateADDIU, generateSLTI, generateSLTIU, generateANDI, generateORI, generateXORI, generateLUI, generateCop0, generateCop1, 'executeUnknown', 'executeUnknown', generateBEQL, generateBNEL, 'executeBLEZL', 'executeBGTZL', 'executeDADDI', 'executeDADDIU', 'executeLDL', 'executeLDR', 'executeUnknown', 'executeUnknown', 'executeUnknown', 'executeUnknown', generateLB, generateLH, 'executeLWL', generateLW, generateLBU, generateLHU, 'executeLWR', generateLWU, generateSB, generateSH, 'executeSWL', generateSW, 'executeSDL', 'executeSDR', 'executeSWR', generateCACHE, 'executeLL', generateLWC1, 'executeUnknown', 'executeUnknown', 'executeLLD', generateLDC1, 'executeLDC2', generateLD, 'executeSC', generateSWC1, 'executeUnknown', 'executeUnknown', 'executeSCD', generateSDC1, 'executeSDC2', generateSD ]; if (simpleTableGen.length != 64) { throw "Oops, didn't build the simple gen table correctly"; } // Expose all the functions that we don't yet generate n64js.executeBLEZL = executeBLEZL; n64js.executeBGTZL = executeBGTZL; n64js.executeDADDI = executeDADDI; n64js.executeDADDIU = executeDADDIU; n64js.executeLDL = executeLDL; n64js.executeLDR = executeLDR; n64js.executeLWL = executeLWL; n64js.executeLWR = executeLWR; n64js.executeSWL = executeSWL; n64js.executeSDL = executeSDL; n64js.executeSDR = executeSDR; n64js.executeSWR = executeSWR; n64js.executeLL = executeLL; n64js.executeLLD = executeLLD; n64js.executeLDC2 = executeLDC2; n64js.executeSC = executeSC; n64js.executeSCD = executeSCD; n64js.executeSDC2 = executeSDC2; function FragmentContext() { this.fragment = undefined; this.pc = 0; this.instruction = 0; this.post_pc = 0; this.bailOut = false; // Set this if the op does something to manipulate event timers. this.needsDelayCheck = true; // Set on entry to generate handler. If set, must check for delayPC when updating the pc. this.isTrivial = false; // Set by the code generation handler if the op is considered trivial. this.delayedPCUpdate = 0; // Trivial ops can try to delay setting the pc so that back-to-back trivial ops can emit them entirely. this.dump = false; // Display this op when finished. } FragmentContext.prototype.genAssert = function (test, msg) { if (kDebugDynarec) { return 'n64js.assert(' + test + ', "' + msg + '");\n'; } return ''; }; FragmentContext.prototype.newFragment = function () { this.delayedPCUpdate = 0; }; FragmentContext.prototype.set = function (fragment, pc, instruction, post_pc) { this.fragment = fragment; this.pc = pc; this.instruction = instruction; this.post_pc = post_pc; this.bailOut = false; this.needsDelayCheck = true; this.isTrivial = false; this.dump = false; // Persist this between ops //this.delayedPCUpdate = 0; }; FragmentContext.prototype.instr_rs = function () { return rs(this.instruction); }; FragmentContext.prototype.instr_rt = function () { return rt(this.instruction); }; FragmentContext.prototype.instr_rd = function () { return rd(this.instruction); }; FragmentContext.prototype.instr_sa = function () { return sa(this.instruction); }; FragmentContext.prototype.instr_fs = function () { return fs(this.instruction); }; FragmentContext.prototype.instr_ft = function () { return ft(this.instruction); }; FragmentContext.prototype.instr_fd = function () { return fd(this.instruction); }; FragmentContext.prototype.instr_base = function () { return base(this.instruction); }; FragmentContext.prototype.instr_offset = function () { return offset(this.instruction); }; FragmentContext.prototype.instr_imms = function () { return imms(this.instruction); }; function checkCauseIP3Consistent() { var mi_interrupt_set = n64js.miInterruptsUnmasked(); var cause_int_3_set = (cpu0.control[cpu0.kControlCause] & CAUSE_IP3) !== 0; n64js.assert(mi_interrupt_set === cause_int_3_set, 'CAUSE_IP3 inconsistent with MI_INTR_REG'); } function mix(a,b,c) { a -= b; a -= c; a ^= (c>>>13); b -= c; b -= a; b ^= (a<<8); c -= a; c -= b; c ^= (b>>>13); a -= b; a -= c; a ^= (c>>>12); b -= c; b -= a; b ^= (a<<16); c -= a; c -= b; c ^= (b>>>5); a -= b; a -= c; a ^= (c>>>3); b -= c; b -= a; b ^= (a<<10); c -= a; c -= b; c ^= (b>>>15); return a; } function checkSyncState(sync, pc) { var i; if (!sync.sync32(pc, 'pc')) return false; // var next_vbl = 0; // for (i = 0; i < cpu0.events.length; ++i) { // var event = cpu0.events[i]; // next_vbl += event.countdown; // if (event.type === kEventVbl) { // next_vbl = next_vbl*2+1; // break; // } else if (event.type == kEventCompare) { // next_vbl = next_vbl*2; // break; // } // } // if (!sync.sync32(next_vbl, 'event')) // return false; if (1) { var a = 0; for (i = 0; i < 32; ++i) { a = mix(a,cpu0.gprLo[i], 0); } a = a>>>0; if (!sync.sync32(a, 'regs')) return false; } // if(0) { // if (!sync.sync32(cpu0.multLo[0], 'multlo')) // return false; // if (!sync.sync32(cpu0.multHi[0], 'multhi')) // return false; // } // if(0) { // if (!sync.sync32(cpu0.control[cpu0.kControlCount], 'count')) // return false; // if (!sync.sync32(cpu0.control[cpu0.kControlCompare], 'compare')) // return false; // } return true; } function handleTLBException() { cpu0.pc = cpu0.nextPC; cpu0.delayPC = cpu0.branchTarget; cpu0.control_signed[cpu0.kControlCount] += COUNTER_INCREMENT_PER_OP; var evt = cpu0.events[0]; evt.countdown -= COUNTER_INCREMENT_PER_OP; if (evt.countdown <= 0) { handleCounter(); } } function handleCounter() { while (cpu0.events.length > 0 && cpu0.events[0].countdown <= 0) { var evt = cpu0.events[0]; cpu0.events.splice(0, 1); // if it's our cycles event then just bail if (evt.type === kEventRunForCycles) { cpu0.stuffToDo |= kStuffToDoBreakout; } else if (evt.type === kEventCompare) { cpu0.control[cpu0.kControlCause] |= CAUSE_IP8; if (cpu0.checkForUnmaskedInterrupts()) { cpu0.stuffToDo |= kStuffToDoCheckInterrupts; } } else if (evt.type === kEventVbl) { // FIXME: this should be based on VI_V_SYNC_REG cpu0.addEvent(kEventVbl, kVIIntrCycles); n64js.verticalBlank(); cpu0.stuffToDo |= kStuffToDoBreakout; } else { n64js.halt('unhandled event!'); } } } n64js.singleStep = function () { var restore_breakpoint_address = 0; if (n64js.isBreakpoint(cpu0.pc)) { restore_breakpoint_address = cpu0.pc; n64js.toggleBreakpoint(restore_breakpoint_address); } n64js.run(1); if (restore_breakpoint_address) { n64js.toggleBreakpoint(restore_breakpoint_address); } }; n64js.run = function (cycles) { cpu0.stuffToDo &= ~kStuffToDoHalt; checkCauseIP3Consistent(); n64js.checkSIStatusConsistent(); cpu0.addEvent(kEventRunForCycles, cycles); while (cpu0.hasEvent(kEventRunForCycles)) { try { // NB: the bulk of run() is implemented as a separate function. // v8 won't optimise code with try/catch blocks, so structuring the code in this way allows runImpl to be optimised. runImpl(); break; } catch (e) { if (e instanceof TLBException) { // If we hit a TLB exception we apply the nextPC (which should have been set to an exception vector) and continue looping. handleTLBException(); } else if (e instanceof BreakpointException) { n64js.stopForBreakpoint(); } else { // Other exceptions are bad news, so display an error and bail out. n64js.halt('Exception :' + e); break; } } } // Clean up any kEventRunForCycles events before we bail out var cycles_remaining = cpu0.removeEventsOfType(kEventRunForCycles); // If the event no longer exists, assume we've executed all the cycles if (cycles_remaining < 0) { cycles_remaining = 0; } if (cycles_remaining < cycles) { cpu0.opsExecuted += cycles - cycles_remaining; } }; function executeFragment(fragment, c, ram, events) { var evt = events[0]; if (evt.countdown >= fragment.opsCompiled*COUNTER_INCREMENT_PER_OP) { fragment.executionCount++; var ops_executed = fragment.func(c, c.gprLo_signed, c.gprHi_signed, ram); // Absolute value is number of ops executed. // refresh latest event - may have changed evt = events[0]; evt.countdown -= ops_executed * COUNTER_INCREMENT_PER_OP; if (!accurateCountUpdating) { c.control_signed[c.kControlCount] += ops_executed * COUNTER_INCREMENT_PER_OP; } //n64js.assert(fragment.bailedOut || evt.countdown >= 0, "Executed too many ops. Possibly didn't bail out of trace when new event was set up?"); if (evt.countdown <= 0) { handleCounter(); } // If stuffToDo is set, we'll break on the next loop var next_fragment = fragment.nextFragments[ops_executed]; if (!next_fragment || next_fragment.entryPC !== c.pc) { next_fragment = fragment.getNextFragment(c.pc, ops_executed); } fragment = next_fragment; } else { // We're close to another event: drop to the interpreter fragment = null; } return fragment; } // We need just one of these - declare at global scope to avoid generating garbage var fragmentContext = new FragmentContext(); // NB: first pc is entry_pc, cpu0.pc is post_pc by this point function addOpToFragment(fragment, entry_pc, instruction, c) { if (fragment.opsCompiled === 0) { fragmentContext.newFragment(); } fragment.opsCompiled++; updateFragment(fragment, entry_pc); fragmentContext.set(fragment, entry_pc, instruction, c.pc); // NB: first pc is entry_pc, c.pc is post_pc by this point generateCodeForOp(fragmentContext); // Break out of the trace as soon as we branch, or too many ops, or last op generated an interrupt (stuffToDo set) var long_fragment = fragment.opsCompiled > 8; if ((long_fragment && c.pc !== entry_pc+4) || fragment.opsCompiled >= 250 || c.stuffToDo) { // Check if the last op has a delayed pc update, and do it now. if (fragmentContext.delayedPCUpdate !== 0) { fragment.body_code += 'c.pc = ' + n64js.toString32(fragmentContext.delayedPCUpdate) + ';\n'; fragmentContext.delayedPCUpdate = 0; } fragment.body_code += 'return ' + fragment.opsCompiled + ';\n'; // Return the number of ops exected var sync = n64js.getSyncFlow(); if (sync) { fragment.body_code = 'var sync = n64js.getSyncFlow();\n' + fragment.body_code; } if (fragment.usesCop1) { var cpu1_shizzle = ''; cpu1_shizzle += 'var cpu1 = n64js.cpu1;\n'; cpu1_shizzle += 'var SR_CU1 = ' + n64js.toString32(SR_CU1) + ';\n'; cpu1_shizzle += 'var FPCSR_C = ' + n64js.toString32(FPCSR_C) + ';\n'; fragment.body_code = cpu1_shizzle + '\n\n' + fragment.body_code; } var code = 'return function fragment_' + n64js.toString32(fragment.entryPC) + '_' + fragment.opsCompiled + '(c, rlo, rhi, ram) {\n' + fragment.body_code + '}\n'; // Clear these strings to reduce garbage fragment.body_code =''; fragment.func = new Function(code)(); fragment.nextFragments = []; for (var i = 0; i < fragment.opsCompiled; i++) { fragment.nextFragments.push(undefined); } fragment = lookupFragment(c.pc); } return fragment; } function runImpl() { //var sync = n64js.getSyncFlow(); var c = cpu0; var events = c.events; var ram = c.ram; var fragment; var evt; while (c.hasEvent(kEventRunForCycles)) { fragment = lookupFragment(c.pc); //fragment = null; while (!c.stuffToDo) { if (fragment && fragment.func) { fragment = executeFragment(fragment, c, ram, events); } else { // if (sync) { // if (!checkSyncState(sync, cpu0.pc)) { // n64js.halt('sync error'); // break; // } // } var pc = c.pc; // take a copy of this, so we can refer to it later // NB: set nextPC before the call to readMemoryS32. If this throws an exception, we need nextPC to be set up correctly. if (c.delayPC) { c.nextPC = c.delayPC; } else { c.nextPC = c.pc + 4; } // NB: load instruction using normal memory access routines - this means that we throw a tlb miss/refill approptiately //var instruction = n64js.load_s32(ram, pc); var instruction; if (pc < -2139095040) { var phys = (pc + 0x80000000) | 0; // NB: or with zero ensures we return an SMI if possible. instruction = ((ram[phys] << 24) | (ram[phys+1] << 16) | (ram[phys+2] << 8) | ram[phys+3]) | 0; } else { instruction = lw_slow(pc); } c.branchTarget = 0; executeOp(instruction); c.pc = c.nextPC; c.delayPC = c.branchTarget; c.control_signed[c.kControlCount] += COUNTER_INCREMENT_PER_OP; //checkCauseIP3Consistent(); //n64js.checkSIStatusConsistent(); evt = events[0]; evt.countdown -= COUNTER_INCREMENT_PER_OP; if (evt.countdown <= 0) { handleCounter(); } // If we have a fragment, we're assembling code as we go if (fragment) { fragment = addOpToFragment(fragment, pc, instruction, c); } else { // If there's no current fragment and we branch backwards, this is possibly a new loop if (c.pc < pc) { fragment = lookupFragment(c.pc); } } } } c.stuffToDo &= ~kStuffToDoBreakout; if (c.stuffToDo & kStuffToDoCheckInterrupts) { c.stuffToDo &= ~kStuffToDoCheckInterrupts; c.handleInterrupt(); } else if (c.stuffToDo & kStuffToDoHalt) { break; } else if (c.stuffToDo) { n64js.warn("Don't know how to handle this event!"); break; } } } n64js.getFragmentMap = function () { return fragmentMap; }; n64js.getFragmentInvalidationEvents = function() { var t = fragmentInvalidationEvents; fragmentInvalidationEvents = []; return t; }; function Fragment(pc) { this.entryPC = pc; this.minPC = pc; this.maxPC = pc+4; this.func = undefined; this.opsCompiled = 0; this.executionCount = 0; this.bailedOut = false; // Set if a fragment bailed out. this.nextFragments = []; // One slot per op // State used when compiling this.body_code = ''; this.needsDelayCheck = true; this.cop1statusKnown = false; this.usesCop1 = false; } Fragment.prototype.invalidate = function () { // reset all but entryPC this.minPC = this.entryPC; this.maxPC = this.entryPC+4; this.func = undefined; this.opsCompiled = 0; this.bailedOut = false; this.executionCount = 0; this.nextFragments = []; this.body_code = ''; this.needsDelayCheck = true; this.cop1statusKnown = false; this.usesCop1 = false; }; Fragment.prototype.getNextFragment = function (pc, ops_executed) { var next_fragment = this.nextFragments[ops_executed]; if (!next_fragment || next_fragment.entryPC !== pc) { // If not jump to self, look up if (pc === this.entryPC) { next_fragment = this; } else { next_fragment = lookupFragment(pc); } // And cache for next time around. this.nextFragments[ops_executed] = next_fragment; } return next_fragment; }; function lookupFragment(pc) { // Check if we already have a fragment var fragment = fragmentMap[pc]; if (!fragment) { if (!kEnableDynarec) { return null; } // Check if this pc is hot enough yet var hc = hitCounts[pc] || 0; hc++; hitCounts[pc] = hc; if (hc < kHotFragmentThreshold) { return null; } fragment = new Fragment(pc); fragmentMap[pc] = fragment; } // If we failed to complete the fragment for any reason, reset it if (!fragment.func) { fragment.invalidate(); } return fragment; } var invals = 0; function FragmentMapWho() { var i; this.kNumEntries = 16*1024; this.entries = []; for (i = 0; i < this.kNumEntries; ++i) { this.entries.push({}); } } FragmentMapWho.prototype.addressToCacheLine = function (address) { return Math.floor(address >>> 5); }; FragmentMapWho.prototype.addressToCacheLineRoundUp = function (address) { return Math.floor((address+31) >>> 5); }; FragmentMapWho.prototype.add = function (pc, fragment) { var cache_line_idx = this.addressToCacheLine(pc); var entry_idx = cache_line_idx % this.entries.length; var entry = this.entries[entry_idx]; entry[fragment.entryPC] = fragment; }; FragmentMapWho.prototype.invalidateEntry = function (address) { var cache_line_idx = this.addressToCacheLine(address), entry_idx = cache_line_idx % this.entries.length, entry = this.entries[entry_idx], removed = 0; var i, fragment; for (i in entry) { if (entry.hasOwnProperty(i)) { fragment = entry[i]; if (fragment.minPC <= address && fragment.maxPC > address) { fragment.invalidate(); delete entry[i]; removed++; } } } if (removed) { n64js.log('Fragment cache removed ' + removed + ' entries.'); } //fragmentInvalidationEvents.push({'address': address, 'length': 0x20, 'system': 'CACHE', 'fragmentsRemoved': removed}); }; FragmentMapWho.prototype.invalidateRange = function (address, length) { var minaddr = address, maxaddr = address + length, minpage = this.addressToCacheLine(minaddr), maxpage = this.addressToCacheLineRoundUp(maxaddr), entries = this.entries, removed = 0; var cache_line_idx, entry_idx, entry, i, fragment; for (cache_line_idx = minpage; cache_line_idx <= maxpage; ++cache_line_idx) { entry_idx = cache_line_idx % entries.length; entry = entries[entry_idx]; for (i in entry) { if (entry.hasOwnProperty(i)) { fragment = entry[i]; if (fragment.minPC <= maxaddr && fragment.maxPC > minaddr) { fragment.invalidate(); delete entry[i]; removed++; } } } } if (removed) { n64js.log('Fragment cache removed ' + removed + ' entries.'); } //fragmentInvalidationEvents.push({'address': address, 'length': length, 'system': system, 'fragmentsRemoved': removed}); }; // Invalidate a single cache line n64js.invalidateICacheEntry = function (address) { //n64js.log('cache flush ' + n64js.toString32(address)); ++invals; if ((invals%10000) === 0) { n64js.log(invals + ' invals'); } fragmentMapWho.invalidateEntry(address); }; // This isn't called right now. We n64js.invalidateICacheRange = function (address, length, system) { //n64js.log('cache flush ' + n64js.toString32(address) + ' ' + n64js.toString32(length)); // FIXME: check for overlapping ranges // NB: not sure PI events are useful right now. if (system==='PI') { return; } fragmentMapWho.invalidateRange(address, length); }; var fragmentMapWho = new FragmentMapWho(); function updateFragment(fragment, pc) { fragment.minPC = Math.min(fragment.minPC, pc); fragment.maxPC = Math.max(fragment.maxPC, pc+4); fragmentMapWho.add(pc, fragment); } function checkEqual(a,b,m) { if (a !== b) { var msg = n64js.toString32(a) + ' !== ' + n64js.toString32(b) + ' : ' + m; console.assert(false, msg); n64js.halt(msg); return false; } return true; } n64js.checkSyncState = checkSyncState; // Needs to be callable from dynarec function generateCodeForOp(ctx) { ctx.needsDelayCheck = ctx.fragment.needsDelayCheck; ctx.isTrivial = false; var fn_code = generateOp(ctx); if (ctx.dump) { console.log(fn_code); } // if (fn_code.indexOf('execute') >= 0 && fn_code.indexOf('executeCop1_disabled') < 0 ) { // console.log('slow' + fn_code); // } // If the last op tried to delay updating the pc, see if it needs updating now. if (!ctx.isTrivial && ctx.delayedPCUpdate !== 0) { ctx.fragment.body_code += '/*applying delayed pc*/\nc.pc = ' + n64js.toString32(ctx.delayedPCUpdate) + ';\n'; ctx.delayedPCUpdate = 0; } ctx.fragment.needsDelayCheck = ctx.needsDelayCheck; //code += 'if (!checkEqual( n64js.readMemoryU32(cpu0.pc), ' + n64js.toString32(instruction) + ', "unexpected instruction (need to flush icache?)")) { return false; }\n'; ctx.fragment.bailedOut |= ctx.bailOut; var sync = n64js.getSyncFlow(); if (sync) { fn_code = 'if (!n64js.checkSyncState(sync, ' + n64js.toString32(ctx.pc) + ')) { return ' + ctx.fragment.opsCompiled + '; }\n' + fn_code; } ctx.fragment.body_code += fn_code + '\n'; } function generateOp(ctx) { var opcode = (ctx.instruction >>> 26) & 0x3f; var fn = simpleTableGen[opcode]; return generateOpHelper(fn, ctx); } function generateSpecial(ctx) { var special_fn = ctx.instruction & 0x3f; var fn = specialTableGen[special_fn]; return generateOpHelper(fn, ctx); } function generateRegImm(ctx) { var rt = (ctx.instruction >>> 16) & 0x1f; var fn = regImmTableGen[rt]; return generateOpHelper(fn, ctx); } function generateCop0(ctx) { var fmt = (ctx.instruction >>> 21) & 0x1f; var fn = cop0TableGen[fmt]; return generateOpHelper(fn,ctx); } // This takes a fn - either a string (in which case we generate some unoptimised boilerplate) or a function (which we call recursively) function generateOpHelper(fn,ctx) { // fn can be a handler function, in which case defer to that. if (typeof fn === 'string') { //n64js.log(fn); return generateGenericOpBoilerplate('n64js.' + fn + '(' + n64js.toString32(ctx.instruction) + ');\n', ctx); } else { return fn(ctx); } } function generateGenericOpBoilerplate(fn,ctx) { var code = ''; code += ctx.genAssert('c.pc === ' + n64js.toString32(ctx.pc), 'pc mismatch'); if (ctx.needsDelayCheck) { // NB: delayPC not cleared here - it's always overwritten with branchTarget below. code += 'if (c.delayPC) { c.nextPC = c.delayPC; } else { c.nextPC = ' + n64js.toString32(ctx.pc+4) +'; }\n'; } else { code += ctx.genAssert('c.delayPC === 0', 'delay pc should be zero'); code += 'c.nextPC = ' + n64js.toString32(ctx.pc+4) + ';\n'; } code += 'c.branchTarget = 0;\n'; code += fn; code += 'c.pc = c.nextPC;\n'; code += 'c.delayPC = c.branchTarget;\n'; // We don't know if the generic op set delayPC, so assume the worst ctx.needsDelayCheck = true; if (accurateCountUpdating) { code += 'c.control_signed[9] += 1;\n'; } // If bailOut is set, always return immediately if (ctx.bailOut) { code += 'return ' + ctx.fragment.opsCompiled + ';\n'; } else { code += 'if (c.stuffToDo) { return ' + ctx.fragment.opsCompiled + '; }\n'; code += 'if (c.pc !== ' + n64js.toString32(ctx.post_pc) + ') { return ' + ctx.fragment.opsCompiled + '; }\n'; } return code; } // Standard code for manipulating the pc function generateStandardPCUpdate(fn, ctx, might_adjust_next_pc) { var code = ''; code += ctx.genAssert('c.pc === ' + n64js.toString32(ctx.pc), 'pc mismatch'); if (ctx.needsDelayCheck) { // We should probably assert on this - two branch instructions back-to-back is weird, but the flag could just be set because of a generic op code += 'if (c.delayPC) { c.nextPC = c.delayPC; c.delayPC = 0; } else { c.nextPC = ' + n64js.toString32(ctx.pc+4) +'; }\n'; code += fn; code += 'c.pc = c.nextPC;\n'; } else if (might_adjust_next_pc) { // If the branch op might manipulate nextPC, we need to ensure that it's set to the correct value code += ctx.genAssert('c.delayPC === 0', 'delay pc should be zero'); code += 'c.nextPC = ' + n64js.toString32(ctx.pc+4) + ';\n'; code += fn; code += 'c.pc = c.nextPC;\n'; } else { code += ctx.genAssert('c.delayPC === 0', 'delay pc should be zero'); code += fn; code += 'c.pc = ' + n64js.toString32(ctx.pc+4) + ';\n'; } return code; } // Memory access does not adjust branchTarget, but nextPC may be adjusted if they cause an exception. function generateMemoryAccessBoilerplate(fn,ctx) { var code = ''; var might_adjust_next_pc = true; code += generateStandardPCUpdate(fn, ctx, might_adjust_next_pc); // Memory instructions never cause a branch delay code += ctx.genAssert('c.delayPC === 0', 'delay pc should be zero'); ctx.needsDelayCheck = false; if (accurateCountUpdating) { code += 'c.control_signed[9] += 1;\n'; } // If bailOut is set, always return immediately n64js.assert(!ctx.bailOut, "Not expecting bailOut to be set for memory access"); code += 'if (c.stuffToDo) { return ' + ctx.fragment.opsCompiled + '; }\n'; code += 'if (c.pc !== ' + n64js.toString32(ctx.post_pc) + ') { return ' + ctx.fragment.opsCompiled + '; }\n'; return code; } // Branch ops explicitly manipulate nextPC rather than branchTarget. They also guarnatee that stuffToDo is not set. // might_adjust_next_pc is typically used by branch likely instructions. function generateBranchOpBoilerplate(fn,ctx, might_adjust_next_pc) { var code = ''; // We only need to check for off-trace branches var need_pc_test = ctx.needsDelayCheck || might_adjust_next_pc || ctx.post_pc !== ctx.pc+4; code += generateStandardPCUpdate(fn, ctx, might_adjust_next_pc); // Branch instructions can always set a branch delay ctx.needsDelayCheck = true; if (accurateCountUpdating) { code += 'c.control_signed[9] += 1;\n'; } code += ctx.genAssert('c.stuffToDo === 0', 'stuffToDo should be zero'); // If bailOut is set, always return immediately if (ctx.bailOut) { code += 'return ' + ctx.fragment.opsCompiled + ';\n'; } else { if (need_pc_test) { code += 'if (c.pc !== ' + n64js.toString32(ctx.post_pc) + ') { return ' + ctx.fragment.opsCompiled + '; }\n'; } else { code += '/* skipping pc test */\n'; } } return code; } // Trivial ops can use this specialised handler which eliminates a lot of overhead. // Trivial ops are defined as those which: // Don't require cpu0.pc to be set correctly (required by branches, stuff that can throw exceptions for instance) // Don't set cpu0.stuffToDo // Don't set branchTarget // Don't manipulate nextPC (e.g. ERET, cop1 unusable, likely instructions) function generateTrivialOpBoilerplate(fn,ctx) { var code = ''; // NB: trivial functions don't rely on pc being set up, so we perform the op before updating the pc. code += fn; ctx.isTrivial = true; if (accurateCountUpdating) { code += 'c.control_signed[9] += 1;\n'; } // NB: do delay handler after executing op, so we can set pc directly if (ctx.needsDelayCheck) { code += 'if (c.delayPC) { c.pc = c.delayPC; c.delayPC = 0; } else { c.pc = ' + n64js.toString32(ctx.pc+4) + '; }\n'; // Might happen: delay op from previous instruction takes effect code += 'if (c.pc !== ' + n64js.toString32(ctx.post_pc) + ') { return ' + ctx.fragment.opsCompiled + '; }\n'; } else { code += ctx.genAssert('c.delayPC === 0', 'delay pc should be zero'); // We can avoid off-branch checks in this case. if (ctx.post_pc !== ctx.pc+4) { n64js.assert("post_pc should always be pc+4 for trival ops?"); code += 'c.pc = ' + n64js.toString32(ctx.pc+4) + ';\n'; code += 'if (c.pc !== ' + n64js.toString32(ctx.post_pc) + ') { return ' + ctx.fragment.opsCompiled + '; }\n'; } else { //code += 'c.pc = ' + n64js.toString32(ctx.pc+4) + ';\n'; code += '/* delaying pc update */\n'; ctx.delayedPCUpdate = ctx.pc+4; } } // Trivial instructions never cause a branch delay code += ctx.genAssert('c.delayPC === 0', 'delay pc should be zero'); ctx.needsDelayCheck = false; // Trivial instructions never cause stuffToDo to be set code += ctx.genAssert('c.stuffToDo === 0', 'stuffToDo should be zero'); return code; } function generateNOPBoilerplate(comment, ctx) { return generateTrivialOpBoilerplate(comment + '\n',ctx); } }(window.n64js = window.n64js || {}));
"use strict"; var helpers = require("../../helpers/helpers"); exports["Pacific/Rarotonga"] = { "guess:by:offset" : helpers.makeTestGuess("Pacific/Rarotonga", { offset: true, expect: "Pacific/Honolulu" }), "guess:by:abbr" : helpers.makeTestGuess("Pacific/Rarotonga", { abbr: true, expect: "Pacific/Honolulu" }), "1978" : helpers.makeTestYear("Pacific/Rarotonga", [ ["1978-11-12T10:29:59+00:00", "23:59:59", "-1030", 630], ["1978-11-12T10:30:00+00:00", "01:00:00", "-0930", 570] ]), "1979" : helpers.makeTestYear("Pacific/Rarotonga", [ ["1979-03-04T09:29:59+00:00", "23:59:59", "-0930", 570], ["1979-03-04T09:30:00+00:00", "23:30:00", "-10", 600], ["1979-10-28T09:59:59+00:00", "23:59:59", "-10", 600], ["1979-10-28T10:00:00+00:00", "00:30:00", "-0930", 570] ]), "1980" : helpers.makeTestYear("Pacific/Rarotonga", [ ["1980-03-02T09:29:59+00:00", "23:59:59", "-0930", 570], ["1980-03-02T09:30:00+00:00", "23:30:00", "-10", 600], ["1980-10-26T09:59:59+00:00", "23:59:59", "-10", 600], ["1980-10-26T10:00:00+00:00", "00:30:00", "-0930", 570] ]), "1981" : helpers.makeTestYear("Pacific/Rarotonga", [ ["1981-03-01T09:29:59+00:00", "23:59:59", "-0930", 570], ["1981-03-01T09:30:00+00:00", "23:30:00", "-10", 600], ["1981-10-25T09:59:59+00:00", "23:59:59", "-10", 600], ["1981-10-25T10:00:00+00:00", "00:30:00", "-0930", 570] ]), "1982" : helpers.makeTestYear("Pacific/Rarotonga", [ ["1982-03-07T09:29:59+00:00", "23:59:59", "-0930", 570], ["1982-03-07T09:30:00+00:00", "23:30:00", "-10", 600], ["1982-10-31T09:59:59+00:00", "23:59:59", "-10", 600], ["1982-10-31T10:00:00+00:00", "00:30:00", "-0930", 570] ]), "1983" : helpers.makeTestYear("Pacific/Rarotonga", [ ["1983-03-06T09:29:59+00:00", "23:59:59", "-0930", 570], ["1983-03-06T09:30:00+00:00", "23:30:00", "-10", 600], ["1983-10-30T09:59:59+00:00", "23:59:59", "-10", 600], ["1983-10-30T10:00:00+00:00", "00:30:00", "-0930", 570] ]), "1984" : helpers.makeTestYear("Pacific/Rarotonga", [ ["1984-03-04T09:29:59+00:00", "23:59:59", "-0930", 570], ["1984-03-04T09:30:00+00:00", "23:30:00", "-10", 600], ["1984-10-28T09:59:59+00:00", "23:59:59", "-10", 600], ["1984-10-28T10:00:00+00:00", "00:30:00", "-0930", 570] ]), "1985" : helpers.makeTestYear("Pacific/Rarotonga", [ ["1985-03-03T09:29:59+00:00", "23:59:59", "-0930", 570], ["1985-03-03T09:30:00+00:00", "23:30:00", "-10", 600], ["1985-10-27T09:59:59+00:00", "23:59:59", "-10", 600], ["1985-10-27T10:00:00+00:00", "00:30:00", "-0930", 570] ]), "1986" : helpers.makeTestYear("Pacific/Rarotonga", [ ["1986-03-02T09:29:59+00:00", "23:59:59", "-0930", 570], ["1986-03-02T09:30:00+00:00", "23:30:00", "-10", 600], ["1986-10-26T09:59:59+00:00", "23:59:59", "-10", 600], ["1986-10-26T10:00:00+00:00", "00:30:00", "-0930", 570] ]), "1987" : helpers.makeTestYear("Pacific/Rarotonga", [ ["1987-03-01T09:29:59+00:00", "23:59:59", "-0930", 570], ["1987-03-01T09:30:00+00:00", "23:30:00", "-10", 600], ["1987-10-25T09:59:59+00:00", "23:59:59", "-10", 600], ["1987-10-25T10:00:00+00:00", "00:30:00", "-0930", 570] ]), "1988" : helpers.makeTestYear("Pacific/Rarotonga", [ ["1988-03-06T09:29:59+00:00", "23:59:59", "-0930", 570], ["1988-03-06T09:30:00+00:00", "23:30:00", "-10", 600], ["1988-10-30T09:59:59+00:00", "23:59:59", "-10", 600], ["1988-10-30T10:00:00+00:00", "00:30:00", "-0930", 570] ]), "1989" : helpers.makeTestYear("Pacific/Rarotonga", [ ["1989-03-05T09:29:59+00:00", "23:59:59", "-0930", 570], ["1989-03-05T09:30:00+00:00", "23:30:00", "-10", 600], ["1989-10-29T09:59:59+00:00", "23:59:59", "-10", 600], ["1989-10-29T10:00:00+00:00", "00:30:00", "-0930", 570] ]), "1990" : helpers.makeTestYear("Pacific/Rarotonga", [ ["1990-03-04T09:29:59+00:00", "23:59:59", "-0930", 570], ["1990-03-04T09:30:00+00:00", "23:30:00", "-10", 600], ["1990-10-28T09:59:59+00:00", "23:59:59", "-10", 600], ["1990-10-28T10:00:00+00:00", "00:30:00", "-0930", 570] ]), "1991" : helpers.makeTestYear("Pacific/Rarotonga", [ ["1991-03-03T09:29:59+00:00", "23:59:59", "-0930", 570], ["1991-03-03T09:30:00+00:00", "23:30:00", "-10", 600] ]) };
import { moduleForComponent, test } from 'ember-qunit'; import hbs from 'htmlbars-inline-precompile'; import Ember from 'ember'; import wait from 'ember-test-helpers/wait'; const { Service, RSVP, Object:EmberObject } = Ember; const { resolve } = RSVP; moduleForComponent('leadership-search', 'Integration | Component | leadership search', { integration: true }); test('it renders', function(assert) { this.set('nothing', parseInt); this.set('existingUsers', []); this.render(hbs`{{leadership-search existingUsers=existingUsers selectUser=(action nothing)}}`); const search = 'input[type="search"]'; assert.equal(this.$(search).length, 1); }); test('less than 3 charecters triggers warning', function(assert) { this.set('nothing', parseInt); this.set('existingUsers', []); this.render(hbs`{{leadership-search existingUsers=existingUsers selectUser=(action nothing)}}`); const search = 'input[type="search"]'; const results = 'ul'; this.$(search).val('ab').trigger('keyup'); return wait().then(()=>{ assert.equal(this.$(results).text().trim(), 'keep typing...'); }); }); test('input triggers search', function(assert) { let storeMock = Service.extend({ query(what, {q, limit}){ assert.equal('user', what); assert.equal(100, limit); assert.equal('search words', q); return resolve([EmberObject.create({fullName: 'test person', email: 'testemail'})]); } }); this.register('service:store', storeMock); this.set('nothing', parseInt); this.set('existingUsers', []); this.render(hbs`{{leadership-search existingUsers=existingUsers selectUser=(action nothing)}}`); const search = 'input[type="search"]'; const results = 'ul li'; const resultsCount = `${results}:eq(0)`; const firstResult = `${results}:eq(1)`; this.$(search).val('search words').trigger('keyup'); return wait().then(()=>{ assert.equal(this.$(resultsCount).text().trim(), '1 result'); assert.equal(this.$(firstResult).text().replace(/[\t\n\s]+/g, ""), 'testpersontestemail'); }); }); test('no results displays messages', function(assert) { let storeMock = Service.extend({ query(what, {q, limit}){ assert.equal('user', what); assert.equal(100, limit); assert.equal('search words', q); return resolve([]); } }); this.register('service:store', storeMock); this.set('nothing', parseInt); this.set('existingUsers', []); this.render(hbs`{{leadership-search existingUsers=existingUsers selectUser=(action nothing)}}`); const search = 'input[type="search"]'; const results = 'ul li'; const resultsCount = `${results}:eq(0)`; this.$(search).val('search words').trigger('keyup'); return wait().then(()=>{ assert.equal(this.$(resultsCount).text().trim(), 'no results'); }); }); test('click user fires add user', function(assert) { let user1 = EmberObject.create({ fullName: 'test person', email: 'testemail' }); let storeMock = Service.extend({ query(){ return resolve([user1]); } }); this.register('service:store', storeMock); this.set('select', user => { assert.equal(user1, user); }); this.set('existingUsers', []); this.render(hbs`{{leadership-search existingUsers=existingUsers selectUser=(action select)}}`); const search = 'input[type="search"]'; const results = 'ul li'; const firstResult = `${results}:eq(1)`; this.$(search).val('test').trigger('keyup'); return wait().then(()=>{ assert.equal(this.$(firstResult).text().replace(/[\t\n\s]+/g, ""), 'testpersontestemail'); this.$(firstResult).click(); }); }); test('can not add users twice', function(assert) { assert.expect(6); let user1 = EmberObject.create({ id: 1, fullName: 'test person', email: 'testemail' }); let user2 = EmberObject.create({ id: 2, fullName: 'test person2', email: 'testemail2' }); let storeMock = Service.extend({ query(){ return resolve([user1, user2]); } }); this.register('service:store', storeMock); this.set('select', (user) => { assert.equal(user, user2, 'only user2 should be sent here'); }); this.set('existingUsers', [user1]); this.render(hbs`{{leadership-search existingUsers=existingUsers selectUser=(action select)}}`); const search = 'input[type="search"]'; const results = 'ul li'; const resultsCount = `${results}:eq(0)`; const firstResult = `${results}:eq(1)`; const secondResult = `${results}:eq(2)`; this.$(search).val('test').trigger('keyup'); return wait().then(()=>{ assert.equal(this.$(resultsCount).text().trim(), '2 results'); assert.equal(this.$(firstResult).text().replace(/[\t\n\s]+/g, ""), 'testpersontestemail'); assert.notOk(this.$(firstResult).hasClass('clickable')); assert.equal(this.$(secondResult).text().replace(/[\t\n\s]+/g, ""), 'testperson2testemail2'); assert.ok(this.$(secondResult).hasClass('clickable')); this.$(firstResult).click(); this.$(secondResult).click(); }); });
'use strict'; var React = require('react'); var SvgIcon = require('../../svg-icon'); var ImageCrop169 = React.createClass({ displayName: 'ImageCrop169', render: function render() { return React.createElement( SvgIcon, this.props, React.createElement('path', { d: 'M19 6H5c-1.1 0-2 .9-2 2v8c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2zm0 10H5V8h14v8z' }) ); } }); module.exports = ImageCrop169;
var makeIterator = require('../function/makeIterator_'); /** * Array some */ /** * Description * @method some * @param {} arr * @param {} callback * @param {} thisObj * @return result */ function some(arr, callback, thisObj) { callback = makeIterator(callback, thisObj); var result = false; if (arr == null) { return result; } var i = -1, len = arr.length; while (++i < len) { // we iterate over sparse items since there is no way to make it // work properly on IE 7-8. see #64 if ( callback(arr[i], i, arr) ) { result = true; break; } } return result; } module.exports = some;
//________________________________________________________________________________________________ // statevector.js //todo: update description // // cStateVector object - This is a generic container useful for ... // Every item added to the queue is time stamped for time series analyis, playback, etc. // There are optional functions onAdd[1,2,..]() that the user can define that will be //cp-not right!!!!! // called each time imageUpdate() is called. // // Note that the debug statements are commented outin some functions to reduce vpRefresh time. //cp-mention that this saves mouse & moves only > a fixed amount... // // history // 1106 cperz created // _______________________________________end_Rel 12.1 __________________________________________ // // 131119 cperz renamed imageUpdate to viewUpdate to avoid confusion with public interface // // todo // - could make queue trim on time instead of size (with size max still...) // - add methods for getlast direction, mouse position, etc.... // much more straightforward, no need to understand internal storage of this object! //________________________________________________________________________________________________ // state types: // image: set by viewUpdate() // mouse: set by mouseUpdate() // us.eStateTypes = { image: 0, mouse: 1 }; //________________________________________________________________________________________________ function cStateVector(vpObj) { var thisImg = vpObj; // the viewport object - the parent var self = this; // local var for closure var imageId_ = thisImg.getImageId(); var uScopeIdx_ = thisImg.getImageIdx(); var imageSizeMax; var mouseSizeMax; var idxPrevNext = -1; // index in image queue var idxPrevNextStart = -1; // index of starting position of prev/next sequence var d = new Date(); var dTime = 1. / 10.; // get the start time and scale it from millisecs to 1/100th sec var startTime = d.getTime() * dTime; var imageQueue = []; // the image state vector queue var mouseQueue = []; // the mouse state vector queue var cb_imageState = []; // array of image state function callbacks var cb_mouseState = []; // array of mouse state function callbacks var stateTypeView = us.eStateTypes.view; // for quick access var stateTypeMouse = us.eStateTypes.mouse; var minMoveMagnitude_ = 12; // the minimum magnitude in pixels of movement to record var slopeLimit = 4; var slopeLimtInv = 0.25; // 1. / slopeLimit var kSVQUEUE_VIEW_SIZE = 500; // number of view states to retain in state vector queue // this throttles the responsivity of the state vector! //............................................ _sinceStartTime local // This function is used for all time stamps in this object. // It converts absolute time from "new Date().getTime()" to a differntial in seconds // (to the 3rd decimal place - milliseconds) since the start time of this object. var _sinceStartTime = function (time) { return (time * dTime - startTime).toFixed(3); }; //............................................ _setSize local // This function sets the image and mouse queue maximum sizes. var _setSize = function (newSize) { var newMax = (newSize) ? newSize : 200; // maximum size for queue if (newMax < 1 || newMax > 2000) // sanity check on the queue size return; imageSizeMax = newMax; mouseSizeMax = 100; // parseInt(newMax / 2); // limit the mouse queue to half the size while (imageQueue.length > imageSizeMax) imageQueue.shift(); while (mouseQueue.length > mouseSizeMax) mouseQueue.shift(); }; //............................................ registerForEvent // This function adds a subscription to state change event. // The imageUpdate() and mouseUpdate() functions call these subscribers. // this.registerForEvent = function (functionString, stateType) { if (typeof functionString === "function") { if (isUnDefined(stateType)) stateType = us.eStateTypes.view; if (us.DBGSTATEVECTOR) thisImg.log("statevector: add callback: (" + functionString + ") Type: " + stateType); if (stateType === us.eStateTypes.view) cb_imageState.push(functionString); else cb_mouseState.push(functionString); } }; //............................................ unRegisterForEvent // This function removes a subscription to state change event. this.unRegisterForEvent = function (functionString) { // find a string match in the call back arrays and remove it. if (typeof functionString === "function") { functionString = functionString.toString(); // search image state queue for the event for (var c = 0, len = cb_imageState.length; c < len; c++) { var str = cb_imageState[c].toString(); if (str.indexOf(functionString) !== -1) { if (us.DBGSTATEVECTOR) thisImg.log("statevector: remove image callback: (" + functionString + ")"); cb_imageState.remove(c); return; } } // search mouse state queue for the event for (var c = 0, len = cb_mouseState.length; c < len; c++) { var str = cb_mouseState[c].toString(); if (str.indexOf(functionString) !== -1) { if (us.DBGSTATEVECTOR) thisImg.log("statevector: remove mouse callback: (" + functionString + ")"); cb_mouseState.remove(c); return; } } } }; //............................................ viewUpdate // This function adds an image state vector to its queue. // If the state description is a move, the city block distance between this position and the previous state on the queue // must be greater than a threshold. Otherwise the state is not added to the queue. // // An Image State Vector is a definition of the view state plus: // time stamp // + desc {"all", "move", "zoom", "focus", "dims", } // + viewport's vpView contents {left, top, width, height, zoom, focus, angleDeg} // + dir {"none", "wholeview", "north", "east", "west", "south", northwest, ...} //cp-fill in and define // + magpx { magnitude of move in pixels } // // parameters // state: is viewport's vpView contents // changeDesc: {"all", "move", "zoom", "focus", "dims", "rotate"} // // todo: // - I'd like to know if there are listenters, perhaps I don't do all this if not var lastViewState_ = new cPoint(0,0); this.viewUpdate = function (state, changeDesc) { var zoom = state.zoom; var x = state.left; var y = state.top; //debug-only thisImg.log("image state: X,Y,ZOOM: " + x + "," + y + "," + zoom); if (imageQueue.length == imageSizeMax) // maintain queue size imageQueue.shift(); // remove the top element of the array to make room at the bottom var magpx = 0; if (changeDesc == "move") { // throttle the responsivity to motion var magpx = Math.abs(state.left - lastViewState_.x) + Math.abs(state.top - lastViewState_.y); // city-street magnitude of move in pixels if (magpx < minMoveMagnitude_) { //dbg-only if (us.DBGSTATEVECTOREX) thisImg.log("cStateVector: viewUpdate: magnitude of move (" + magpx + ") < minimum (" + minMoveMagnitude_ + ")"); return; } //consoleWrite("cur state: " + state.left + "," + state.top + " last state: " + lastViewState_.toString() + " magpx: " + magpx); } var sv = []; // add info to new state vector sv.time = _sinceStartTime(new Date().getTime()); // add time stamp sv.desc = changeDesc; // add input change description sv.state = jQuery.extend(true, {}, state); // add input view state, must clone state first if (changeDesc == "move") // sv.magpx = magpx; // add magnitude of move (units are pixels) _computeDir(sv); // add computed direction 'dir' imageQueue.push(sv); // add state vector to the queue lastViewState_.set(state.left, state.top); // save last queue view position //if (us.DBGSTATEVECTOR) sv.magpx ? thisImg.log("cStateVector: viewUpdate: dir: " + sv.dir + " magpx: " + sv.magpx) // : thisImg.log("cStateVector: viewUpdate: desc: " + sv.desc); for (var c = 0, len = cb_imageState.length; c < len; c++) // execute the callbacks to signal a SV update event cb_imageState[c](); triggerUScopeEvent(us.evVIEWCHANGE, { // fire event that the view has changed imageId: imageId_, uScopeIdx: uScopeIdx_, desc: sv.desc, x: thisImg.getViewCenterX(), y: thisImg.getViewCenterY(), zoom: zoom, angleDeg: state.angleDeg }); }; //............................................ mouseUpdate // This function adds an mouse state vector to its queue. // If the state description is a mousemove, the city block distance between this position and the previous state on the queue // must be greater than a threshold. Otherwise the state is not added to the queue. // // A Mouse State Vector is a definition of the mouse state: // time stamp // + desc {"mousemove", "mousedown", ...} // + state cPoint {x,y} of mouse position in base image coordinates // // parameters // state: cPoint {x,y} of mouse position in base image coordinates // eventDesc: {"mousemove", "mousedown",} // bForce: boolean, if true the function does not exit when there are no listeners // so us.evMOUSECHANGE event is fired if mouse move is sufficient var lastMouseState_ = new cPoint(0, 0); this.mouseUpdate = function (state, eventDesc, bForce) { if (bForce == false && cb_mouseState.length == 0) // do not save state if no one is subscribed return; //dbg-only if (us.DBGSTATEVECTOREX) thisImg.log("cStateVector: mouseUpdate: " + state.toString() + " desc: " + eventDesc); if (mouseQueue.length == mouseSizeMax) // maintain queue size mouseQueue.shift(); // remove the top element of the array to make room at the bottom var magpx = 0; if (eventDesc == "mousemove") { if (lastMouseState_) { // throttle the responsivity to motion magpx = lastMouseState_.cityBlockDistance(state); //consoleWrite("cur state: " + state + " last state: " + lastMouseState_.toString() + " magpx: " + magpx); if (magpx < minMoveMagnitude_) { //dbg-only if (us.DBGSTATEVECTOREX) thisImg.log("cStateVector: mouseUpdate: magnitude of move (" + magpx + ") < minimum (" + minMoveMagnitude_ + ")"); return; } } } var sv = []; // add info to new state vector sv.time = _sinceStartTime(new Date().getTime()); // add time stamp sv.desc = eventDesc; // add input change description sv.state = jQuery.extend(true, {}, state); // add input view state, must clone state first mouseQueue.push(sv); // add state vector to the queue lastMouseState_.setPoint(sv.state); // save last queue mouse position //dbg-only if (us.DBGSTATEVECTOREX) thisImg.log("cStateVector: mouseUpdate: desc: " + sv.desc + sv.state.toString() + " magnitude: " + magpx); for (var c = 0, len = cb_mouseState.length; c < len; c++) // execute the callbacks to signal a SV update event cb_mouseState[c](); triggerUScopeEvent(us.evMOUSECHANGE, { imageId: imageId_, uScopeIdx: uScopeIdx_, uScopeIdx: thisImg.getImageIdx(), x: state.x, y: state.y }); }; //............................................ getLastMousePosition // This function returns the last recorded mouse position or undefined if none have been recorded. this.getLastMousePosition = function () { return (mouseQueue.length > 0) ? mouseQueue[mouseQueue.length - 1].state : undefined; }; //............................................ getMouseEventsSince // This function returns an array in ascending order of the mouse events since a specified time. // The time stamp in the list of events is in this object's format - delta time since the start of the object scaled by dTime; // Optionally a specific type of mouse event can be selected. // A maximum number of returned events is enforced but can be overridden. // // parameters: // sinceTime required, time to start collecting the event, sinceTime = new Date().getTime() // eventDesc optional, return this mouse event type {"mousemove", "mousedown", ...} default is all // maxRtnSize optional, maximum number of mousestates to return, default is 100 this.getMouseEventsSince = function (sinceTime, eventDesc, maxRtnSize) { var rtnQueue = []; if (isUnDefined(sinceTime)) return rtnQueue; sinceTime = _sinceStartTime(sinceTime); // convert to same time format as used here in if (mouseQueue.length > 0) { eventDesc = (eventDesc) ? eventDesc : "all"; // set event filter maxRtnSize = (maxRtnSize) ? maxRtnSize + 1 : 101; // set limit of number of items returned var cnt = 0; var startIdx = mouseQueue.length; while (--startIdx > 0 && ++cnt < maxRtnSize) { if (mouseQueue[startIdx].time < sinceTime) // am I now before my time? break; if (eventDesc == "all" || eventDesc == mouseQueue[startIdx].desc) rtnQueue.unshift(mouseQueue[startIdx]); // add to the begining of the array for ascending order } } return rtnQueue; }; //............................................ getPrevNext this.getPrevNext = function (incr) {//incr s/b +/-1 if (imageQueue.length < 1) return undefined; var rtnSV = undefined; if (idxPrevNext == -1) { idxPrevNext = imageQueue.length - 1 + incr; idxPrevNextStart = imageQueue.length - 1; } else { idxPrevNext = idxPrevNext + incr; if (idxPrevNext > idxPrevNextStart) idxPrevNext = idxPrevNextStart; // don't move past starting position } /////thisImg.log("getPrevNext: idxPrevNext: " + idxPrevNext); if (idxPrevNext > 0 && idxPrevNext < imageQueue.length) rtnSV = imageQueue[idxPrevNext]; if (idxPrevNext == idxPrevNextStart) idxPrevNext = -1; //reset return rtnSV; }; //............................................ getLastDirection // This function returns the last recorded image direction or undefined if none have been recorded. this.getLastDirection = function () { return (imageQueue.length > 0) ? imageQueue[imageQueue.length - 1].dir : undefined; }; //............................................ getLastDescription // This function returns the last recorded image description or undefined if none have been recorded. this.getLastDescription = function () { return (imageQueue.length > 0) ? imageQueue[imageQueue.length - 1].desc : undefined; }; //............................................ getLast // This function returns the last state vector for the specified state type. this.getLast = function (stateType) {//cp-todo rename to get LastState if (isUnDefined(stateType)) stateType = us.eStateTypes.view; if (stateType === us.eStateTypes.view) return (imageQueue.length > 0) ? imageQueue[imageQueue.length - 1] : undefined; else return (mouseQueue.length > 0) ? mouseQueue[mouseQueue.length - 1] : undefined; }; //............................................ reportLast // This function returns a string containing the last state vector report for the specified state type. this.reportLast = function (stateType) { var str = ""; var queue = (stateType === us.eStateTypes.view) ? imageQueue : mouseQueue; if (queue.length > 0) { str = (stateType === us.eStateTypes.view) ? "LastViewState: " : "LastMouseState: "; var state = queue[queue.length - 1]; str += this.report(state, stateType); } return str; }; //............................................ report // This function converts the passed state into a csv string. this.report = function (stateVector, stateType) { var str = ""; if (isUnDefined(stateVector)) return str; if (isUnDefined(stateType)) stateType = us.eStateTypes.view; if (stateType === us.eStateTypes.view) { var zoom = stateVector.state.zoom; var isFit = thisImg.isFitZoom(zoom); var mag = (isFit) ? "Fit" : thisImg.convertToMag(zoom); zoom = (isFit) ? "Fit" : zoom; // note that this format is copied into the performance test sequence in cPerformanceTest str = parseInt(stateVector.time) + ', \"' + stateVector.desc + '\", ' + stateVector.state.left + ", " + stateVector.state.top + ", " + zoom + ", " + mag; //note: stateVector.dir & stateVector.magpx not reported (yet?) } else { var sv = mouseQueue[mouseQueue.length - 1]; str = stateVector.desc; str += stateVector.state.toString(); if (stateVector.magpx) str += " magnitude_px:" + stateVector.magpx; } return str; }; this.reportTitle = function (stateType) { var str = ""; if (isUnDefined(stateType)) stateType = us.eStateTypes.view; str = "Filename: " + thisImg.getFileName() + " Width: " + thisImg.getImageWidth() + " Height:" + thisImg.getImageHeight() + "\n"; if (stateType === us.eStateTypes.view) { str += "time, desc, centerX, centerY, zoom, mag\n"; //note: stateVector.dir & stateVector.magpx not reported (yet?) } else { // not implemented } return str; }; //............................................ reportAll this.reportAll = function (stateType, normalize) { var str = this.reportTitle(stateType); if (isUnDefined(stateType)) stateType = us.eStateTypes.view; if (isUnDefined(normalize)) normalize = false; var queue = (stateType === us.eStateTypes.view) ? imageQueue : mouseQueue; if (queue.length > 0) { for (var s = 0, len = queue.length; s < len; s++) { var svRef = queue[s]; // get state vector at index s var sv = new cloneObject(svRef); // clone the state vector so I can modify it var x = sv.state.left; // state reports top left corner, convert to center position var y = sv.state.top; x = parseInt(x + thisImg.getViewWidth() / 2); y = parseInt(y + thisImg.getViewHeight() / 2); if (normalize == true) { // if normalize, x and y are proportion of the image dims x = (x / thisImg.getImageWidth()).toFixed(5); y = (y / thisImg.getImageHeight()).toFixed(5); } sv.state.left = x; sv.state.top = y; str += (this.report(sv, stateType) + "\n"); } } return str; }; //............................................ _computeDir // This function evaluates the most recent state change and concludes the view motion direction. // It then adds that direction to the passed array. var _computeDir = function (ioSV) { ioSV.dir = "none"; if (imageQueue.length == 0 || ioSV.desc == "all" || ioSV.desc != "move") return; var lastState = self.getLast(stateTypeView).state; var dx = ioSV.state.left - lastState.left; var dy = ioSV.state.top - lastState.top; if (Math.abs(dx) > lastState.width * 2 || Math.abs(dy) > lastState.height * 2 // if moved N views //cp-revisit factor of 2 || ioSV.desc == "dim") { // or resized view dimensions ioSV.dir = "wholeview"; // then indicate whole view change return; } var dr = slopeLimit + 1; // slope of motion if (dy != 0) dr = dx / dy; if (us.DBGSTATEVECTOREX) ioSV.magpx ? thisImg.log("cStateVector: computeDir: " + dr.toFixed(2) + " dx dy:" + dx + " " + dy + " magpx:" + ioSV.magpx) : thisImg.log("cStateVector: computeDir: " + dr.toFixed(2) + " dx dy:" + dx + " " + dy); var dir = "none"; // default direction of move if (Math.abs(dr) > slopeLimit) { // if horizontal motion if (dx < 0) // if moving left dir = "east"; else dir = "west"; } else if (Math.abs(dr) < slopeLimtInv) { // if vertical motion if (dy < 0) // if moving up dir = "south"; else dir = "north"; } else if (dx < 0) { // diagnal motion, moving left if (dy < 0) // if moving up, too dir = "southeast"; else dir = "northeast"; } else { // diagnal motion, moving right if (dy < 0) // if moving up, too dir = "southwest"; else dir = "northwest"; } ioSV.dir = dir; // add direction to return ioSV }; //............................................................................................ // construction _setSize(kSVQUEUE_VIEW_SIZE); // save the max queue size allowed }; //________________________________________________________________________________________________
export function seed(db) { const table = 'states' let id = 1 return Promise.all([ db(table).del(), // `id` is autoincrement and not generally necessary to explicitly define // However, for the `company_state` seed, having a consistent `id` to // reference makes things easier. db(table).insert({ id: id++, abbreviation: 'AL', name: 'Alabama', country_id: 1 }), db(table).insert({ id: id++, abbreviation: 'AK', name: 'Alaska', country_id: 1 }), db(table).insert({ id: id++, abbreviation: 'AZ', name: 'Arizona', country_id: 1 }), db(table).insert({ id: id++, abbreviation: 'AR', name: 'Arkansas', country_id: 1 }), db(table).insert({ id: id++, abbreviation: 'CA', name: 'California', country_id: 1 }), db(table).insert({ id: id++, abbreviation: 'CO', name: 'Colorado', country_id: 1 }), db(table).insert({ id: id++, abbreviation: 'CT', name: 'Connecticut', country_id: 1 }), db(table).insert({ id: id++, abbreviation: 'DE', name: 'Delaware', country_id: 1 }), db(table).insert({ id: id++, abbreviation: 'FL', name: 'Florida', country_id: 1 }), db(table).insert({ id: id++, abbreviation: 'GA', name: 'Georgia', country_id: 1 }), db(table).insert({ id: id++, abbreviation: 'HI', name: 'Hawaii', country_id: 1 }), db(table).insert({ id: id++, abbreviation: 'ID', name: 'Idaho', country_id: 1 }), db(table).insert({ id: id++, abbreviation: 'IL', name: 'Illinois', country_id: 1 }), db(table).insert({ id: id++, abbreviation: 'IN', name: 'Indiana', country_id: 1 }), db(table).insert({ id: id++, abbreviation: 'IA', name: 'Iowa', country_id: 1 }), db(table).insert({ id: id++, abbreviation: 'KS', name: 'Kansas', country_id: 1 }), db(table).insert({ id: id++, abbreviation: 'KY', name: 'Kentucky', country_id: 1 }), db(table).insert({ id: id++, abbreviation: 'LA', name: 'Louisiana', country_id: 1 }), db(table).insert({ id: id++, abbreviation: 'ME', name: 'Maine', country_id: 1 }), db(table).insert({ id: id++, abbreviation: 'MD', name: 'Maryland', country_id: 1 }), db(table).insert({ id: id++, abbreviation: 'MA', name: 'Massachusetts', country_id: 1 }), db(table).insert({ id: id++, abbreviation: 'MI', name: 'Michigan', country_id: 1 }), db(table).insert({ id: id++, abbreviation: 'MN', name: 'Minnesota', country_id: 1 }), db(table).insert({ id: id++, abbreviation: 'MS', name: 'Mississippi', country_id: 1 }), db(table).insert({ id: id++, abbreviation: 'MO', name: 'Missouri', country_id: 1 }), db(table).insert({ id: id++, abbreviation: 'MT', name: 'Montana', country_id: 1 }), db(table).insert({ id: id++, abbreviation: 'NE', name: 'Nebraska', country_id: 1 }), db(table).insert({ id: id++, abbreviation: 'NV', name: 'Nevada', country_id: 1 }), db(table).insert({ id: id++, abbreviation: 'NH', name: 'New Hampshire', country_id: 1 }), db(table).insert({ id: id++, abbreviation: 'NJ', name: 'New Jersey', country_id: 1 }), db(table).insert({ id: id++, abbreviation: 'NM', name: 'New Mexico', country_id: 1 }), db(table).insert({ id: id++, abbreviation: 'NY', name: 'New York', country_id: 1 }), db(table).insert({ id: id++, abbreviation: 'NC', name: 'North Carolina', country_id: 1 }), db(table).insert({ id: id++, abbreviation: 'ND', name: 'North Dakota', country_id: 1 }), db(table).insert({ id: id++, abbreviation: 'OH', name: 'Ohio', country_id: 1 }), db(table).insert({ id: id++, abbreviation: 'OK', name: 'Oklahoma', country_id: 1 }), db(table).insert({ id: id++, abbreviation: 'OR', name: 'Oregon', country_id: 1 }), db(table).insert({ id: id++, abbreviation: 'PA', name: 'Pennsylvania', country_id: 1 }), db(table).insert({ id: id++, abbreviation: 'RI', name: 'Rhode Island', country_id: 1 }), db(table).insert({ id: id++, abbreviation: 'SC', name: 'South Carolina', country_id: 1 }), db(table).insert({ id: id++, abbreviation: 'SD', name: 'South Dakota', country_id: 1 }), db(table).insert({ id: id++, abbreviation: 'TN', name: 'Tennessee', country_id: 1 }), db(table).insert({ id: id++, abbreviation: 'TX', name: 'Texas', country_id: 1 }), db(table).insert({ id: id++, abbreviation: 'UT', name: 'Utah', country_id: 1 }), db(table).insert({ id: id++, abbreviation: 'VT', name: 'Vermont', country_id: 1 }), db(table).insert({ id: id++, abbreviation: 'VA', name: 'Virginia', country_id: 1 }), db(table).insert({ id: id++, abbreviation: 'WA', name: 'Washington', country_id: 1 }), db(table).insert({ id: id++, abbreviation: 'WV', name: 'West Virginia', country_id: 1 }), db(table).insert({ id: id++, abbreviation: 'WI', name: 'Wisconsin', country_id: 1 }), db(table).insert({ id: id++, abbreviation: 'WY', name: 'Wyoming', country_id: 1 }), db(table).insert({ id: id++, abbreviation: 'DC', name: 'Washington DC', country_id: 1 }), ]) }
import { put, takeEvery } from 'redux-saga/effects'; import { push } from 'react-router-redux'; import { CRUD_CREATE_FAILURE, CRUD_CREATE_SUCCESS, CRUD_DELETE_FAILURE, CRUD_DELETE_SUCCESS, CRUD_GET_LIST_FAILURE, CRUD_GET_MANY_FAILURE, CRUD_GET_MANY_REFERENCE_FAILURE, CRUD_GET_ONE_FAILURE, CRUD_UPDATE_FAILURE, CRUD_UPDATE_SUCCESS, } from '../../actions/dataActions'; import { showNotification } from '../../actions/notificationActions'; import linkToRecord from '../../util/linkToRecord'; /** * Side effects for fetch responses * * Mostly redirects and notifications */ function* handleResponse({ type, requestPayload, error, payload }) { switch (type) { case CRUD_UPDATE_SUCCESS: return requestPayload.redirect ? yield [ put(showNotification('aor.notification.updated')), put(push(requestPayload.basePath)), ] : yield [put(showNotification('aor.notification.updated'))]; case CRUD_CREATE_SUCCESS: return requestPayload.redirect ? yield [ put(showNotification('aor.notification.created')), put(push(linkToRecord(requestPayload.basePath, payload.data.id))), ] : yield [put(showNotification('aor.notification.created'))]; case CRUD_DELETE_SUCCESS: return requestPayload.redirect ? yield [ put(showNotification('aor.notification.deleted')), put(push(requestPayload.basePath)), ] : yield [put(showNotification('aor.notification.deleted'))]; case CRUD_GET_ONE_FAILURE: return requestPayload.basePath ? yield [ put(showNotification('aor.notification.item_doesnt_exist', 'warning')), put(push(requestPayload.basePath)), ] : yield []; case CRUD_GET_LIST_FAILURE: case CRUD_GET_MANY_FAILURE: case CRUD_GET_MANY_REFERENCE_FAILURE: case CRUD_CREATE_FAILURE: case CRUD_UPDATE_FAILURE: case CRUD_DELETE_FAILURE: { console.error(error); const errorMessage = typeof error === 'string' ? error : (error.message || 'aor.notification.http_error'); return yield [ put(showNotification(errorMessage, 'warning')), ]; } default: return yield []; } } export default function* () { yield takeEvery(action => action.meta && action.meta.fetchResponse, handleResponse); }
#!/usr/bin/env node 'use strict'; // Pseudo-constants: var DEFAULT_OPTIONS = { "format": "manifest" , "compactUrls": true , "includeErrors": false , "includeTypes": false }; // “Global” variables: var Nightmare = require("nightmare") , phantomjs = require("phantomjs-prebuilt") , pth = require("path") , u = require("url") , document , baseUrl , options , callback , found , failed , pending ; var dumpResult = function() { var result , i , j ; if ("manifest" === options.format) { result = ''; for (i in found) { if (options.compactUrls) result += found[i].compactUrl + '\n'; else result += i + '\n'; } if (options.includeErrors) { for (i in failed) { if (options.compactUrls) result += failed[i].compactUrl + '\n'; else result += i + '\n'; } } if (callback) { callback(result); } else { console.log(result); } } else if ("json" === options.format) { result = {ok: []}; for (i in found) { j = {}; if (options.compactUrls) j.url = found[i].compactUrl; else j.url = i; if (options.includeTypes) j.type = found[i].type; result.ok.push(j); } if (options.includeErrors) { result.error = []; for (i in failed) { j = {}; if (options.compactUrls) j.url = failed[i].compactUrl; else j.url = i; if (options.includeTypes) j.type = failed[i].type; result.error.push(j); } } if (callback) { callback(result); } else { console.log(JSON.stringify(result, null, 2)); } } else if ("plain" === options.format) { result = ''; for (i in found) { if (options.compactUrls) result += found[i].compactUrl + ' ok'; else result += i + ' ok'; if (options.includeTypes) result += ' ' + found[i].type; result += '\n'; } if (options.includeErrors) { for (i in failed) { if (options.compactUrls) result += failed[i].compactUrl + ' error'; else result += i + ' error'; if (options.includeTypes) result += ' ' + failed[i].type; result += '\n'; } } if (callback) { callback(result); } else { console.log(result); } } }; var getMetadata = function(res) { var compactUrl = u.parse(res.url).href.replace(baseUrl, '') , type = '[unknown]' ; if (res.status && 200 === res.status) { if (/text\/html?/i .test(res.contentType)) type = 'html'; else if (/text\/css/i .test(res.contentType)) type = 'css'; else if (/image\/\w+/i .test(res.contentType)) type = 'img'; else if (/(application|text)\/(javascript|js)/i.test(res.contentType)) type = 'js'; else type = 'js'; } return {compactUrl: compactUrl, type: type}; }; var processRequest = function(res) { pending ++; }; var processResult = function(res) { if (res && res.status && res.stage && 'end' === res.stage) { if (200 === res.status) { found[res.url] = getMetadata(res); pending --; } else if (404 === res.status) { failed[res.url] = getMetadata(res); pending --; } if (0 === pending) dumpResult(); } }; exports.run = function (url, opts, cb) { document = url; baseUrl = document.replace(/[^\/]*$/, ""); options = JSON.parse(JSON.stringify(DEFAULT_OPTIONS)); if (opts) { if (opts.hasOwnProperty("format")) options.format = opts.format; if (opts.hasOwnProperty("compactUrls")) options.compactUrls = opts.compactUrls; if (opts.hasOwnProperty("includeErrors")) options.includeErrors = opts.includeErrors; if (opts.hasOwnProperty("includeTypes")) options.includeTypes = opts.includeTypes; } callback = cb; found = {}; failed = {}; pending = 0; var nm = new Nightmare({ phantomPath: pth.dirname(phantomjs.path) + "/" }); nm.on("resourceRequested", processRequest); nm.on("resourceReceived", processResult); nm.on("resourceError", processResult); nm.goto(document); nm.run(); }; // running directly if (!module.parent) { var source = process.argv[2] , opts ; if (process.argv.length > 3) { opts = JSON.parse(process.argv[3]); } if (!source) console.error("Usage: echidna-manifester <PATH-or-URL> [OPTIONS-as-json]"); // if path is a file, make a URL from it if (!/^\w+:/.test(source)) source = "file://" + pth.join(process.cwd(), source); exports.run(source, opts); }
'use strict' const db = require('APP/db') const User = db.model('users') const {mustBeLoggedIn, forbidden,} = require('./auth.filters') module.exports = require('express').Router() .get('/', forbidden('only admins can list users'), (req, res, next) => User.findAll() .then(users => res.json(users)) .catch(next)) .post('/', (req, res, next) => User.create(req.body) .then(user => res.status(201).json(user)) .catch(next)) .get('/:id', mustBeLoggedIn, (req, res, next) => User.findById(req.params.id) .then(user => res.json(user)) .catch(next))
var React = require('react/addons'); var blacklist = require('blacklist'); var classNames = require('classnames'); module.exports = React.createClass({ displayName: 'FormLabel', propTypes: { className: React.PropTypes.string, htmlFor: React.PropTypes.string, id: React.PropTypes.string, style: React.PropTypes.object, verticalAlign: React.PropTypes.oneOf(['baseline', 'bottom', 'inherit', 'initial', 'middle', 'sub', 'super', 'text-bottom', 'text-top', 'top']) }, render() { // classes var className = classNames('form-label', this.props.className); // props var props = blacklist(this.props, 'htmlFor', 'id', 'className', 'style'); // style var style; if (this.props.verticalAlign) { style = { verticalAlign: this.props.verticalAlign }; } return ( <label className={className} htmlFor={this.props.htmlFor || this.props.id} style={style || this.props.style} {...props}> {this.props.children} </label> ); } });
'use strict'; require('../configfile').watch_files = false; var vm_harness = require('./fixtures/vm_harness'); var fs = require('fs'); var vm = require('vm'); var config = require('../config'); var path = require('path'); var util_hmailitem = require('./fixtures/util_hmailitem'); var queue_dir = path.resolve(__dirname + '/test-queue/'); var ensureTestQueueDirExists = function(done) { fs.exists(queue_dir, function (exists) { if (exists) { done(); } else { fs.mkdir(queue_dir, function (err) { if (err) { return done(err); } done(); }); } }); }; var removeTestQueueDir = function (done) { fs.exists(queue_dir, function (exists) { if (exists) { var files = fs.readdirSync(queue_dir); files.forEach(function(file,index){ var curPath = queue_dir + "/" + file; if (fs.lstatSync(curPath).isDirectory()) { // recurse return done(new Error('did not expect an sub folder here ("' + curPath + '")! cancel')); } }); files.forEach(function(file,index){ var curPath = queue_dir + "/" + file; fs.unlinkSync(curPath); }); done(); } else { done(); } }); }; exports.outbound_protocol_tests = { setUp : ensureTestQueueDirExists, tearDown : removeTestQueueDir, }; vm_harness.add_tests( path.join(__dirname, '/../outbound.js'), path.join(__dirname, 'outbound_protocol/'), exports.outbound_protocol_tests, { test_queue_dir: queue_dir, process: process } );
// flow-typed signature: 51fe58a87c9b5ce4a9e89ea80ffebcc3 // flow-typed version: <<STUB>>/babel-plugin-add-module-exports_v^0.2.1/flow_v0.39.0 /** * This is an autogenerated libdef stub for: * * 'babel-plugin-add-module-exports' * * Fill this stub out by replacing all the `any` types. * * Once filled out, we encourage you to share your work with the * community by sending a pull request to: * https://github.com/flowtype/flow-typed */ declare module 'babel-plugin-add-module-exports' { declare module.exports: any; } /** * We include stubs for each file inside this npm package in case you need to * require those files directly. Feel free to delete any files that aren't * needed. */ declare module 'babel-plugin-add-module-exports/changelog' { declare module.exports: any; } declare module 'babel-plugin-add-module-exports/lib/index' { declare module.exports: any; } // Filename aliases declare module 'babel-plugin-add-module-exports/changelog.js' { declare module.exports: $Exports<'babel-plugin-add-module-exports/changelog'>; } declare module 'babel-plugin-add-module-exports/lib/index.js' { declare module.exports: $Exports<'babel-plugin-add-module-exports/lib/index'>; }
var gulp = require('gulp'); var tingpng = require('gulp-tinypng'); gulp.task('default', function () { gulp.src('source/*.png') .pipe(tingpng('q3BNdXVPRfkwwful4l0Hlf1cb8KlhmUE')) .pipe(gulp.dest('destination')); });
export * from './MenuButton'; export * from './ScoreRecap.js';
/** * Module dependancies */ var express = require('express') , models = require('../../models'); var router = express.Router() , Applicant = models.applicant() , JobPosting = models.jobPosting(); var ObjectIdBase64Conv = require('../../util').ObjectIdBase64Conv , objectIdToBase64 = ObjectIdBase64Conv.objectIdToBase64 , base64ToObjectId = ObjectIdBase64Conv.base64ToObjectId; /** * Add job posting id to applicants bookmarks * @req id {String} encoded job posting id */ router.post('/add', function(req, res, next){ var applicantId = req.session.applicantUserId; // User can't save bookmark if they arn't logged in if (!applicantId){ var Err = new Error(); Err.status = 403; return next(Err); } var postId = req.body.id; // Response must have a post id if (!postId){ var Err = new Error(); Err.status = 400; return next(Err); } Applicant.findById(applicantId, function(err, applicant){ if (err) { return next(err); } if (!applicant){ var Err = new Error(); Err.status = 400; return next(err); } var decodedId = base64ToObjectId(postId); // Save bookmark applicant.addBookmark(decodedId, function(err){ // Database err, but we should make it seem // like its the users fault :P if(err){ return next(err); } res.status(200).end(); }); }); }); /** * Remove a job posting id from an applicants bookmarks * @req id {String} encoded job posting id */ router.post('/remove', function(req, res, next){ var applicantId = req.session.applicantUserId; // User can't remove a bookmark if they arn't logged in if (!applicantId){ var Err = new Error(); Err.status = 403; return next(Err); } var postId = req.body.id; // Response must have a post id if (!postId){ var Err = new Error(); Err.status = 400; return next(Err); } Applicant.findById(applicantId, function(err, applicant){ if (err) { return next(err); } if (!applicant){ var Err = new Error(); Err.status = 400; return next(err); } var decodedId = base64ToObjectId(postId); // Save bookmark applicant.removeBookmark(decodedId, function(err){ // Database err, but we should make it seem // like its the users fault :P if(err){ return next(err); } res.status(200).end(); }); }); }); /** * Exports */ exports = module.exports = router;
/** * @author Richard Davey <[email protected]> * @copyright 2019 Photon Storm Ltd. * @license {@link https://opensource.org/licenses/MIT|MIT License} */ // Adapted from [gl-matrix](https://github.com/toji/gl-matrix) by toji // and [vecmath](https://github.com/mattdesl/vecmath) by mattdesl var Class = require('../utils/Class'); /** * @classdesc * A representation of a vector in 4D space. * * A four-component vector. * * @class Vector4 * @memberof Phaser.Math * @constructor * @since 3.0.0 * * @param {number} [x] - The x component. * @param {number} [y] - The y component. * @param {number} [z] - The z component. * @param {number} [w] - The w component. */ var Vector4 = new Class({ initialize: function Vector4 (x, y, z, w) { /** * The x component of this Vector. * * @name Phaser.Math.Vector4#x * @type {number} * @default 0 * @since 3.0.0 */ this.x = 0; /** * The y component of this Vector. * * @name Phaser.Math.Vector4#y * @type {number} * @default 0 * @since 3.0.0 */ this.y = 0; /** * The z component of this Vector. * * @name Phaser.Math.Vector4#z * @type {number} * @default 0 * @since 3.0.0 */ this.z = 0; /** * The w component of this Vector. * * @name Phaser.Math.Vector4#w * @type {number} * @default 0 * @since 3.0.0 */ this.w = 0; if (typeof x === 'object') { this.x = x.x || 0; this.y = x.y || 0; this.z = x.z || 0; this.w = x.w || 0; } else { this.x = x || 0; this.y = y || 0; this.z = z || 0; this.w = w || 0; } }, /** * Make a clone of this Vector4. * * @method Phaser.Math.Vector4#clone * @since 3.0.0 * * @return {Phaser.Math.Vector4} A clone of this Vector4. */ clone: function () { return new Vector4(this.x, this.y, this.z, this.w); }, /** * Copy the components of a given Vector into this Vector. * * @method Phaser.Math.Vector4#copy * @since 3.0.0 * * @param {Phaser.Math.Vector4} src - The Vector to copy the components from. * * @return {Phaser.Math.Vector4} This Vector4. */ copy: function (src) { this.x = src.x; this.y = src.y; this.z = src.z || 0; this.w = src.w || 0; return this; }, /** * Check whether this Vector is equal to a given Vector. * * Performs a strict quality check against each Vector's components. * * @method Phaser.Math.Vector4#equals * @since 3.0.0 * * @param {Phaser.Math.Vector4} v - The vector to check equality with. * * @return {boolean} A boolean indicating whether the two Vectors are equal or not. */ equals: function (v) { return ((this.x === v.x) && (this.y === v.y) && (this.z === v.z) && (this.w === v.w)); }, /** * Set the `x`, `y`, `z` and `w` components of the this Vector to the given `x`, `y`, `z` and `w` values. * * @method Phaser.Math.Vector4#set * @since 3.0.0 * * @param {(number|object)} x - The x value to set for this Vector, or an object containing x, y, z and w components. * @param {number} y - The y value to set for this Vector. * @param {number} z - The z value to set for this Vector. * @param {number} w - The z value to set for this Vector. * * @return {Phaser.Math.Vector4} This Vector4. */ set: function (x, y, z, w) { if (typeof x === 'object') { this.x = x.x || 0; this.y = x.y || 0; this.z = x.z || 0; this.w = x.w || 0; } else { this.x = x || 0; this.y = y || 0; this.z = z || 0; this.w = w || 0; } return this; }, /** * Add a given Vector to this Vector. Addition is component-wise. * * @method Phaser.Math.Vector4#add * @since 3.0.0 * * @param {(Phaser.Math.Vector2|Phaser.Math.Vector3|Phaser.Math.Vector4)} v - The Vector to add to this Vector. * * @return {Phaser.Math.Vector4} This Vector4. */ add: function (v) { this.x += v.x; this.y += v.y; this.z += v.z || 0; this.w += v.w || 0; return this; }, /** * Subtract the given Vector from this Vector. Subtraction is component-wise. * * @method Phaser.Math.Vector4#subtract * @since 3.0.0 * * @param {(Phaser.Math.Vector2|Phaser.Math.Vector3|Phaser.Math.Vector4)} v - The Vector to subtract from this Vector. * * @return {Phaser.Math.Vector4} This Vector4. */ subtract: function (v) { this.x -= v.x; this.y -= v.y; this.z -= v.z || 0; this.w -= v.w || 0; return this; }, /** * Scale this Vector by the given value. * * @method Phaser.Math.Vector4#scale * @since 3.0.0 * * @param {number} scale - The value to scale this Vector by. * * @return {Phaser.Math.Vector4} This Vector4. */ scale: function (scale) { this.x *= scale; this.y *= scale; this.z *= scale; this.w *= scale; return this; }, /** * Calculate the length (or magnitude) of this Vector. * * @method Phaser.Math.Vector4#length * @since 3.0.0 * * @return {number} The length of this Vector. */ length: function () { var x = this.x; var y = this.y; var z = this.z; var w = this.w; return Math.sqrt(x * x + y * y + z * z + w * w); }, /** * Calculate the length of this Vector squared. * * @method Phaser.Math.Vector4#lengthSq * @since 3.0.0 * * @return {number} The length of this Vector, squared. */ lengthSq: function () { var x = this.x; var y = this.y; var z = this.z; var w = this.w; return x * x + y * y + z * z + w * w; }, /** * Normalize this Vector. * * Makes the vector a unit length vector (magnitude of 1) in the same direction. * * @method Phaser.Math.Vector4#normalize * @since 3.0.0 * * @return {Phaser.Math.Vector4} This Vector4. */ normalize: function () { var x = this.x; var y = this.y; var z = this.z; var w = this.w; var len = x * x + y * y + z * z + w * w; if (len > 0) { len = 1 / Math.sqrt(len); this.x = x * len; this.y = y * len; this.z = z * len; this.w = w * len; } return this; }, /** * Calculate the dot product of this Vector and the given Vector. * * @method Phaser.Math.Vector4#dot * @since 3.0.0 * * @param {Phaser.Math.Vector4} v - The Vector4 to dot product with this Vector4. * * @return {number} The dot product of this Vector and the given Vector. */ dot: function (v) { return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w; }, /** * Linearly interpolate between this Vector and the given Vector. * * Interpolates this Vector towards the given Vector. * * @method Phaser.Math.Vector4#lerp * @since 3.0.0 * * @param {Phaser.Math.Vector4} v - The Vector4 to interpolate towards. * @param {number} [t=0] - The interpolation percentage, between 0 and 1. * * @return {Phaser.Math.Vector4} This Vector4. */ lerp: function (v, t) { if (t === undefined) { t = 0; } var ax = this.x; var ay = this.y; var az = this.z; var aw = this.w; this.x = ax + t * (v.x - ax); this.y = ay + t * (v.y - ay); this.z = az + t * (v.z - az); this.w = aw + t * (v.w - aw); return this; }, /** * Perform a component-wise multiplication between this Vector and the given Vector. * * Multiplies this Vector by the given Vector. * * @method Phaser.Math.Vector4#multiply * @since 3.0.0 * * @param {(Phaser.Math.Vector2|Phaser.Math.Vector3|Phaser.Math.Vector4)} v - The Vector to multiply this Vector by. * * @return {Phaser.Math.Vector4} This Vector4. */ multiply: function (v) { this.x *= v.x; this.y *= v.y; this.z *= v.z || 1; this.w *= v.w || 1; return this; }, /** * Perform a component-wise division between this Vector and the given Vector. * * Divides this Vector by the given Vector. * * @method Phaser.Math.Vector4#divide * @since 3.0.0 * * @param {(Phaser.Math.Vector2|Phaser.Math.Vector3|Phaser.Math.Vector4)} v - The Vector to divide this Vector by. * * @return {Phaser.Math.Vector4} This Vector4. */ divide: function (v) { this.x /= v.x; this.y /= v.y; this.z /= v.z || 1; this.w /= v.w || 1; return this; }, /** * Calculate the distance between this Vector and the given Vector. * * @method Phaser.Math.Vector4#distance * @since 3.0.0 * * @param {(Phaser.Math.Vector2|Phaser.Math.Vector3|Phaser.Math.Vector4)} v - The Vector to calculate the distance to. * * @return {number} The distance from this Vector to the given Vector. */ distance: function (v) { var dx = v.x - this.x; var dy = v.y - this.y; var dz = v.z - this.z || 0; var dw = v.w - this.w || 0; return Math.sqrt(dx * dx + dy * dy + dz * dz + dw * dw); }, /** * Calculate the distance between this Vector and the given Vector, squared. * * @method Phaser.Math.Vector4#distanceSq * @since 3.0.0 * * @param {(Phaser.Math.Vector2|Phaser.Math.Vector3|Phaser.Math.Vector4)} v - The Vector to calculate the distance to. * * @return {number} The distance from this Vector to the given Vector, squared. */ distanceSq: function (v) { var dx = v.x - this.x; var dy = v.y - this.y; var dz = v.z - this.z || 0; var dw = v.w - this.w || 0; return dx * dx + dy * dy + dz * dz + dw * dw; }, /** * Negate the `x`, `y`, `z` and `w` components of this Vector. * * @method Phaser.Math.Vector4#negate * @since 3.0.0 * * @return {Phaser.Math.Vector4} This Vector4. */ negate: function () { this.x = -this.x; this.y = -this.y; this.z = -this.z; this.w = -this.w; return this; }, /** * Transform this Vector with the given Matrix. * * @method Phaser.Math.Vector4#transformMat4 * @since 3.0.0 * * @param {Phaser.Math.Matrix4} mat - The Matrix4 to transform this Vector4 with. * * @return {Phaser.Math.Vector4} This Vector4. */ transformMat4: function (mat) { var x = this.x; var y = this.y; var z = this.z; var w = this.w; var m = mat.val; this.x = m[0] * x + m[4] * y + m[8] * z + m[12] * w; this.y = m[1] * x + m[5] * y + m[9] * z + m[13] * w; this.z = m[2] * x + m[6] * y + m[10] * z + m[14] * w; this.w = m[3] * x + m[7] * y + m[11] * z + m[15] * w; return this; }, /** * Transform this Vector with the given Quaternion. * * @method Phaser.Math.Vector4#transformQuat * @since 3.0.0 * * @param {Phaser.Math.Quaternion} q - The Quaternion to transform this Vector with. * * @return {Phaser.Math.Vector4} This Vector4. */ transformQuat: function (q) { // TODO: is this really the same as Vector3? // Also, what about this: http://molecularmusings.wordpress.com/2013/05/24/a-faster-quaternion-vector-multiplication/ // benchmarks: http://jsperf.com/quaternion-transform-vec3-implementations var x = this.x; var y = this.y; var z = this.z; var qx = q.x; var qy = q.y; var qz = q.z; var qw = q.w; // calculate quat * vec var ix = qw * x + qy * z - qz * y; var iy = qw * y + qz * x - qx * z; var iz = qw * z + qx * y - qy * x; var iw = -qx * x - qy * y - qz * z; // calculate result * inverse quat this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy; this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz; this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx; return this; }, /** * Make this Vector the zero vector (0, 0, 0, 0). * * @method Phaser.Math.Vector4#reset * @since 3.0.0 * * @return {Phaser.Math.Vector4} This Vector4. */ reset: function () { this.x = 0; this.y = 0; this.z = 0; this.w = 0; return this; } }); // TODO: Check if these are required internally, if not, remove. Vector4.prototype.sub = Vector4.prototype.subtract; Vector4.prototype.mul = Vector4.prototype.multiply; Vector4.prototype.div = Vector4.prototype.divide; Vector4.prototype.dist = Vector4.prototype.distance; Vector4.prototype.distSq = Vector4.prototype.distanceSq; Vector4.prototype.len = Vector4.prototype.length; Vector4.prototype.lenSq = Vector4.prototype.lengthSq; module.exports = Vector4;
module.exports = { <% if (modules === 'systemjs') { -%> templateUrl: 'app/header.html' <% } else { -%> template: require('./header.html') <% } -%> };
it("should load the component from container", () => { return import("./App").then(({ default: App }) => { const rendered = App(); expect(rendered).toBe( "App rendered with [This is react 2.1.0] and [ComponentA rendered with [This is react 2.1.0]] and [ComponentB rendered with [This is react 2.1.0]]" ); return import("./upgrade-react").then(({ default: upgrade }) => { upgrade(); const rendered = App(); expect(rendered).toBe( "App rendered with [This is react 3.2.1] and [ComponentA rendered with [This is react 3.2.1]] and [ComponentB rendered with [This is react 3.2.1]]" ); }); }); });
'use strict'; // Adapted from https://github.com/tleunen/babel-plugin-module-resolver/blob/master/src/normalizeOptions.js const path = require('path'); const { createSelector } = require('reselect'); const defaultExtensions = ['.js']; const normalizeRoots = (optsRoot, cwd) => { return Object.keys(optsRoot).reduce((acc, current) => { const dirPath = path.resolve(cwd, optsRoot[current]); acc[current] = dirPath; return acc; }, {}); }; const normalizeOptions = createSelector( // TODO check if needed currentFile => (currentFile.includes('.') ? path.dirname(currentFile) : currentFile), (_, opts) => opts, (_, opts) => { const cwd = process.cwd(); const roots = normalizeRoots(opts.roots, cwd); return { cwd, roots, extensions: defaultExtensions, }; } ); module.exports = normalizeOptions;
function MemoryCache() { } MemoryCache.prototype.get = function() { } MemoryCache.prototype.set = function() { } exports = module.exports = function() { return new MemoryCache(); } exports['@singleton'] = true; exports.MemoryCache = MemoryCache;
/*global App*/ /* Backbone View */ App.View.NodeView = App.View.BaseView.extend({ templateId: 'node', model: App.models.nodePage });
/*global SixSpeed */ var Fs = require('fs'), Path = require('path'); var $type = process.argv[2]; if ($type === 'babel') { require('babel-polyfill'); } if ($type === 'traceur') { require('traceur/bin/traceur-runtime'); } require('./runner'); var testDir = Path.join(__dirname, '..', 'build/tests'); Fs.readdirSync(testDir).forEach(function(test) { if (test.indexOf($type + '.js') < 0) { return; } try { require(Path.join(testDir, test)); } catch (err) { // NOP: Init errors should have been caught bo the master process init } }); process.on('message', function(exec) { SixSpeed.benchTest(exec.name, $type, function(result) { process.send({result: result}); }); });
App.CreateResponseView = Ember.View.extend({ templateName: "studentapp/create_response", didInsertElement: function() { this.get('controller').send('loadFields'); }.observes('controller.model') });
require('./harness')({ numRuns: 10000, concurrency: 1 }, function (err, time) { console.log('Ran 10000 jobs through Bull with concurrency 1 in %d ms', time); });
import baseIteratee from './_baseIteratee'; import basePickBy from './_basePickBy'; /** * The opposite of `_.pickBy`; this method creates an object composed of * the own and inherited enumerable properties of `object` that `predicate` * doesn't return truthy for. The predicate is invoked with two arguments: * (value, key). * * @static * @memberOf _ * @category Object * @param {Object} object The source object. * @param {Function|Object|string} [predicate=_.identity] The function invoked per property. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.omitBy(object, _.isNumber); * // => { 'b': '2' } */ function omitBy(object, predicate) { predicate = baseIteratee(predicate); return basePickBy(object, function(value, key) { return !predicate(value, key); }); } export default omitBy;
/*! * Angular Material Design * https://github.com/angular/material * @license MIT * v1.1.0-rc3-master-30e6657 */ (function( window, angular, undefined ){ "use strict"; /** * @ngdoc module * @name material.components.progressLinear * @description Linear Progress module! */ angular.module('material.components.progressLinear', [ 'material.core' ]) .directive('mdProgressLinear', MdProgressLinearDirective); /** * @ngdoc directive * @name mdProgressLinear * @module material.components.progressLinear * @restrict E * * @description * The linear progress directive is used to make loading content * in your app as delightful and painless as possible by minimizing * the amount of visual change a user sees before they can view * and interact with content. * * Each operation should only be represented by one activity indicator * For example: one refresh operation should not display both a * refresh bar and an activity circle. * * For operations where the percentage of the operation completed * can be determined, use a determinate indicator. They give users * a quick sense of how long an operation will take. * * For operations where the user is asked to wait a moment while * something finishes up, and it’s not necessary to expose what's * happening behind the scenes and how long it will take, use an * indeterminate indicator. * * @param {string} md-mode Select from one of four modes: determinate, indeterminate, buffer or query. * * Note: if the `md-mode` value is set as undefined or specified as 1 of the four (4) valid modes, then `indeterminate` * will be auto-applied as the mode. * * Note: if not configured, the `md-mode="indeterminate"` will be auto injected as an attribute. If `value=""` is also specified, however, * then `md-mode="determinate"` would be auto-injected instead. * @param {number=} value In determinate and buffer modes, this number represents the percentage of the primary progress bar. Default: 0 * @param {number=} md-buffer-value In the buffer mode, this number represents the percentage of the secondary progress bar. Default: 0 * @param {boolean=} ng-disabled Determines whether to disable the progress element. * * @usage * <hljs lang="html"> * <md-progress-linear md-mode="determinate" value="..."></md-progress-linear> * * <md-progress-linear md-mode="determinate" ng-value="..."></md-progress-linear> * * <md-progress-linear md-mode="indeterminate"></md-progress-linear> * * <md-progress-linear md-mode="buffer" value="..." md-buffer-value="..."></md-progress-linear> * * <md-progress-linear md-mode="query"></md-progress-linear> * </hljs> */ function MdProgressLinearDirective($mdTheming, $mdUtil, $log) { var MODE_DETERMINATE = "determinate"; var MODE_INDETERMINATE = "indeterminate"; var MODE_BUFFER = "buffer"; var MODE_QUERY = "query"; var DISABLED_CLASS = "_md-progress-linear-disabled"; return { restrict: 'E', template: '<div class="_md-container">' + '<div class="_md-dashed"></div>' + '<div class="_md-bar _md-bar1"></div>' + '<div class="_md-bar _md-bar2"></div>' + '</div>', compile: compile }; function compile(tElement, tAttrs, transclude) { tElement.attr('aria-valuemin', 0); tElement.attr('aria-valuemax', 100); tElement.attr('role', 'progressbar'); return postLink; } function postLink(scope, element, attr) { $mdTheming(element); var lastMode; var isDisabled = attr.hasOwnProperty('disabled'); var toVendorCSS = $mdUtil.dom.animator.toCss; var bar1 = angular.element(element[0].querySelector('._md-bar1')); var bar2 = angular.element(element[0].querySelector('._md-bar2')); var container = angular.element(element[0].querySelector('._md-container')); element .attr('md-mode', mode()) .toggleClass(DISABLED_CLASS, isDisabled); validateMode(); watchAttributes(); /** * Watch the value, md-buffer-value, and md-mode attributes */ function watchAttributes() { attr.$observe('value', function(value) { var percentValue = clamp(value); element.attr('aria-valuenow', percentValue); if (mode() != MODE_QUERY) animateIndicator(bar2, percentValue); }); attr.$observe('mdBufferValue', function(value) { animateIndicator(bar1, clamp(value)); }); attr.$observe('disabled', function(value) { if (value === true || value === false) { isDisabled = value; } else { isDisabled = angular.isDefined(value); } element.toggleClass(DISABLED_CLASS, !!isDisabled); }); attr.$observe('mdMode',function(mode){ if (lastMode) container.removeClass( lastMode ); switch( mode ) { case MODE_QUERY: case MODE_BUFFER: case MODE_DETERMINATE: case MODE_INDETERMINATE: container.addClass( lastMode = "_md-mode-" + mode ); break; default: container.addClass( lastMode = "_md-mode-" + MODE_INDETERMINATE ); break; } }); } /** * Auto-defaults the mode to either `determinate` or `indeterminate` mode; if not specified */ function validateMode() { if ( angular.isUndefined(attr.mdMode) ) { var hasValue = angular.isDefined(attr.value); var mode = hasValue ? MODE_DETERMINATE : MODE_INDETERMINATE; var info = "Auto-adding the missing md-mode='{0}' to the ProgressLinear element"; //$log.debug( $mdUtil.supplant(info, [mode]) ); element.attr("md-mode",mode); attr.mdMode = mode; } } /** * Is the md-mode a valid option? */ function mode() { var value = (attr.mdMode || "").trim(); if ( value ) { switch(value) { case MODE_DETERMINATE: case MODE_INDETERMINATE: case MODE_BUFFER: case MODE_QUERY: break; default: value = MODE_INDETERMINATE; break; } } return value; } /** * Manually set CSS to animate the Determinate indicator based on the specified * percentage value (0-100). */ function animateIndicator(target, value) { if ( isDisabled || !mode() ) return; var to = $mdUtil.supplant("translateX({0}%) scale({1},1)", [ (value-100)/2, value/100 ]); var styles = toVendorCSS({ transform : to }); angular.element(target).css( styles ); } } /** * Clamps the value to be between 0 and 100. * @param {number} value The value to clamp. * @returns {number} */ function clamp(value) { return Math.max(0, Math.min(value || 0, 100)); } } MdProgressLinearDirective.$inject = ["$mdTheming", "$mdUtil", "$log"]; })(window, window.angular);
export const PAGINATION_PIECE_PREVIOUS = 'Previous' export const PAGINATION_PIECE_ELLIPSIS = 'ellipsis' export const PAGINATION_PIECE_PAGE_NUMBER = 'page-number' export const PAGINATION_PIECE_NEXT = 'Next' export const DEFAULT_MAX_PAGE_NUMBER_LINKS = 5
/*{"name":"Control Panel","elements":[{"name":"Components link"},{"name":"Features link"},{"name":"Step Definitions link"},{"name":"Mock Data link"},{"name":"Run Protractor button"},{"name":"Server Status badge"}],"actions":[{"name":"go to Components","parameters":[]},{"name":"go to Features","parameters":[]},{"name":"go to Step Definitions","parameters":[]},{"name":"go to Mock Data","parameters":[]},{"name":"run Protractor","parameters":[]}]}*/ module.exports = function () { var ControlPanel = function ControlPanel() { this.componentsLink = element(by.css('[href="/components/"]')); this.featuresLink = element(by.css('[href="/features/"]')); this.stepDefinitionsLink = element(by.css('[href="/step-definitions/"]')); this.mockDataLink = element(by.css('[href="/mock-data/"]')); this.runProtractorButton = element(by.css('tractor-action[action="Run protractor"]')); this.serverStatusBadge = element(by.css('.control-panel__server-status')); }; ControlPanel.prototype.goToComponents = function () { var self = this; return self.componentsLink.click(); }; ControlPanel.prototype.goToFeatures = function () { var self = this; return self.featuresLink.click(); }; ControlPanel.prototype.goToStepDefinitions = function () { var self = this; return self.stepDefinitionsLink.click(); }; ControlPanel.prototype.goToMockData = function () { var self = this; return self.mockDataLink.click(); }; ControlPanel.prototype.runProtractor = function () { var self = this; return self.runProtractorButton.click(); }; return ControlPanel; }();
"use strict"; 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; }; })(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var Tink = (function () { function Tink(PIXI, element) { var scale = arguments.length <= 2 || arguments[2] === undefined ? 1 : arguments[2]; _classCallCheck(this, Tink); //Add element and scale properties this.element = element; this.scale = scale; //An array to store all the draggable sprites this.draggableSprites = []; //An array to store all the pointer objects //(there will usually just be one) this.pointers = []; //An array to store all the buttons and button-like //interactive sprites this.buttons = []; //A local PIXI reference this.PIXI = PIXI; //Aliases for Pixi objects this.TextureCache = this.PIXI.utils.TextureCache; this.MovieClip = this.PIXI.extras.MovieClip; this.Texture = this.PIXI.Texture; } //`makeDraggable` lets you make a drag-and-drop sprite by pushing it //into the `draggableSprites` array _createClass(Tink, [{ key: "makeDraggable", value: function makeDraggable() { var _this = this; for (var _len = arguments.length, sprites = Array(_len), _key = 0; _key < _len; _key++) { sprites[_key] = arguments[_key]; } //If the first argument isn't an array of sprites... if (!(sprites[0] instanceof Array)) { sprites.forEach(function (sprite) { _this.draggableSprites.push(sprite); //If the sprite's `draggable` property hasn't already been defined by //another library, like Hexi, define it if (sprite.draggable === undefined) { sprite.draggable = true; sprite._localDraggableAllocation = true; } }); } //If the first argument is an array of sprites... else { var spritesArray = sprites[0]; if (spritesArray.length > 0) { for (var i = spritesArray.length - 1; i >= 0; i--) { var sprite = spritesArray[i]; this.draggableSprites.push(sprite); //If the sprite's `draggable` property hasn't already been defined by //another library, like Hexi, define it if (sprite.draggable === undefined) { sprite.draggable = true; sprite._localDraggableAllocation = true; } } } } } //`makeUndraggable` removes the sprite from the `draggableSprites` //array }, { key: "makeUndraggable", value: function makeUndraggable() { var _this2 = this; for (var _len2 = arguments.length, sprites = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { sprites[_key2] = arguments[_key2]; } //If the first argument isn't an array of sprites... if (!(sprites[0] instanceof Array)) { sprites.forEach(function (sprite) { _this2.draggableSprites.splice(_this2.draggableSprites.indexOf(sprite), 1); if (sprite._localDraggableAllocation === true) sprite.draggable = false; }); } //If the first argument is an array of sprites else { var spritesArray = sprites[0]; if (spritesArray.length > 0) { for (var i = spritesArray.length - 1; i >= 0; i--) { var sprite = spritesArray[i]; this.draggableSprites.splice(this.draggableSprites.indexOf(sprite), 1); if (sprite._localDraggableAllocation === true) sprite.draggable = false; } } } } }, { key: "makePointer", value: function makePointer() { var element = arguments.length <= 0 || arguments[0] === undefined ? this.element : arguments[0]; var scale = arguments.length <= 1 || arguments[1] === undefined ? this.scale : arguments[1]; //Get a reference to Tink's global `draggableSprites` array var draggableSprites = this.draggableSprites; //Get a reference to Tink's `addGlobalPositionProperties` method var addGlobalPositionProperties = this.addGlobalPositionProperties; //The pointer object will be returned by this function var pointer = { element: element, scale: scale, //Private x and y properties _x: 0, _y: 0, //Width and height width: 1, height: 1, //The public x and y properties are divided by the scale. If the //HTML element that the pointer is sensitive to (like the canvas) //is scaled up or down, you can change the `scale` value to //correct the pointer's position values get x() { return this._x / this.scale; }, get y() { return this._y / this.scale; }, //Add `centerX` and `centerY` getters so that we //can use the pointer's coordinates with easing //and collision functions get centerX() { return this.x; }, get centerY() { return this.y; }, //`position` returns an object with x and y properties that //contain the pointer's position get position() { return { x: this.x, y: this.y }; }, //Add a `cursor` getter/setter to change the pointer's cursor //style. Values can be "pointer" (for a hand icon) or "auto" for //an ordinary arrow icon. get cursor() { return this.element.style.cursor; }, set cursor(value) { this.element.style.cursor = value; }, //Booleans to track the pointer state isDown: false, isUp: true, tapped: false, //Properties to help measure the time between up and down states downTime: 0, elapsedTime: 0, //Optional `press`,`release` and `tap` methods press: undefined, release: undefined, tap: undefined, //A `dragSprite` property to help with drag and drop dragSprite: null, //The drag offsets to help drag sprites dragOffsetX: 0, dragOffsetY: 0, //A property to check whether or not the pointer //is visible _visible: true, get visible() { return this._visible; }, set visible(value) { if (value === true) { this.cursor = "auto"; } else { this.cursor = "none"; } this._visible = value; }, //The pointer's mouse `moveHandler` moveHandler: function moveHandler(event) { //Get the element that's firing the event var element = event.target; //Find the pointer’s x and y position (for mouse). //Subtract the element's top and left offset from the browser window this._x = event.pageX - element.offsetLeft; this._y = event.pageY - element.offsetTop; //Prevent the event's default behavior event.preventDefault(); }, //The pointer's `touchmoveHandler` touchmoveHandler: function touchmoveHandler(event) { var element = event.target; //Find the touch point's x and y position this._x = event.targetTouches[0].pageX - element.offsetLeft; this._y = event.targetTouches[0].pageY - element.offsetTop; event.preventDefault(); }, //The pointer's `downHandler` downHandler: function downHandler(event) { //Set the down states this.isDown = true; this.isUp = false; this.tapped = false; //Capture the current time this.downTime = Date.now(); //Call the `press` method if it's been assigned if (this.press) this.press(); event.preventDefault(); }, //The pointer's `touchstartHandler` touchstartHandler: function touchstartHandler(event) { var element = event.target; //Find the touch point's x and y position this._x = event.targetTouches[0].pageX - element.offsetLeft; this._y = event.targetTouches[0].pageY - element.offsetTop; //Set the down states this.isDown = true; this.isUp = false; this.tapped = false; //Capture the current time this.downTime = Date.now(); //Call the `press` method if it's been assigned if (this.press) this.press(); event.preventDefault(); }, //The pointer's `upHandler` upHandler: function upHandler(event) { //Figure out how much time the pointer has been down this.elapsedTime = Math.abs(this.downTime - Date.now()); //If it's less than 200 milliseconds, it must be a tap or click if (this.elapsedTime <= 200 && this.tapped === false) { this.tapped = true; //Call the `tap` method if it's been assigned if (this.tap) this.tap(); } this.isUp = true; this.isDown = false; //Call the `release` method if it's been assigned if (this.release) this.release(); event.preventDefault(); }, //The pointer's `touchendHandler` touchendHandler: function touchendHandler(event) { //Figure out how much time the pointer has been down this.elapsedTime = Math.abs(this.downTime - Date.now()); //If it's less than 200 milliseconds, it must be a tap or click if (this.elapsedTime <= 200 && this.tapped === false) { this.tapped = true; //Call the `tap` method if it's been assigned if (this.tap) this.tap(); } this.isUp = true; this.isDown = false; //Call the `release` method if it's been assigned if (this.release) this.release(); event.preventDefault(); }, //`hitTestSprite` figures out if the pointer is touching a sprite hitTestSprite: function hitTestSprite(sprite) { //Add global `gx` and `gy` properties to the sprite if they //don't already exist addGlobalPositionProperties(sprite); //The `hit` variable will become `true` if the pointer is //touching the sprite and remain `false` if it isn't var hit = false; //Find out the sprite's offset from its anchor point var xAnchorOffset = undefined, yAnchorOffset = undefined; if (sprite.anchor !== undefined) { xAnchorOffset = sprite.width * sprite.anchor.x; yAnchorOffset = sprite.height * sprite.anchor.y; } else { xAnchorOffset = 0; yAnchorOffset = 0; } //Is the sprite rectangular? if (!sprite.circular) { //Get the position of the sprite's edges using global //coordinates var left = sprite.gx - xAnchorOffset, right = sprite.gx + sprite.width - xAnchorOffset, top = sprite.gy - yAnchorOffset, bottom = sprite.gy + sprite.height - yAnchorOffset; //Find out if the pointer is intersecting the rectangle. //`hit` will become `true` if the pointer is inside the //sprite's area hit = this.x > left && this.x < right && this.y > top && this.y < bottom; } //Is the sprite circular? else { //Find the distance between the pointer and the //center of the circle var vx = this.x - (sprite.gx + sprite.width / 2 - xAnchorOffset), vy = this.y - (sprite.gy + sprite.width / 2 - yAnchorOffset), distance = Math.sqrt(vx * vx + vy * vy); //The pointer is intersecting the circle if the //distance is less than the circle's radius hit = distance < sprite.width / 2; } return hit; } }; //Bind the events to the handlers //Mouse events element.addEventListener("mousemove", pointer.moveHandler.bind(pointer), false); element.addEventListener("mousedown", pointer.downHandler.bind(pointer), false); //Add the `mouseup` event to the `window` to //catch a mouse button release outside of the canvas area window.addEventListener("mouseup", pointer.upHandler.bind(pointer), false); //Touch events element.addEventListener("touchmove", pointer.touchmoveHandler.bind(pointer), false); element.addEventListener("touchstart", pointer.touchstartHandler.bind(pointer), false); //Add the `touchend` event to the `window` object to //catch a mouse button release outside of the canvas area window.addEventListener("touchend", pointer.touchendHandler.bind(pointer), false); //Disable the default pan and zoom actions on the `canvas` element.style.touchAction = "none"; //Add the pointer to Tink's global `pointers` array this.pointers.push(pointer); //Return the pointer return pointer; } //Many of Tink's objects, like pointers, use collision //detection using the sprites' global x and y positions. To make //this easier, new `gx` and `gy` properties are added to sprites //that reference Pixi sprites' `getGlobalPosition()` values. }, { key: "addGlobalPositionProperties", value: function addGlobalPositionProperties(sprite) { if (sprite.gx === undefined) { Object.defineProperty(sprite, "gx", { get: function get() { return sprite.getGlobalPosition().x; } }); } if (sprite.gy === undefined) { Object.defineProperty(sprite, "gy", { get: function get() { return sprite.getGlobalPosition().y; } }); } } //A method that implments drag-and-drop functionality //for each pointer }, { key: "updateDragAndDrop", value: function updateDragAndDrop(draggableSprites) { //Create a pointer if one doesn't already exist if (this.pointers.length === 0) { this.makePointer(this.element, this.scale); } //Loop through all the pointers in Tink's global `pointers` array //(there will usually just be one, but you never know) this.pointers.forEach(function (pointer) { //Check whether the pointer is pressed down if (pointer.isDown) { //You need to capture the co-ordinates at which the pointer was //pressed down and find out if it's touching a sprite //Only run pointer.code if the pointer isn't already dragging //sprite if (pointer.dragSprite === null) { //Loop through the `draggableSprites` in reverse to start searching at the bottom of the stack for (var i = draggableSprites.length - 1; i > -1; i--) { //Get a reference to the current sprite var sprite = draggableSprites[i]; //Check for a collision with the pointer using `hitTestSprite` if (pointer.hitTestSprite(sprite) && sprite.draggable) { //Calculate the difference between the pointer's //position and the sprite's position pointer.dragOffsetX = pointer.x - sprite.gx; pointer.dragOffsetY = pointer.y - sprite.gy; //Set the sprite as the pointer's `dragSprite` property pointer.dragSprite = sprite; //The next two lines re-order the `sprites` array so that the //selected sprite is displayed above all the others. //First, splice the sprite out of its current position in //its parent's `children` array var children = sprite.parent.children; children.splice(children.indexOf(sprite), 1); //Next, push the `dragSprite` to the end of its `children` array so that it's //displayed last, above all the other sprites children.push(sprite); //Reorganize the `draggableSpites` array in the same way draggableSprites.splice(draggableSprites.indexOf(sprite), 1); draggableSprites.push(sprite); //Break the loop, because we only need to drag the topmost sprite break; } } } //If the pointer is down and it has a `dragSprite`, make the sprite follow the pointer's //position, with the calculated offset else { pointer.dragSprite.x = pointer.x - pointer.dragOffsetX; pointer.dragSprite.y = pointer.y - pointer.dragOffsetY; } } //If the pointer is up, drop the `dragSprite` by setting it to `null` if (pointer.isUp) { pointer.dragSprite = null; } //Change the mouse arrow pointer to a hand if it's over a //draggable sprite draggableSprites.some(function (sprite) { if (pointer.hitTestSprite(sprite) && sprite.draggable) { if (pointer.visible) pointer.cursor = "pointer"; return true; } else { if (pointer.visible) pointer.cursor = "auto"; return false; } }); }); } }, { key: "makeInteractive", value: function makeInteractive(o) { //The `press`,`release`, `over`, `out` and `tap` methods. They're `undefined` //for now, but they can be defined in the game program o.press = o.press || undefined; o.release = o.release || undefined; o.over = o.over || undefined; o.out = o.out || undefined; o.tap = o.tap || undefined; //The `state` property tells you the button's //current state. Set its initial state to "up" o.state = "up"; //The `action` property tells you whether its being pressed or //released o.action = ""; //The `pressed` and `hoverOver` Booleans are mainly for internal //use in this code to help figure out the correct state. //`pressed` is a Boolean that helps track whether or not //the sprite has been pressed down o.pressed = false; //`hoverOver` is a Boolean which checks whether the pointer //has hovered over the sprite o.hoverOver = false; //tinkType is a string that will be set to "button" if the //user creates an object using the `button` function o.tinkType = ""; //Set `enabled` to true to allow for interactivity //Set `enabled` to false to disable interactivity o.enabled = true; //Add the sprite to the global `buttons` array so that it can //be updated each frame in the `updateButtons method this.buttons.push(o); } //The `updateButtons` method will be called each frame //inside the game loop. It updates all the button-like sprites }, { key: "updateButtons", value: function updateButtons() { var _this3 = this; //Create a pointer if one doesn't already exist if (this.pointers.length === 0) { this.makePointer(this.element, this.scale); } //Loop through all the button-like sprites that were created //using the `makeInteractive` method this.buttons.forEach(function (o) { //Only do this if the interactive object is enabled if (o.enabled) { //Loop through all of Tink's pointers (there will usually //just be one) _this3.pointers.forEach(function (pointer) { //Figure out if the pointer is touching the sprite var hit = pointer.hitTestSprite(o); //1. Figure out the current state if (pointer.isUp) { //Up state o.state = "up"; //Show the first image state frame, if this is a `Button` sprite if (o.tinkType === "button") o.gotoAndStop(0); } //If the pointer is touching the sprite, figure out //if the over or down state should be displayed if (hit) { //Over state o.state = "over"; //Show the second image state frame if this sprite has //3 frames and it's a `Button` sprite if (o.totalFrames && o.totalFrames === 3 && o.tinkType === "button") { o.gotoAndStop(1); } //Down state if (pointer.isDown) { o.state = "down"; //Show the third frame if this sprite is a `Button` sprite and it //has only three frames, or show the second frame if it //only has two frames if (o.tinkType === "button") { if (o.totalFrames === 3) { o.gotoAndStop(2); } else { o.gotoAndStop(1); } } } //Change the pointer icon to a hand if (pointer.visible) pointer.cursor = "pointer"; } else { //Turn the pointer to an ordinary arrow icon if the //pointer isn't touching a sprite if (pointer.visible) pointer.cursor = "auto"; } //Perform the correct interactive action //a. Run the `press` method if the sprite state is "down" and //the sprite hasn't already been pressed if (o.state === "down") { if (!o.pressed) { if (o.press) o.press(); o.pressed = true; o.action = "pressed"; } } //b. Run the `release` method if the sprite state is "over" and //the sprite has been pressed if (o.state === "over") { if (o.pressed) { if (o.release) o.release(); o.pressed = false; o.action = "released"; //If the pointer was tapped and the user assigned a `tap` //method, call the `tap` method if (pointer.tapped && o.tap) o.tap(); } //Run the `over` method if it has been assigned if (!o.hoverOver) { if (o.over) o.over(); o.hoverOver = true; } } //c. Check whether the pointer has been released outside //the sprite's area. If the button state is "up" and it's //already been pressed, then run the `release` method. if (o.state === "up") { if (o.pressed) { if (o.release) o.release(); o.pressed = false; o.action = "released"; } //Run the `out` method if it has been assigned if (o.hoverOver) { if (o.out) o.out(); o.hoverOver = false; } } }); } }); } //A function that creates a sprite with 3 frames that //represent the button states: up, over and down }, { key: "button", value: function button(source) { var x = arguments.length <= 1 || arguments[1] === undefined ? 0 : arguments[1]; var y = arguments.length <= 2 || arguments[2] === undefined ? 0 : arguments[2]; //The sprite object that will be returned var o = undefined; //Is it an array of frame ids or textures? if (typeof source[0] === "string") { //They're strings, but are they pre-existing texture or //paths to image files? //Check to see if the first element matches a texture in the //cache if (this.TextureCache[source[0]]) { //It does, so it's an array of frame ids o = this.MovieClip.fromFrames(source); } else { //It's not already in the cache, so let's load it o = this.MovieClip.fromImages(source); } } //If the `source` isn't an array of strings, check whether //it's an array of textures else if (source[0] instanceof this.Texture) { //Yes, it's an array of textures. //Use them to make a MovieClip o o = new this.MovieClip(source); } //Add interactive properties to the button this.makeInteractive(o); //Set the `tinkType` to "button" o.tinkType = "button"; //Position the button o.x = x; o.y = y; //Return the new button sprite return o; } //Run the `udpate` function in your game loop //to update all of Tink's interactive objects }, { key: "update", value: function update() { //Update the drag and drop system if (this.draggableSprites.length !== 0) this.updateDragAndDrop(this.draggableSprites); //Update the buttons and button-like interactive sprites if (this.buttons.length !== 0) this.updateButtons(); } /* `keyboard` is a method that listens for and captures keyboard events. It's really just a convenient wrapper function for HTML `keyup` and `keydown` events so that you can keep your application code clutter-free and easier to write and read. Here's how to use the `keyboard` method. Create a new keyboard object like this: ```js let keyObject = keyboard(asciiKeyCodeNumber); ``` It's one argument is the ASCII key code number of the keyboard key that you want to listen for. [Here's a list of ASCII key codes you can use](http://www.asciitable.com). Then assign `press` and `release` methods to the keyboard object like this: ```js keyObject.press = () => { //key object pressed }; keyObject.release = () => { //key object released }; ``` Keyboard objects also have `isDown` and `isUp` Boolean properties that you can use to check the state of each key. */ }, { key: "keyboard", value: function keyboard(keyCode) { var key = {}; key.code = keyCode; key.isDown = false; key.isUp = true; key.press = undefined; key.release = undefined; //The `downHandler` key.downHandler = function (event) { if (event.keyCode === key.code) { if (key.isUp && key.press) key.press(); key.isDown = true; key.isUp = false; } event.preventDefault(); }; //The `upHandler` key.upHandler = function (event) { if (event.keyCode === key.code) { if (key.isDown && key.release) key.release(); key.isDown = false; key.isUp = true; } event.preventDefault(); }; //Attach event listeners window.addEventListener("keydown", key.downHandler.bind(key), false); window.addEventListener("keyup", key.upHandler.bind(key), false); //Return the key object return key; } //`arrowControl` is a convenience method for updating a sprite's velocity //for 4-way movement using the arrow directional keys. Supply it //with the sprite you want to control and the speed per frame, in //pixels, that you want to update the sprite's velocity }, { key: "arrowControl", value: function arrowControl(sprite, speed) { if (speed === undefined) { throw new Error("Please supply the arrowControl method with the speed at which you want the sprite to move"); } var upArrow = this.keyboard(38), rightArrow = this.keyboard(39), downArrow = this.keyboard(40), leftArrow = this.keyboard(37); //Assign key `press` methods leftArrow.press = function () { //Change the sprite's velocity when the key is pressed sprite.vx = -speed; sprite.vy = 0; }; leftArrow.release = function () { //If the left arrow has been released, and the right arrow isn't down, //and the sprite isn't moving vertically: //Stop the sprite if (!rightArrow.isDown && sprite.vy === 0) { sprite.vx = 0; } }; upArrow.press = function () { sprite.vy = -speed; sprite.vx = 0; }; upArrow.release = function () { if (!downArrow.isDown && sprite.vx === 0) { sprite.vy = 0; } }; rightArrow.press = function () { sprite.vx = speed; sprite.vy = 0; }; rightArrow.release = function () { if (!leftArrow.isDown && sprite.vy === 0) { sprite.vx = 0; } }; downArrow.press = function () { sprite.vy = speed; sprite.vx = 0; }; downArrow.release = function () { if (!upArrow.isDown && sprite.vx === 0) { sprite.vy = 0; } }; } }]); return Tink; })(); //# sourceMappingURL=tink.js.map
const { assign, set } = require('lodash') const { renderDocuments } = require('../documents') describe('Contacts documents controller', () => { beforeEach(() => { this.breadcrumbStub = sinon.stub().returnsThis() this.resMock = assign({}, globalRes, { breadcrumb: this.breadcrumbStub, render: sinon.spy(), }) this.reqMock = assign({}, globalReq) this.nextSpy = sinon.spy() }) describe('#renderDocuments', () => { context('when documents path is an empty string', () => { beforeEach(() => { set(this.resMock, 'locals.contact.archived_documents_url_path', '') renderDocuments(this.reqMock, this.resMock, this.nextSpy) }) it('should call breadcrumb', () => { expect(this.resMock.breadcrumb).to.be.calledOnce }) it('should call breadcrumb with', () => { expect(this.resMock.breadcrumb).to.be.calledWith('Documents') }) it('should call render', () => { expect(this.resMock.render).to.be.calledOnce }) it('should call render with', () => { expect(this.resMock.render).to.be.calledWith( 'contacts/views/documents', { archivedDocumentPath: '' } ) }) }) context('when documents path contains a url', () => { const mockDocumentUrl = 'mock-document-url' beforeEach(() => { set( this.resMock, 'locals.contact.archived_documents_url_path', mockDocumentUrl ) renderDocuments(this.reqMock, this.resMock, this.nextSpy) }) it('should call breadcrumb', () => { expect(this.resMock.breadcrumb).to.be.calledOnce }) it('should call breadcrumb with', () => { expect(this.resMock.breadcrumb).to.be.calledWith('Documents') }) it('should call render', () => { expect(this.resMock.render).to.be.calledOnce }) it('should call render with', () => { expect(this.resMock.render).to.be.calledWith( 'contacts/views/documents', { archivedDocumentPath: mockDocumentUrl, } ) }) }) }) })
const should = require('should'); const sinon = require('sinon'); const Promise = require('bluebird'); const mail = require('../../../../../core/server/services/mail'); const settingsCache = require('../../../../../core/shared/settings-cache'); const configUtils = require('../../../../utils/configUtils'); const urlUtils = require('../../../../../core/shared/url-utils'); let mailer; // Mock SMTP config const SMTP = { transport: 'SMTP', options: { service: 'Gmail', auth: { user: 'nil', pass: '123' } } }; // test data const mailDataNoDomain = { to: '[email protected]', subject: 'testemail', html: '<p>This</p>' }; const mailDataNoServer = { to: '[email protected]', subject: 'testemail', html: '<p>This</p>' }; const mailDataIncomplete = { subject: 'testemail', html: '<p>This</p>' }; const sandbox = sinon.createSandbox(); describe('Mail: Ghostmailer', function () { afterEach(function () { mailer = null; configUtils.restore(); sandbox.restore(); }); it('should attach mail provider to ghost instance', function () { mailer = new mail.GhostMailer(); should.exist(mailer); mailer.should.have.property('send').and.be.a.Function(); }); it('should setup SMTP transport on initialization', function () { configUtils.set({mail: SMTP}); mailer = new mail.GhostMailer(); mailer.should.have.property('transport'); mailer.transport.transporter.name.should.eql('SMTP'); mailer.transport.sendMail.should.be.a.Function(); }); it('should fallback to direct if config is empty', function () { configUtils.set({mail: {}}); mailer = new mail.GhostMailer(); mailer.should.have.property('transport'); mailer.transport.transporter.name.should.eql('SMTP (direct)'); }); it('sends valid message successfully ', function (done) { configUtils.set({mail: {transport: 'stub'}}); mailer = new mail.GhostMailer(); mailer.transport.transporter.name.should.eql('Stub'); mailer.send(mailDataNoServer).then(function (response) { should.exist(response.response); should.exist(response.envelope); response.envelope.to.should.containEql('[email protected]'); done(); }).catch(done); }); it('handles failure', function (done) { configUtils.set({mail: {transport: 'stub', options: {error: 'Stub made a boo boo :('}}}); mailer = new mail.GhostMailer(); mailer.transport.transporter.name.should.eql('Stub'); mailer.send(mailDataNoServer).then(function () { done(new Error('Stub did not error')); }).catch(function (error) { error.message.should.containEql('Stub made a boo boo :('); done(); }).catch(done); }); it('should fail to send messages when given insufficient data', async function () { mailer = new mail.GhostMailer(); await mailer.send().should.be.rejectedWith('Incomplete message data.'); await mailer.send({subject: '123'}).should.be.rejectedWith('Incomplete message data.'); await mailer.send({subject: '', html: '123'}).should.be.rejectedWith('Incomplete message data.'); }); describe('Direct', function () { beforeEach(function () { configUtils.set({mail: {}}); mailer = new mail.GhostMailer(); }); afterEach(function () { mailer = null; }); it('return correct failure message for domain doesn\'t exist', function (done) { mailer.transport.transporter.name.should.eql('SMTP (direct)'); mailer.send(mailDataNoDomain).then(function () { done(new Error('Error message not shown.')); }, function (error) { error.message.should.startWith('Failed to send email.'); done(); }).catch(done); }); it('return correct failure message for no mail server at this address', function (done) { mailer.transport.transporter.name.should.eql('SMTP (direct)'); mailer.send(mailDataNoServer).then(function () { done(new Error('Error message not shown.')); }, function (error) { error.message.should.startWith('Failed to send email.'); done(); }).catch(done); }); it('return correct failure message for incomplete data', function (done) { mailer.transport.transporter.name.should.eql('SMTP (direct)'); mailer.send(mailDataIncomplete).then(function () { done(new Error('Error message not shown.')); }, function (error) { error.message.should.eql('Incomplete message data.'); done(); }).catch(done); }); }); describe('From address', function () { it('should use the config', async function () { configUtils.set({ mail: { from: '"Blog Title" <[email protected]>' } }); mailer = new mail.GhostMailer(); sandbox.stub(mailer, 'sendMail').resolves(); mailer.transport.transporter.name = 'NOT DIRECT'; await mailer.send({ to: '[email protected]', subject: 'subject', html: 'content' }); mailer.sendMail.firstCall.args[0].from.should.equal('"Blog Title" <[email protected]>'); }); describe('should fall back to [blog.title] <noreply@[blog.url]>', function () { beforeEach(async function () { mailer = new mail.GhostMailer(); sandbox.stub(mailer, 'sendMail').resolves(); mailer.transport.transporter.name = 'NOT DIRECT'; sandbox.stub(settingsCache, 'get').returns('Test'); }); it('standard domain', async function () { sandbox.stub(urlUtils, 'urlFor').returns('http://default.com'); configUtils.set({mail: {from: null}}); await mailer.send({ to: '[email protected]', subject: 'subject', html: 'content' }); mailer.sendMail.firstCall.args[0].from.should.equal('"Test" <[email protected]>'); }); it('trailing slash', async function () { sandbox.stub(urlUtils, 'urlFor').returns('http://default.com/'); configUtils.set({mail: {from: null}}); await mailer.send({ to: '[email protected]', subject: 'subject', html: 'content' }); mailer.sendMail.firstCall.args[0].from.should.equal('"Test" <[email protected]>'); }); it('strip port', async function () { sandbox.stub(urlUtils, 'urlFor').returns('http://default.com:2368/'); configUtils.set({mail: {from: null}}); await mailer.send({ to: '[email protected]', subject: 'subject', html: 'content' }); mailer.sendMail.firstCall.args[0].from.should.equal('"Test" <[email protected]>'); }); it('Escape title', async function () { settingsCache.get.restore(); sandbox.stub(settingsCache, 'get').returns('Test"'); sandbox.stub(urlUtils, 'urlFor').returns('http://default.com:2368/'); configUtils.set({mail: {from: null}}); await mailer.send({ to: '[email protected]', subject: 'subject', html: 'content' }); mailer.sendMail.firstCall.args[0].from.should.equal('"Test\\"" <[email protected]>'); }); }); it('should use mail.from', async function () { // Standard domain configUtils.set({mail: {from: '"bar" <[email protected]>'}}); mailer = new mail.GhostMailer(); sandbox.stub(mailer, 'sendMail').resolves(); mailer.transport.transporter.name = 'NOT DIRECT'; await mailer.send({ to: '[email protected]', subject: 'subject', html: 'content' }); mailer.sendMail.firstCall.args[0].from.should.equal('"bar" <[email protected]>'); }); it('should attach blog title', async function () { sandbox.stub(settingsCache, 'get').returns('Test'); configUtils.set({mail: {from: '[email protected]'}}); mailer = new mail.GhostMailer(); sandbox.stub(mailer, 'sendMail').resolves(); mailer.transport.transporter.name = 'NOT DIRECT'; await mailer.send({ to: '[email protected]', subject: 'subject', html: 'content' }); mailer.sendMail.firstCall.args[0].from.should.equal('"Test" <[email protected]>'); // only from set configUtils.set({mail: {from: '[email protected]'}}); await mailer.send({ to: '[email protected]', subject: 'subject', html: 'content' }); mailer.sendMail.firstCall.args[0].from.should.equal('"Test" <[email protected]>'); }); it('should ignore theme title if from address is Title <[email protected]> format', async function () { configUtils.set({mail: {from: '"R2D2" <[email protected]>'}}); mailer = new mail.GhostMailer(); sandbox.stub(mailer, 'sendMail').resolves(); mailer.transport.transporter.name = 'NOT DIRECT'; await mailer.send({ to: '[email protected]', subject: 'subject', html: 'content' }); mailer.sendMail.firstCall.args[0].from.should.equal('"R2D2" <[email protected]>'); // only from set configUtils.set({mail: {from: '"R2D2" <[email protected]>'}}); await mailer.send({ to: '[email protected]', subject: 'subject', html: 'content' }); mailer.sendMail.firstCall.args[0].from.should.equal('"R2D2" <[email protected]>'); }); it('should use default title if not theme title is provided', async function () { configUtils.set({mail: {from: null}}); sandbox.stub(urlUtils, 'urlFor').returns('http://default.com:2368/'); mailer = new mail.GhostMailer(); sandbox.stub(mailer, 'sendMail').resolves(); mailer.transport.transporter.name = 'NOT DIRECT'; await mailer.send({ to: '[email protected]', subject: 'subject', html: 'content' }); mailer.sendMail.firstCall.args[0].from.should.equal('"Ghost at default.com" <[email protected]>'); }); }); });
/** * Created by moshensky on 6/17/15. */ import {inject} from 'aurelia-dependency-injection'; import {Session} from './session'; import {Logger} from './logger'; import {Locale} from './locale'; import {Config} from './config'; import {Redirect} from 'aurelia-router'; class BaseAuthorizeStep { constructor(session, logger) { this.session = session; this.logger = logger; this.locale = Locale.Repository.default; this.loginRoute = Config.routerAuthStepOpts.loginRoute; } run(navigationInstruction, next) { if (!this.session.isUserLoggedIn() && navigationInstruction.config.route !== this.loginRoute) { this.logger.warn(this.locale.translate('pleaseLogin')); return next.cancel(new Redirect(this.loginRoute)); } let canAccess = this.authorize(navigationInstruction); if (canAccess === false) { this.logger.error(this.locale.translate('notAuthorized')); return next.cancel(); } return next(); } authorize(navigationInstruction) { if (navigationInstruction.parentInstruction === null) { return this.canAccess(navigationInstruction); } else { let canAccess = this.canAccess(navigationInstruction); if (hasRole){ return this.authorize(navigationInstruction.parentInstruction) } else { return false; } } } canAccess() { } } @inject(Session, Logger) export class RolesAuthorizeStep extends BaseAuthorizeStep { constructor(session, logger) { super(session, logger); } canAccess(navigationInstruction) { if (navigationInstruction.config.roles) { return this.session.userHasAtLeastOneRole(navigationInstruction.config.roles); } return true; } } @inject(Session, Logger) export class AccessRightsAuthorizeStep extends BaseAuthorizeStep { constructor(session, logger) { super(session, logger); } canAccess(navigationInstruction) { if (navigationInstruction.config.accessRight) { return this.session.userHasAccessRight(navigationInstruction.config.accessRight); } return true; } }
"use strict"; 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; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var core_1 = require('@angular/core'); var platform_browser_1 = require('@angular/platform-browser'); var forms_1 = require('@angular/forms'); var app_component_1 = require('./app.component'); var person_detail_component_1 = require('./person-detail.component'); var AppModule = (function () { function AppModule() { } AppModule = __decorate([ core_1.NgModule({ imports: [platform_browser_1.BrowserModule, forms_1.FormsModule], declarations: [app_component_1.AppComponent, person_detail_component_1.PersonDetailComponent], bootstrap: [app_component_1.AppComponent] }), __metadata('design:paramtypes', []) ], AppModule); return AppModule; }()); exports.AppModule = AppModule; //# sourceMappingURL=app.module.js.map
import React from 'react' import Icon from 'react-icon-base' const IoMerge = props => ( <Icon viewBox="0 0 40 40" {...props}> <g><path d="m30 17.5c2.7 0 5 2.3 5 5s-2.3 5-5 5c-1.9 0-3.4-1-4.3-2.5h-0.8c-4.7 0-9-2-12.4-5.8v9c1.5 0.9 2.5 2.4 2.5 4.3 0 2.7-2.3 5-5 5s-5-2.3-5-5c0-1.9 1-3.4 2.5-4.3v-16.4c-1.5-0.9-2.5-2.4-2.5-4.3 0-2.7 2.3-5 5-5s5 2.3 5 5c0 1.5-0.6 2.9-1.7 3.8 0.3 0.7 1.3 2.8 2.9 4.6 2.5 2.7 5.4 4.1 8.7 4.1h0.8c0.9-1.5 2.4-2.5 4.3-2.5z m-20-12.5c-1.4 0-2.5 1.1-2.5 2.5s1.1 2.5 2.5 2.5 2.5-1.1 2.5-2.5-1.1-2.5-2.5-2.5z m0 30c1.4 0 2.5-1.1 2.5-2.5s-1.1-2.5-2.5-2.5-2.5 1.1-2.5 2.5 1.1 2.5 2.5 2.5z m20-10c1.4 0 2.5-1.1 2.5-2.5s-1.1-2.5-2.5-2.5-2.5 1.1-2.5 2.5 1.1 2.5 2.5 2.5z"/></g> </Icon> ) export default IoMerge
import React from 'react' import Icon from 'react-icon-base' const TiMicrophoneOutline = props => ( <Icon viewBox="0 0 40 40" {...props}> <g><path d="m20 26.7c-3.7 0-6.7-3-6.7-6.7v-10c0-3.7 3-6.7 6.7-6.7s6.7 3 6.7 6.7v10c0 3.7-3 6.7-6.7 6.7z m0-20c-1.8 0-3.3 1.5-3.3 3.3v10c0 1.8 1.5 3.3 3.3 3.3s3.3-1.5 3.3-3.3v-10c0-1.8-1.5-3.3-3.3-3.3z m11.7 13.3v-3.3c0-1-0.8-1.7-1.7-1.7s-1.7 0.7-1.7 1.7v3.3c0 4.6-3.7 8.3-8.3 8.3s-8.3-3.7-8.3-8.3v-3.3c0-1-0.8-1.7-1.7-1.7s-1.7 0.7-1.7 1.7v3.3c0 5.9 4.4 10.7 10 11.5v1.8h-5c-0.9 0-1.6 0.8-1.6 1.7s0.7 1.7 1.6 1.7h13.4c0.9 0 1.6-0.8 1.6-1.7s-0.7-1.7-1.6-1.7h-5v-1.8c5.6-0.8 10-5.6 10-11.5z"/></g> </Icon> ) export default TiMicrophoneOutline
version https://git-lfs.github.com/spec/v1 oid sha256:2dedd72ad88f001dd7d65d94d327a0ea91999927a59d328fa4a7628fbb4c81f3 size 4281
/** * Baobab Cursors * =============== * * Cursors created by selecting some data within a Baobab tree. */ import Emitter from 'emmett'; import {Monkey} from './monkey'; import type from './type'; import { Archive, arrayFrom, before, coercePath, deepClone, getIn, makeError, shallowClone, solveUpdate } from './helpers'; /** * Traversal helper function for dynamic cursors. Will throw a legible error * if traversal is not possible. * * @param {string} method - The method name, to create a correct error msg. * @param {array} solvedPath - The cursor's solved path. */ function checkPossibilityOfDynamicTraversal(method, solvedPath) { if (!solvedPath) throw makeError( `Baobab.Cursor.${method}: ` + `cannot use ${method} on an unresolved dynamic path.`, {path: solvedPath} ); } /** * Cursor class * * @constructor * @param {Baobab} tree - The cursor's root. * @param {array} path - The cursor's path in the tree. * @param {string} hash - The path's hash computed ahead by the tree. */ export default class Cursor extends Emitter { constructor(tree, path, hash) { super(); // If no path were to be provided, we fallback to an empty path (root) path = path || []; // Privates this._identity = '[object Cursor]'; this._archive = null; // Properties this.tree = tree; this.path = path; this.hash = hash; // State this.state = { killed: false, recording: false, undoing: false }; // Checking whether the given path is dynamic or not this._dynamicPath = type.dynamicPath(this.path); // Checking whether the given path will meet a monkey this._monkeyPath = type.monkeyPath(this.tree._monkeys, this.path); if (!this._dynamicPath) this.solvedPath = this.path; else this.solvedPath = getIn(this.tree._data, this.path).solvedPath; /** * Listener bound to the tree's writes so that cursors with dynamic paths * may update their solved path correctly. * * @param {object} event - The event fired by the tree. */ this._writeHandler = ({data}) => { if (this.state.killed || !solveUpdate([data.path], this._getComparedPaths())) return; this.solvedPath = getIn(this.tree._data, this.path).solvedPath; }; /** * Function in charge of actually trigger the cursor's updates and * deal with the archived records. * * @note: probably should wrap the current solvedPath in closure to avoid * for tricky cases where it would fail. * * @param {mixed} previousData - the tree's previous data. */ const fireUpdate = (previousData) => { const self = this; const eventData = { get previousData() { return getIn(previousData, self.solvedPath).data; }, get currentData() { return self.get(); } }; if (this.state.recording && !this.state.undoing) this.archive.add(eventData.previousData); this.state.undoing = false; return this.emit('update', eventData); }; /** * Listener bound to the tree's updates and determining whether the * cursor is affected and should react accordingly. * * Note that this listener is lazily bound to the tree to be sure * one wouldn't leak listeners when only creating cursors for convenience * and not to listen to updates specifically. * * @param {object} event - The event fired by the tree. */ this._updateHandler = (event) => { if (this.state.killed) return; const {paths, previousData} = event.data, update = fireUpdate.bind(this, previousData), comparedPaths = this._getComparedPaths(); if (solveUpdate(paths, comparedPaths)) return update(); }; // Lazy binding let bound = false; this._lazyBind = () => { if (bound) return; bound = true; if (this._dynamicPath) this.tree.on('write', this._writeHandler); return this.tree.on('update', this._updateHandler); }; // If the path is dynamic, we actually need to listen to the tree if (this._dynamicPath) { this._lazyBind(); } else { // Overriding the emitter `on` and `once` methods this.on = before(this._lazyBind, this.on.bind(this)); this.once = before(this._lazyBind, this.once.bind(this)); } } /** * Internal helpers * ----------------- */ /** * Method returning the paths of the tree watched over by the cursor and that * should be taken into account when solving a potential update. * * @return {array} - Array of paths to compare with a given update. */ _getComparedPaths() { // Checking whether we should keep track of some dependencies const additionalPaths = this._monkeyPath ? getIn(this.tree._monkeys, this._monkeyPath) .data .relatedPaths() : []; return [this.solvedPath].concat(additionalPaths); } /** * Predicates * ----------- */ /** * Method returning whether the cursor is at root level. * * @return {boolean} - Is the cursor the root? */ isRoot() { return !this.path.length; } /** * Method returning whether the cursor is at leaf level. * * @return {boolean} - Is the cursor a leaf? */ isLeaf() { return type.primitive(this._get().data); } /** * Method returning whether the cursor is at branch level. * * @return {boolean} - Is the cursor a branch? */ isBranch() { return !this.isRoot() && !this.isLeaf(); } /** * Traversal Methods * ------------------ */ /** * Method returning the root cursor. * * @return {Baobab} - The root cursor. */ root() { return this.tree.select(); } /** * Method selecting a subpath as a new cursor. * * Arity (1): * @param {path} path - The path to select. * * Arity (*): * @param {...step} path - The path to select. * * @return {Cursor} - The created cursor. */ select(path) { if (arguments.length > 1) path = arrayFrom(arguments); return this.tree.select(this.path.concat(path)); } /** * Method returning the parent node of the cursor or else `null` if the * cursor is already at root level. * * @return {Baobab} - The parent cursor. */ up() { if (!this.isRoot()) return this.tree.select(this.path.slice(0, -1)); return null; } /** * Method returning the child node of the cursor. * * @return {Baobab} - The child cursor. */ down() { checkPossibilityOfDynamicTraversal('down', this.solvedPath); if (!(this._get().data instanceof Array)) throw Error('Baobab.Cursor.down: cannot go down on a non-list type.'); return this.tree.select(this.solvedPath.concat(0)); } /** * Method returning the left sibling node of the cursor if this one is * pointing at a list. Returns `null` if this cursor is already leftmost. * * @return {Baobab} - The left sibling cursor. */ left() { checkPossibilityOfDynamicTraversal('left', this.solvedPath); const last = +this.solvedPath[this.solvedPath.length - 1]; if (isNaN(last)) throw Error('Baobab.Cursor.left: cannot go left on a non-list type.'); return last ? this.tree.select(this.solvedPath.slice(0, -1).concat(last - 1)) : null; } /** * Method returning the right sibling node of the cursor if this one is * pointing at a list. Returns `null` if this cursor is already rightmost. * * @return {Baobab} - The right sibling cursor. */ right() { checkPossibilityOfDynamicTraversal('right', this.solvedPath); const last = +this.solvedPath[this.solvedPath.length - 1]; if (isNaN(last)) throw Error('Baobab.Cursor.right: cannot go right on a non-list type.'); if (last + 1 === this.up()._get().data.length) return null; return this.tree.select(this.solvedPath.slice(0, -1).concat(last + 1)); } /** * Method returning the leftmost sibling node of the cursor if this one is * pointing at a list. * * @return {Baobab} - The leftmost sibling cursor. */ leftmost() { checkPossibilityOfDynamicTraversal('leftmost', this.solvedPath); const last = +this.solvedPath[this.solvedPath.length - 1]; if (isNaN(last)) throw Error('Baobab.Cursor.leftmost: cannot go left on a non-list type.'); return this.tree.select(this.solvedPath.slice(0, -1).concat(0)); } /** * Method returning the rightmost sibling node of the cursor if this one is * pointing at a list. * * @return {Baobab} - The rightmost sibling cursor. */ rightmost() { checkPossibilityOfDynamicTraversal('rightmost', this.solvedPath); const last = +this.solvedPath[this.solvedPath.length - 1]; if (isNaN(last)) throw Error( 'Baobab.Cursor.rightmost: cannot go right on a non-list type.'); const list = this.up()._get().data; return this.tree .select(this.solvedPath.slice(0, -1).concat(list.length - 1)); } /** * Method mapping the children nodes of the cursor. * * @param {function} fn - The function to map. * @param {object} [scope] - An optional scope. * @return {array} - The resultant array. */ map(fn, scope) { checkPossibilityOfDynamicTraversal('map', this.solvedPath); const array = this._get().data, l = arguments.length; if (!type.array(array)) throw Error('baobab.Cursor.map: cannot map a non-list type.'); return array.map(function(item, i) { return fn.call( l > 1 ? scope : this, this.select(i), i, array ); }, this); } /** * Getter Methods * --------------- */ /** * Internal get method. Basically contains the main body of the `get` method * without the event emitting. This is sometimes needed not to fire useless * events. * * @param {path} [path=[]] - Path to get in the tree. * @return {object} info - The resultant information. * @return {mixed} info.data - Data at path. * @return {array} info.solvedPath - The path solved when getting. */ _get(path = []) { if (!type.path(path)) throw makeError('Baobab.Cursor.getters: invalid path.', {path}); if (!this.solvedPath) return {data: undefined, solvedPath: null, exists: false}; return getIn(this.tree._data, this.solvedPath.concat(path)); } /** * Method used to check whether a certain path exists in the tree starting * from the current cursor. * * Arity (1): * @param {path} path - Path to check in the tree. * * Arity (2): * @param {..step} path - Path to check in the tree. * * @return {boolean} - Does the given path exists? */ exists(path) { path = coercePath(path); if (arguments.length > 1) path = arrayFrom(arguments); return this._get(path).exists; } /** * Method used to get data from the tree. Will fire a `get` event from the * tree so that the user may sometimes react upon it to fetch data, for * instance. * * Arity (1): * @param {path} path - Path to get in the tree. * * Arity (2): * @param {..step} path - Path to get in the tree. * * @return {mixed} - Data at path. */ get(path) { path = coercePath(path); if (arguments.length > 1) path = arrayFrom(arguments); const {data, solvedPath} = this._get(path); // Emitting the event this.tree.emit('get', {data, solvedPath, path: this.path.concat(path)}); return data; } /** * Method used to shallow clone data from the tree. * * Arity (1): * @param {path} path - Path to get in the tree. * * Arity (2): * @param {..step} path - Path to get in the tree. * * @return {mixed} - Cloned data at path. */ clone(...args) { const data = this.get(...args); return shallowClone(data); } /** * Method used to deep clone data from the tree. * * Arity (1): * @param {path} path - Path to get in the tree. * * Arity (2): * @param {..step} path - Path to get in the tree. * * @return {mixed} - Cloned data at path. */ deepClone(...args) { const data = this.get(...args); return deepClone(data); } /** * Method used to return raw data from the tree, by carefully avoiding * computed one. * * @todo: should be more performant as the cloning should happen as well as * when dropping computed data. * * Arity (1): * @param {path} path - Path to serialize in the tree. * * Arity (2): * @param {..step} path - Path to serialize in the tree. * * @return {mixed} - The retrieved raw data. */ serialize(path) { path = coercePath(path); if (arguments.length > 1) path = arrayFrom(arguments); if (!type.path(path)) throw makeError('Baobab.Cursor.getters: invalid path.', {path}); if (!this.solvedPath) return undefined; const fullPath = this.solvedPath.concat(path); const data = deepClone(getIn(this.tree._data, fullPath).data), monkeys = getIn(this.tree._monkeys, fullPath).data; const dropComputedData = (d, m) => { if (!type.object(m) || !type.object(d)) return; for (const k in m) { if (m[k] instanceof Monkey) delete d[k]; else dropComputedData(d[k], m[k]); } }; dropComputedData(data, monkeys); return data; } /** * Method used to project some of the data at cursor onto a map or a list. * * @param {object|array} projection - The projection's formal definition. * @return {object|array} - The resultant map/list. */ project(projection) { if (type.object(projection)) { const data = {}; for (const k in projection) data[k] = this.get(projection[k]); return data; } else if (type.array(projection)) { const data = []; for (let i = 0, l = projection.length; i < l; i++) data.push(this.get(projection[i])); return data; } throw makeError('Baobab.Cursor.project: wrong projection.', {projection}); } /** * History Methods * ---------------- */ /** * Methods starting to record the cursor's successive states. * * @param {integer} [maxRecords] - Maximum records to keep in memory. Note * that if no number is provided, the cursor * will keep everything. * @return {Cursor} - The cursor instance for chaining purposes. */ startRecording(maxRecords) { maxRecords = maxRecords || Infinity; if (maxRecords < 1) throw makeError('Baobab.Cursor.startRecording: invalid max records.', { value: maxRecords }); this.state.recording = true; if (this.archive) return this; // Lazy binding this._lazyBind(); this.archive = new Archive(maxRecords); return this; } /** * Methods stopping to record the cursor's successive states. * * @return {Cursor} - The cursor instance for chaining purposes. */ stopRecording() { this.state.recording = false; return this; } /** * Methods undoing n steps of the cursor's recorded states. * * @param {integer} [steps=1] - The number of steps to rollback. * @return {Cursor} - The cursor instance for chaining purposes. */ undo(steps = 1) { if (!this.state.recording) throw new Error('Baobab.Cursor.undo: cursor is not recording.'); const record = this.archive.back(steps); if (!record) throw Error('Baobab.Cursor.undo: cannot find a relevant record.'); this.state.undoing = true; this.set(record); return this; } /** * Methods returning whether the cursor has a recorded history. * * @return {boolean} - `true` if the cursor has a recorded history? */ hasHistory() { return !!(this.archive && this.archive.get().length); } /** * Methods returning the cursor's history. * * @return {array} - The cursor's history. */ getHistory() { return this.archive ? this.archive.get() : []; } /** * Methods clearing the cursor's history. * * @return {Cursor} - The cursor instance for chaining purposes. */ clearHistory() { if (this.archive) this.archive.clear(); return this; } /** * Releasing * ---------- */ /** * Methods releasing the cursor from memory. */ release() { // Removing listeners on parent if (this._dynamicPath) this.tree.off('write', this._writeHandler); this.tree.off('update', this._updateHandler); // Unsubscribe from the parent if (this.hash) delete this.tree._cursors[this.hash]; // Dereferencing delete this.tree; delete this.path; delete this.solvedPath; delete this.archive; // Killing emitter this.kill(); this.state.killed = true; } /** * Output * ------- */ /** * Overriding the `toJSON` method for convenient use with JSON.stringify. * * @return {mixed} - Data at cursor. */ toJSON() { return this.serialize(); } /** * Overriding the `toString` method for debugging purposes. * * @return {string} - The cursor's identity. */ toString() { return this._identity; } } /** * Method used to allow iterating over cursors containing list-type data. * * e.g. for(let i of cursor) { ... } * * @returns {object} - Each item sequentially. */ if (typeof Symbol === 'function' && typeof Symbol.iterator !== 'undefined') { Cursor.prototype[Symbol.iterator] = function() { const array = this._get().data; if (!type.array(array)) throw Error('baobab.Cursor.@@iterate: cannot iterate a non-list type.'); let i = 0; const cursor = this, length = array.length; return { next() { if (i < length) { return { value: cursor.select(i++) }; } return { done: true }; } }; }; } /** * Setter Methods * --------------- * * Those methods are dynamically assigned to the class for DRY reasons. */ // Not using a Set so that ES5 consumers don't pay a bundle size price const INTRANSITIVE_SETTERS = { unset: true, pop: true, shift: true }; /** * Function creating a setter method for the Cursor class. * * @param {string} name - the method's name. * @param {function} [typeChecker] - a function checking that the given value is * valid for the given operation. */ function makeSetter(name, typeChecker) { /** * Binding a setter method to the Cursor class and having the following * definition. * * Note: this is not really possible to make those setters variadic because * it would create an impossible polymorphism with path. * * @todo: perform value validation elsewhere so that tree.update can * beneficiate from it. * * Arity (1): * @param {mixed} value - New value to set at cursor's path. * * Arity (2): * @param {path} path - Subpath to update starting from cursor's. * @param {mixed} value - New value to set. * * @return {mixed} - Data at path. */ Cursor.prototype[name] = function(path, value) { // We should warn the user if he applies to many arguments to the function if (arguments.length > 2) throw makeError(`Baobab.Cursor.${name}: too many arguments.`); // Handling arities if (arguments.length === 1 && !INTRANSITIVE_SETTERS[name]) { value = path; path = []; } // Coerce path path = coercePath(path); // Checking the path's validity if (!type.path(path)) throw makeError(`Baobab.Cursor.${name}: invalid path.`, {path}); // Checking the value's validity if (typeChecker && !typeChecker(value)) throw makeError(`Baobab.Cursor.${name}: invalid value.`, {path, value}); // Checking the solvability of the cursor's dynamic path if (!this.solvedPath) throw makeError( `Baobab.Cursor.${name}: the dynamic path of the cursor cannot be solved.`, {path: this.path} ); const fullPath = this.solvedPath.concat(path); // Filing the update to the tree return this.tree.update( fullPath, { type: name, value } ); }; } /** * Making the necessary setters. */ makeSetter('set'); makeSetter('unset'); makeSetter('apply', type.function); makeSetter('push'); makeSetter('concat', type.array); makeSetter('unshift'); makeSetter('pop'); makeSetter('shift'); makeSetter('splice', type.splicer); makeSetter('merge', type.object); makeSetter('deepMerge', type.object);
function ResourceLoader(baseurl) { this.BASEURL = baseurl; } ResourceLoader.prototype.loadResource = function(resource, callback) { var self = this; evaluateScripts([resource], function(success) { if(success) { var resource = Template.call(self); callback.call(self, resource); } else { var title = "Resource Loader Error", description = `Error loading resource '${resource}'. \n\n Try again later.`, alert = createAlert(title, description); navigationDocument.presentModal(alert); } }); }
var _ = require('lodash'), moment = require('moment-timezone'); function dateStringToTimestampWithZone(timeIn, zone) { // 07/09/2015 11:00 AM var pieces = timeIn.split(' '), dateString = pieces[0], timeString = pieces[1], ampm = pieces[2], datePieces = dateString.split('/'), timePieces = timeString.split(':'), timeObject = {}, timestamp; timeObject.month = parseInt(datePieces.shift()) - 1; timeObject.day = parseInt(datePieces.shift()); timeObject.year = parseInt(datePieces.shift()); timeObject.hour = parseInt(timePieces.shift()); timeObject.minute = parseInt(timePieces.shift()); if (ampm.toLowerCase() == 'pm' && (timeObject.hour != 12 || timeObject.hour != 24)) { timeObject.hour += 12; } timestamp = moment.tz(timeObject, zone).unix(); return timestamp; } module.exports = function(dataArray, options, temporalDataCallback, metaDataCallback) { var config = options.config, fieldNames = config.fields, metadataNames = config.metadata; moment.tz.setDefault(config.timezone); _.each(dataArray, function(dataPoint) { var fieldValues = [], metadata = {}, streamId = dataPoint.beach_name, dateString = dataPoint.measurement_timestamp_label, timestamp = dateStringToTimestampWithZone(dateString, config.timezone); // Temporal data _.each(fieldNames, function(fieldName) { fieldValues.push(parseFloat(dataPoint[fieldName])); }); temporalDataCallback(streamId, timestamp, fieldValues); // Metadata _.each(metadataNames, function(metadataName) { metadata[metadataName] = dataPoint[metadataName]; }); metaDataCallback(streamId, metadata); }); };
'use strict'; var util = require('util'); var events = require('events'); var _ = require('lodash'); var table = require('text-table'); var chalk = require('chalk'); // padding step var step = ' '; var padding = ' '; // color -> status mappings var colors = { skip: 'yellow', force: 'yellow', create: 'green', invoke: 'bold', conflict: 'red', identical: 'cyan', info: 'gray' }; function pad(status) { var max = 'identical'.length; var delta = max - status.length; return delta ? new Array(delta + 1).join(' ') + status : status; } // borrowed from https://github.com/mikeal/logref/blob/master/main.js#L6-15 function formatter(msg, ctx) { while (msg.indexOf('%') !== -1) { var start = msg.indexOf('%'); var end = msg.indexOf(' ', start); if (end === -1) { end = msg.length; } msg = msg.slice(0, start) + ctx[msg.slice(start + 1, end)] + msg.slice(end); } return msg; } module.exports = function logger() { // `this.log` is a [logref](https://github.com/mikeal/logref) // compatible logger, with an enhanced API. // // It also has EventEmitter like capabilities, so you can call on / emit // on it, namely used to increase or decrease the padding. // // All logs are done against STDERR, letting you stdout for meaningfull // value and redirection, should you need to generate output this way. // // Log functions take two arguments, a message and a context. For any // other kind of paramters, `console.error` is used, so all of the // console format string goodies you're used to work fine. // // - msg - The message to show up // - context - The optional context to escape the message against // // Retunrns the logger function log(msg, ctx) { msg = msg || ''; if (!ctx) { ctx = {}; } if (typeof ctx === 'object' && !Array.isArray(ctx)) { console.error(formatter(msg, ctx)); } else { console.error.apply(console, arguments); } return log; } _.extend(log, events.EventEmitter.prototype); // A simple write method, with formatted message. If `msg` is // ommitted, then a single `\n` is written. // // Returns the logger log.write = function (msg) { if (!msg) { return this.write('\n'); } process.stderr.write(util.format.apply(util, arguments)); return this; }; // Same as `log.write()` but automatically appends a `\n` at the end // of the message. log.writeln = function () { return this.write.apply(this, arguments).write(); }; // Convenience helper to write sucess status, this simply prepends the // message with a gren `✔`. log.ok = function () { this.write(chalk.green('✔ ') + util.format.apply(util, arguments) + '\n'); return this; }; log.error = function () { this.write(chalk.red('✗ ') + util.format.apply(util, arguments) + '\n'); return this; }; log.on('up', function () { padding = padding + step; }); log.on('down', function () { padding = padding.replace(step, ''); }); Object.keys(colors).forEach(function (status) { // Each predefined status has its logging method utility, handling // status color and padding before the usual `.write()` // // Example // // this.log // .write() // .info('Doing something') // .force('Forcing filepath %s, 'some path') // .conflict('on %s' 'model.js') // .write() // .ok('This is ok'); // // The list of status and mapping colors // // skip yellow // force yellow // create green // invoke bold // conflict red // identical cyan // info grey // // Returns the logger log[status] = function () { var color = colors[status]; this.write(chalk[color](pad(status))).write(padding); this.write(util.format.apply(util, arguments) + '\n'); return this; }; }); // A basic wrapper around `cli-table` package, resetting any single // char to empty strings, this is used for aligning options and // arguments without too much Math on our side. // // - opts - A list of rows or an Hash of options to pass through cli // table. // // Returns the table reprensetation log.table = function (opts) { var tableData = []; opts = Array.isArray(opts) ? { rows: opts }: opts; opts.rows = opts.rows || []; opts.rows.forEach(function (row) { tableData.push(row); }); return table(tableData); }; return log; };
(this["webpackJsonpcarbonphp-documentation-react"]=this["webpackJsonpcarbonphp-documentation-react"]||[]).push([[2],{860:function(e,a,t){"use strict";function n(e){e.languages.actionscript=e.languages.extend("javascript",{keyword:/\b(?:as|break|case|catch|class|const|default|delete|do|else|extends|finally|for|function|if|implements|import|in|instanceof|interface|internal|is|native|new|null|package|private|protected|public|return|super|switch|this|throw|try|typeof|use|var|void|while|with|dynamic|each|final|get|include|namespace|native|override|set|static)\b/,operator:/\+\+|--|(?:[+\-*\/%^]|&&?|\|\|?|<<?|>>?>?|[!=]=?)=?|[~?@]/}),e.languages.actionscript["class-name"].alias="function",e.languages.markup&&e.languages.insertBefore("actionscript","string",{xml:{pattern:/(^|[^.])<\/?\w+(?:\s+[^\s>\/=]+=("|')(?:\\[\s\S]|(?!\2)[^\\])*\2)*\s*\/?>/,lookbehind:!0,inside:{rest:e.languages.markup}}})}e.exports=n,n.displayName="actionscript",n.aliases=[]}}]); //# sourceMappingURL=react-syntax-highlighter_languages_refractor_actionscript.38f66c84.chunk.js.map
'use strict'; angular.module('core').controller('TimelineController', ['$scope', function($scope) { // Timeline controller logic // ... } ]);
'use strict'; angular.module('testing').controller('TestingController', ['$scope', '$http', '$location', 'Authentication', 'Appprogress', 'Users', 'Registrations', 'creditCardMgmt', 'createDialog', 'bankAccountMgmt', function ($scope, $http, $location, Authentication, Appprogress, Users, Registrations, creditCardMgmt, createDialogService, bankAccountMgmt) { $scope.user = Authentication.user; $scope.registration = null; $scope.cards = []; $scope.accounts = []; $scope.selectedPart = []; // If user is not signed in then redirect back home if (!$scope.user) $location.path('/'); var appProgress = Appprogress; // $scope.isExistingUser = true; $scope.getBankAccountsList = function () { console.log('getBankAccountsList()'); appProgress.showPleaseWait(); $http.get('/registrationsdetails/' + $scope.user._id).success(function (reg) { if (reg[0] && reg[0].bankAccountId) { for (var i = 0; i < reg[0].bankAccountId.length; i++) { $http.post('/getObject', { "objectHref": "/bank_accounts/" + reg[0].bankAccountId[i] }).success(function (response) { $scope.accounts.push({ "bankName": response.bank_name, "bankAccountName": response.name, "bankAccountNumber": response.account_number, "bankAccountType": response.account_type }); }); } } appProgress.hidePleaseWait(); }).error(function (err) { appProgress.hidePleaseWait(); }); $scope.gridAccounts = { data: 'accounts', multiSelect: false, selectedItems: $scope.selectedPart, columnDefs: [{ field: 'bankName', displayName: 'Bank Name', width: '**' }, { field: 'bankAccountName', displayName: 'Account Name' }, { field: 'bankAccountNumber', displayName: 'Account Number' }, { field: 'bankAccountType', displayName: 'Account Type' }] }; }; $scope.getBankAccount = function () { console.log('getBankAccount()'); appProgress.showPleaseWait(); $http.get('/registrationsdetails/' + $scope.user._id).success(function (reg) { if (reg && reg[0].bankAccountId) { $http.post('/getObject', { "objectHref": "/bank_accounts/" + reg[0].bankAccountIdbankAccountId }).success(function (response) { $("#bankName").val(response.bank_name); $("#bankAccountName").val(response.name); $("#bankAccountNumber").val(response.account_number); $("#bankAccountType").val(response.account_type); $("#bankSwift").val(response.routing_number); $("#bankAddress1").val(response.address ? response.address.line1 : ""); $("#bankAddress2").val(response.address ? response.address.line2 : ""); $("#bankCity").val(response.address ? response.address.city : ""); $("#bankState").val(response.address ? response.address.state : ""); $("#bankZip").val(response.address ? response.address.postal_code : ""); $("#bankCountry").val(response.address ? response.address.country_code : ""); appProgress.hidePleaseWait(); }). error(function (response) { appProgress.hidePleaseWait(); $scope.error = response.message; $scope.payment = null; }); } appProgress.hidePleaseWait(); }) .error(function (error) { appProgress.hidePleaseWait(); alert(error); }); }; $scope.updateBankAccount = function () { console.log('testing.updateBankAccount()'); // create objects for balanced payments to store bank account var account = { "routing_number": $("#bankSwift").val(), "account_type": $("#bankAccountType").val(), "name": $("#bankAccountName").val(), "account_number": $("#bankAccountNumber").val(), }; var address = { "city": $("#bankCity").val(), "line1": $("#bankAddress1").val(), "line2": $("#bankAddress2").val(), "state": $("#bankState").val(), "postal_code": $("#bankZip").val(), "country_code": $("#bankCountry").val() }; var createAccountObj = { "account": account, "address": address }; var userEmail = $scope.user.email; var userHref = ''; //TODO:balanced2 get the balanced customer identifier from the registration for this user // use that identifier to see if we have a customer record matching in balanced // if not theoretically it is a system error if we have the id locally and it is not in balanced however // we can for now just create a new one in that case and log the error $http.get('/registrationsdetails/' + $scope.user._id).success(function (reg) { if (reg && reg[0].balancedPaymentsId) { $http.post('/getObject', { "objectHref": "/customers/" + reg[0].balancedPaymentsId }).success(function (customer_response) { $http.post('/createAccount', createAccountObj).success(function (account_response) { console.log(account_response); var accountHref = account_response.href; if (accountHref == undefined) { console.log('error creating bank acount'); alert('error creating bank account'); return; } $http.post('/addAccountToCustomer', { "customerHref": "/customers/" + reg[0].balancedPaymentsId, "accountHref": accountHref }).success(function (addAccount_response) { console.log('Add account to customer'); console.log(addAccount_response); //Updare the registration object with the card id and save the reg object. var registration = new Registrations({ _id: reg[0]._id, user: $scope.user._id }); reg[0].bankAccountId.push(account_response.id); registration.bankAccountId = reg[0].bankAccountId; registration.$update(function (response) { console.log('registration saved'); $scope.success = true; }, function (error) { console.log('failed saving registration data.'); }); //TODO:balanced get the response credit card account identifier and store with registration.js schema for user alert("created"); }).error(function (response) { alert(response.message); }); }).error(function (response) { alert(response.message); }); }); } else { var customer = { "name": $scope.user.firstName + ' ' + $scope.user.lastName, "email": $scope.user.email, "phone": "" }; $http.post('/createCustomer', customer).success(function (customer_response) { console.log(customer_response); if (!customer_response.id) { alert('Error creating customer'); return; } //Updare the registration object with the customer id and save the reg object. //Updare the registration object with the card id and save the reg object. var registration = new Registrations({ balancedPaymentsId: customer_response.id, _id: reg[0]._id, user: $scope.user._id }); registration.$update(function (save_response) { console.log('registration saved'); $scope.success = true; $http.post('/createAccount', createAccountObj).success(function (account_response) { console.log(account_response); var accountHref = account_response.href; if (!accountHref) { alert('Error creating bank account'); return; } $http.post('/addAccountToCustomer', { "customerHref": "/customers/" + customer_response.id, "accountHref": accountHref }).success(function (addAccountResponse) { console.log(addAccountResponse); registration = new Registrations({ _id: reg[0]._id, user: $scope.user._id }); reg[0].bankAccountId.push(addAccountResponse.id); registration.bankAccountId = reg[0].bankAccountId; registration.$update(function (save_response) { console.log('registration saved'); $scope.success = true; }).error(function (err) { console.log('failed saving registration data.'); }); //TODO:balanced get the response credit card account identifier and store with registration.js schema for user alert("created"); }).error(function (response) { alert(response.message); }); }).error(function (response) { alert(response.message); }); }).error(function (err) { console.log('failed saving registration data.'); }); }). error(function (error) { alert(error); }); } }); }; $scope.getCreditCardsList = function () { console.log('getCreditCardsList()'); appProgress.showPleaseWait(); $http.get('/registrationsdetails/' + $scope.user._id).success(function (reg) { if (reg[0] && reg[0].creditCardId) { for (var i = 0; i < reg[0].creditCardId.length; i++) { $http.post('/getObject', { "objectHref": "/cards/" + reg[0].creditCardId[i] }).success(function (response) { $scope.cards.push({ "cardNumber": response.number, "ExpDate": response.expiration_month + "/" + response.expiration_year, "brand": response.brand, }); }); } } appProgress.hidePleaseWait(); }).error(function (err) { appProgress.hidePleaseWait(); }); $scope.cards = []; $scope.gridCards = { data: 'cards', multiSelect: false, selectedItems: $scope.selectedPart, columnDefs: [{ field: 'cardNumber', displayName: 'Card Number', width: '**', cellTemplate: '<div style="padding:5px"><img src="/img/icons/{{row.entity.brand}}.png" width="40px"/> {{row.entity.cardNumber}} </div>' }, { field: 'ExpDate', displayName: 'Expiration Date' }] }; }; $scope.selectGridRowMyCards = function () { }; $scope.addCard = function () { $('#addCardModal').modal({ backdrop: 'static', keyboard: false }); }; $scope.addCreditCardDialog2 = function () { createDialogService({ id: 'addCreditCardDialog2', title: 'Add Credit Card', backdrop: true, css: { margin: 'auto', width: '50%' }, controller: 'TestingController', templateUrl: 'modules/testing/views/createCreditCard.html', successButtonVisibility: true, cancelButtonVisibility: true, cancel: { label: 'Cancel'}, success: { label: 'Add Card', fn: function () { var successCallback = function () { appProgress.hidePleaseWait(); }; var failureCallback = function (error) { alert("An error occured while adding card."); console.error(error); appProgress.hidePleaseWait(); }; appProgress.showPleaseWait(); creditCardMgmt.updateCreditCard($scope, $scope.user, successCallback, failureCallback); } } }); }; $scope.addBankAccountDialog = function () { createDialogService({ id: 'addBankAccountDialog', title: 'Add Bank Account', backdrop: true, css: { margin: 'auto', width: '50%' }, controller: 'TestingController', templateUrl: 'modules/testing/views/dialogCreateBankAccount.html', successButtonVisibility: true, cancelButtonVisibility: true, cancel: { label: 'Cancel' }, success: { label: 'Add Account', fn: function () { var successCallback = function () { //TODO: refresh page? appProgress.hidePleaseWait(); }; var failureCallback = function (error) { alert("An error occured while adding bank account."); console.error(error); appProgress.hidePleaseWait(); }; appProgress.showPleaseWait(); bankAccountMgmt.updateBankAccount($scope, $scope.user, successCallback, failureCallback); } } }); }; $scope.getCreditCard = function () { console.log('getCreditCard()'); appProgress.showPleaseWait(); $http.get('/registrationsdetails/' + $scope.user._id).success(function (reg) { if (reg && reg[0].creditCardId[0]) { $http.post('/getObject', { "objectHref": "/cards/" + reg[0].creditCardId[0] }).success(function (response) { $("#ccNumber").val(response.number); $("#ccName").val(response.name); $("#ccCode").val(response.cvv); $("#ccExpMonth").val(response.expiration_month); $("#ccExpYear").val(response.expiration_year); $("#ccAddress1").val(response.address.line1); $("#ccAddress2").val(response.address.line2); $("#ccCity").val(response.address.city); $("#ccState").val(response.address.state); $("#ccZip").val(response.address.postal_code); appProgress.hidePleaseWait(); }). error(function (response) { appProgress.hidePleaseWait(); $scope.error = response.message; $scope.payment = null; }); } appProgress.hidePleaseWait(); }) .error(function (error) { appProgress.hidePleaseWait(); alert(error); }); appProgress.hidePleaseWait(); }; $scope.updateCreditCard = function () { console.log('testing.updateCreditCard()'); console.log($scope.payment); appProgress.showPleaseWait(); var card = { "expiration_month": $("#ccExpMonth").val(), "cvv": $("#ccCode").val(), "number": $("#ccNumber").val(), "expiration_year": $("#ccExpYear").val(), "name": $("#ccName").val() }; var address = { "city": $("#ccCity").val(), "line1": $("#ccAddress1").val(), "line2": $("#ccAddress2").val(), "state": $("#ccState").val(), "postal_code": $("#ccZip").val() }; var createCardObj = { "card": card, "address": address }; $http.get('/registrationsdetails/' + $scope.user._id).success(function (reg) { if (reg && reg[0].balancedPaymentsId) { $http.post('/getObject', { "objectHref": "/customers/" + reg[0].balancedPaymentsId }).success(function (response) { $scope.success = $scope.error = null; $http.post('/createCard', createCardObj).success(function (card_response) { console.log(card_response); var cardHref = card_response.href; created_card = card_response; $http.post('/addCardToCustomer', { "customerHref": "/customers/" + reg[0].balancedPaymentsId, "cardHref": created_card.href }).success(function (addCardResponse) { console.log(addCardResponse); console.log('created customer card'); //Updare the registration object with the card id and save the reg object. var registration = new Registrations({ _id: reg[0]._id, user: $scope.user._id }); reg[0].creditCardId.push(addCardResponse.id); registration.creditCardId = reg[0].creditCardId; registration.$update(function (response) { console.log('registration saved'); $scope.success = true; appProgress.hidePleaseWait(); $('#addCardModal').modal('hide'); $scope.getCreditCardsList(); }, function (error) { console.log('failed saving registration data.'); }); }).error(function (response) { alert(response.message); }); }).error(function (response) { alert(response.message); }); }).error(function (response) { }); } else { var customer = { "name": $scope.user.firstName + ' ' + $scope.user.lastName, "email": $scope.user.email, "phone": "" }; $http.post('/createCustomer', customer).success(function (customer_response) { console.log(customer_response); var userHref = customer_response.href; if (userHref == undefined) { console.log('Error creating customer'); appProgress.hidePleaseWait(); return; } var registration = new Registrations({ balancedPaymentsId: customer_response.id, _id: reg[0]._id, user: $scope.user._id }); registration.$update(function (response) { $scope.success = true; //TODO:balanced get the response customer identifier and store with registration.js schema for user $http.post('/createCard', createCardObj).success(function (card_response) { console.log(card_response); var cardHref = card_response.href; created_card = card_response; $http.post('/addCardToCustomer', { "customerHref": "/customers/" + customer_response.id, "cardHref": created_card.href }).success(function (addCardResponse) { console.log(addCardResponse); console.log('created customer card'); console.log(addCardResponse); registration = new Registrations({ _id: reg[0]._id, user: $scope.user._id }); reg[0].creditCardId.push(addCardResponse.id); registration.creditCardId = reg[0].creditCardId; registration.$update(function (save_response) { console.log('registration saved'); $scope.success = true; appProgress.hidePleaseWait(); $('#addCardModal').modal('hide'); $scope.getCreditCardsList(); }).error(function (err) { console.log('failed saving registration data.'); $scope.error = err; }); }).error(function (response) { alert(response.message); }); }).error(function (response) { alert(response.message); }); }, function (response) { $scope.error = response.data.message; }); }) .error(function (error) { alert(error); }); } }); }; $scope.sendSMS = function () { console.log('send sms test'); appProgress.showPleaseWait(); $http.post('/sendSMS', $scope.sms).success(function (response) { // If successful show success message and clear form $scope.success = true; $scope.sms = null; appProgress.hidePleaseWait(); }).error(function (response) { appProgress.hidePleaseWait(); $scope.error = response.message; $scope.sms = null; }); }; $scope.completePurchase = function () { appProgress.showPleaseWait(); $http.post('/completePurchase', $scope.payment).success(function (response) { // If successful show success message and clear form $scope.success = true; $scope.payment = null; appProgress.hidePleaseWait(); }).error(function (response) { appProgress.hidePleaseWait(); $scope.error = response.message; $scope.payment = null; }); }; $scope.sendEmail = function () { appProgress.showPleaseWait(); $http.post('/sendEmail', $scope.email).success(function (response) { // If successful show success message and clear form $scope.success = true; $scope.email = null; appProgress.hidePleaseWait(); }).error(function (response) { appProgress.hidePleaseWait(); $scope.error = response.message; $scope.email = null; }); }; var customer = { "name": "Mahmoud Ali", "dob_year": 1983, "dob_month": 12, "email": "[email protected]", "phone": "+201003183708" }; var card = { "expiration_month": "12", "cvv": "123", "number": "5105105105105100", "expiration_year": "2020", "customer": "" }; var address = { "city": '', "line1": '', "line2": '', "state": '', "postal_code": '' }; var createCardObj = { "card": card, "address": address }; var account = { "routing_number": "121000358", "account_type": "checking", "name": "Johann Bernoulli", "account_number": "9900000001" }; var debit = { "appears_on_statement_as": "TEST Transaction", "amount": 5000, "description": "TEST description", "cardHref": "" }; var credit = { "appears_on_statement_as": "TEST Transaction", "amount": 5000, "description": "TEST description", "accountHref": "" }; var created_customer; var created_card; var created_account; var customerHref = ''; $scope.createDemo = function () { $http.post('/createCustomer', customer).success(function (customer_response) { console.log(customer_response); created_customer = customer_response; customerHref = customer_response.href; createCardObj.card.customer = created_customer; $http.post('/createCard', createCardObj).success(function (card_response) { console.log(card_response); var cardHref = card_response.href; created_card = card_response; debit.cardHref = cardHref; $http.post('/addCardToCustomer', { "customerHref": created_customer.href, "cardHref": created_card.href }).success(function (addCardResponse) { console.log(addCardResponse); $http.post('/debitCard', debit).success(function (debit_response) { console.log(debit_response); }); }); }); $http.post('/createAccount', account).success(function (account_response) { console.log(account_response); var accountHref = account_response.href; created_account = account_response; credit.accountHref = accountHref; $http.post('/addAccountToCustomer', { "customerHref": created_customer.href, "accountHref": created_account.href }).success(function (addAccountResponse) { console.log(addAccountResponse); $http.post('/creditAccount', credit).success(function (credit_response) { console.log(credit_response); }); }); }); }); }; /*$http.post('/deleteItem', {"objectHref":"/debits/WD5e3Cc1fRS4D76Zfjf0Vv8l"}).success(function (response) { console.log(response); });/*/ /* $http.post('/deleteItem', {"objectHref":"/cards/CCzkUIc7fbXT48UT73v3XOH"}).success(function (response) { console.log(response); }); $http.post('/deleteItem', {"objectHref":"/customers/CU3pVBwQatDaKcwmgzacl1KH"}).success(function (response) { console.log(response); }).error(function(err) { console.log(err); }); */ //$http.post('/deleteItem', {"objectHref":"/customers/CUwLmXhuPxwRkLVIcRQmqYb"}).success(function (response) { // console.log(response); // }).error(function(err) { // console.log(err); // }); /* $http.post('/deleteItem', {"objectHref":"/customers/CU1LjRwaTmFrhL4uDYhx8ni3"}).success(function (response) { console.log(response); }).error(function(err) { console.log(err); }); /*/ /*$http.post('/debits').success(function (response) { console.log(response); });*/ /*$http.post('/listCustomers', {}).success(function (response) { console.log(response); });*/ /*$http.post('/getObject', {"objectHref":"/debits/"}).success(function (response) { console.log(response); });*/ $scope.addPart = function () { appProgress.showPleaseWait(); $http.post('/createPart', $scope.part).success(function (response) { // If successful show success message and clear form $scope.success = true; $scope.part = null; appProgress.hidePleaseWait(); }).error(function (response) { appProgress.hidePleaseWait(); $scope.error = response.message; $scope.part = null; }); }; } ]);
'use strict'; /** * Module dependencies. */ var should = require('should'), mongoose = require('mongoose'), User = mongoose.model('User'); /** * Globals */ var user, user2; /** * Unit tests */ describe.skip('User Model Unit Tests:', function() { before(function(done) { user = new User({ firstName: 'Full', lastName: 'Name', displayName: 'Full Name', email: '[email protected]', username: 'username', password: 'password', provider: 'local' }); user2 = new User({ firstName: 'Full', lastName: 'Name', displayName: 'Full Name', email: '[email protected]', username: 'username', password: 'password', provider: 'local' }); done(); }); describe('Method Save', function() { it('should begin with no users', function(done) { User.find({}, function(err, users) { users.should.have.length(0); done(); }); }); it('should be able to save without problems', function(done) { user.save(done); }); it('should fail to save an existing user again', function(done) { user.save(); return user2.save(function(err) { should.exist(err); done(); }); }); it('should be able to show an error when try to save without first name', function(done) { user.firstName = ''; return user.save(function(err) { should.exist(err); done(); }); }); }); after(function(done) { User.remove().exec(); done(); }); });
import { moduleForComponent, test } from 'ember-qunit'; moduleForComponent('model-selector', 'Unit | Component | model selector', { // Specify the other units that are required for this test // needs: ['component:foo', 'helper:bar'], unit: true }); test('it renders', function(assert) { assert.expect(2); // Creates the component instance var component = this.subject(); assert.equal(component._state, 'preRender'); // Renders the component to the page this.render(); assert.equal(component._state, 'inDOM'); });
{ "name": "jquery.thumbs.js", "url": "https://github.com/nfort/jquery.thumbs.js.git" }
'use strict'; import eachLimit from './eachLimit'; import doLimit from './internal/doLimit'; /** * Applies the function `iteratee` to each item in `coll`, in parallel. * The `iteratee` is called with an item from the list, and a callback for when * it has finished. If the `iteratee` passes an error to its `callback`, the * main `callback` (for the `each` function) is immediately called with the * error. * * Note, that since this function applies `iteratee` to each item in parallel, * there is no guarantee that the iteratee functions will complete in order. * * @name each * @static * @memberOf async * @alias forEach * @category Collection * @param {Array|Object} coll - A collection to iterate over. * @param {Function} iteratee - A function to apply to each item * in `coll`. The iteratee is passed a `callback(err)` which must be called once * it has completed. If no error has occurred, the `callback` should be run * without arguments or with an explicit `null` argument. The array index is not * passed to the iteratee. Invoked with (item, callback). If you need the index, * use `eachOf`. * @param {Function} [callback] - A callback which is called when all * `iteratee` functions have finished, or an error occurs. Invoked with (err). * @example * * // assuming openFiles is an array of file names and saveFile is a function * // to save the modified contents of that file: * * async.each(openFiles, saveFile, function(err){ * // if any of the saves produced an error, err would equal that error * }); * * // assuming openFiles is an array of file names * async.each(openFiles, function(file, callback) { * * // Perform operation on file here. * console.log('Processing file ' + file); * * if( file.length > 32 ) { * console.log('This file name is too long'); * callback('File name too long'); * } else { * // Do work to process file here * console.log('File processed'); * callback(); * } * }, function(err) { * // if any of the file processing produced an error, err would equal that error * if( err ) { * // One of the iterations produced an error. * // All processing will now stop. * console.log('A file failed to process'); * } else { * console.log('All files have been processed successfully'); * } * }); */ export default doLimit(eachLimit, Infinity);
import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; export default createSvgIcon([/*#__PURE__*/_jsx("path", { d: "M16 7h-1l-1-1h-4L9 7H8c-1.1 0-2 .9-2 2v6c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V9c0-1.1-.9-2-2-2zm-4 7c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2z" }, "0"), /*#__PURE__*/_jsx("path", { d: "M9.45.28c-.4.08-.55.56-.26.84l3.01 3.01c.32.31.85.09.85-.35V2.04c4.45.44 8.06 3.82 8.84 8.17.08.46.5.78.97.78.62 0 1.09-.57.98-1.18C22.61 2.89 15.79-1.12 9.45.28zm2.35 19.59c-.32-.32-.85-.09-.85.35v1.74c-4.45-.44-8.06-3.82-8.84-8.17-.08-.46-.5-.78-.97-.78-.62 0-1.09.57-.98 1.18 1.24 6.92 8.06 10.93 14.4 9.53.39-.09.55-.56.26-.85l-3.02-3z" }, "1")], 'CameraswitchRounded');
KISSY.add("brix/gallery/switchable/index", function(S,Brick,KSSwitchable) { /** * kissy switchable 组件的封装。 * @extends Brix.Brick * @class Brix.Gallery.Switchable * <a target="_blank" href="http://docs.kissyui.com/docs/html/api/component/switchable/">其他配置、方法、事件请参考KISSY API</a> * @param {Object} config 配置信息 */ var Switchable = Brick.extend({ constructor:function(config){ this.config = config; Switchable.superclass.constructor.apply(this, arguments); }, bindUI:function(){ var self = this, config = self.config; if(config.switchType){ var switchType = config.switchType; delete config.switchType; self.switchable = new KSSwitchable[switchType](self.get('el'),config); } else{ self.switchable = new KSSwitchable(self.get('el'),config); } config = null; delete self.config; }, destructor:function(){ var self = this; if(self.switchable&&self.switchable.destroy){ self.switchable.destroy(); } } }); /** * Switchable 实例对象类型Tabs|Slide|Carousel|Accordion。 * @cfg switchType */ /** * @property {Object} switchable KISSY switchable实例化后的对象 */ return Switchable; }, { requires: ["brix/core/brick",'switchable'] });
/*! * Flowtime.js * http://marcolago.com/flowtime-js/ * MIT licensed * * Copyright (C) 2012-2013 Marco Lago, http://marcolago.com */ var Flowtime = (function () { /** * test if the device is touch enbled */ var isTouchDevice = 'ontouchstart' in document.documentElement; /** * test if the HTML History API's where available * this value can be overridden to disable the History API */ var pushHistory = window.history.pushState; /** * application constants */ var SECTION_CLASS = "ft-section"; var SECTION_SELECTOR = "." + SECTION_CLASS; var PAGE_CLASS = "ft-page"; var PAGE_SELECTOR = "." + PAGE_CLASS; var FRAGMENT_CLASS = "ft-fragment"; var FRAGMENT_SELECTOR = "." + FRAGMENT_CLASS; var FRAGMENT_REVEALED_CLASS = "revealed"; var FRAGMENT_ACTUAL_CLASS = "actual"; var FRAGMENT_REVEALED_TEMP_CLASS = "revealed-temp"; var DEFAULT_PROGRESS_CLASS = "ft-default-progress"; var DEFAULT_PROGRESS_SELECTOR = "." + DEFAULT_PROGRESS_CLASS; var SECTION_THUMB_CLASS = "ft-section-thumb"; var SECTION_THUMB_SELECTOR = "." + SECTION_THUMB_CLASS; var PAGE_THUMB_CLASS = "ft-page-thumb"; var PAGE_THUMB_SELECTOR = "." + PAGE_THUMB_CLASS; /** * events */ var NAVIGATION_EVENT = "flowtimenavigation"; /** * application variables */ var ftContainer = document.querySelector(".flowtime"); // cached reference to .flowtime element var html = document.querySelector("html"); // cached reference to html element var body = document.querySelector("body"); // cached reference to body element var useHash = false; // if true the engine uses only the hash change logic var currentHash = ""; // the hash string of the current section / page pair var pastIndex = { section:0, page:0 }; // section and page indexes of the past page var isOverview = false; // Boolean status for the overview var siteName = document.title; // cached base string for the site title var overviewCachedDest; // caches the destination before performing an overview zoom out for navigation back purposes var overviewFixedScaleFactor = 22; // fixed scale factor for overview variant var defaultProgress = null; // default progress bar reference var _fragmentsOnSide = false; // enable or disable fragments navigation when navigating from sections var _fragmentsOnBack = true; // shows or hide fragments when navigating back to a page var _slideInPx = false; // calculate the slide position in px instead of %, use in case the % mode does not works var _sectionsSlideToTop = false; // if true navigation with right or left arrow go to the first page of the section var _useOverviewVariant = false; // use an alternate overview layout and navigation (experimental - useful in case of rendering issues) var _twoStepsSlide = false; // not yet implemented! slides up or down before, then slides to the page var _showProgress = false; // show or hide the default progress indicator (leave false if you want to implement a custom progress indicator) var _parallaxInPx = false; // if false the parallax movement is calulated in % values, if true in pixels var defaultParallaxX = 50; // the default parallax horizontal value used when no data-parallax value were specified var defaultParallaxY = 50; // the default parallax vertical value used when no data-parallax value were specified var parallaxEnabled = document.querySelector(".parallax") != null; // performance tweak, if there is no elements with .parallax class disable the dom manipulation to boost performances /** * test the base support */ var browserSupport = true; try { var htmlClass = document.querySelector("html").className.toLowerCase(); if (htmlClass.indexOf("ie7") != -1 || htmlClass.indexOf("ie8") != -1 || htmlClass.indexOf("lt-ie9") != -1 ) { browserSupport = false; } } catch(e) { browserSupport = false; } /** * add "ft-absolute-nav" hook class to body * to set the CSS properties * needed for application scrolling */ if (browserSupport) { Brav1Toolbox.addClass(body, "ft-absolute-nav"); } /* ## ## ### ## ## #### ###### ### ######## #### ####### ## ## ## ## ### ######## ######## #### ## ## ### ## ## ## ## ## ## ## ## ## ## ## ## ## ## ### ## ### ### ## ## ## ## ## ## ## ## #### ## ## ## ## ## ## ## ## ## ## ## ## ## #### ## #### #### ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## #### ## ## ## ## ## ## ## ## ## ## ### ## ## ## ## ######## ## ### ## #### ######### ## ## ## ## ## ######### ## ## ## ## ## #### ## ## ######### ## ## ## ## ## ## ## ### ## ## ## ## ## ## ## ## ## ## ## ## ## ## ### ## ## ## ## ## ## ## ## ## ## ## ## ## ## ### #### ###### ## ## ## #### ####### ## ## ## ## ## ## ## ## ## #### ## ## */ /** * NavigationMatrix is the Object who store the navigation grid structure * and which expose all the methods to get and set the navigation destinations */ var NavigationMatrix = (function () { var sections; // HTML Collection of .flowtime > .ft-section elements var sectionsArray; // multi-dimensional array containing the pages' array var allPages; // HTML Collection of .flowtime .ft-page elements var fragments; // HTML Collection of .fragment elements var fragmentsArray; // multi-dimensional array containing the per page fragments' array var fr = []; // multi-dimensional array containing the index of the current active fragment per page var parallaxElements = []; // array containing all elements with parrallax var sectionsLength = 0; // cached total number of .ft-section elements var pagesLength = 0; // cached max number of .page elements var pagesTotalLength = 0; // cached total number of .page elements var p = 0; // index of the current section viewved or higlighted var sp = 0; // index of the current page viewved or higlighted var pCache = 0; // cache index of the current section var spCache = 0; // cache index of the current page var hilited; // the current page higlighted, useful for overview mode /** * update the navigation matrix array * this is a publicy exposed method * useful for updating the matrix whne the site structure changes at runtime */ function _updateMatrix() { sectionsArray = []; parallaxElements = []; fragments = document.querySelectorAll(FRAGMENT_SELECTOR); fragmentsArray = []; sections = ftContainer.querySelectorAll(".flowtime > " + SECTION_SELECTOR); allPages = ftContainer.querySelectorAll(".flowtime " + PAGE_SELECTOR); // for (var i = 0; i < sections.length; i++) { var pagesArray = []; var section = sections[i]; fragmentsArray[i] = []; fr[i] = []; // if (section.getAttribute("data-id")) { section.setAttribute("data-id", "__" + unsafeAttr(section.getAttribute("data-id"))); // prevents attributes starting with a number } section.setAttribute("data-prog", "__" + (i + 1)); section.index = i; section.setAttribute("id", ""); // pages = section.querySelectorAll(PAGE_SELECTOR); pagesTotalLength += pages.length; pagesLength = Math.max(pagesLength, pages.length); // sets the pages max number for overview purposes for (var ii = 0; ii < pages.length; ii++) { var _sp = pages[ii]; if (_sp.getAttribute("data-id")) { _sp.setAttribute("data-id", "__" + unsafeAttr(_sp.getAttribute("data-id"))); // prevents attributes starting with a number } _sp.setAttribute("data-prog", "__" + (ii + 1)); _sp.index = ii; _sp.setAttribute("id", ""); // set data-title attributes to pages that doesn't have one and have at least an h1 heading element inside if (!_sp.getAttribute("data-title")) { var heading = _sp.querySelector("h1"); if (heading != null && heading.textContent.lenght != "") { _sp.setAttribute("data-title", heading.textContent); } } // store parallax data on elements setParallax(_sp, i, ii); // pagesArray.push(_sp); // var subFragments = _sp.querySelectorAll(FRAGMENT_SELECTOR); fragmentsArray[i][ii] = subFragments; fr[i][ii] = -1; } sectionsArray.push(pagesArray); } // sectionsLength = sections.length; // sets the sections max number for overview purposes resetScroll(); _updateOffsets(); } /** * stores parallax data directly on the dome elements with a data-parallax attribute * data are stored on a multi dimensional array ordered per section and per page to easily manage the position */ function setParallax(page, sectionIndex, pageIndex) { if (parallaxEnabled) { if (parallaxElements[sectionIndex] == undefined) { parallaxElements[sectionIndex] = []; } if (parallaxElements[sectionIndex][pageIndex] == undefined) { parallaxElements[sectionIndex][pageIndex] = []; } // var pxs = page.querySelectorAll(".parallax"); if (pxs.length > 0) { for (var i = 0; i < pxs.length; i++) { var el = pxs[i]; var pX = defaultParallaxX; var pY = defaultParallaxY; if (el.getAttribute("data-parallax") != null) { var pValues = el.getAttribute("data-parallax").split(","); pX = pY = pValues[0]; if (pValues.length > 1) { pY = pValues[1]; } } el.pX = pX; el.pY = pY; parallaxElements[sectionIndex][pageIndex].push(el); } } } } function _getParallaxElements() { return parallaxElements; } /** * cache the position for every page, useful when navigatin in pixels or when attaching a page after scrolling */ function _updateOffsets () { for (var i = 0; i < allPages.length; i++) { var _sp = allPages[i]; _sp.x = _sp.offsetLeft + _sp.parentNode.offsetLeft; _sp.y = _sp.offsetTop + _sp.parentNode.offsetTop; } }; /** * returns the next section in navigation * @param top Boolean if true the next page will be the first page in the next array; if false the next section will be the same index page in the next array * @param fos Boolean value of _fragmentsOnSide * @param io Boolean value of isOverview */ function _getNextSection(top, fos, io) { var sub = sp; var toTop = top == !_sectionsSlideToTop; if (fos == true && fragmentsArray[p][sp].length > 0 && fr[p][sp] < fragmentsArray[p][sp].length - 1 && toTop != true && io == false) { _showFragment(p, sp); } else { sub = 0; if (toTop == true && p + 1 < sectionsArray.length - 1) { sub = 0; } else if (toTop != true || _fragmentsOnBack == true || p + 1 > sectionsArray.length - 1) { sub = sp; } p = Math.min(p + 1, sectionsArray.length - 1); return _getNearestPage(sectionsArray[p], sub, io); } return hiliteOrNavigate(sectionsArray[p][sp], io); } /** * returns the prev section in navigation * @param top Boolean if true the next section will be the first page in the prev array; if false the prev section will be the same index page in the prev array * @param fos Boolean value of _fragmentsOnSide * @param io Boolean value of isOverview */ function _getPrevSection(top, fos, io) { var sub = sp; var toTop = top == !_sectionsSlideToTop; if (fos == true && fragmentsArray[p][sp].length > 0 && fr[p][sp] >= 0 && toTop != true && io == false) { _hideFragment(p, sp); } else { var sub = 0; sub = 0; if (toTop == true && p - 1 >= 0) { sub = 0; } else if (toTop != true || _fragmentsOnBack == true || p - 1 < 0) { sub = sp; } p = Math.max(p - 1, 0); return _getNearestPage(sectionsArray[p], sub, io); } return hiliteOrNavigate(sectionsArray[p][sp], io); } /** * checks if there is a valid page in the current section array * if the passed page is not valid thne check which is the first valid page in the array * then returns the page * @param p Number the section index in the sections array * @param sub Number the page index in the sections->page array * @param io Boolean value of isOverview */ function _getNearestPage(pg, sub, io) { var nsp = pg[sub]; if (nsp == undefined) { for (var i = sub; i >= 0; i--) { if (pg[i] != undefined) { nsp = pg[i]; sub = i; break; } } } sp = sub; if (!isOverview) { _updateFragments(); } return hiliteOrNavigate(nsp, io); } /** * returns the next page in navigation * if the next page is not in the current section array returns the first page in the next section array * @param jump Boolean if true jumps over the fragments directly to the next page * @param io Boolean value of isOverview */ function _getNextPage(jump, io) { if (fragmentsArray[p][sp].length > 0 && fr[p][sp] < fragmentsArray[p][sp].length - 1 && jump != true && io == false) { _showFragment(p, sp); } else { if (sectionsArray[p][sp + 1] == undefined && sectionsArray[p + 1] != undefined) { p += 1; sp = 0; } else { sp = Math.min(sp + 1, sectionsArray[p].length - 1); } } return hiliteOrNavigate(sectionsArray[p][sp], io); } /** * returns the prev page in navigation * if the prev page is not in the current section array returns the last page in the prev section array * @param jump Boolean if true jumps over the fragments directly to the prev page * @param io Boolean value of isOverview */ function _getPrevPage(jump, io) { if (fragmentsArray[p][sp].length > 0 && fr[p][sp] >= 0 && jump != true && io == false) { _hideFragment(p, sp); } else { if (sp == 0 && sectionsArray[p - 1] != undefined) { p -= 1; sp = sectionsArray[p].length - 1; } else { sp = Math.max(sp - 1, 0); } } return hiliteOrNavigate(sectionsArray[p][sp], io); } /** * returns the destination page or * if the application is in overview mode * switch the active page without returning a destination * @param d HTMLElement the candidate destination * @param io Boolean value of isOverview */ function hiliteOrNavigate(d, io) { if (io == true) { _switchActivePage(d); return; } else { return d; } } /** * show a single fragment inside the specified section / page * the fragment index parameter is optional, if passed force the specified fragment to show * otherwise the method shows the current fragment * @param fp Number the section index * @param fsp Number the page index * @param f Number the fragment index (optional) */ function _showFragment(fp, fsp, f) { if (f != undefined) { fr[fp][fsp] = f; } else { f = fr[fp][fsp] += 1; } for (var i = 0; i <= f; i++) { Brav1Toolbox.addClass(fragmentsArray[fp][fsp][i], FRAGMENT_REVEALED_CLASS); Brav1Toolbox.removeClass(fragmentsArray[fp][fsp][i], FRAGMENT_ACTUAL_CLASS); } Brav1Toolbox.addClass(fragmentsArray[fp][fsp][f], FRAGMENT_ACTUAL_CLASS); } /** * hide a single fragment inside the specified section / page * the fragment index parameter is optional, if passed force the specified fragment to hide * otherwise the method hides the current fragment * @param fp Number the section index * @param fsp Number the page index * @param f Number the fragment index (optional) */ function _hideFragment(fp, fsp, f) { if (f != undefined) { fr[fp][fsp] = f; } else { f = fr[fp][fsp]; } for (var i = 0; i < fragmentsArray[fp][fsp].length; i++) { if (i >= f) { Brav1Toolbox.removeClass(fragmentsArray[fp][fsp][i], FRAGMENT_REVEALED_CLASS); Brav1Toolbox.removeClass(fragmentsArray[fp][fsp][i], FRAGMENT_REVEALED_TEMP_CLASS); } Brav1Toolbox.removeClass(fragmentsArray[fp][fsp][i], FRAGMENT_ACTUAL_CLASS); } f -= 1; if (f >= 0) { Brav1Toolbox.addClass(fragmentsArray[fp][fsp][f], FRAGMENT_ACTUAL_CLASS); } fr[fp][fsp] = f; } /** * show all the fragments or the fragments in the specified page * adds a temporary class which does not override the current status of fragments */ function _showFragments() { for (var i = 0; i < fragments.length; i++) { Brav1Toolbox.addClass(fragments[i], FRAGMENT_REVEALED_TEMP_CLASS); } } /** * hide all the fragments or the fragments in the specified page * removes a temporary class which does not override the current status of fragments */ function _hideFragments() { for (var i = 0; i < fragments.length; i++) { Brav1Toolbox.removeClass(fragments[i], FRAGMENT_REVEALED_TEMP_CLASS); } } function _updateFragments() { for (var ip = 0; ip < fragmentsArray.length; ip++) { var frp = fragmentsArray[ip]; for (var isp = 0; isp < frp.length; isp++) { var frsp = frp[isp]; if (frsp.length > 0) { // there are fragments if (ip > p) { // previous section for (var f = frsp.length - 1; f >= 0; f--) { _hideFragment(ip, isp, f); } } else if (ip < p) { // next section for (var f = 0; f < frsp.length; f++) { _showFragment(ip, isp, f); } } else if (ip == p) { // same section if (isp > sp) { // previous page for (var f = frsp.length - 1; f >= 0; f--) { _hideFragment(ip, isp, f); } } else if (isp < sp) { // next page for (var f = 0; f < frsp.length; f++) { _showFragment(ip, isp, f); } } else if (isp == sp) { // same page if (_fragmentsOnBack == true && (pastIndex.section > NavigationMatrix.getPageIndex().section || pastIndex.page > NavigationMatrix.getPageIndex().page)) { for (var f = 0; f < frsp.length; f++) { _showFragment(ip, isp, f); } } else { for (var f = frsp.length - 1; f >= 0; f--) { _hideFragment(ip, isp, f); } } if (_fragmentsOnBack == false) { fr[ip][isp] = -1 } else { if (pastIndex.section > NavigationMatrix.getPageIndex().section || pastIndex.page > NavigationMatrix.getPageIndex().page) { fr[ip][isp] = frsp.length - 1; } else { fr[ip][isp] = -1 } } } } } } } } /** * returns the current section index */ function _getSection(h) { if (h) { // TODO return the index of the section by hash } return p; } /** * returns the current page index */ function _getPage(h) { if (h) { // TODO return the index of the page by hash } return sp; } /** * returns the sections collection */ function _getSections() { return sections; } /** * returns the pages collection inside the passed section index */ function _getPages(i) { return sectionsArray[i]; } /** * returns the pages collection of all pages in the presentation */ function _getAllPages() { return allPages; } /** * returns the number of sections */ function _getSectionsLength() { return sectionsLength; } /** * returns the max number of pages */ function _getPagesLength() { return pagesLength; } /** * returns the total number of pages */ function _getPagesTotalLength() { return pagesTotalLength; } /** * returns a object with the index of the current section and page */ function _getPageIndex(d) { var pIndex = p; var spIndex = sp; if (d != undefined) { pIndex = d.parentNode.index; //parseInt(d.parentNode.getAttribute("data-prog").replace(/__/, "")) - 1; spIndex = d.index; //parseInt(d.getAttribute("data-prog").replace(/__/, "")) - 1; } return { section: pIndex, page: spIndex }; } function _getSectionByIndex(i) { return sections[i]; } function _getPageByIndex(i, pi) { return sectionsArray[pi][i]; } function _getCurrentSection() { return sections[p]; } function _getCurrentPage() { return sectionsArray[p][sp]; } function _getCurrentFragment() { return fragmentsArray[p][sp][_getCurrentFragmentIndex()]; } function _getCurrentFragmentIndex() { return fr[p][sp]; } function _hasNextSection() { return p < sections.length - 1; } function _hasPrevSection() { return p > 0; } function _hasNextPage() { return sp < sectionsArray[p].length - 1; } function _hasPrevPage() { return sp > 0; } /** * get a progress value calculated on the total number of pages */ function _getProgress() { if (p == 0 && sp == 0) { return 0; } var c = 0; for (var i = 0; i < p; i++) { c += sectionsArray[i].length; } c += sectionsArray[p][sp].index + 1; return c; } /** * get a composed hash based on current section and page */ function _getHash(d) { if (d != undefined) { sp = _getPageIndex(d).page; p = _getPageIndex(d).section; } var h = ""; // append to h the value of data-id attribute or, if data-id is not defined, the data-prog attribute var _p = sections[p]; h += getPageId(_p); if (sectionsArray[p].length > 1) { var _sp = sectionsArray[p][sp]; h += "/" + getPageId(_sp); } return h; } /** * expose the method to set the page from a hash */ function _setPage(h) { var elem = getElementByHash(h); if (elem) { var pElem = elem.parentNode; for (var i = 0; i < sectionsArray.length; i++) { var pa = sectionsArray[i]; if (sections[i] === pElem) { p = i; for (var ii = 0; ii < pa.length; ii++) { if (pa[ii] === elem) { sp = ii; break; } } } } _updateFragments(); } return elem; } function _switchActivePage(d, navigate) { var sIndex = d.parentNode.index; for (var i = 0; i < sectionsArray.length; i++) { var pa = sectionsArray[i]; for (var ii = 0; ii < pa.length; ii++) { var spa = pa[ii]; // Brav1Toolbox.removeClass(spa, "past-section"); Brav1Toolbox.removeClass(spa, "future-section"); Brav1Toolbox.removeClass(spa, "past-page"); Brav1Toolbox.removeClass(spa, "future-page"); // if (spa !== d) { Brav1Toolbox.removeClass(spa, "hilite"); if (isOverview == false && spa !== _getCurrentPage()) { Brav1Toolbox.removeClass(spa, "actual"); } if (i < sIndex) { Brav1Toolbox.addClass(spa, "past-section"); } else if (i > sIndex) { Brav1Toolbox.addClass(spa, "future-section"); } if (spa.index < d.index) { Brav1Toolbox.addClass(spa, "past-page"); } else if (spa.index > d.index) { Brav1Toolbox.addClass(spa, "future-page"); } } } } Brav1Toolbox.addClass(d, "hilite"); if (navigate) { setActual(d); } hilited = d; } function _getCurrentHilited() { return hilited; } function setActual(d) { Brav1Toolbox.addClass(d, "actual"); } _updateMatrix(); // update the navigation matrix on the first run return { update: _updateMatrix, updateFragments: _updateFragments, showFragments: _showFragments, hideFragments: _hideFragments, getSection: _getSection, getPage: _getPage, getSections: _getSections, getPages: _getPages, getAllPages: _getAllPages, getNextSection: _getNextSection, getPrevSection: _getPrevSection, getNextPage: _getNextPage, getPrevPage: _getPrevPage, getSectionsLength: _getSectionsLength, getPagesLength: _getPagesLength, getPagesTotalLength: _getPagesTotalLength, getPageIndex: _getPageIndex, getSectionByIndex: _getSectionByIndex, getPageByIndex: _getPageByIndex, getCurrentSection: _getCurrentSection, getCurrentPage: _getCurrentPage, getCurrentFragment: _getCurrentFragment, getCurrentFragmentIndex: _getCurrentFragmentIndex, getProgress: _getProgress, getHash: _getHash, setPage: _setPage, switchActivePage: _switchActivePage, getCurrentHilited: _getCurrentHilited, hasNextSection: _hasNextSection, hasPrevSection: _hasPrevSection, hasNextPage: _hasNextPage, hasPrevPage: _hasPrevPage, updateOffsets: _updateOffsets, getParallaxElements: _getParallaxElements } })(); /* ## ## ### ## ## #### ###### ### ######## #### ####### ## ## ######## ## ## ######## ## ## ######## ###### ### ## ## ## ## ## ## ## ## ## ## ## ## ## ## ### ## ## ## ## ## ### ## ## ## ## #### ## ## ## ## ## ## ## ## ## ## ## ## ## #### ## ## ## ## ## #### ## ## ## ## ## ## ## ## ## ## ## ## #### ## ## ## ## ## ## ## ## ## ###### ## ## ###### ## ## ## ## ###### ## #### ######### ## ## ## ## ## ######### ## ## ## ## ## #### ## ## ## ## ## #### ## ## ## ### ## ## ## ## ## ## ## ## ## ## ## ## ## ## ### ## ## ## ## ## ### ## ## ## ## ## ## ## ### #### ###### ## ## ## #### ####### ## ## ######## ### ######## ## ## ## ###### */ /** * add a listener for event delegation * used for navigation purposes */ if (browserSupport) { if (isTouchDevice) { Brav1Toolbox.addListener(document, "touchend", onNavClick, false); } else { Brav1Toolbox.addListener(document, "click", onNavClick, false); } } function onNavClick(e) { var href = e.target.getAttribute("href"); // links with href starting with # if (href && href.substr(0,1) == "#") { e.target.blur(); e.preventDefault(); var h = href; var dest = NavigationMatrix.setPage(h); navigateTo(dest, true, true); } // pages in oveview mode if (isOverview) { var dest = e.target; while (dest && !Brav1Toolbox.hasClass(dest, PAGE_CLASS)) { dest = dest.parentNode; } if (Brav1Toolbox.hasClass(dest, PAGE_CLASS)) { e.preventDefault(); navigateTo(dest, null, true); } } // thumbs in the default progress indicator if (Brav1Toolbox.hasClass(e.target, PAGE_THUMB_CLASS)) { e.preventDefault(); var pTo = Number(unsafeAttr(e.target.getAttribute("data-section"))); var spTo = Number(unsafeAttr(e.target.getAttribute("data-page"))); _gotoPage(pTo, spTo); } } /** * set callback for onpopstate event * uses native history API to manage navigation * but uses the # for client side navigation on return */ if (useHash == false && window.history.pushState) { window.onpopstate = onPopState; } else { useHash = true; } // function onPopState(e) { useHash = false; var h; if (e.state) { h = e.state.token.replace("#/", ""); } else { h = document.location.hash.replace("#/", ""); } var dest = NavigationMatrix.setPage(h); navigateTo(dest, false); } /** * set callback for hashchange event * this callback is used not only when onpopstate event wasn't available * but also when the user resize the window or for the firs visit on the site */ Brav1Toolbox.addListener(window, "hashchange", onHashChange); // /** * @param e Event the hashChange Event * @param d Boolean force the hash change */ function onHashChange(e, d) { if (useHash || d) { var h = document.location.hash.replace("#/", ""); var dest = NavigationMatrix.setPage(h); navigateTo(dest, false); } } /* ######## ####### ## ## ###### ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ######### ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ####### ####### ###### ## ## */ var _ftX = ftContainer.offsetX; var _ftY = 0; var _touchStartX = 0; var _touchStartY = 0; var _deltaX = 0; var _deltaY = 0; var _dragging = 0; var _dragAxis = "x"; var _swipeLimit = 100; html.addEventListener("touchstart", onTouchStart, false); html.addEventListener("touchmove", onTouchMove, false); html.addEventListener("touchend", onTouchEnd, false); function onTouchStart(e) { _deltaX = 0; _deltaY = 0; e.preventDefault(); e = getTouchEvent(e); _touchStartX = e.clientX; _touchStartY = e.clientY; _dragging = 1; var initOffset = getInitOffset(); _ftX = initOffset.x; _ftY = initOffset.y; } function onTouchMove(e) { e.preventDefault(); e = getTouchEvent(e); _deltaX = e.clientX - _touchStartX; _deltaY = e.clientY - _touchStartY; } function onTouchEnd(e) { // e.preventDefault(); e = getTouchEvent(e); _dragging = 0; _dragAxis = Math.abs(_deltaX) >= Math.abs(_deltaY) ? "x" : "y"; if (_dragAxis == "x" && Math.abs(_deltaX) >= _swipeLimit) { if (_deltaX > 0) { _prevSection(); return; } else if (_deltaX < 0) { _nextSection(); return; } } else { if (_deltaY > 0 && Math.abs(_deltaY) >= _swipeLimit) { _prevPage(); return; } else if (_deltaY < 0) { _nextPage(); return; } } } function getTouchEvent(e) { if (e.touches) { e = e.touches[0]; } return e; } function getInitOffset() { var off = ftContainer.style[Brav1Toolbox.getPrefixed("transform")]; // X var indexX = off.indexOf("translateX(") + 11; var offX = off.substring(indexX, off.indexOf(")", indexX)); if (offX.indexOf("%") != -1) { offX = offX.replace("%", ""); offX = (parseInt(offX) / 100) * window.innerWidth; } else if (offX.indexOf("px") != -1) { offX = parseInt(offX.replace("px", "")); } // Y var indexY = off.indexOf("translateY(") + 11; var offY = off.substring(indexY, off.indexOf(")", indexY)); if (offY.indexOf("%") != -1) { offY = offY.replace("%", ""); offY = (parseInt(offY) / 100) * window.innerHeight; } else if (offY.indexOf("px") != -1) { offY = parseInt(offY.replace("px", "")); } return { x:offX, y:offY }; } /* ###### ###### ######## ####### ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ###### ## ######## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ###### ###### ## ## ####### ######## ######## */ /** * native scroll management */ var scrollEventEnabled = true; Brav1Toolbox.addListener(window, "scroll", onNativeScroll); function onNativeScroll(e) { e.preventDefault(); resetScroll(); } /* ######## ######## ###### #### ######## ######## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ######## ###### ###### ## ## ###### ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ######## ###### #### ######## ######## */ /** * monitoring function that triggers hashChange when resizing window */ var resizeMonitor = (function _resizeMonitor() { var ticker = NaN; function _enable() { _disable(); if (!isOverview) { ticker = setTimeout(doResizeHandler, 300); } } function _disable() { clearTimeout(ticker); } function doResizeHandler() { NavigationMatrix.updateOffsets(); navigateTo(); } Brav1Toolbox.addListener(window, "resize", _enable); window.addEventListener("orientationchange", _enable, false); return { enable: _enable, disable: _disable, } })(); /* ## ## ######## #### ## ###### ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ###### ## ## ## ## ## ## ## ## ## ## ## ## ## ####### ## #### ######## ###### */ /** * returns the element by parsing the hash * @param h String the hash string to evaluate */ function getElementByHash(h) { if (h.length > 0) { var aHash = h.replace("#/", "").split("/"); // TODO considerare l'ultimo slash come nullo var p = document.querySelector(SECTION_SELECTOR + "[data-id=__" + aHash[0] + "]") || document.querySelector(SECTION_SELECTOR + "[data-prog=__" + aHash[0] + "]"); if (p != null) { var sp = null; if (aHash.length > 1) { sp = p.querySelector(PAGE_SELECTOR + "[data-id=__" + aHash[1] + "]") || p.querySelector(PAGE_SELECTOR + "[data-prog=__" + aHash[1] + "]"); } if (sp == null) { sp = p.querySelector(PAGE_SELECTOR); } return sp; } } return; } /** * public method to force navigation updates */ function _updateNavigation() { NavigationMatrix.update(); onHashChange(null, true); } /** * builds and sets the title of the document parsing the attributes of the current section * if a data-title is available in a page and or in a section then it will be used * otherwise it will be used a formatted version of the hash string */ function setTitle(h) { var t = siteName; var ht = NavigationMatrix.getCurrentPage().getAttribute("data-title"); if (ht == null) { var hs = h.split("/"); for (var i = 0; i < hs.length; i++) { t += " | " + hs[i]; } } else { if (NavigationMatrix.getCurrentSection().getAttribute("data-title") != null) { t += " | " + NavigationMatrix.getCurrentSection().getAttribute("data-title"); } t += " | " + ht } document.title = t; } /** * returns a clean string of navigation atributes of the passed page * if there is a data-id attribute it will be returned * otherwise will be returned the data-prog attribute */ function getPageId(d) { return (d.getAttribute("data-id") != null ? d.getAttribute("data-id").replace(/__/, "") : d.getAttribute("data-prog").replace(/__/, "")); } /** * returns a safe version of an attribute value * adding __ in front of the value */ function safeAttr(a) { if (a.substr(0,2) != "__") { return "__" + a; } else { return a; } } /** * clean the save value of an attribute * removing __ from the beginning of the value */ function unsafeAttr(a) { if (a.substr(0,2) == "__") { return a.replace(/__/, ""); } else { return a; } } /* ## ## ### ## ## #### ###### ### ######## ######## ######## ####### ### ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## #### ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## #### ## ## ## ###### ## ## ## ## #### ######### ## ## ## ## ## ######### ## ## ## ## ## ## ### ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ### #### ###### ## ## ## ######## ## ####### */ /** * navigation transition logic * @param dest HTMLElement the page to go to * @param push Boolean if true the hash string were pushed to the history API * @param linked Boolean if true triggers a forced update of all the fragments in the pages, used when navigating from links or overview */ function navigateTo(dest, push, linked) { push = push == false ? push : true; // if dest doesn't exist then go to homepage if (!dest) { if (NavigationMatrix.getCurrentPage() != null) { dest = NavigationMatrix.getCurrentPage(); } else { dest = document.querySelector(PAGE_SELECTOR); } push = true; } // checks what properties use for navigation and set the style navigate(dest); // moveParallax(dest); // if (isOverview) { _toggleOverview(false, false); } // var h = NavigationMatrix.getHash(dest); if (linked == true) { NavigationMatrix.updateFragments(); } // set history properties var pageIndex = NavigationMatrix.getPageIndex(dest); if (pastIndex.section != pageIndex.section || pastIndex.page != pageIndex.page) { if (pushHistory != null && push != false && NavigationMatrix.getCurrentFragmentIndex() == -1) { var stateObj = { token: h }; var nextHash = "#/" + h; currentHash = nextHash; window.history.pushState(stateObj, null, currentHash); } else { document.location.hash = "/" + h; } } // set the title setTitle(h); // // dispatches an event populated with navigation data fireNavigationEvent(); // cache the section and page index, useful to determine the direction of the next navigation pastIndex = pageIndex; NavigationMatrix.switchActivePage(dest, true); // if (_showProgress) { updateProgress(); } } function fireNavigationEvent() { var pageIndex = NavigationMatrix.getPageIndex(); Brav1Toolbox.dispatchEvent(NAVIGATION_EVENT, { section: NavigationMatrix.getCurrentSection(), page: NavigationMatrix.getCurrentPage(), sectionIndex: pageIndex.section, pageIndex: pageIndex.page, pastSectionIndex: pastIndex.section, pastPageIndex: pastIndex.page, prevSection: NavigationMatrix.hasPrevSection(), nextSection: NavigationMatrix.hasNextSection(), prevPage: NavigationMatrix.hasPrevPage(), nextPage: NavigationMatrix.hasNextPage(), fragment: NavigationMatrix.getCurrentFragment(), fragmentIndex: NavigationMatrix.getCurrentFragmentIndex(), isOverview: isOverview, progress: NavigationMatrix.getProgress(), total: NavigationMatrix.getPagesTotalLength() } ); } /** * check the availability of transform CSS property * if transform is not available then fallbacks to position absolute behaviour */ function navigate(dest) { var x; var y; var pageIndex = NavigationMatrix.getPageIndex(dest); if (_slideInPx == true) { // calculate the coordinates of the destination x = dest.x; y = dest.y; } else { // calculate the index of the destination page x = pageIndex.section; y = pageIndex.page; } // if (Brav1Toolbox.testCSS("transform")) { if (_slideInPx) { ftContainer.style[Brav1Toolbox.getPrefixed("transform")] = "translateX(" + -x + "px) translateY(" + -y + "px)"; } else { ftContainer.style[Brav1Toolbox.getPrefixed("transform")] = "translateX(" + -x * 100 + "%) translateY(" + -y * 100 + "%)"; } } else { if (_slideInPx) { ftContainer.style.top = -y + "px"; ftContainer.style.left = -x + "px"; } else { ftContainer.style.top = -y * 100 + "%"; ftContainer.style.left = -x * 100 + "%"; } } resetScroll(); } function moveParallax(dest) { if (parallaxEnabled) { var pageIndex = NavigationMatrix.getPageIndex(dest); var pxElements = NavigationMatrix.getParallaxElements(); for (var i = 0; i < pxElements.length; i++) { var pxSection = pxElements[i]; if (pxSection != undefined) { for (var ii = 0; ii < pxSection.length; ii++) { var pxPage = pxSection[ii]; if (pxPage != undefined) { for (var iii = 0; iii < pxPage.length; iii++) { var pxElement = pxPage[iii] var pX = 0; var pY = 0; // sections if (pageIndex.section < i) { pX = pxElement.pX; } else if (pageIndex.section > i) { pX = -pxElement.pX; } // pages if (pageIndex.page < ii) { pY = pxElement.pY; } else if (pageIndex.page > ii) { pY = -pxElement.pY; } // animation if (_parallaxInPx) { pxElement.style[Brav1Toolbox.getPrefixed("transform")] = "translateX(" + pX + "px) translateY(" + pY + "px)"; } else { pxElement.style[Brav1Toolbox.getPrefixed("transform")] = "translateX(" + pX + "%) translateY(" + pY + "%)"; } } } } } } } } function resetScroll() { window.scrollTo(0,0); // fix the eventually occurred page scrolling resetting the scroll values to 0 } /* ######## ######## ####### ###### ######## ######## ###### ###### ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ######## ######## ## ## ## #### ######## ###### ###### ###### ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ####### ###### ## ## ######## ###### ###### */ var defaultProgress = null; var progressFill = null; function buildProgressIndicator() { var domFragment = document.createDocumentFragment(); // create the progress container div defaultProgress = document.createElement("div"); defaultProgress.className = DEFAULT_PROGRESS_CLASS; domFragment.appendChild(defaultProgress); // loop through sections for (var i = 0; i < NavigationMatrix.getSectionsLength(); i++) { var pDiv = document.createElement("div"); pDiv.setAttribute("data-section", "__" + i); pDiv.className = SECTION_THUMB_CLASS; Brav1Toolbox.addClass(pDiv, "thumb-section-" + i); // loop through pages var spArray = NavigationMatrix.getPages(i) for (var ii = 0; ii < spArray.length; ii++) { var spDiv = document.createElement("div"); spDiv.className = PAGE_THUMB_CLASS; spDiv.setAttribute("data-section", "__" + i); spDiv.setAttribute("data-page", "__" + ii); Brav1Toolbox.addClass(spDiv, "thumb-page-" + ii); pDiv.appendChild(spDiv); }; defaultProgress.appendChild(pDiv); }; body.appendChild(defaultProgress); } function hideProgressIndicator() { if (defaultProgress != null) { body.removeChild(defaultProgress); defaultProgress = null; } } function updateProgress() { if (defaultProgress != null) { var spts = defaultProgress.querySelectorAll(PAGE_THUMB_SELECTOR); for (var i = 0; i < spts.length; i++) { var spt = spts[i]; var pTo = Number(unsafeAttr(spt.getAttribute("data-section"))); var spTo = Number(unsafeAttr(spt.getAttribute("data-page"))); if (pTo == NavigationMatrix.getPageIndex().section && spTo == NavigationMatrix.getPageIndex().page) { Brav1Toolbox.addClass(spts[i], "actual"); } else { Brav1Toolbox.removeClass(spts[i], "actual"); } } } } function _getDefaultProgress() { return defaultProgress; } /* ####### ## ## ######## ######## ## ## #### ######## ## ## ## ## ### ## ## ### ###### ######## ## ## ######## ## ## ######## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ### ### ## ## ### ## ## ## ## ## ## ### ### ## ### ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## #### #### ## ## #### ## ## ## ## ## #### #### ## #### ## ## ## ## ## ## ###### ######## ## ## ## ###### ## ## ## ## ### ## ## ## ## ## ## ## ## ## #### ###### ## ### ## ###### ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ######### ## #### ######### ## ## ## ## ## ## ## #### ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ### ## ## ## ## ## ## ## ## ## ### ## ####### ### ######## ## ## ### #### ######## ### ### ## ## ## ## ## ## ## ## ###### ######## ## ## ######## ## ## ## */ /** * switch from the overview states */ function _toggleOverview(back, navigate) { if (isOverview) { zoomIn(back, navigate); } else { overviewCachedDest = NavigationMatrix.getCurrentPage(); zoomOut(); } } /** * zoom in the view to focus on the current section / page */ function zoomIn(back, navigate) { isOverview = false; Brav1Toolbox.removeClass(body, "ft-overview"); NavigationMatrix.hideFragments(); navigate = navigate === false ? false : true; if (navigate == true) { if (back == true) { navigateTo(overviewCachedDest); } else { navigateTo(); } } } /** * zoom out the view for an overview of all the sections / pages */ function zoomOut() { isOverview = true; Brav1Toolbox.addClass(body, "ft-overview"); NavigationMatrix.showFragments(); // if (_useOverviewVariant == false) { overviewZoomTypeA(true); } else { overviewZoomTypeB(true); } fireNavigationEvent(); } function overviewZoomTypeA(out) { // ftContainer scale version if (out) { var scaleX = 100 / NavigationMatrix.getSectionsLength(); var scaleY = 100 / NavigationMatrix.getPagesLength(); var scale = Math.min(scaleX, scaleY) * 0.9; var offsetX = (100 - NavigationMatrix.getSectionsLength() * scale) / 2; var offsetY = (100 - NavigationMatrix.getPagesLength() * scale) / 2; ftContainer.style[Brav1Toolbox.getPrefixed("transform")] = "translate(" + offsetX + "%, " + offsetY + "%) scale(" + scale/100 + ", " + scale/100 + ")"; } } function overviewZoomTypeB(out) { // ftContainer scale alternative version if (out) { var scale = overviewFixedScaleFactor // Math.min(scaleX, scaleY) * 0.9; var pIndex = NavigationMatrix.getPageIndex(); var offsetX = 50 - (scale * pIndex.section) - (scale / 2); var offsetY = 50 - (scale * pIndex.page) - (scale / 2); ftContainer.style[Brav1Toolbox.getPrefixed("transform")] = "translate(" + offsetX + "%, " + offsetY + "%) scale(" + scale/100 + ", " + scale/100 + ")"; } } /* ## ## ######## ## ## ######## ####### ### ######## ######## ## ## ### ## ## #### ###### ### ######## #### ####### ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ### ## ## ## ## ## ## ## ## ## ## ## ## ## ## ### ## ## ## ## #### ## ## ## ## ## ## ## ## ## ## #### ## ## ## ## ## ## ## ## ## ## ## ## ## #### ## ##### ###### ## ######## ## ## ## ## ######## ## ## ## ## ## ## ## ## ## ## ## #### ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ######### ## ## ## ## ## #### ######### ## ## ## ## ## ######### ## ## ## ## ## #### ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ### ## ## ## ## ## ## ## ## ## ## ## ## ## ## ### ## ## ######## ## ######## ####### ## ## ## ## ######## ## ## ## ## ### #### ###### ## ## ## #### ####### ## ## */ /** * KEYBOARD NAVIGATION */ Brav1Toolbox.addListener(window, "keydown", onKeyDown); Brav1Toolbox.addListener(window, "keyup", onKeyUp); function onKeyDown(e) { var tag = e.target.tagName; if (tag != "INPUT" && tag != "TEXTAREA" && tag != "SELECT") { if (e.keyCode >= 37 && e.keyCode <= 40) { e.preventDefault(); } } } function onKeyUp(e) { var tag = e.target.tagName; var elem; if (tag != "INPUT" && tag != "TEXTAREA" && tag != "SELECT") { e.preventDefault(); switch (e.keyCode) { case 27 : // esc _toggleOverview(true); break; case 33 : // pag up _gotoTop(); break; case 34 : // pag down _gotoBottom(); break; case 35 : // end _gotoEnd(); break; case 36 : // home _gotoHome(); break; case 37 : // left _prevSection(e.shiftKey); break; case 39 : // right _nextSection(e.shiftKey); break; case 38 : // up _prevPage(e.shiftKey); break; case 40 : // down _nextPage(e.shiftKey); break; case 13 : // return { if (isOverview) { _gotoPage(NavigationMatrix.getCurrentHilited()); } break; } default : break; } } } /* ######## ## ## ######## ## #### ###### ### ######## #### ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ######## ## ## ######## ## ## ## ## ## ######## ## ## ## ## ## ## ## ## ## ######### ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ####### ######## ######## #### ###### ## ## ## #### */ /** * triggers the first animation when visiting the site * if the hash is not empty */ function _start() { // init and configuration if (_showProgress && defaultProgress == null) { buildProgressIndicator(); } // start navigation if (document.location.hash.length > 0) { Brav1Toolbox.addClass(ftContainer, "no-transition"); onHashChange(null, true); Brav1Toolbox.removeClass(ftContainer, "no-transition"); } else { if (_start.arguments.length > 0) { _gotoPage.apply(this, _start.arguments); } else { _gotoPage(0,0); updateProgress(); } } } /* * Public API to go to the next section * @param top Boolean if true the next section will be the first page in the next array; if false the next section will be the same index page in the next array */ function _nextSection(top) { var d = NavigationMatrix.getNextSection(top, _fragmentsOnSide, isOverview); if (d != undefined) { navigateTo(d); } else { if (isOverview && _useOverviewVariant) { zoomOut(); } } } /* * Public API to go to the prev section * */ function _prevSection(top) { var d = NavigationMatrix.getPrevSection(top, _fragmentsOnSide, isOverview); if (d != undefined) { navigateTo(d); } else { if (isOverview && _useOverviewVariant) { zoomOut(); } } } /* * Public API to go to the next page */ function _nextPage(jump) { var d = NavigationMatrix.getNextPage(jump, isOverview); if (d != undefined) { navigateTo(d); } else { if (isOverview && _useOverviewVariant) { zoomOut(); } } } /* * Public API to go to the prev page */ function _prevPage(jump) { var d = NavigationMatrix.getPrevPage(jump, isOverview); if (d != undefined) { navigateTo(d); } else { if (isOverview && _useOverviewVariant) { zoomOut(); } } } /* * Public API to go to a specified section / page * the method accepts vary parameters: * if two numbers were passed it assumes that the first is the section index and the second is the page index; * if an object is passed it assumes that the object has a section property and a page property to get the indexes to navigate; * if an HTMLElement is passed it assumes the element is a destination page */ function _gotoPage() { var args = _gotoPage.arguments; if (args.length > 0) { if (args.length == 1) { if (Brav1Toolbox.typeOf(args[0]) === "Object") { var o = args[0]; var p = o.section; var sp = o.page; if (p != null && p != undefined) { var pd = document.querySelector(SECTION_SELECTOR + "[data-id=" + safeAttr(p) + "]"); if (sp != null && sp != undefined) { var spd = pd.querySelector(PAGE_SELECTOR + "[data-id=" + safeAttr(sp) + "]"); if (spd != null) { navigateTo(spd); return; } } } } else if (args[0].nodeName != undefined) { navigateTo(args[0], null, true); } } if (Brav1Toolbox.typeOf(args[0]) === "Number" || args[0] === 0) { var spd = NavigationMatrix.getPageByIndex(args[1], args[0]); navigateTo(spd); return; } } } function _gotoHome() { _gotoPage(0,0); } function _gotoEnd() { var sl = NavigationMatrix.getSectionsLength() - 1; _gotoPage(sl, NavigationMatrix.getPages(sl).length - 1); } function _gotoTop() { var pageIndex = NavigationMatrix.getPageIndex(); _gotoPage(pageIndex.section, 0); } function _gotoBottom() { var pageIndex = NavigationMatrix.getPageIndex(); _gotoPage(pageIndex.section, NavigationMatrix.getPages(pageIndex.section).length - 1); } function _addEventListener(type, handler, useCapture) { Brav1Toolbox.addListener(document, type, handler, useCapture); } /* ###### ######## ######## ######## ######## ######## ###### ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ###### ###### ## ## ###### ######## ###### ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ###### ######## ## ## ######## ## ## ###### */ function _setFragmentsOnSide(v) { _fragmentsOnSide = v; _setFragmentsOnBack(v); } function _setFragmentsOnBack(v) { _fragmentsOnBack = v; } function _setUseHistory(v) { pushHistory = v; } function _setSlideInPx(v) { _slideInPx = v; navigateTo(); } function _setSectionsSlideToTop(v) { _sectionsSlideToTop = v; } function _setGridNavigation(v) { _sectionsSlideToTop = !v; } function _setUseOverviewVariant(v) { _useOverviewVariant = v; } function _setTwoStepsSlide(v) { _twoStepsSlide = v; } function _setShowProgress(v) { _showProgress = v; if (_showProgress) { if (defaultProgress == null) { buildProgressIndicator(); } updateProgress(); } else { if (defaultProgress != null) { hideProgressIndicator(); } } } function _setDefaultParallaxValues(x, y) { defaultParallaxX = x; defaultParallaxY = y == undefined ? defaultParallaxX : y; NavigationMatrix.update(); } function _setParallaxInPx(v) { _parallaxInPx = v; } /** * return object for public methods */ return { start: _start, updateNavigation: _updateNavigation, nextSection: _nextSection, prevSection: _prevSection, next: _nextPage, prev: _prevPage, nextFragment: _nextPage, prevFragment: _prevPage, gotoPage: _gotoPage, gotoHome: _gotoHome, gotoTop: _gotoTop, gotoBottom: _gotoBottom, gotoEnd: _gotoEnd, toggleOverview: _toggleOverview, fragmentsOnSide: _setFragmentsOnSide, fragmentsOnBack: _setFragmentsOnBack, useHistory: _setUseHistory, slideInPx: _setSlideInPx, sectionsSlideToTop: _setSectionsSlideToTop, gridNavigation: _setGridNavigation, useOverviewVariant: _setUseOverviewVariant, twoStepsSlide: _setTwoStepsSlide, showProgress: _setShowProgress, addEventListener: _addEventListener, defaultParallaxValues: _setDefaultParallaxValues, parallaxInPx: _setParallaxInPx, getDefaultProgress: _getDefaultProgress }; })();
import React from 'react'; import xhttp from 'xhttp'; import {Modal, Button, Input, Alert} from 'react-bootstrap'; import ee from './../Emitter.js'; import ModalComponent from '../components/ModalComponent.js' import RegistrationForm from './../forms/RegistrationForm.js' export default class RegisterModal extends ModalComponent { constructor(props) { super(props) ee.addListener('route:/register', this.open.bind(this)); } componentDidUpdate() { if (this.refs.registrationForm) this.refs.registrationForm.ee.removeAllListeners('success') .addListener('success', this.handleRegistrationSuccess.bind(this)); } handleRegistrationSuccess(data) { if (data && data.request_received) ee.emit('alert', { msg: 'Registration request received. You will receive an email when an admin approves your request.', style: 'success' }) else ee.emit('update_app_data', data); this.close(); } open(props) { if (this.props.user.username) return window.history.pushState({}, '', '/'); super.open(props) } submit() { this.refs.registrationForm.submit(); } render() { return ( <Modal show={this.state.show} onHide={this.close.bind(this)}> <Modal.Header closeButton> <Modal.Title>Register</Modal.Title> </Modal.Header> <Modal.Body> <RegistrationForm ref='registrationForm' /> <hr/> <div className='text-center'> Already registered? Login <a href='/login'>here</a>. </div> </Modal.Body> <Modal.Footer> <Button onClick={this.close.bind(this)}>Close</Button> <Button onClick={this.submit.bind(this)}>Submit</Button> </Modal.Footer> </Modal> ) } }
/* * @flow */ import type {Suite} from "flow-dev-tools/src/test/Suite"; const { suite, test } = require("flow-dev-tools/src/test/Tester"); module.exports = (suite(({ addFile, addFiles, addCode }) => [ test("BigInt invalid decimal type literal", [ addCode(` type InvalidDecimal = 1.0n; `).newErrors( ` test.js:4 4: type InvalidDecimal = 1.0n; ^^^^ A bigint literal must be an integer `, ) ]), test("BigInt invalid negative decimal type literal", [ addCode(` type InvalidNegDecimal = -1.0n; `).newErrors( ` test.js:4 4: type InvalidNegDecimal = -1.0n; ^^^^^ A bigint literal must be an integer `, ) ]), test("BigInt invalid decimal literal", [ addCode(` const invalid_decimal = 1.0n; `).newErrors( ` test.js:4 4: const invalid_decimal = 1.0n; ^^^^ A bigint literal must be an integer `, ) ]), test("BigInt invalid negative decimal literal", [ addCode(` const invalid_neg_decimal = -1.0n; `).newErrors( ` test.js:4 4: const invalid_neg_decimal = -1.0n; ^^^^ A bigint literal must be an integer `, ) ]), test("BigInt invalid scientific type literal", [ addCode(` type InvalidE = 2e9n; `).newErrors( ` test.js:4 4: type InvalidE = 2e9n; ^^^^ A bigint literal cannot use exponential notation `, ) ]), test("BigInt invalid negative scientific type literal", [ addCode(` type InvalidNegE = -2e9n; `).newErrors( ` test.js:4 4: type InvalidNegE = -2e9n; ^^^^^ A bigint literal cannot use exponential notation `, ) ]), test("BigInt invalid scientific decimal type literal", [ addCode(` type InvalidNegDecimalE = 2.0e9n; `).newErrors( ` test.js:4 4: type InvalidNegDecimalE = 2.0e9n; ^^^^^^ A bigint literal cannot use exponential notation `, ) ]), test("BigInt invalid negative scientific decimal type literal", [ addCode(` type InvalidNegDecimalE = -2.0e9n; `).newErrors( ` test.js:4 4: type InvalidNegDecimalE = -2.0e9n; ^^^^^^^ A bigint literal cannot use exponential notation `, ) ]), test("BigInt invalid scientific literal", [ addCode(` const invalid_e = 2e9n; `).newErrors( ` test.js:4 4: const invalid_e = 2e9n; ^^^^ A bigint literal cannot use exponential notation `, ) ]), test("BigInt invalid negative scientific literal", [ addCode(` const invalid_neg_e = -2e9n; `).newErrors( ` test.js:4 4: const invalid_neg_e = -2e9n; ^^^^ A bigint literal cannot use exponential notation `, ) ]), test("BigInt invalid octal legacy type literal", [ addCode(` type InvalidOctalLegacy = 016432n; `).newErrors( ` test.js:4 4: type InvalidOctalLegacy = 016432n; ^^^^^^^ Unexpected token ILLEGAL `, ) ]), test("BigInt invalid negative octal legacy type literal", [ addCode(` type InvalidNegOctalLegacy = -016432n; `).newErrors( ` test.js:4 4: type InvalidNegOctalLegacy = -016432n; ^^^^^^^^ Unexpected token ILLEGAL `, ) ]), test("BigInt invalid octal legacy literal", [ addCode(` const invalid_octal_legacy = 016432n; `).newErrors( ` test.js:4 4: const invalid_octal_legacy = 016432n; ^^^^^^^ Unexpected token ILLEGAL `, ) ]), test("BigInt invalid negative octal legacy literal", [ addCode(` const invalid_neg_octal_legacy = -016432n; `).newErrors( ` test.js:4 4: const invalid_neg_octal_legacy = -016432n; ^^^^^^^ Unexpected token ILLEGAL `, ) ]), test("BigInt is not supported yet", [ addCode(` type S = bigint; const valid_binary = 0b101011101n; const valid_neg_binary = -0b101011101n; type ValidBinary = 0b101011101n; type ValidNegBinary = -0b101011101n; const valid_hex = 0xfff123n; const valid_neg_hex = -0xfff123n; type ValidHex = 0xfff123n; type ValidNegHex = -0xfff123n; const valid_large = 9223372036854775807n; const valid_neg_large = -9223372036854775807n; type ValidLarge = 9223372036854775807n; type ValidNegLarge = -9223372036854775807n; const valid_octal_new = 0o16432n; const valid_neg_octal_new = -0o16432n; type ValidOctalNew = 0o16432n; type ValidNegOctalNew = -0o16432n; const valid_small = 100n; const valid_neg_small = -100n; type ValidSmall = 100n; type ValidNegSmall = -1n; `).newErrors( ` test.js:4 4: type S = bigint; ^^^^^^ BigInt bigint [1] is not yet supported. [bigint-unsupported] References: 4: type S = bigint; ^^^^^^ [1] test.js:6 6: const valid_binary = 0b101011101n; ^^^^^^^^^^^^ BigInt bigint literal \`0b101011101n\` [1] is not yet supported. [bigint-unsupported] References: 6: const valid_binary = 0b101011101n; ^^^^^^^^^^^^ [1] test.js:7 7: const valid_neg_binary = -0b101011101n; ^^^^^^^^^^^^ BigInt bigint literal \`0b101011101n\` [1] is not yet supported. [bigint-unsupported] References: 7: const valid_neg_binary = -0b101011101n; ^^^^^^^^^^^^ [1] test.js:8 8: type ValidBinary = 0b101011101n; ^^^^^^^^^^^^ BigInt bigint literal \`0b101011101n\` [1] is not yet supported. [bigint-unsupported] References: 8: type ValidBinary = 0b101011101n; ^^^^^^^^^^^^ [1] test.js:9 9: type ValidNegBinary = -0b101011101n; ^^^^^^^^^^^^^ BigInt bigint literal \`-0b101011101n\` [1] is not yet supported. [bigint-unsupported] References: 9: type ValidNegBinary = -0b101011101n; ^^^^^^^^^^^^^ [1] test.js:11 11: const valid_hex = 0xfff123n; ^^^^^^^^^ BigInt bigint literal \`0xfff123n\` [1] is not yet supported. [bigint-unsupported] References: 11: const valid_hex = 0xfff123n; ^^^^^^^^^ [1] test.js:12 12: const valid_neg_hex = -0xfff123n; ^^^^^^^^^ BigInt bigint literal \`0xfff123n\` [1] is not yet supported. [bigint-unsupported] References: 12: const valid_neg_hex = -0xfff123n; ^^^^^^^^^ [1] test.js:13 13: type ValidHex = 0xfff123n; ^^^^^^^^^ BigInt bigint literal \`0xfff123n\` [1] is not yet supported. [bigint-unsupported] References: 13: type ValidHex = 0xfff123n; ^^^^^^^^^ [1] test.js:14 14: type ValidNegHex = -0xfff123n; ^^^^^^^^^^ BigInt bigint literal \`-0xfff123n\` [1] is not yet supported. [bigint-unsupported] References: 14: type ValidNegHex = -0xfff123n; ^^^^^^^^^^ [1] test.js:16 16: const valid_large = 9223372036854775807n; ^^^^^^^^^^^^^^^^^^^^ BigInt bigint literal \`9223372036854775807n\` [1] is not yet supported. [bigint-unsupported] References: 16: const valid_large = 9223372036854775807n; ^^^^^^^^^^^^^^^^^^^^ [1] test.js:17 17: const valid_neg_large = -9223372036854775807n; ^^^^^^^^^^^^^^^^^^^^ BigInt bigint literal \`9223372036854775807n\` [1] is not yet supported. [bigint-unsupported] References: 17: const valid_neg_large = -9223372036854775807n; ^^^^^^^^^^^^^^^^^^^^ [1] test.js:18 18: type ValidLarge = 9223372036854775807n; ^^^^^^^^^^^^^^^^^^^^ BigInt bigint literal \`9223372036854775807n\` [1] is not yet supported. [bigint-unsupported] References: 18: type ValidLarge = 9223372036854775807n; ^^^^^^^^^^^^^^^^^^^^ [1] test.js:19 19: type ValidNegLarge = -9223372036854775807n; ^^^^^^^^^^^^^^^^^^^^^ BigInt bigint literal \`-9223372036854775807n\` [1] is not yet supported. [bigint-unsupported] References: 19: type ValidNegLarge = -9223372036854775807n; ^^^^^^^^^^^^^^^^^^^^^ [1] test.js:21 21: const valid_octal_new = 0o16432n; ^^^^^^^^ BigInt bigint literal \`0o16432n\` [1] is not yet supported. [bigint-unsupported] References: 21: const valid_octal_new = 0o16432n; ^^^^^^^^ [1] test.js:22 22: const valid_neg_octal_new = -0o16432n; ^^^^^^^^ BigInt bigint literal \`0o16432n\` [1] is not yet supported. [bigint-unsupported] References: 22: const valid_neg_octal_new = -0o16432n; ^^^^^^^^ [1] test.js:23 23: type ValidOctalNew = 0o16432n; ^^^^^^^^ BigInt bigint literal \`0o16432n\` [1] is not yet supported. [bigint-unsupported] References: 23: type ValidOctalNew = 0o16432n; ^^^^^^^^ [1] test.js:24 24: type ValidNegOctalNew = -0o16432n; ^^^^^^^^^ BigInt bigint literal \`-0o16432n\` [1] is not yet supported. [bigint-unsupported] References: 24: type ValidNegOctalNew = -0o16432n; ^^^^^^^^^ [1] test.js:26 26: const valid_small = 100n; ^^^^ BigInt bigint literal \`100n\` [1] is not yet supported. [bigint-unsupported] References: 26: const valid_small = 100n; ^^^^ [1] test.js:27 27: const valid_neg_small = -100n; ^^^^ BigInt bigint literal \`100n\` [1] is not yet supported. [bigint-unsupported] References: 27: const valid_neg_small = -100n; ^^^^ [1] test.js:28 28: type ValidSmall = 100n; ^^^^ BigInt bigint literal \`100n\` [1] is not yet supported. [bigint-unsupported] References: 28: type ValidSmall = 100n; ^^^^ [1] test.js:29 29: type ValidNegSmall = -1n; ^^^ BigInt bigint literal \`-1n\` [1] is not yet supported. [bigint-unsupported] References: 29: type ValidNegSmall = -1n; ^^^ [1] `, ) ]), test("BigInt can be suppressed", [ addCode(` //$FlowFixMe type S = bigint; //$FlowFixMe type A = 1n; //$FlowFixMe const valid_binary = 0b101011101n; //$FlowFixMe const valid_hex = 0xfff123n; //$FlowFixMe const valid_large = 9223372036854775807n; //$FlowFixMe const valid_octal_new = 0o16432n; //$FlowFixMe const valid_small = 100n; `).noNewErrors() ]) ]): Suite);
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.jssPluginPropsSort = {})); }(this, (function (exports) { 'use strict'; /** * Sort props by length. */ function jssPropsSort() { var sort = function sort(prop0, prop1) { if (prop0.length === prop1.length) { return prop0 > prop1 ? 1 : -1; } return prop0.length - prop1.length; }; return { onProcessStyle: function onProcessStyle(style, rule) { if (rule.type !== 'style') return style; var newStyle = {}; var props = Object.keys(style).sort(sort); for (var i = 0; i < props.length; i++) { newStyle[props[i]] = style[props[i]]; } return newStyle; } }; } exports.default = jssPropsSort; Object.defineProperty(exports, '__esModule', { value: true }); }))); //# sourceMappingURL=jss-plugin-props-sort.js.map
var isObject = require('./isObject'); /** `Object#toString` result references. */ var regexpTag = '[object RegExp]'; /** Used for built-in method references. */ var objectProto = Object.prototype; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) * of values. */ var objectToString = objectProto.toString; /** * Checks if `value` is classified as a `RegExp` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, * else `false`. * @example * * _.isRegExp(/abc/); * // => true * * _.isRegExp('/abc/'); * // => false */ function isRegExp(value) { return isObject(value) && objectToString.call(value) == regexpTag; } module.exports = isRegExp;
/** * Module dependencies */ var _ = require('lodash'); var async = require('async'); var path = require('path'); var router = require('express') .Router(); /** * Models */ var Account = require('../models/Account'); var App = require('../models/App'); var Invite = require('../models/Invite'); /** * Policies */ var isAuthenticated = require('../policies/isAuthenticated'); /** * Services */ var accountMailer = require('../services/account-mailer'); /** * Helpers */ var logger = require('../../helpers/logger'); function sendConfirmationMail(acc, verifyToken, cb) { /** * Apps config */ var config = require('../../../config')('api'); var dashboardUrl = config.hosts.dashboard; var confirmUrl = dashboardUrl + '/account/' + acc._id.toString() + '/verify-email/' + verifyToken; var mailOptions = { locals: { confirmUrl: confirmUrl, name: acc.name }, to: { email: acc.email, name: acc.name } }; accountMailer.sendConfirmation(mailOptions, cb); } /** * GET /account/ * * NOTE: isAuthenticated middleware is called only for * get /account and not post /account */ router .route('/') .get(isAuthenticated) .get(function (req, res, next) { if (!req.user) { return res.notFound(); } res .status(200) .json(req.user); }); /** * POST /account * * Create a new account * * Check if invited: * - if invited, add as team member to app * - else, send email confirmation mail (TODO) */ router .route('/') .post(function (req, res, next) { /** * Apps config */ var config = require('../../../config')('api'); var account = req.body; async.waterfall( [ function createAccount(cb) { account.emailVerified = false; Account.create(account, cb); }, function defaultApp(acc, cb) { App.createDefaultApp(acc._id, acc.name, function (err, app) { cb(err, acc, app); }); }, function createVerifyToken(acc, app, cb) { acc.createVerifyToken(function (err, acc, verifyToken) { cb(err, acc, app, verifyToken); }); }, function sendMail(acc, app, verifyToken, cb) { sendConfirmationMail(acc, verifyToken, function (err) { cb(err, acc, app); }); }, function autoLogin(acc, app, cb) { req.login(acc, function (err) { cb(err, acc, app); }); } ], function callback(err, acc, app) { if (err) return next(err); return res .status(201) .json({ account: acc, app: app, message: 'Logged In Successfully' }); } ); }); /** * POST /account/invite * * Create a new account with invite * * Check if invited: * - if invited, add as team member to app * - else, send email confirmation mail (TODO) */ router .route('/invite') .post(function (req, res, next) { /** * Apps config */ var config = require('../../../config')('api'); var account = req.body; var inviteId = req.body.inviteId; logger.trace({ at: 'AccountController:createInvite', body: req.body }); if (!inviteId) return res.badRequest('inviteId is required'); async.waterfall( [ function findInvite(cb) { Invite .findById(inviteId) .exec(function (err, invite) { if (err) return cb(err); if (!invite) return cb(new Error('Invite not found')); cb(null, invite); }); }, function createAccount(invite, cb) { // set emailVerified as true account.emailVerified = true; Account.create(account, function (err, acc) { cb(err, acc, invite); }); }, function addMember(acc, invite, cb) { // add as a team member to the app the user was invited to App.addMember(invite.aid, acc._id, acc.name, function (err, app) { cb(err, acc, invite, app); }); }, function deleteInvite(acc, invite, app, cb) { // delete invite Invite.findByIdAndRemove(invite._id, function (err) { cb(err, acc, app); }); } ], function callback(err, acc, app) { if (err) return next(err); return res .status(201) .json({ account: acc, app: app, message: 'Logged In Successfully' }); } ); }); /** * POST /account/invite * * Creates a new account with an invite id * * Check if invited: * - if invited, add as team member to app * - else, send email confirmation mail (TODO) */ router .route('/') .post(function (req, res, next) { /** * Apps config */ var config = require('../../../config')('api'); var account = req.body; var inviteId = req.body.inviteId; var respond = function (err, acc, app) { if (err) return next(err); req.login(acc, function (err) { if (err) return next(err); return res .status(201) .json({ account: acc, app: app, message: 'Logged In Successfully' }); }); } if (!inviteId) return signupWithoutInvite(account, respond); signupWithInvite(account, inviteId, function (err, acc) { if (err && err.message === 'Invite not found') { return signupWithoutInvite(account, respond); } respond(err, acc); }); }); /** * POST /account/verify-email/resend * * Resend verification email * * @param {string} email email-address-of-account * */ router .route('/verify-email/resend') .post(function (req, res, next) { var email = req.body.email; if (!email) return res.badRequest('Please provide your email'); Account .findOne({ email: email }) .select('verifyToken emailVerified name email') .exec(function (err, acc) { if (err) return next(err); if (!acc) return res.notFound('Account not found'); if (acc.emailVerified) { return res.badRequest( 'Your email is already verified. Please login to access your account' ); } sendConfirmationMail(acc, acc.verifyToken, function (err) { if (err) return next(err); res .status(200) .json({ message: 'Verification email has been sent' }); }); }); }); /** * GET /account/:id/verify-email/:token * * TODO : Update this endpoint to /account/verify-email/:token * for consistency */ router .route('/:id/verify-email/:token') .get(function (req, res, next) { var accountId = req.params.id; var token = req.params.token; Account .verify(accountId, token, function (err, account) { if (err) { if (_.contains(['Invalid Token', 'Account Not Found'], err.message)) { return res.badRequest('Invalid Attempt'); } return next(err); } res .status(200) .json(account); }); }); /** * PUT /account/forgot-password/new * * * @param {string} token reset-password-token * @param {string} password new-password * * Verfies reset password token and updates password * * TODO: Make this more secure by prepending the account id to the token */ router .route('/forgot-password/new') .put(function (req, res, next) { var token = req.body.token; var newPass = req.body.password; if (!token || !newPass) { return res.badRequest('Please provide token and new password'); } logger.trace({ at: 'AccountController forgot-password/new', body: req.body }) async.waterfall([ function verify(cb) { Account .findOne({ passwordResetToken: token, }) .exec(function (err, account) { if (err) return cb(err); if (!account) return cb(new Error('INVALID_TOKEN')); cb(null, account); }); }, function updatePasswordAndRemoveToken(account, cb) { account.passwordResetToken = undefined; account.password = newPass account.save(cb); } ], function (err, account) { if (err) { if (err.message === 'INVALID_TOKEN') { return res.badRequest('Invalid Attempt. Please try again.'); } return next(err); } // remove password from response if (account.toJSON) account = account.toJSON(); delete account.password; res .status(200) .json({ message: 'Password token verified', account: account }); }); }); /** * PUT /account/name * Update account name */ router .route('/name') .put(isAuthenticated) .put(function (req, res, next) { req.user.name = req.body.name; req.user.save(function (err, account) { if (err) { return next(err); } res .status(200) .json(account); }); }); /** * PUT /account/default-app * Update account default app * * @param {string} defaultApp */ router .route('/default-app') .put(isAuthenticated) .put(function (req, res, next) { var defaultApp = req.body.defaultApp; if (!defaultApp) return res.badRequest('Please provide the app id'); req.user.defaultApp = defaultApp; req.user.save(function (err, account) { if (err) { return next(err); } res .status(200) .json({ message: 'Updated default app', account: account }); }); }); /** * PUT /account/forgot-password * * TODO: add the respective get request * which will check the token and redirect * user to new-password page */ router .route('/forgot-password') .put(function (req, res, next) { Account.createResetPasswordToken(req.body.email, function (err, account) { if (err) { if (err.message === 'Invalid Email') { return res.badRequest('Provide a valid email'); } if (err.message === 'Account Not Found') { return res.notFound('Provide a valid email'); } return next(err); } /** * Apps config */ var config = require('../../../config')('api'); var dashboardUrl = config.hosts.dashboard; accountMailer.sendForgotPassword({ locals: { url: dashboardUrl + '/forgot-password/' + account.passwordResetToken, name: account.name }, to: { email: account.email, name: account.name }, }, function (err) { if (err) return next(err); res .status(200) .json({ message: 'Reset password email sent' }); }); }); }); /** * PUT /account/password/update * Update account password */ router .route('/password/update') .put(isAuthenticated) .put(function (req, res, next) { var currPass = req.body.currentPassword; var newPass = req.body.newPassword; req.user.updatePassword(currPass, newPass, function (err) { if (err) { if (err.message === 'Incorrect Password') { return res.badRequest( 'Please provide the correct current password'); } return next(err); } res .status(200) .json({ message: 'Password updated' }); }); }); module.exports = router;
import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; export default createSvgIcon( /*#__PURE__*/_jsx("path", { d: "M11 17h10v-2H11v2zm-8-5 4 4V8l-4 4zm0 9h18v-2H3v2zM3 3v2h18V3H3zm8 6h10V7H11v2zm0 4h10v-2H11v2z" }), 'FormatIndentDecrease');
const makeUnique = array => [...new Set(array)]; export default makeUnique;