text
stringlengths
2
6.14k
import React, { Component } from 'react'; import ReactDOM from 'react-dom'; class MaterialInput extends Component { constructor(){ super(); this.isValid = this.isValid.bind(this); this.getName = this.getName.bind(this); } isValid() { if (this.props.valid !== undefined) { return this.props.valid; } else if (this.props.error !== undefined) { return this.props.error.length == 0; } // if nothing is given, assume value as valid return true; } getClass() { return (this.isValid() ? "react-validate" : "react-validate invalid"); } getName() { if (this.props.name.trim().length > 0) { return this.props.name; } return this.props.id; } render() { let valid = true; let error = this.props.error; if (this.props.validate) { let result = this.props.validate(this.props.value); if (typeof(result) === "boolean") { valid = result; } if (typeof(result) === "object") { if (result.hasOwnProperty('valid')) { valid = result['valid']; } if (result.hasOwnProperty('error')) { error = result['error']; } } } const outerClass = "input-field " + (this.props.className ? this.props.className : ""); const labelClass = (this.props.value.length > 0 ? "active " : ""); return ( <div className={outerClass}> <input type="text" id={this.props.id} name={this.getName()} key={this.getName()} className={this.getClass()} value={this.props.value} onChange={this.props.onChange} /> <label htmlFor={this.props.id} data-error={this.props.error} data-success="" className={labelClass}> {this.props.children} </label> </div> ) } } export default MaterialInput;
function PublishItemCtrl($scope, $http, $templateCache) { "use strict"; $scope.item; $scope.loading = false; $scope.loaded = false; $scope.convertURL = function() { var converter_url = django_js_utils.urls.resolve('urltoitem'); $scope.loading = true; jQuery.ajax( { url:converter_url, data: { url:$scope.url }, dataType:"json", traditional: true, success: function(data, status,request) { $scope.item = data[0]; $scope.loaded = true; $scope.loading = false; $('#urls').removeClass('error'); $scope.$apply(); }, error: function(data, status, request) { $scope.loaded = true; $scope.loading = false; $('#urls').addClass('error'); $scope.$apply(); } }); }; $scope.fetch = function(item_id) { $scope.loading = true; $http( { method: "GET", url: '/api/v2/feeditem/', params: { limit:1, id:item_id, }, cache: $templateCache, transformResponse: function(data,headersGetter) { return JSON.parse(data).objects; } }).success(function(data,status) { $scope.item = data[0]; $scope.loaded = true; $scope.loading = false; $scope.$apply(); }); } }
function serverStatus(serverID) { $.ajax({ type: "GET", url: "include/ajdb.php", data: "a=refresh_gamestatus&id="+serverID, success: function(html){ $("#checkStatusResponse").html(html); } }); }
function set_mitschat_variable(Y, mitsopts) { wwwroot = mitsopts.wwwroot; sid = mitsopts.sid; id = mitsopts.id; fname = mitsopts.fname; lname = mitsopts.lname; path = mitsopts.rid; imageurl = mitsopts.imageurl; }
(function() { /* 弹窗指令 */ angular.module('eolinker').directive('eoModel', ['$timeout', "$window", function($timeout, $window, EVENT) { return { restrict: 'AE', templateUrl: 'app/model/model.html', //replace: true, controller: eoModel } }]) eoModel.$inject = ['$scope'] function eoModel($scope) { } })();
const {app, BrowserWindow} = require('electron') const path = require('path') const url = require('url') // This line keeps a global reference of the window object, if you don't the //window will be closed automatically when the JS object is garbage collected. let win function createWindow () { //Create the browser window win = new BrowserWindow({width: 800, height:600}) //load the index.html of the app. win.loadURL(url.format({ pathname: path.join(__dirname, 'index.html'), protocol: 'file:', slashes: true })) //Open the DevTools. win.webContents.openDevTools() //Emitted when the window is closed. win.on('closed', () => { //Deference the window object, usually you would store windows in an array //if your app supports multi windows, this is the time when //you should delete the corresponding element. win = null }) } //This method will be called when Electron has finished initialization //and is ready to create browser windows. //Some APIs can only be used after this event occurs. app.on('ready', createWindow) //Quit when all windows are closed. app.on('window-all-closed', () => { if (process.platform !== 'darwin') { app.quit() } }) app.on('activate', () => { if (win === null) { createWindow() } })
"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 http_1 = require('@angular/http'); require('rxjs/add/operator/toPromise'); var HeroService = (function () { function HeroService(http) { this.http = http; this.heroesUrl = 'app/heroes'; // URL to web api this.headers = new http_1.Headers({ 'Content-Type': 'application/json' }); } /** getHeroes(): Promise<Hero[]> { return Promise.resolve(HEROES); } */ HeroService.prototype.getHeroes = function () { return this.http.get(this.heroesUrl) .toPromise() .then(function (response) { return response.json().data; }) .catch(this.handleError); }; HeroService.prototype.getHeroesSlowly = function () { var _this = this; return new Promise(function (resolve) { return setTimeout(resolve, 2000); }) // delay 2 seconds .then(function () { return _this.getHeroes(); }); }; HeroService.prototype.getHero = function (id) { return this.getHeroes() .then(function (heroes) { return heroes.find(function (hero) { return hero.id === id; }); }); }; HeroService.prototype.handleError = function (error) { console.error('An error occurred', error); // for demo purposes only return Promise.reject(error.message || error); }; HeroService.prototype.update = function (hero) { var url = this.heroesUrl + "/" + hero.id; return this.http .put(url, JSON.stringify(hero), { headers: this.headers }) .toPromise() .then(function () { return hero; }) .catch(this.handleError); }; HeroService.prototype.create = function (name) { return this.http .post(this.heroesUrl, JSON.stringify({ name: name }), { headers: this.headers }) .toPromise() .then(function (res) { return res.json().data; }) .catch(this.handleError); }; HeroService.prototype.delete = function (id) { var url = this.heroesUrl + "/" + id; return this.http.delete(url, { headers: this.headers }) .toPromise() .then(function () { return null; }) .catch(this.handleError); }; HeroService = __decorate([ core_1.Injectable(), __metadata('design:paramtypes', [http_1.Http]) ], HeroService); return HeroService; }()); exports.HeroService = HeroService; //# sourceMappingURL=hero.service.js.map
/** * Route Mappings * (sails.config.routes) * * Your routes map URLs to views and controllers. * * If Sails receives a URL that doesn't match any of the routes below, * it will check for matching files (images, scripts, stylesheets, etc.) * in your assets directory. e.g. `http://localhost:1337/images/foo.jpg` * might match an image file: `/assets/images/foo.jpg` * * Finally, if those don't match either, the default 404 handler is triggered. * See `api/responses/notFound.js` to adjust your app's 404 logic. * * Note: Sails doesn't ACTUALLY serve stuff from `assets`-- the default Gruntfile in Sails copies * flat files from `assets` to `.tmp/public`. This allows you to do things like compile LESS or * CoffeeScript for the front-end. * * For more information on configuring custom routes, check out: * http://sailsjs.org/#!/documentation/concepts/Routes/RouteTargetSyntax.html */ module.exports.routes = { /*************************************************************************** * * * Make the view located at `views/homepage.ejs` (or `views/homepage.jade`, * * etc. depending on your default view engine) your home page. * * * * (Alternatively, remove this and add an `index.html` file in your * * `assets` directory) * * * ***************************************************************************/ '/': { view: 'homepage' }, /*************************************************************************** * * * Custom routes here... * * * * If a request to a URL doesn't match any of the custom routes above, it * * is matched against Sails route blueprints. See `config/blueprints.js` * * for configuration options and examples. * * * ***************************************************************************/ '/concursantes':'MainController.getConcursantes', '/platos':'MainController.getPlatos', '/ingredientes':'MainController.getIngredientes', '/rondas':'MainController.getRondas', '/concursante/:id':'MainController.oneConcursante', '/plato/:id':'MainController.onePlato', '/ingrediente/:id':'MainController.oneIngrediente', '/ronda/:id':'MainController.oneRonda', '/eliminar/:id':'MainController.eliminar', '/detallePlato/:id':'MainController.detallePlato' };
/** * This file is part of the MailWizz EMA application. * * @package MailWizz EMA * @author Serban George Cristian <cristian.serban@mailwizz.com> * @link http://www.mailwizz.com/ * @copyright 2013-2016 MailWizz EMA (http://www.mailwizz.com) * @license http://www.mailwizz.com/license/ * @since 1.3.5 */ jQuery(document).ready(function($){ var ajaxData = {}; if ($('meta[name=csrf-token-name]').length && $('meta[name=csrf-token-value]').length) { var csrfTokenName = $('meta[name=csrf-token-name]').attr('content'); var csrfTokenValue = $('meta[name=csrf-token-value]').attr('content'); ajaxData[csrfTokenName] = csrfTokenValue; } $('a.allow-all').on('click', function(){ $(this).closest('div.box-body').find('select').val('allow'); return false; }); $('a.deny-all').on('click', function(){ $(this).closest('div.box-body').find('select').val('deny'); return false; }); $('.btn-save-route-access').on('click', function(){ var $this = $(this), $form = $this.closest('form'); $.post('', $form.serialize(), function(){ $this.text($this.data('init-text')).removeClass('disabled').removeAttr('disabled'); }); return false; }); });
import CreateAdministrator from '../../components/CreateAdministrator.vue'; describe('CreateAdministrator', () => { it('should be able to display a form to add a new administrator to the database', function() { expect($('<span class="card-title">Create New Administrator</span>')).toHaveText('Create New Administrator'); }) });
/** * @Filename: color.js * @Description: les couleurs du projet en objet JS */ // ----------------------------------------------------------------------------- BASIC exports.colors = { color1: '#ffffff', // blanc total color2: '#000000', // noir total color3: '#84CBD5', // bleu vert color4: '#e2e2e2', // grey };
// Given an array w of positive integers, where w[i] describes the weight of index i, write a function pickIndex which randomly picks an index in proportion to its weight. // Note: // 1 <= w.length <= 10000 // 1 <= w[i] <= 10^5 // pickIndex will be called at most 10000 times. // Example 1: // Input: // ["Solution","pickIndex"] // [[[1]],[]] // Output: [null,0] // Example 2: // Input: // ["Solution","pickIndex","pickIndex","pickIndex","pickIndex","pickIndex"] // [[[1,3]],[],[],[],[],[]] // Output: [null,0,1,1,1,0] // Explanation of Input Syntax: // The input is two lists: the subroutines called and their arguments. Solution's constructor has one argument, the array w. pickIndex has no arguments. Arguments are always wrapped with a list, even if there aren't any. /** * @param {number[]} w */ var Solution = function(w) { for (let i = 1; i < w.length; i++) { w[i] += w[i-1]; } // console.log(w) this.w = w; }; /** * @return {number} * time:O(logn) * space:O(1) * score:180ms */ Solution.prototype.pickIndex = function() { let size = this.w.length; let randomPick = getRandomInt(this.w[size-1])+1; // console.log(randomPick) let left = 0; let right = size-1; while (left < right) { let mid = Math.floor((left+right)/2); if (this.w[mid] == randomPick) { return mid; } else if (this.w[mid] < randomPick) { left = mid+1; } else { right = mid; } } return left; }; function getRandomInt(max) { return Math.floor(Math.random() * Math.floor(max)); } /** * Your Solution object will be instantiated and called as such: * var obj = new Solution(w) * var param_1 = obj.pickIndex() */
/* index.js is part of NodeWebSample. * Copyright (C) 2014 Nicola Cimmino * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see http://www.gnu.org/licenses/. * */ var server = require("./server"); var router = require("./router"); var requestHandlers = require("./requestHandlers"); requestHandlers.initialize(); var handle = {}; handle["/get"] = requestHandlers.get; handle["/set"] = requestHandlers.set; server.start(router.route, handle);
var objects_8hpp = [ [ "operator<", "objects_8hpp.html#aff5f5378d2bd22f69f8b864d0869b98b", null ], [ "operator>", "objects_8hpp.html#a4fd942cc9aac07c5936174a83c90a412", null ], [ "TailOfWorm", "objects_8hpp.html#ae325b12a82aa0c72194eef3a8f46dc9f", null ], [ "TerminalOfWorldline", "objects_8hpp.html#a7e9f609bd12089deadc2fa0b12b81c2b", null ], [ "TheRVIPool", "objects_8hpp.html#ae849ff5cc28ba781cc63ca4dac7e18e5", null ], [ "TheSegmentPool", "objects_8hpp.html#ad63cad901b00e2ab131820e06912a75c", null ], [ "TheVertexPool", "objects_8hpp.html#ab1ca7e71887bb2726043a57140b7bf03", null ] ];
/* * Aran / Cygnus Job Advancer * v83 MoopleDEV Rev 116 * Author: ShEtY */ var status = -1; var ask = "Oh, I see you've grown stronger! Do you wish to job advance?"; var job; var koc = new Array(); function start() { cm.sendNext("Hey #e#h ##n, I'm the Aran & Cygnus Job Advancer."); } function action(m, t, s) { status++; if (m != 1) { cm.dispose(); return; } if (status == 0) { if (cm.getJobId() % 10 == 2) { cm.dispose(); } else if (cm.getJobId() % 10 == 1 && cm.getJobId() < 2000) { cm.dispose(); } else if (cm.getJobId() % 1000 == 0 && cm.getJobId() != 0 && cm.getLevel() >= 10) { if (cm.getJobId() == 1000) { for (var i = 1; i < 6; i++) koc.push(cm.getJobId() + 100 * i); var list = "What class of Cygnus Knight do you wish to advance to?"; for (var k = 0; k < koc.length; k++) list += "\r\n#L" + k + "#" + cm.getJobName(koc[k]) + "#l"; cm.sendSimple(list); } else if (cm.getJobId() == 2000) { job = cm.getJobId() + 100; cm.sendYesNo(ask); } else cm.dispose(); } else if (cm.getJobId() % 1000 != 0) { if (cm.getJobId() % 100 == 0 && cm.getLevel() >= 30) { job = cm.getJobId() + 10; cm.sendYesNo(ask); } else if (cm.getJobId() % 10 == 0 && cm.getLevel() >= 70) { job = cm.getJobId() + 1; cm.sendYesNo(ask); } else if (cm.getJobId() % 10 == 1 && cm.getJobId() >= 2000 && cm.getLevel() >= 120) { job = cm.getJobId() + 1; cm.sendYesNo(ask); } } } else if (status == 1) { if (cm.getJobId() != 1000) { if (cm.getJobId() == 2000) { cm.changeJobById(job); cm.maxMastery(); cm.resetStats(); cm.dispose(); } else { cm.changeJobById(job); cm.dispose(); } } else if (cm.getJobId() == 1000) { cm.changeJobById(koc[s]); cm.resetStats(); cm.dispose(); } } }
GPSCALLBACKFUNCTION = null; function onSuccessGPS(event){ if(GPSCALLBACKFUNCTION != null) GPSCALLBACKFUNCTION(event); } function onFailureGPS(event){ } function registerGpsCallback(functionname) { GPSCALLBACKFUNCTION = functionname; } function unRegisterGpsCallback() { GPSCALLBACKFUNCTION = null; }
/* Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'list', 'nl', { bulletedlist: 'Opsomming', numberedlist: 'Genummerde lijst' });
"use strict"; tutao.provide('tutao.event.PushListEventTracker'); /** * The PushListEventTracker uses the EventBusClient to fetch information about * updated or added data for a specific list of generated id types. * @param {Object} listType The list type that shall be tracked. * @param {string} listId The list id of the type. * @param {string} typeName The typeName of the type. * @constructor * @implements {tutao.event.ListEventTracker} * @implements {tutao.event.EventBusListener} */ tutao.event.PushListEventTracker = function(listType, listId, typeName) { tutao.util.FunctionUtils.bindPrototypeMethodsToThis(this); // listener methods are invoked from the observable EventBusClient this._listType = listType; this._path = listType.PATH; this._typeName = typeName; this._listId = listId; this._version = listType.MODEL_VERSION; this._highestElementId = tutao.rest.EntityRestInterface.GENERATED_MIN_ID; this._observable = new tutao.event.Observable(); }; /** * @inheritDoc */ tutao.event.PushListEventTracker.prototype.addObserver = function(observer) { this._observable.addObserver(observer); }; /** * @inheritDoc */ tutao.event.PushListEventTracker.prototype.removeObserver = function(observer) { this._observable.removeObserver(observer); }; /** * @inheritDoc */ tutao.event.PushListEventTracker.prototype.notifyObservers = function(data) { this._observable.notifyObservers(data); }; /** * @inheritDoc */ tutao.event.PushListEventTracker.prototype.observeList = function(highestId) { this._highestElementId = highestId; var self = this; this._notifyAboutExistingElements().then(function() { // avoid dublicate notifications tutao.locator.eventBus.addListener(self); }); }; tutao.event.PushListEventTracker.prototype.stopObservingList = function() { this._highestElementId = tutao.rest.EntityRestInterface.GENERATED_MIN_ID; tutao.locator.eventBus.removeListener(this); }; /** * @param {tutao.entity.sys.EntityUpdate} update The update notification. */ tutao.event.PushListEventTracker.prototype._handleEventBusNotification = function(update) { var self = this; if (update.getType() === this._typeName && update.getInstanceListId() === this._listId && update.getOperation() == tutao.entity.tutanota.TutanotaConstants.OPERATION_TYPE_CREATE) { return tutao.locator.entityRestClient.getElement(self._listType, self._path, update.getInstanceId(), self._listId, { "v": self._version }, tutao.entity.EntityHelper.createAuthHeaders()).then(function(instance) { return instance._entityHelper.loadSessionKey().then(function(instance) { self.notifyObservers([instance]); if (tutao.rest.EntityRestInterface.firstBiggerThanSecond(instance.getId()[1], self._highestElementId)) { self._highestElementId = instance.getId()[1]; } }); }).caught(function(exception) { // this error should not occur when full sync is available console.log(exception); }); } else { return Promise.resolve(); } }; tutao.event.PushListEventTracker.prototype._notifyAboutExistingElements = function() { var self = this; return tutao.rest.EntityRestInterface.loadAll(self._listType, self._listId, self._highestElementId).then(function(newElements) { if (newElements.length > 0) { return tutao.entity.EntityHelper.loadSessionKeys(newElements).then(function(newElements) { self.notifyObservers(newElements); if ( newElements.length > 0 ){ self._highestElementId = newElements[newElements.length - 1].getId()[1]; } }); } else { return Promise.resolve(); } }).caught(function(exception) { // this error should not occur when full sync is available console.log(exception); }); }; /** * @inheritDoc */ tutao.event.PushListEventTracker.prototype.notifyNewDataReceived = function (data) { this._handleEventBusNotification(data); }; /** * @inheritDoc */ tutao.event.PushListEventTracker.prototype.notifyReconnected = function() { this._notifyAboutExistingElements(); };
define(["wc/dom/ariaAnalog", "wc/dom/initialise", "wc/dom/shed", "wc/dom/Widget", "wc/ui/table/common", "wc/ui/icon"], function(ariaAnalog, initialise, shed, Widget, table, icon) { "use strict"; var instance; /** * @constructor * @alias module:wc/ui/RowAnalog~RowAnalog * @private */ function RowAnalog() { var EXPANDER; /** * The selection mode is mixed: list boxes may be single or multiple as per select elements. * @var * @protected * @type int * @override */ this.exclusiveSelect = this.SELECT_MODE.MIXED; /** * @override */ this.simpleSelection = true; /** * The definition of a grouped item in a row analog. This is the equivalent of an option element. * @var * @public * @type {module:wc/dom/Widget} * @override */ this.ITEM = table.TR.extend("", {"aria-selected": null}); /** * Holds a reference to the last activated member of any identified listBox analog keyed on the listbox * id with the property value being the id of the last activated item. Needed for correct implementation of * group selection (such as with SHIFT+ Click). * @var * @type {Object} * @protected * @override */ this.lastActivated = {}; /** * According to the WAI-ARIA spec listbox MUST contain option and option must be contained by listbox. * However the rdf is broken on this point with regard to looking up what 'option' is contained by. So this * is a fill for that bug. * * @constant * @public * @type {module:wc/dom/Widget} * @override */ this.CONTAINER = table.TABLE; /** * Change icon on select/deselect. * @function * @public * @override * @param {Element} element the element being acted upon * @param {String} action the shed action */ this.shedObserver = function(element, action) { var cell, isMultiSelect, add, remove; if (element && (action === shed.actions.SELECT || action === shed.actions.DESELECT) && this.ITEM.isOneOfMe(element)) { EXPANDER = EXPANDER || new Widget("td", "wc_table_sel_wrapper"); if ((cell = EXPANDER.findDescendant(element, true))) { isMultiSelect = this.isMultiSelect(element); if (action === shed.actions.SELECT) { add = isMultiSelect ? "fa-check-square-o" : "fa-dot-circle-o"; remove = isMultiSelect ? "fa-square-o" : "fa-circle-o"; } else { add = isMultiSelect ? "fa-square-o" : "fa-circle-o"; remove = isMultiSelect ? "fa-check-square-o" : "fa-dot-circle-o"; } icon.change(cell, add, remove); } } this.constructor.prototype.shedObserver.call(this, element, action); }; } RowAnalog.prototype = ariaAnalog; /** * Provides ARIA based row in treegrid functionality (lists of selectable options - cf a select element). * @module module:wc/ui/RowAnalog * @extends module:wc/dom/ariaAnalog * @requires module:wc/dom/ariaAnalog * @requires module:wc/dom/initialise * @requires module:wc/dom/shed * @requires module:wc/ui/table/common */ instance = new RowAnalog(); instance.constructor = RowAnalog; return initialise.register(instance); });
import { do_pie } from './charts/pie-chart' global.do_pie = do_pie import './components.scss' import { ChartWidget, WidgetUtils } from './widget/widgets' import './sidebar/sidebar' window.ChartWidget = ChartWidget window.WidgetUtils = WidgetUtils
/* Copyright (c) 2015-present terrestris GmbH & Co. KG * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * Permalink Button * * Button used to open a permalink window. * * @class BasiGX.view.button.Permalink */ Ext.define('BasiGX.view.button.Permalink', { extend: 'BasiGX.view.button.Base', xtype: 'basigx-button-permalink', requires: [ 'Ext.window.Window', 'Ext.app.ViewModel', 'BasiGX.view.form.Permalink', 'BasiGX.util.Animate', 'BasiGX.util.Application' ], /** * */ viewModel: { data: { tooltip: 'Permalink erzeugen', text: 'Permalink', windowTitle: 'Link zur Anwendung', documentation: '<h2>Permalink erzeugen</h2>• Ein Klick auf ' + 'den Button öffnet ein Fenster, in dem ein Permalink erzeugt ' + 'werden kann. Dieser Link kann benutzt werden, um die ' + 'Applikation in einem vordefinierten Zustand, wie z.B. ' + 'Zentrum der Karte oder sichtbare Themen, zu öffnen.' } }, /** * A config object to show this tool in action (live demo) when using the * context sensitive help */ liveDemoConfig: [ { moveMouseTo: 'basigx-button-permalink' }, { clickOnButton: 'basigx-button-permalink' }, { moveMouseTo: 'window[name=permalink-window]' }, { destroy: 'window[name=permalink-window]' } ], bind: { text: '{text}' }, config: { handler: function() { var win = Ext.ComponentQuery.query('[name=permalink-window]')[0]; if (!win) { Ext.create('Ext.window.Window', { name: 'permalink-window', constrain: true, title: this.getViewModel().get('windowTitle'), layout: 'fit', items: [{ xtype: 'basigx-form-permalink' }] }).show(); } else { BasiGX.util.Animate.shake(win); } } } });
/******************************************************************************* Copyright (C) 2013 Tomáš Hanák <tomas.hanak@gmail.com> This file is part of web-html5-autogallery project. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. *******************************************************************************/ define([ 'jquery', 'underscore', 'backbone', 'models/media', ], function($, _, Backbone, MediaModel) { var GalleryCollection = Backbone.Collection.extend({ model: MediaModel, galleryId: '', initialize: function(options) { if (options.galleryId == '') { console.log('GalleryCollection: Initialized without galleryId'); } this.galleryId = options.galleryId; }, url: function() { return '/site-metadata/galleries/' + this.galleryId + '.json'; }, }); return GalleryCollection; });
const express = require("express"); const session = require("express-session"); const RedisStore = require("connect-redis")(session); const { merge } = require("lodash"); const config = require("../config"); const { redisClient, ltiRequestValidator, ltiSessionValidator, ltiXAssignmentValidator, ltiInstructorValidator, } = require("./route-validators"); const LtiContentItemLink = require("./models/lti-content-item-link.class"); const ResponseFormData = require("./models/response-form-data.class"); const assignmentService = require("../lti/services/assignments"); const ltiUserService = require("./services/lti-user"); const responseService = require("./services/responses"); const questionService = require("./services/questions"); const { LtiSessionError } = require("./utils/custom-errors"); const router = express.Router(); const ltiSession = session( merge( { store: new RedisStore({ client: redisClient }) }, { resave: false, saveUninitialized: false, }, config.session ) ); router.use(ltiSession); router.use(express.urlencoded({ extended: true })); router.use(express.json()); /** * Route that should be accessed by the LTI Tool Coonsumer when a user wants to select a Tool activity * It renders the `item-selection` templates containing the list of all the available assignments. */ router.post("/select", ltiRequestValidator, async (req, res) => { res.redirect(`${config.app.frontUrl}/admin/ltiselect`); }); /** * Route that should be accessed by the LTI Tool Consumer when a user has selected an assignment. * It sends an LTI Response to the TC that contains the properties of the selected assignment. */ router.post("/selected", ltiSessionValidator, async (req, res) => { try { const returnUrl = req.session.lti.rawData.content_item_return_url; const consumer = req.session.lti.consumer; const assignment = await assignmentService.getAssignment(req.body.id); const itemCustomValues = { assignment_id: assignment.id, }; const item = new LtiContentItemLink( assignment.name, assignment.description, itemCustomValues ); const formData = new ResponseFormData(returnUrl, consumer, item); formData.signedWith(consumer); res.json(formData); } catch (err) { console.log(err); res.status(500); res.send(err); } }); /** * This is the entry point of any LTI assignment. * It check the access rights and then redirect to the requested assignment. */ router.post( "/launch", ltiRequestValidator, ltiUserService.upsert, (req, res, next) => { req.session.save((err) => { if (err) next(err); res.redirect( `${config.app.frontUrl}/assignmentlti/${req.session.lti.rawData.custom_assignment_id}` ); }); } ); /** * **This route can only be accessed if the user accessed the assignment through an LTI Launch Request.** * * Loads an assignment based on its `:id`. * If one tries to access this route directly, an error will be shown instead. */ router.get( "/assignment/:id", ltiSessionValidator, ltiXAssignmentValidator, assignmentService.getAssignmentWithQuestionList, (req, res) => { res.json(res.assignmentData); } ); /** * **This route can only be accessed if the user accessed the assignment through an LTI Launch Request.** * * Route called by the front-end when a user submit their response to a specific SQL question. * It saves the response in the DB and, if neceserry, notifiy the TC that the user's note should be updated. */ async function saveResponse(data) { const userId = data.lti.user.id; const responseData = { assignment_id: data.lti.rawData.custom_assignment_id, question_id: data.questionId, lti_user_id: userId, sql: data.sql, is_correct: data.is_correct, }; if (!ltiUserService.isInstructor(data.lti)) { const questionStateId = await responseService.upsertQuestionState( responseData ); await responseService.addToQuestionState(questionStateId, responseData); await ltiUserService.updateScore(data); } } /** * **This route can only be accessed if the user accessed the assignment through an LTI Launch Request.** * * Route that allows to retrieve a user's question history, that is all the responses they submitted for this question of this assignment. */ router.get( "/assignment/:id/question/:qId/history", ltiSessionValidator, ltiXAssignmentValidator, async (req, res, next) => { try { const history = await responseService.getResponseHistory( req.params.id, req.params.qId, req.session.lti.user.id ); res.json(history); } catch (error) { res.status(500).json([]); } } ); router.get( "/assignment/:id/question/:qId/solution", ltiSessionValidator, ltiXAssignmentValidator, ltiInstructorValidator, async (req, res, next) => { try { const questionSolution = await questionService.getSolution( req.params.qId ); res.send(questionSolution); } catch (err) { res.status(500).json(err); } } ); /** * **This route can only be accessed if the user accessed the assignment through an LTI Launch Request.** * * Send all the current user's data that have been provided by the TC by the original LTI Launch Request. */ router.get("/me", ltiSessionValidator, (req, res) => { const me = req.session.lti.user; // Checks if the current user has the `Instructor` LTI Roles and add this to the returned object. me.isInstructor = ltiUserService.isInstructor(req.session.lti); res.json(me); }); const routerModule = (module.exports = router); routerModule.ltiSession = ltiSession; routerModule.saveResponse = saveResponse;
/* Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ */ "use strict"; /** * Tests that the profiler can handle creation and stopping of console profiles * after being opened. */ const { Constants } = require("devtools/client/performance/modules/constants"); const { SIMPLE_URL } = require("devtools/client/performance/test/helpers/urls"); const { initPerformanceInTab, initConsoleInNewTab, teardownToolboxAndRemoveTab } = require("devtools/client/performance/test/helpers/panel-utils"); const { waitForRecordingStartedEvents, waitForRecordingStoppedEvents } = require("devtools/client/performance/test/helpers/actions"); const { times } = require("devtools/client/performance/test/helpers/event-utils"); const { getSelectedRecording } = require("devtools/client/performance/test/helpers/recording-utils"); add_task(function* () { let { target, console } = yield initConsoleInNewTab({ url: SIMPLE_URL, win: window }); let { panel } = yield initPerformanceInTab({ tab: target.tab }); let { EVENTS, PerformanceController, OverviewView } = panel.panelWin; let started = waitForRecordingStartedEvents(panel, { // only emitted for manual recordings skipWaitingForBackendReady: true }); yield console.profile("rust"); yield started; let recordings = PerformanceController.getRecordings(); is(recordings.length, 1, "One recording found in the performance panel."); is(recordings[0].isConsole(), true, "Recording came from console.profile."); is(recordings[0].getLabel(), "rust", "Correct label in the recording model."); is(recordings[0].isRecording(), true, "Recording is still recording."); const selected = getSelectedRecording(panel); is(selected, recordings[0], "The profile from console should be selected as it's the only one."); is(selected.getLabel(), "rust", "The profile label for the first recording is correct."); // Ensure overview is still rendering. yield times(OverviewView, EVENTS.UI_OVERVIEW_RENDERED, 3, { expectedArgs: { "1": Constants.FRAMERATE_GRAPH_LOW_RES_INTERVAL } }); let stopped = waitForRecordingStoppedEvents(panel, { // only emitted for manual recordings skipWaitingForBackendReady: true }); yield console.profileEnd("rust"); yield stopped; yield teardownToolboxAndRemoveTab(panel); });
"use strict"; const PERMISSIONS_URL = "chrome://browser/content/preferences/permissions.xul"; add_task(function* urlFieldVisibleForPopupPermissions(finish) { yield openPreferencesViaOpenPreferencesAPI("paneContent", null, {leaveOpen: true}); let win = gBrowser.selectedBrowser.contentWindow; let doc = win.document; let popupPolicyCheckbox = doc.getElementById("popupPolicy"); ok(!popupPolicyCheckbox.checked, "popupPolicyCheckbox should be unchecked by default"); popupPolicyCheckbox.click(); let popupPolicyButton = doc.getElementById("popupPolicyButton"); ok(popupPolicyButton, "popupPolicyButton found"); let dialogPromise = promiseLoadSubDialog(PERMISSIONS_URL); popupPolicyButton.click(); let dialog = yield dialogPromise; ok(dialog, "dialog loaded"); let urlLabel = dialog.document.getElementById("urlLabel"); ok(!urlLabel.hidden, "urlLabel should be visible when one of block/session/allow visible"); let url = dialog.document.getElementById("url"); ok(!url.hidden, "url should be visible when one of block/session/allow visible"); popupPolicyCheckbox.click(); gBrowser.removeCurrentTab(); }); add_task(function* urlFieldHiddenForNotificationPermissions() { yield openPreferencesViaOpenPreferencesAPI("paneContent", null, {leaveOpen: true}); let win = gBrowser.selectedBrowser.contentWindow; let doc = win.document; let notificationsPolicyButton = doc.getElementById("notificationsPolicyButton"); ok(notificationsPolicyButton, "notificationsPolicyButton found"); let dialogPromise = promiseLoadSubDialog(PERMISSIONS_URL); notificationsPolicyButton.click(); let dialog = yield dialogPromise; ok(dialog, "dialog loaded"); let urlLabel = dialog.document.getElementById("urlLabel"); ok(urlLabel.hidden, "urlLabel should be hidden as requested"); let url = dialog.document.getElementById("url"); ok(url.hidden, "url should be hidden as requested"); gBrowser.removeCurrentTab(); });
/* -*- Mode: javascript; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ gTestfile = 'ToLong-002.js'; /** * Preferred Argument Conversion. * * Passing a JavaScript boolean to a Java method should prefer to call * a Java method of the same name that expects a Java boolean. * */ var SECTION = "Preferred argument conversion: JavaScript Object to Long"; var VERSION = "1_4"; var TITLE = "LiveConnect 3.0 JavaScript to Java Data Type Conversion " + SECTION; startTest(); var TEST_CLASS = new Packages.com.netscape.javascript.qa.lc3.jsobject.JSObject_006; function MyFunction() { return "hello"; } MyFunction.valueOf = new Function( "return 999" ); function MyOtherFunction() { return "goodbye"; } MyOtherFunction.valueOf = null; MyOtherFunction.toString = new Function( "return 999" ); function MyObject(value) { this.value = value; this.valueOf = new Function("return this.value"); } function MyOtherObject(stringValue) { this.stringValue = String( stringValue ); this.toString = new Function( "return this.stringValue" ); this.valueOf = null; } function AnotherObject( value ) { this.value = value; this.valueOf = new Function( "return this.value" ); this.toString = new Function( "return 666" ); } // should pass MyFunction.valueOf() to ambiguous new TestCase( "TEST_CLASS.ambiguous( MyFunction ) +''", "LONG", TEST_CLASS.ambiguous( MyFunction )+'' ); // should pass MyOtherFunction.toString() to ambiguous new TestCase( "TEST_CLASS.ambiguous( MyOtherFunction ) +''", "LONG", TEST_CLASS.ambiguous( MyOtherFunction )+'' ); // should pass MyObject.valueOf() to ambiguous new TestCase( "TEST_CLASS.ambiguous( new MyObject(12345) ) +''", "LONG", TEST_CLASS.ambiguous( new MyObject(12345) )+'' ); // should pass MyOtherObject.toString() to ambiguous new TestCase( "TEST_CLASS.ambiguous( new MyOtherObject(\"12345\") ) +''", "LONG", TEST_CLASS.ambiguous( new MyOtherObject("12345") )+'' ); // should pass AnotherObject.valueOf() to ambiguous new TestCase( "TEST_CLASS.ambiguous( new AnotherObject(\"12345\") ) +''", "LONG", TEST_CLASS.ambiguous( new AnotherObject("12345") )+'' ); test();
/** * Created by CCristi <ccovali@mitocgroup.com> on 12/10/15. */ 'use strict'; import {AbstractFsDriver} from './AbstractFsDriver'; import {MethodNotAvailableException} from './Exception/MethodNotAvailableException'; import {SharedKey as Key} from '../SharedKey'; /** * CloudFront Cache Driver */ export class CloudFrontDriver extends AbstractFsDriver { /** * @todo: Find better way to extract the working microservice identifier * * @param {ContainerAware} containerAware * @param {String} directory */ constructor(containerAware, directory = AbstractFsDriver.DEFAULT_DIRECTORY) { super(directory); this._containerAware = containerAware; this._cache = {}; } /** * @returns {String} * @private */ _type() { return 'CloudFront'; } /** * @param {String} key * @param {Function} callback * @private */ _has(key, callback = () => {}) { this._get(key, (err, data) => { callback(err, data !== null); }); } /** * @todo: Find a way to invalidate broken or expired keys * * @param {String} key * @param {Function} callback * @private */ _get(key, callback = () => {}) { // @todo: get rid of this cache? if (this._cache.hasOwnProperty(key)) { let parsedData = this._cache[key]; if (parsedData.expires && parsedData.expires < AbstractFsDriver._now || parsedData.buildId !== this._buildId) { delete this._cache[key]; } else { callback(null, this._cache[key].value); return; } } this._request(key, (err, data) => { if (err) { return callback(err, null); } try { let parsedData = JSON.parse(data); if (parsedData.expires && parsedData.expires < AbstractFsDriver._now || parsedData.buildId !== this._buildId) { callback(null, null); return; } this._cache[key] = parsedData; callback(null, parsedData.value); } catch (e) { // avoid parse error on missing or broken object in S3 callback(null, null); } }); } /** * Throw MethodNotAvailableException * * @private */ _set() { throw new MethodNotAvailableException('set'); } /** * Throw MethodNotAvailableException * * @private */ _invalidate() { throw new MethodNotAvailableException('invalidate'); } /** * @param {String|Key} key * @returns {String} * @private */ _buildKey(key) { return key instanceof Key ? this._asset.locate(`@${key.microservice}:${super._buildKey(key.toString())}`) : this._asset.locate(`@${this._microservice}:${super._buildKey(key)}`); } /** * @param {String} url * @param {Function} callback * @private */ _request(url, callback) { var client = new XMLHttpRequest(); client.onreadystatechange = function() { if (client.readyState === 4) { if (client.status !== 200) { return callback(client.statusText, null); } callback(null, client.responseText); } }; client.open('GET', url); client.send(); } /** * Returns the microservice binded to `resource` service * * @returns {Instance} * @private */ get _microservice() { return this._containerAware.container.get('resource').microservice; } /** * @returns {Asset} * @private */ get _asset() { return this._containerAware.container.get('asset'); } }
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ define([ 'underscore', 'backbone', 'jquery', 'views/base', 'stache!templates/welcome', 'lib/modal_manager', 'config' ], function (_, Backbone, $, BaseView, WelcomeTemplate, modalManager, config) { 'use strict'; var WelcomeView = BaseView.extend({ className: 'welcome', template: WelcomeTemplate, events: { 'click button.install': 'install', 'click button.continue': 'continue' }, install: function (event) { event.preventDefault(); $.Velocity.RunSequence([ { e: this.$('#install-container'), p: 'transition.fadeOut' }, { e: this.$('#continue-container'), p: 'transition.fadeIn' } ]); // Trigger add-on installation window.location = config.addon.firefox.url; }, continue: function (event) { event.preventDefault(); // Set the URL to the root but don't trigger since the view is already in place Backbone.history.navigate('/'); modalManager.close({ effect: 'transition.fadeOut' }); }, getContext: function () { return { supportedBrowser: /firefox/i.test(window.navigator.userAgent) }; } }); return WelcomeView; });
import { later, run } from '@ember/runloop'; import { resolve } from 'rsvp'; import EmberObject, { computed } from '@ember/object'; import Service from '@ember/service'; import { module, test } from 'qunit'; import { setupRenderingTest } from 'ember-qunit'; import { click, render, settled } from '@ember/test-helpers'; import hbs from 'htmlbars-inline-precompile'; import sinon from 'sinon'; import engineResolverFor from 'ember-engines/test-support/engine-resolver-for'; import { COMPUTEDS } from 'vault/models/kmip/role'; const resolver = engineResolverFor('kmip'); const flash = Service.extend({ success: sinon.stub(), }); const namespace = Service.extend({}); const fieldToCheckbox = (field) => ({ name: field, type: 'boolean' }); const createModel = (options) => { let model = EmberObject.extend(COMPUTEDS, { /* eslint-disable ember/avoid-leaking-state-in-ember-objects */ newFields: [ 'role', 'operationActivate', 'operationAddAttribute', 'operationAll', 'operationCreate', 'operationDestroy', 'operationDiscoverVersion', 'operationGet', 'operationGetAttributes', 'operationLocate', 'operationNone', 'operationRekey', 'operationRevoke', 'tlsClientKeyBits', 'tlsClientKeyType', 'tlsClientTtl', ], fields: computed('operationFields', function () { return this.operationFields.map(fieldToCheckbox); }), destroyRecord() { return resolve(); }, save() { return resolve(); }, rollbackAttributes() {}, }); return model.create({ ...options, }); }; module('Integration | Component | edit form kmip role', function (hooks) { setupRenderingTest(hooks, { resolver }); hooks.beforeEach(function () { run(() => { this.owner.unregister('service:flash-messages'); this.owner.register('service:flash-messages', flash); this.owner.register('service:namespace', namespace); }); }); test('it renders: new model', async function (assert) { let model = createModel({ isNew: true }); this.set('model', model); await render(hbs`<EditFormKmipRole @model={{model}} />`); assert.dom('[data-test-input="operationAll"]').isChecked('sets operationAll'); }); test('it renders: operationAll', async function (assert) { let model = createModel({ operationAll: true }); this.set('model', model); await render(hbs`<EditFormKmipRole @model={{model}} />`); assert.dom('[data-test-input="operationAll"]').isChecked('sets operationAll'); }); test('it renders: operationNone', async function (assert) { let model = createModel({ operationNone: true }); this.set('model', model); await render(hbs`<EditFormKmipRole @model={{model}} />`); assert.dom('[data-test-input="operationNone"]').isNotChecked('sets operationNone'); }); test('it renders: choose operations', async function (assert) { let model = createModel({ operationGet: true }); this.set('model', model); await render(hbs`<EditFormKmipRole @model={{model}} />`); assert.dom('[data-test-input="operationNone"]').isChecked('sets operationNone'); assert.dom('[data-test-input="operationAll"]').isNotChecked('sets operationAll'); }); let savingTests = [ [ 'setting operationAll', { operationNone: true, operationGet: true }, 'operationNone', { operationAll: true, operationNone: false, operationGet: true, }, { operationGet: null, operationNone: false, }, ], [ 'setting operationNone', { operationAll: true, operationCreate: true }, 'operationNone', { operationAll: false, operationNone: true, operationCreate: true, }, { operationNone: true, operationCreate: null, operationAll: false, }, ], [ 'setting choose, and selecting an additional item', { operationAll: true, operationGet: true, operationCreate: true }, 'operationAll,operationDestroy', { operationAll: false, operationCreate: true, operationGet: true, }, { operationGet: true, operationCreate: true, operationDestroy: true, operationAll: false, }, ], ]; for (let testCase of savingTests) { let [name, initialState, displayClicks, stateBeforeSave, stateAfterSave] = testCase; test(name, async function (assert) { let model = createModel(initialState); this.set('model', model); let clickTargets = displayClicks.split(','); await render(hbs`<EditFormKmipRole @model={{model}} />`); for (let clickTarget of clickTargets) { await click(`label[for=${clickTarget}]`); } for (let beforeStateKey of Object.keys(stateBeforeSave)) { assert.equal(model.get(beforeStateKey), stateBeforeSave[beforeStateKey], `sets ${beforeStateKey}`); } click('[data-test-edit-form-submit]'); later(() => run.cancelTimers(), 50); return settled().then(() => { for (let afterStateKey of Object.keys(stateAfterSave)) { assert.equal( model.get(afterStateKey), stateAfterSave[afterStateKey], `sets ${afterStateKey} on save` ); } }); }); } });
/* global GestureDetector, KeyEvent */ 'use strict'; (function(exports) { function initGesture() { function fireKeyEvent(keyCode, key) { var eventObj = document.createEvent('Events'); eventObj.initEvent('keydown', true, true); eventObj.key = key; eventObj.keyCode = keyCode; eventObj.which = keyCode; window.dispatchEvent(eventObj); eventObj = document.createEvent('Events'); eventObj.initEvent('keypress', true, true); eventObj.key = key; eventObj.keyCode = keyCode; eventObj.which = keyCode; window.dispatchEvent(eventObj); eventObj = document.createEvent('Events'); eventObj.initEvent('keyup', true, true); eventObj.key = key; eventObj.keyCode = keyCode; eventObj.which = keyCode; window.dispatchEvent(eventObj); } new GestureDetector(document.body).startDetecting(); document.addEventListener('swipe', function(evt) { var direction = evt.detail.direction; var keyDefine = { 'up': [KeyEvent.DOM_VK_UP, 'Up'], 'right': [KeyEvent.DOM_VK_RIGHT, 'Right'], 'down': [KeyEvent.DOM_VK_DOWN, 'Down'], 'left': [KeyEvent.DOM_VK_LEFT, 'Left'] }; fireKeyEvent(keyDefine[direction][0], keyDefine[direction][1]); }); document.addEventListener('dbltap', function(evt) { fireKeyEvent(KeyEvent.DOM_VK_RETURN, 'Enter'); }); document.addEventListener('transform', function(evt) { fireKeyEvent(KeyEvent.DOM_VK_ESCAPE, 'Esc'); }); } /* exports.initFakeAppEvent = initFakeAppEvent; */ exports.initGesture = initGesture; })(window); window.initGesture();
export const USER_SESSION = 'react-auth0-session'; export const BASE_URL = `${process.env.BALROG_ROOT_URL}/api`; export const OBJECT_NAMES = { PERMISSIONS_REQUIRED_SIGNOFF: 'required_signoffs/permissions', PRODUCT_REQUIRED_SIGNOFF: 'required_signoffs/product', }; export const LABELS = { PENDING: 'pending', PENDING_INSERT: 'pendingInsert', PENDING_DELETE: 'pendingDelete', PENDING_UPDATE: 'pendingUpdate', }; export const RULE_DIFF_PROPERTIES = [ 'alias', 'fallbackMapping', 'mapping', 'backgroundRate', 'buildTarget', 'buildID', 'comment', 'data_version', 'distVersion', 'distribution', 'headerArchitecture', 'instructionSet', 'jaws', 'locale', 'memory', 'mig64', 'osVersion', 'priority', 'product', 'channel', 'rule_id', 'update_type', 'version', ]; // Products that use only a subset of the available Rule fields // should define them here. export const RULE_PRODUCT_UNSUPPORTED_PROPERTIES = { Guardian: [ 'buildID', 'distVersion', 'distribution', 'headerArchitecture', 'instructionSet', 'jaws', 'locale', 'memory', 'mig64', 'osVersion', ], }; export const CONTENT_MAX_WIDTH = 980; export const APP_BAR_HEIGHT = 64; export const SNACKBAR_AUTO_HIDE_DURATION = 5000; export const SNACKBAR_INITIAL_STATE = { message: '', variant: 'success', open: false, }; export const DIALOG_ACTION_INITIAL_STATE = { error: null, title: '', body: '', confirmText: '', item: null, open: false, destructive: false, mode: null, handleSubmit: Function.prototype, handleClose: Function.prototype, handleError: Function.prototype, handleComplete: Function.prototype, }; export const EMPTY_MENU_ITEM_CHAR = '-'; // product/action restrictions need to match the backend definitions from // https://github.com/mozilla-releng/balrog/blob/master/auslib/db.py#L2144 export const PERMISSION_RESTRICTION_MAPPINGS = { admin: { restrict_products: true, restrict_actions: false, supported_actions: [], }, emergency_shutoff: { restrict_products: true, restrict_actions: true, supported_actions: ['create', 'modify'], }, rule: { restrict_products: true, restrict_actions: true, supported_actions: ['create', 'modify', 'delete'], }, release: { restrict_products: true, restrict_actions: true, supported_actions: ['create', 'modify', 'delete'], }, release_read_only: { restrict_products: true, restrict_actions: true, supported_actions: ['set', 'unset'], }, release_locale: { restrict_products: true, restrict_actions: true, supported_actions: ['modify'], }, required_signoff: { restrict_products: true, restrict_actions: false, supported_actions: ['create', 'modify', 'delete'], }, permission: { restrict_products: false, restrict_actions: true, supported_actions: ['create', 'modify', 'delete'], }, scheduled_change: { restrict_products: false, restrict_actions: true, supported_actions: ['enact'], }, }; export const ALL_PERMISSIONS = [ 'admin', 'emergency_shutoff', 'rule', 'release', 'release_read_only', 'release_locale', 'required_signoff', 'permission', 'scheduled_change', ]; export const NEW_LINES_REGEX = /\r?\n|\r/g; export const SPLIT_WITH_NEWLINES_AND_COMMA_REGEX = /[,\r\n]+/; export const RULES_COMMON_FILTERS = [ { label: 'Firefox Release', link: '/rules?product=Firefox&channel=release', }, { label: 'Firefox Beta', link: '/rules?product=Firefox&channel=beta', }, { label: 'Firefox Aurora (DevEdition)', link: '/rules?product=Firefox&channel=aurora', }, { label: 'Thunderbird Release', link: '/rules?product=Thunderbird&channel=release', }, { label: 'Thunderbird Beta', link: '/rules?product=Thunderbird&channel=beta', }, ]; export const DIFF_COLORS = { ADDED: '#eaffee', REMOVED: '#fdeff0', }; export const INITIAL_JS_DIFF_SUMMARY = { added: 0, removed: 0 };
function run_test() { do_get_profile(); if (!newCacheBackEndUsed()) { do_check_true(true, "This test doesn't run when the old cache back end is used since the behavior is different"); return; } // Open for write, delay the actual write asyncOpenCacheEntry("http://a/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, new OpenCallback(NEW|DONTFILL, "a1m", "a1d", function(entry) { var bypassed = false; // Open and bypass asyncOpenCacheEntry("http://a/", "disk", Ci.nsICacheStorage.OPEN_BYPASS_IF_BUSY, null, new OpenCallback(NOTFOUND, "", "", function(entry) { do_check_false(bypassed); bypassed = true; }) ); // do_execute_soon for two reasons: // 1. we want finish_cache2_test call for sure after do_test_pending, but all the callbacks here // may invoke synchronously // 2. precaution when the OPEN_BYPASS_IF_BUSY invocation become a post one day do_execute_soon(function() { do_check_true(bypassed); finish_cache2_test(); }); }) ); do_test_pending(); }
import Ember from 'ember'; const { run, $ } = Ember; export default Ember.Mixin.create({ setupWindowResize: function() { run.scheduleOnce('afterRender', this, () => { this.set('_windowResizeHandler', this.get('windowResizeHandler').bind(this)); $(window).on('resize', this.get('_windowResizeHandler')); }); }.on('didInsertElement'), removeWindowResize: function() { $(window).off('resize', this.get('_windowResizeHandler')); }.on('willDestroyElement'), });
import ApplicationSerializer from './application'; import classic from 'ember-classic-decorator'; @classic export default class TaskState extends ApplicationSerializer { normalize(typeHash, hash) { // TODO API: finishedAt is always marshaled as a date even when unset. // To simplify things, unset it here when it's the empty date value. if (hash.FinishedAt === '0001-01-01T00:00:00Z') { hash.FinishedAt = null; } return super.normalize(typeHash, hash); } }
var join = require("path").join; var createRDF = require("./rdf"); var when = require("when"); var fs = require("fs-promise"); var zip = require("./zip"); var validate = require("./validate"); var console = require("./utils").console; var hasAOMSupport = require("./utils").hasAOMSupport; var getID = require("jetpack-id"); /** * Takes a manifest object (from package.json) and build options * object and zipz up the current directory into a XPI, copying * over default `install.rdf` and `bootstrap.js` if needed * and not yet defined. Returns a promise that resolves * upon completion. * * @param {Object} manifest * @param {Object} options * @return {Promise} */ function xpi (manifest, options) { options = options || {}; var dir = process.cwd(); var xpiName = getID(manifest) + ".xpi"; var xpiPath = join(dir, xpiName); var useFallbacks = !(options.forceAOM || hasAOMSupport(manifest)); var sdkPath = typeof options.overload === "string" ? options.overload : process.env.JETPACK_ROOT; return validate(dir, options) .then(createFallbacks) .then(createZip) .then(removeFallbacks) .then(function () { return xpiPath; }); // Creates bootstrap.js/install.rdf -- will be removed once // AOM is updated function createFallbacks () { if (!useFallbacks) return when.resolve(); var rdfPath = join(dir, "install.rdf"); var bsPath = join(dir, "bootstrap.js"); var bootstrapSrc = join(__dirname, "../data/bootstrap.js"); return when.all([ fs.writeFile(rdfPath, createRDF(manifest)), fs.copy(bootstrapSrc, bsPath) ]); } function createZip () { console.log("Creating XPI at ", xpiPath); return zip(dir, xpiPath); } function removeFallbacks () { if (!useFallbacks) return when.resolve(); var rdfPath = join(dir, "install.rdf"); var bsPath = join(dir, "bootstrap.js"); return when.all([ fs.remove(bsPath), fs.remove(rdfPath) ]); } } module.exports = xpi; /** * Vestigial overloading of SDK functions below. Possibly unneeded * based off of manifest's aliases. */ function overloadSDK (dir, sdkPath) { var localSDKPath = join(dir, "addon-sdk/lib"); return fs.copy(join(sdkPath, "lib"), localSDKPath); } function addOverloadConfig (dir) { var file = join(dir, "config.json"); return fs.exists(file).then(function (exists) { if (!exists) { return fs.writeFile(file, JSON.stringify({"is-sdk-bundled":true})); } else { var json = JSON.parse(fs.readFileSync(file)); json["is-sdk-bundled"] = true; return fs.writeFile(file, JSON.stringify(json)); } }); } function removeSDK (dir) { var localSDKPath = join(dir, "addon-sdk"); return fs.remove(localSDKPath); }
(function() { $(function() { create_chart("/statistics/registrated_users_json", "global_registration", "Line"); create_chart("/statistics/account_types_json", "account_types", "Doughnut"); create_chart("/statistics/users_status_json", "users_status_canvas", "Doughnut"); return create_chart("/statistics/job_categories_json", "job_categories", "Radar"); }); }).call(this);
OC.L10N.register( "breezedark", { "Saved" : "Αποθηκεύτηκε", "Error" : "Σφάλμα", "Breeze Dark" : "Σκούρο Breeze", "Breeze Dark theme for Nextcloud, based on the theme by KDE" : "Θέμα Σκούρο Breeze για το Nextcloud, βασισμένο στο θέμα του KDE", "A Dark theme based on Breeze Dark by the KDE project. Please refresh the page for changes to take effect." : "Ένα σκοτεινό θέμα βασισμένο στο Σκούρο Breeze από το έργο KDE. Παρακαλούμε ανανεώστε τη σελίδα για να ισχύσουν οι αλλαγές.", "Enable Breeze Dark theme by default" : "Ενεργοποίηση από προεπιλογή του θέματος Σκούρο Breeze", "This setting will allow you to choose if the login page should be themed when the theme is enabled by default." : "Αυτή η ρύθμιση θα σας επιτρέψει να επιλέξετε εάν η σελίδα σύνδεσης πρέπει να έχει θέμα όταν το θέμα είναι ενεργοποιημένο από προεπιλογή.", "Theme the login page" : "Θέμα για την σελίδα σύνδεσης", "Custom Styling" : "Προσαρμοσμένο στυλ", "Insert custom styling here …" : "Εισαγάγετε προσαρμοσμένο στυλ εδώ …", "Save" : "Αποθήκευση", "A Breeze Dark theme for Nextcloud." : "Ένα σκούρο θέμα Breeze για το Nextcloud.", "Breeze Dark theme" : "Σκούρο θέμα Breeze", "Enable Breeze Dark theme" : "Ενεργοποίηση θέματος Σκούρο Breeze" }, "nplurals=2; plural=(n != 1);");
/* global GroupProjectCommon */ /* exported GroupProjectCompletionStage */ function GroupProjectCompletionStage(runtime, element) { "use strict"; var $form = $(".group-project-completion-form", element); $(".group-project-completion-checkmark", element).click(function(ev) { var checkbox = this; ev.preventDefault(); if (!$(this)[0].checked) { return false; } $.ajax({ type: $form.attr('method'), url: runtime.handlerUrl(element, $form.attr('action')), data: JSON.stringify({}), success: function (data) { var msg = (data.msg) ? data.msg : GroupProjectCommon.CompletionStage.messages.MARKED_AS_COMPLETE; GroupProjectCommon.Messages.show_message(msg); if (data.result === 'error'){ return; } $(checkbox).prop('checked', true); $(checkbox).prop('disabled', true); if (data.new_stage_states) { for (var i = 0; i < data.new_stage_states.length; i++) { var new_state = data.new_stage_states[i]; $(document).trigger( GroupProjectCommon.ProjectNavigator.events.stage_status_update, [new_state.activity_id, new_state.stage_id, new_state.state] ); } } }, error: function (data) { var msg = (data.msg) ? data.msg : GroupProjectCommon.CompletionStage.messages.ERROR_SAVING_PROGRESS; GroupProjectCommon.Messages.show_message(msg); } }); }); }
/* scrollTo: e = element to scroll to or top position in pixels d = time to scroll in ms scrollToX: e = scrollable element a = initiall scrollable element position (from) b = height to scroll to (to) t = lerp from a to b (0 - 1) v = speed. input 1 / time to scroll s = repeat every 's' miliseconds */ function scrollTo(e,d){if(d>=0){var h=document.documentElement;if(h.scrollTop===0){var t=h.scrollTop;++h.scrollTop;h=t+1===h.scrollTop--?h:document.body}typeof e==="object"&&(e=e.offsetTop);scrollToX(h,h.scrollTop,e,0,1/d,20)}}function scrollToX(e,a,b,t,v,s){function F(){t<0||t>1||v<=0||(k=t-1,e.scrollTop=a-(a-b)*(k*k*k+1),t+=v*s,setTimeout(F,s))}F()}
(function(global) { // This PRNG is inspired by Weyl, which relies on a 32-bit state, which is // necessary as JS does not have native 64-bit numbers. // https://github.com/Marc-B-Reynolds/Stand-alone-junk/blob/master/src/SFH/lprns.h // Randomness visualization: https://thefiletree.com/espadrine/%E2%9A%92/random.html?app=data const LPRNS_WEYL = 0x3504f333, LPRNS_M0 = 0x85ebca77, LPRNS_M1 = 0xc2b2ae3d; const LPRNS_S0 = 15, LPRNS_S1 = 13, LPRNS_S2 = 16; class Weyl { constructor(seed) { this.state = seed; } // Random 32-bit integer. random32() { const oldState = this.state >>> 0; let x = oldState; x ^= oldState >>> LPRNS_S0; x *= LPRNS_M0; x ^= x >>> LPRNS_S1; x *= LPRNS_M1; x ^= x >>> LPRNS_S2; this.state = oldState + LPRNS_WEYL; return x; } // Random number from 0 incl to 1 excl. random() { return this.random32() / 0x100000000; } } if (typeof module !== "undefined" && module.exports) { module.exports = Weyl; } else { global.PRNG = Weyl; } }(this));
var gulp = require("gulp"); var exec = require('child_process').exec; function cmd(cmdString, cb) { exec(cmdString, function (err, stdout, stderr) { console.log(stdout); console.log(stderr); cb(err); }); } gulp.task("build:bgservices", function (cb) { cmd("node_modules/.bin/parcel build ./src/backgroundServices.ts", cb) }); gulp.task("copy:browseraction", function() { return gulp.src("src/browserAction/*") .pipe(gulp.dest("dist/browserAction")); }); gulp.task("copy:contentScript", function() { return gulp.src("src/contentScript/*") .pipe(gulp.dest("dist/contentScript")); }); gulp.task("copy:options", function() { return gulp.src("src/options/*") .pipe(gulp.dest("dist/options")); }); gulp.task("copy:images", function() { return gulp.src("images/*.png") .pipe(gulp.dest("dist/images")) }); gulp.task("copy:manifest", function() { return gulp.src("manifest.json") .pipe(gulp.dest("dist")) }); gulp.task("copy:jwtdecode", function() { return gulp.src("node_modules/jwt-decode/build/jwt-decode*.js") .pipe(gulp.dest("dist")) }); gulp.task("copy:bootstrapcss", function() { return gulp.src("node_modules/bootstrap/dist/css/bootstrap.min.*") .pipe(gulp.dest("dist/browserAction")) }); gulp.task("build", gulp.parallel(["build:bgservices", "copy:browseraction", "copy:contentScript", "copy:options", "copy:manifest", "copy:jwtdecode", "copy:bootstrapcss", "copy:images"])); gulp.task("clean", function(cb) { cmd("rm -rf dist", cb); cmd("rm src/*.js", cb); cmd("rm src/*.js.map", cb); cmd("rm src/browserFacades/*.js", cb); cmd("rm src/browserFacades/*.js.map", cb); cmd("rm src/models/*.js", cb); cmd("rm src/models/*.js.map", cb); cmd("rm src/types/*.js", cb); cmd("rm src/types/*.js.map", cb); });
var Hapi = require('hapi'), git = require('nodegit'); // Create a server with a host and port var server = Hapi.createServer('localhost', 3000); // Add the route server.route({ method: 'GET', path: '/hello', handler: function (request, reply) { reply('hello world'); } }); // Start the server server.start();
import _ from "lodash"; const LOCAL_STORAGE_KEY = "sessionData"; export default class Session { /*@ngInject*/ constructor(USER_ROLES, localStorageService, featureFlags, $rootScope) { const updateFeatureFlags = () => { const flags = this.sessionData.flags || []; featureFlags.set(flags); featureFlags.enable({ key: "none" }); }; this.create = (data) => { if (!data.token) { throw new Error("The token is missing from the session data."); } this.sessionData = data; this.token = this.sessionData.token; this.userRole = [USER_ROLES.user]; updateFeatureFlags(); localStorageService.set(LOCAL_STORAGE_KEY, this.sessionData); $rootScope.$broadcast("sessionCreated"); }; this.update = (newData = {}, replace = true) => { if (!newData.token && replace) { throw new Error("The token is missing from the session data."); } this.sessionData = replace ? newData : _.extend(this.sessionData, newData); this.token = this.sessionData.token; updateFeatureFlags(); localStorageService.set(LOCAL_STORAGE_KEY, this.sessionData); $rootScope.$broadcast("sessionUpdated"); }; this.createFromLocalStorage = () => { try { const storedValue = localStorageService.get(LOCAL_STORAGE_KEY); if (!storedValue) { return; } // Control previously stored the token directly as a string. // Remove it to prevent logged in users from storing an old token without knowing it. localStorageService.remove("token"); this.create(storedValue); } catch (x) { localStorageService.remove(LOCAL_STORAGE_KEY); return; } }; this.destroy = () => { this.sessionData = null; this.token = null; this.userRole = null; localStorageService.remove(LOCAL_STORAGE_KEY); $rootScope.$broadcast("sessionDestroyed"); }; } }
/* jshint node: true */ exports.ValidationError = require('./validation-error'); exports.ActionCooldownError = require('./action-cooldown-error'); exports.UnknownActionError = require('./unknown-action-error'); exports.RateLimitError = require('./rate-limit-error'); exports.InvalidDirectionError = require('./invalid-direction-error'); exports.BrokenBotError = require('./broken-bot-error'); exports.UnknownBotTargetError = require('./unknown-bot-target-error'); exports.UnauthorizedActionError = require('./unauthorized-action-error');
/* eslint-disable no-ternary, no-plusplus, require-jsdoc */ class DisplayCondition { constructor(options = {}) { this.wrapperField = options.wrapperField; this.type = options.type; this.conditionQuestion = options.conditionQuestion; this.answerOption = options.answerOption; this.mandatory = options.mandatory; this.value = options.value; this.onFulfilled = options.onFulfilled; this.bindEvent(); } bindEvent() { this.checkCondition(); this.getInputsToListen().on("change", this.checkCondition.bind(this)); } getInputValue() { const $conditionWrapperField = $(`.question[data-question-id='${this.conditionQuestion}']`); const $textInput = $conditionWrapperField.find("textarea, input[type='text']:not([name$=\\[custom_body\\]])"); if ($textInput.length) { return $textInput.val(); } let multipleInput = []; $conditionWrapperField.find(".radio-button-collection, .check-box-collection").find(".collection-input").each((idx, el) => { const $input = $(el).find("input[name$=\\[body\\]]"); const checked = $input.is(":checked"); if (checked) { const text = $(el).find("input[name$=\\[custom_body\\]]").val(); const value = $input.val(); const id = $(el).find("input[name$=\\[answer_option_id\\]]").val(); multipleInput.push({ id, value, text }); } }); return multipleInput; } getInputsToListen() { const $conditionWrapperField = $(`.question[data-question-id='${this.conditionQuestion}']`); const $textInput = $conditionWrapperField.find("textarea, input[type='text']:not([name$=\\[custom_body\\]])"); if ($textInput.length) { return $textInput; } return $conditionWrapperField.find(".collection-input").find("input:not([type='hidden'])"); } checkAnsweredCondition(value) { if (typeof (value) !== "object") { return Boolean(value); } return Boolean(value.some((it) => it.value)); } checkNotAnsweredCondition(value) { return !this.checkAnsweredCondition(value); } checkEqualCondition(value) { if (value.length) { return value.some((it) => it.id === this.answerOption.toString()); } return false; } checkNotEqualCondition(value) { if (value.length) { return value.every((it) => it.id !== this.answerOption.toString()); } return false; } checkMatchCondition(value) { let regexp = new RegExp(this.value, "i"); if (typeof (value) !== "object") { return Boolean(value.match(regexp)); } return value.some(function (it) { return it.text ? it.text.match(regexp) : it.value.match(regexp) }); } checkCondition() { const value = this.getInputValue(); let fulfilled = false; switch (this.type) { case "answered": fulfilled = this.checkAnsweredCondition(value); break; case "not_answered": fulfilled = this.checkNotAnsweredCondition(value); break; case "equal": fulfilled = this.checkEqualCondition(value); break; case "not_equal": fulfilled = this.checkNotEqualCondition(value); break; case "match": fulfilled = this.checkMatchCondition(value); break; default: fulfilled = false; break; } this.onFulfilled(fulfilled); } } class DisplayConditionsComponent { constructor(options = {}) { this.wrapperField = options.wrapperField; this.conditions = {}; this.showCount = 0; this.initializeConditions(); } initializeConditions() { const $conditionElements = this.wrapperField.find(".display-condition"); $conditionElements.each((idx, el) => { const $condition = $(el); const id = $condition.data("id"); this.conditions[id] = {}; this.conditions[id] = new DisplayCondition({ wrapperField: this.wrapperField, type: $condition.data("type"), conditionQuestion: $condition.data("condition"), answerOption: $condition.data("option"), mandatory: $condition.data("mandatory"), value: $condition.data("value"), onFulfilled: (fulfilled) => { this.onFulfilled(id, fulfilled); } }); }); } mustShow() { const conditions = Object.values(this.conditions); const mandatoryConditions = conditions.filter((condition) => condition.mandatory); const nonMandatoryConditions = conditions.filter((condition) => !condition.mandatory); if (mandatoryConditions.length) { return mandatoryConditions.every((condition) => condition.fulfilled); } return nonMandatoryConditions.some((condition) => condition.fulfilled); } onFulfilled(id, fulfilled) { this.conditions[id].fulfilled = fulfilled; if (this.mustShow()) { this.showQuestion(); } else { this.hideQuestion(); } } showQuestion() { this.wrapperField.fadeIn(); this.wrapperField.find("input, textarea").prop("disabled", null); this.showCount++; } hideQuestion() { if (this.showCount) { this.wrapperField.fadeOut(); } else { this.wrapperField.hide(); } this.wrapperField.find("input, textarea").prop("disabled", "disabled"); } } export default function createDisplayConditions(options) { return new DisplayConditionsComponent(options); }
/** * Created by Serhii Maksymchuk from Ubrainians for imCode * 27.07.17. */ define("imcms-keywords-builder", ["imcms-bem-builder", "imcms-texts-builder", "imcms-buttons-builder", "imcms-primitives-builder", "imcms-uuid-generator", "jquery"], function (BEM, texts, buttons, primitives, uuidGenerator, $) { const keywordMaxLength = 128; function createRemoveKeywordButton() { return buttons.closeButton({click: removeKeyword}); } function isUniqueKeyWord(keyWord, $keywordsContainer) { return $keywordsContainer.find(".imcms-keyword__keyword") .map(function () { return $(this) }) .toArray() .reduce((isUnique, $keyword) => isUnique && ($keyword.text() !== keyWord), true); } function addKeyword() { const $btn = $(this), $keywordInput = $btn.parent().find(".imcms-keyword__input"), keywordInputVal = $keywordInput.val().trim(), $keywordsContainer = $btn.parent().find(".imcms-keyword__keywords") ; $keywordInput.val(""); if ((keywordInputVal !== "") && isUniqueKeyWord(keywordInputVal, $keywordsContainer)) { $keywordsContainer.css({"display": "block"}); keywordsBoxBEM.buildBlockElement("keyword", "<div>", { text: keywordInputVal }).append(createRemoveKeywordButton()).appendTo($keywordsContainer); } } function removeKeyword() { const $btn = $(this), $keyword = $btn.parents(".imcms-keyword__keyword"), $keywords = $keyword.parent() ; $keyword.remove(); if ($keywords.children().length === 0) { $keywords.css({"display": "none"}) } } function bindAddKeyword($input, $addKeywordButton, $keywordsBlock) { return keyword => { $input.val(keyword); $addKeywordButton.click(); return $keywordsBlock; }; } function bindGetKeywords($keywordsBlock) { return function () { return $keywordsBlock.find(".imcms-keyword__keyword") .map(function () { return $(this).text(); }) .toArray(); }; } var keywordsContainerBEM = new BEM({ block: "imcms-field", elements: { "keywords-box": "imcms-keyword" } }), keywordsBoxBEM = new BEM({ block: "imcms-keyword", elements: { "keywords": "", "keyword": "" } }) ; return { keywordsBox: function (tag, attributes) { const inputId = attributes["input-id"] || uuidGenerator.generateUUID(), $label = primitives.imcmsLabel(inputId, attributes.title), $input = primitives.imcmsInputText({ id: inputId, placeholder: attributes.placeholder }, ["wide"]), $addKeywordButton = buttons.neutralButton({ text: attributes["button-text"], click: addKeyword }), $keywordsContainer = keywordsBoxBEM.buildElement("keywords", "<div>"), $keywordsBox = keywordsBoxBEM.buildBlock("<div>", [ {"label": $label}, {"input": $input}, {"button": $addKeywordButton}, {"keywords": $keywordsContainer} ]) ; $input.on("input", function () { const $input = $(this); const keywordValue = $input.val().trim(); if (keywordValue.length > keywordMaxLength) { $input.val(keywordValue.substring(0, keywordMaxLength)); } }); const $keywordsBlock = keywordsContainerBEM.buildBlock("<div>", [{"keywords-box": $keywordsBox}]); $keywordsBlock.addKeyword = bindAddKeyword($input, $addKeywordButton, $keywordsBlock); $keywordsBlock.getKeywords = bindGetKeywords($keywordsBlock); return $keywordsBlock; } }; } );
import React from 'react'; import ComponentModel from '../../../src/js/components/ui/ComponentModel/ComponentModel.js'; import styles from '../../../src/js/components/ui/ComponentModel/ComponentModel.scss'; import { shallow, configure } from 'enzyme'; import Adapter from 'enzyme-adapter-react-16'; configure({ adapter: new Adapter() }); describe('Test ComponentModel component', () => { const mockFn = jest.fn(); const componentModel = shallow(<ComponentModel onClickHandler={mockFn}>Lorem ipsum</ComponentModel>); it('should be defined', () => { expect(componentModel).toBeDefined(); }); it('should render correctly', () => { expect(componentModel).toMatchSnapshot(); }); it('ComponentModel click event', () => { componentModel.find(`.${styles.componentModel}`).simulate('click'); expect(mockFn).toHaveBeenCalledTimes(1); }); });
import { moduleForComponent, test } from 'ember-qunit'; import hbs from 'htmlbars-inline-precompile'; import Ember from 'ember'; moduleForComponent('client-item', 'Integration | Component | client item', { integration: true }); test('it renders', function(assert) { // Set any properties with this.set('myProperty', 'value'); // Handle any actions with this.on('myAction', function(val) { ... }); let model = Ember.Object.create({}); model.set('client_id', 'collection'); model.set('client_name', 'collection'); this.set('model', model); this.render(hbs`{{client-item item=model}}`); assert.equal(this.$('.panel-title').text().trim(), 'collection [collection]'); });
/** * Adds support for schema blueprint and binds :model/schema route for each RESTful model. */ var _ = require('lodash'); var pluralize = require('pluralize'); module.exports = function (sails) { return { initialize: function (cb) { var config = sails.config.blueprints; sails.on('router:before', function () { _.forEach(sails.models, function (model) { var controller = sails.middleware.controllers[model.identity]; if (!controller) return; // Validate blueprint config for this controller if (config.prefix) { if (!_(config.prefix).isString()) { return; } if (!config.prefix.match(/^\//)) { config.prefix = '/' + config.prefix; } } // Validate REST route blueprint config for this controller if (config.restPrefix) { if (!_(config.restPrefix).isString()) { return; } if (!config.restPrefix.match(/^\//)) { config.restPrefix = '/' + config.restPrefix; } } var prefix = config.prefix + config.restPrefix; var baseRoute = [prefix, model.identity].join('/'); if (config.pluralize && _.get(controller, '_config.pluralize', true)) { baseRoute = pluralize(baseRoute); } var route = baseRoute + '/schema'; sails.router.bind(route, _.get(sails.middleware, 'blueprints.schema'), null, {controller: model.identity}); }); }); cb(); } }; };
var class_t_mail___transport___d_b_store = [ [ "send", "class_t_mail___transport___d_b_store.html#a5726d98986db1d07eb65500bde0cdc2b", null ], [ "setModel", "class_t_mail___transport___d_b_store.html#a81d7b82d316cf67681fc28e971527617", null ], [ "$model", "class_t_mail___transport___d_b_store.html#a08fdd91bde255dbe3e2d15a22d9663e8", null ] ];
var controller = angular.module('myLazyClock.controller.home', []); controller.controller('myLazyClock.controller.home', ['$scope', '$timeout', 'GApi', function homeCtl($scope, $timeout, GApi) { GApi.executeAuth('myLazyClock', 'alarmClock.list').then(function(resp) { $scope.alarmClocks = resp.items; }); } ]);
define(function (require) { 'use strict'; var Vector2 = require('common/math/vector2'); var Beaker = require('models/element/beaker'); var EnergyChunkWanderController = require('models/energy-chunk-wander-controller'); /** * */ var BeakerContainer = Beaker.extend({ initialize: function(attributes, options) { options = options || {}; Beaker.prototype.initialize.apply(this, arguments); this.potentiallyContainedElements = options.potentiallyContainedElements || []; this._motionVector = new Vector2(); }, /* * Update the fluid level in the beaker based upon any displacement that * could be caused by the given rectangles. This algorithm is strictly * two dimensional, even though displacement is more of the 3D concept. */ updateFluidLevel: function(potentiallyDisplacingRectangles) { // Calculate the amount of overlap between the rectangle that // represents the fluid and the displacing rectangles. var fluidRectangle = this._fluidRect.set( this.getRect().x, this.getRect().y, this.get('width'), this.get('height') * this.get('fluidLevel') ); var intersection; var overlappingArea = 0; var i; for (i = 0; i < potentiallyDisplacingRectangles.length; i++) { var rectangle = potentiallyDisplacingRectangles[i]; if (rectangle.overlaps(fluidRectangle)) { intersection = rectangle.intersection(fluidRectangle); overlappingArea += intersection.w * intersection.h; } } // Map the overlap to a new fluid height. The scaling factor was // empirically determined to look good. var newFluidLevel = Math.min(Beaker.INITIAL_FLUID_LEVEL + overlappingArea * 120, 1); var proportionateIncrease = newFluidLevel / this.get('fluidLevel'); if (this.get('fluidLevel') != newFluidLevel) { this.set('fluidLevel', newFluidLevel); // Update the shapes of the energy chunk slices. for (i = 0; i < this.slices.length; i++) { var slice = this.slices[i]; var originalBounds = slice.getShape().getBounds().clone(); slice.getShape().scale(1, proportionateIncrease); slice.getShape().translate( originalBounds.x - slice.getShape().getBounds().x, originalBounds.y - slice.getShape().getBounds().y ); } } }, isEnergyChunkObscured: function(chunk) { var element; for (var i = 0; i < this.potentiallyContainedElements.length; i++) { element = this.potentiallyContainedElements[i]; if (this.getThermalContactArea().getBounds().contains(element.getRect()) && element.getProjectedShape().contains(chunk.get('position'))) return true; } return false; }, animateUncontainedEnergyChunks: function(deltaTime) { var controller; var chunk; for (var i = this.energyChunkWanderControllers.length - 1; i >= 0; i--) { controller = this.energyChunkWanderControllers[i]; chunk = controller.energyChunk; if (this.isEnergyChunkObscured(chunk)) { // This chunk is being transferred from a container in the // beaker to the fluid, so move it sideways. var xVelocity = 0.05 * deltaTime * (this.getCenterPoint().x > chunk.get('position').x ? -1 : 1); var motionVector = this._motionVector.set(xVelocity, 0); chunk.translate(motionVector); } else { controller.updatePosition(deltaTime); } if (!this.isEnergyChunkObscured(chunk) && this.getSliceBounds().contains(chunk.get('position'))) { // Chunk is in a place where it can migrate to the slices and // stop moving. this.moveEnergyChunkToSlices(controller.energyChunk); } } }, addEnergyChunk: function(chunk) { if (this.isEnergyChunkObscured(chunk)) { // Chunk obscured by a model element in the beaker, probably // because the chunk just came from the model element. chunk.zPosition = 0; this.approachingEnergyChunks.add(chunk); this.energyChunkWanderControllers.push(new EnergyChunkWanderController(chunk, this.get('position'))); } else { Beaker.prototype.addEnergyChunk.apply(this, [chunk]); } } }); return BeakerContainer; });
OC.L10N.register( "notes", { "Notes" : "Pastabos", "New note" : "Nauja pastaba", "_%n word_::_%n words_" : ["%n žodis","%n žodžių","%n žodžių"], "Delete note" : "Ištrinti pastabą", "Favorite" : "Mėgiamas" }, "nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && (n%100<10 || n%100>=20) ? 1 : 2);");
import React from 'react'; import SPELLS from 'common/SPELLS'; import TalentStatisticBox from 'interface/others/TalentStatisticBox'; import STATISTIC_ORDER from 'interface/others/STATISTIC_ORDER'; import Events from 'parser/core/Events'; import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer'; import { formatThousands} from 'common/format'; import SpellLink from 'common/SpellLink'; /** * Example Report: https://www.warcraftlogs.com/reports/Mz8cTFgNkxXaJt3j/#fight=4&source=18 */ class FelBarrage extends Analyzer{ damage = 0; casts = 0; badCasts = 0; constructor(...args) { super(...args); this.active = this.selectedCombatant.hasTalent(SPELLS.FEL_BARRAGE_TALENT.id); if (!this.active) { return; } this.addEventListener(Events.damage.by(SELECTED_PLAYER).spell(SPELLS.FEL_BARRAGE_DAMAGE), this.felBarrage); this.addEventListener(Events.cast.by(SELECTED_PLAYER).spell(SPELLS.FEL_BARRAGE_TALENT), this.felBarrageCasts); } felBarrage(event) { this.damage += event.amount; } felBarrageCasts(event) { this.casts += 1; const hasMetaBuff = this.selectedCombatant.hasBuff(SPELLS.METAMORPHOSIS_HAVOC_BUFF.id, event.timestamp); if (!hasMetaBuff) { this.badCasts += 1; } } get suggestionThresholds() { return { actual: this.badCasts, isGreaterThan: { minor: 0, average: 0, major: 1, }, style: 'number', }; } suggestions(when) { when(this.suggestionThresholds) .addSuggestion((suggest, actual, recommended) => { return suggest(<>Try to cast <SpellLink id={SPELLS.FEL_BARRAGE_TALENT.id} /> during <SpellLink id={SPELLS.METAMORPHOSIS_HAVOC.id} />.</>) .icon(SPELLS.FEL_BARRAGE_TALENT.icon) .actual(<>{actual} bad <SpellLink id={SPELLS.FEL_BARRAGE_TALENT.id} /> casts without <SpellLink id={SPELLS.METAMORPHOSIS_HAVOC.id} />.</>) .recommended(`No bad casts is recommended.`); }); } statistic(){ return ( <TalentStatisticBox talent={SPELLS.FEL_BARRAGE_TALENT.id} position={STATISTIC_ORDER.OPTIONAL(6)} value={( <> {this.badCasts} <small>casts without <SpellLink id={SPELLS.METAMORPHOSIS_HAVOC.id} /> </small> <br /> {this.owner.formatItemDamageDone(this.damage)} </> )} tooltip={( <> A bad cast is casting Fel Barage without Metamorphosis up.<br /><br /> {formatThousands(this.damage)} total damage </> )} /> ); } } export default FelBarrage;
/** * @license Copyright (c) 2003-2020, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang( 'uploadwidget', 'hu', { abort: 'A feltöltést a felhasználó megszakította.', doneOne: 'A fájl sikeresen feltöltve.', doneMany: '%1 fájl sikeresen feltöltve.', uploadOne: 'Fájl feltöltése ({percentage}%)...', uploadMany: 'Fájlok feltöltése, {current}/{max} kész ({percentage}%)...' } );
import { moduleForModel, test } from 'ember-qunit'; moduleForModel('locality', 'Unit | Model | locality', { // Specify the other units that are required for this test. needs: ['model:geography', 'model:agent', 'model:paleo-context'] }); test('it exists', function(assert) { let model = this.subject(); // let store = this.store(); assert.ok(!!model); });
import classNames from 'classnames' import PropTypes from 'prop-types' import React from 'react' import ReactSelect from 'react-select' import uncontrollableInput from 'uncontrollable-input' import { AutoSizer, CellMeasurer, CellMeasurerCache, List } from 'react-virtualized' const SELECT_STYLE = { minWidth: '10em', } const MENU_STYLE = { overflow: 'hidden', whiteSpace: 'normal', } @uncontrollableInput() export default class Select extends React.PureComponent { static defaultProps = { maxHeight: 200, multi: ReactSelect.defaultProps.multi, required: ReactSelect.defaultProps.required, simpleValue: ReactSelect.defaultProps.simpleValue, valueKey: ReactSelect.defaultProps.valueKey, } static propTypes = { autoSelectSingleOption: PropTypes.bool, // default to props.required maxHeight: PropTypes.number, options: PropTypes.array, // cannot be an object } _cellMeasurerCache = new CellMeasurerCache({ fixedWidth: true, }) // https://github.com/JedWatson/react-select/blob/dd32c27d7ea338a93159da5e40bc06697d0d86f9/src/utils/defaultMenuRenderer.js#L4 _renderMenu(opts) { const { focusOption, options, selectValue } = opts const focusFromEvent = event => focusOption(options[event.currentTarget.dataset.index]) const selectFromEvent = event => selectValue(options[event.currentTarget.dataset.index]) const renderRow = opts2 => this._renderRow(opts, opts2, focusFromEvent, selectFromEvent) let focusedOptionIndex = options.indexOf(opts.focusedOption) if (focusedOptionIndex === -1) { focusedOptionIndex = undefined } const { length } = options const { maxHeight } = this.props const { rowHeight } = this._cellMeasurerCache let height = 0 for (let i = 0; i < length; ++i) { height += rowHeight({ index: i }) if (height > maxHeight) { height = maxHeight break } } return ( <AutoSizer disableHeight> {({ width }) => ( <List deferredMeasurementCache={this._cellMeasurerCache} height={height} rowCount={length} rowHeight={rowHeight} rowRenderer={renderRow} scrollToIndex={focusedOptionIndex} width={width} /> )} </AutoSizer> ) } _renderMenu = this._renderMenu.bind(this) _renderRow( { focusedOption, focusOption, inputValue, optionClassName, optionRenderer, options, selectValue }, { index, key, parent, style }, focusFromEvent, selectFromEvent ) { const option = options[index] const { disabled } = option return ( <CellMeasurer cache={this._cellMeasurerCache} columnIndex={0} key={key} parent={parent} rowIndex={index}> <div className={classNames('Select-option', optionClassName, { 'is-disabled': disabled, 'is-focused': option === focusedOption, })} data-index={index} onClick={disabled ? undefined : selectFromEvent} onMouseEnter={disabled ? undefined : focusFromEvent} style={style} title={option.title} > {optionRenderer(option, index, inputValue)} </div> </CellMeasurer> ) } componentDidMount() { this.componentDidUpdate() } componentDidUpdate() { const { props } = this const { autoSelectSingleOption = props.required, multi, options, simpleValue, value } = props let option if ( autoSelectSingleOption && options != null && (value == null || (simpleValue && value === '') || (multi && value.length === 0)) && ([option] = options.filter(_ => !_.disabled)).length === 1 ) { props.onChange(simpleValue ? option[props.valueKey] : multi ? [option] : option) } } render() { const { props } = this const { multi } = props return ( <ReactSelect backspaceToRemoveMessage='' clearable={multi || !props.required} closeOnSelect={!multi} isLoading={!props.disabled && props.options == null} style={SELECT_STYLE} valueRenderer={props.optionRenderer} {...props} menuRenderer={this._renderMenu} menuStyle={MENU_STYLE} /> ) } }
/** * ownCloud * * @author Vincent Petry * @copyright 2014 Vincent Petry <pvince81@owncloud.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE * License as published by the Free Software Foundation; either * version 3 of the License, or any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU AFFERO GENERAL PUBLIC LICENSE for more details. * * You should have received a copy of the GNU Affero General Public * License along with this library. If not, see <http://www.gnu.org/licenses/>. * */ /** * Simulate the variables that are normally set by PHP code */ // from core/js/config.php window.TESTING = true; window.datepickerFormatDate = 'MM d, yy'; window.dayNames = [ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' ]; window.dayNamesShort = [ 'Sun.', 'Mon.', 'Tue.', 'Wed.', 'Thu.', 'Fri.', 'Sat.' ]; window.dayNamesMin = [ 'Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa' ]; window.monthNames = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ]; window.monthNamesShort = [ 'Jan.', 'Feb.', 'Mar.', 'Apr.', 'May.', 'Jun.', 'Jul.', 'Aug.', 'Sep.', 'Oct.', 'Nov.', 'Dec.' ]; window.firstDay = 0; // setup dummy webroots /* jshint camelcase: false */ window.oc_debug = true; window.oc_isadmin = false; // FIXME: oc_webroot is supposed to be only the path!!! window.oc_webroot = location.href + '/'; window.oc_appswebroots = { "files": window.oc_webroot + '/apps/files/' }; window.oc_config = { session_lifetime: 600 * 1000, session_keepalive: false, blacklist_files_regex: '\.(part|filepart)$' }; window.oc_appconfig = { core: {} }; window.oc_defaults = {}; /* jshint camelcase: true */ // mock for Snap.js plugin window.Snap = function() {}; window.Snap.prototype = { enable: function() {}, disable: function() {}, close: function() {} }; window.isPhantom = /phantom/i.test(navigator.userAgent); // global setup for all tests (function setupTests() { var fakeServer = null, $testArea = null, ajaxErrorStub = null; /** * Utility functions for testing */ var TestUtil = { /** * Returns the image URL set on the given element * @param $el element * @return {String} image URL */ getImageUrl: function($el) { // might be slightly different cross-browser var url = $el.css('background-image'); var r = url.match(/url\(['"]?([^'")]*)['"]?\)/); if (!r) { return url; } return r[1]; } }; beforeEach(function() { // test area for elements that need absolute selector access or measure widths/heights // which wouldn't work for detached or hidden elements $testArea = $('<div id="testArea" style="position: absolute; width: 1280px; height: 800px; top: -3000px; left: -3000px; opacity: 0;"></div>'); $('body').append($testArea); // enforce fake XHR, tests should not depend on the server and // must use fake responses for expected calls fakeServer = sinon.fakeServer.create(); // make it globally available, so that other tests can define // custom responses window.fakeServer = fakeServer; if (!OC.TestUtil) { OC.TestUtil = TestUtil; } moment.locale('en'); // reset plugins OC.Plugins._plugins = []; // dummy select2 (which isn't loaded during the tests) $.fn.select2 = function() { return this; }; ajaxErrorStub = sinon.stub(OC, '_processAjaxError'); }); afterEach(function() { // uncomment this to log requests // console.log(window.fakeServer.requests); fakeServer.restore(); $testArea.remove(); delete($.fn.select2); ajaxErrorStub.restore(); // reset pop state handlers OC.Util.History._handlers = []; }); })();
var util = require( "util" ) ; var f = function ( x ) { return x * x ; } ; var g = function ( x ) { return x + 1 ; } ; var fg = functools.chain( [ g , f ] ) ; var one = function ( x ) { deepEqual( fg( x ) , f( g( x ) ) , util.format("fg( %s ) === f( g( %s ) )" , x , x ) ) ; } ; test( "chain" , function ( ) { one( 0 ) ; one( 1 ) ; one( 2 ) ; } ) ;
'use strict'; const validation = require('dumonda-me-server-lib').jsonValidation; const suggestionCreate = requireModel('superUser/question/suggestion/create'); const suggestionEdit = requireModel('superUser/question/suggestion/edit'); const suggestionDelete = requireModel('superUser/question/suggestion/delete'); const asyncMiddleware = require('dumonda-me-server-lib').asyncMiddleware; const auth = require('dumonda-me-server-lib').auth; const exceptions = require('dumonda-me-server-lib').exceptions; const schemaCreateSuggestion = { name: 'createSuggestion', type: 'object', additionalProperties: false, required: ['questionId'], properties: { questionId: {type: 'string', format: 'notEmptyString', maxLength: 60}, title: {type: 'string', format: 'notEmptyString', maxLength: 140}, description: {type: 'string', format: 'notEmptyString', maxLength: 2000}, explanation: {type: 'string', format: 'notEmptyString', maxLength: 2000}, } }; const schemaEditSuggestion = { name: 'editSuggestion', type: 'object', additionalProperties: false, required: ['suggestionId'], properties: { suggestionId: {type: 'string', format: 'notEmptyString', maxLength: 60}, title: {type: 'string', format: 'notEmptyString', maxLength: 140}, description: {type: 'string', format: 'notEmptyString', maxLength: 2000}, explanation: {type: 'string', format: 'notEmptyString', maxLength: 2000}, } }; const schemaDeleteSuggestion = { name: 'deleteSuggestion', type: 'object', additionalProperties: false, required: ['suggestionId'], properties: { suggestionId: {type: 'string', format: 'notEmptyString', maxLength: 60} } }; const checkParameter = function (title, description, explanation) { if (!title && !description && !explanation) { throw new exceptions.InvalidOperation(`At least one parameter need to be defined`); } }; module.exports = function (router) { router.post('/', auth.isAuthenticated(), asyncMiddleware(async (req, res) => { const params = await validation.validateRequest(req, schemaCreateSuggestion); checkParameter(params.title, params.description, params.explanation); params.title = params.title || null; params.description = params.description || null; params.explanation = params.explanation || null; let response = await suggestionCreate.createSuggestion(req.user.id, params.questionId, params.title, params.description, params.explanation); res.status(200).json(response); })); router.put('/', auth.isAuthenticated(), asyncMiddleware(async (req, res) => { const params = await validation.validateRequest(req, schemaEditSuggestion); checkParameter(params.title, params.description, params.explanation); params.title = params.title || null; params.description = params.description || null; params.explanation = params.explanation || null; await suggestionEdit.editSuggestion(req.user.id, params.suggestionId, params.title, params.description, params.explanation); res.status(200).end(); })); router.delete('/', auth.isAuthenticated(), asyncMiddleware(async (req, res) => { const params = await validation.validateRequest(req, schemaDeleteSuggestion); await suggestionDelete.deleteSuggestion(req.user.id, params.suggestionId); res.status(200).end(); })); };
var path = require('path') var buildumb = require('buildumb') , object = require('isomorph').object // Default configuration for all builds var root = path.normalize(path.join(__dirname, '..')) var baseModules = { // isomorph 'node_modules/isomorph/is.js' : ['isomorph/is', './is'] , 'node_modules/isomorph/object.js' : 'isomorph/object' , 'node_modules/isomorph/array.js' : 'isomorph/array' // DOMBuilder , 'lib/dombuilder/core.js' : ['./dombuilder/core', './core'] } // Configuration for multiple feature builds // [plugin module names, features, build file] var builds = [ [['dom','html', 'template'], 'dom [default], html, template', 'DOMBuilder.template.js'] , [['dom', 'html'], 'dom [default], html', 'DOMBuilder.js'] , [['dom'], 'dom [default]', 'DOMBuilder.dom.js'] , [['html'], 'html [default]', 'DOMBuilder.html.js'] ] for (var i = 0, l = builds.length; i < l; i++) { var build = builds[i] , pluginModules = build[0] , features = build[1] , buildFile = build[2] , outputFile = 'dist/' + buildFile , compressFile = outputFile.replace('.js', '.min.js') , header = buildumb.formatTemplate(path.join(__dirname, 'header.js'), require('../package.json').version, features) var modules = object.extend({}, baseModules) // Include Concur in the build only for plugin modules which use it if (pluginModules.indexOf('template') != -1) { modules['node_modules/Concur/lib/concur.js'] = 'Concur' } pluginModules.forEach(function(pluginModule) { modules['lib/dombuilder/' + pluginModule + '.js'] = './dombuilder/' + pluginModule }) modules['support/' + buildFile] = 'DOMBuilder' console.log('Building version: ' + features) buildumb.build({ root: root , modules: modules , exports: { 'DOMBuilder': 'DOMBuilder' } , output: outputFile , compress: compressFile , header: header }) }
// -- // Core.JavaScriptEnhancements.js - provides functions for validating form inputs // Copyright (C) 2001-2011 OTRS AG, http://otrs.org/ // -- // $Id$ // -- // This software comes with ABSOLUTELY NO WARRANTY. For details, see // the enclosed file COPYING for license information (AGPL). If you // did not receive this file, see http://www.gnu.org/licenses/agpl.txt. // -- "use strict"; (function () { /** * @function * @description * This function checks if all given parameter objects are jQuery objects. * @return * {boolean} Returns true if all parameter objects are jQuery objects */ window.isJQueryObject = function () { var I; if (typeof jQuery === 'undefined') { return false; } for (I = 0; I < arguments.length; I++) { if (!(arguments[I] instanceof jQuery)) { return false; } } return true; }; }());
import { withUpdated, withInsertedBefore, moveUp, moveDown, } from './arrayHelpers'; const testArray = ['a', 'b', 'c', 'd', 'e']; describe('withUpdated', () => { test('updates every array element', () => { const cases = { a: ['x', 'b', 'c', 'd', 'e'], b: ['a', 'x', 'c', 'd', 'e'], c: ['a', 'b', 'x', 'd', 'e'], d: ['a', 'b', 'c', 'x', 'e'], e: ['a', 'b', 'c', 'd', 'x'], }; Object.entries(cases).forEach(([replace, expected]) => { expect(withUpdated(testArray, el => el === replace, el => 'x')).toEqual( expected ); }); }); test('does not mutate the input array', () => { withUpdated(testArray, el => el === 'c', el => 'x'); expect(testArray).toEqual(['a', 'b', 'c', 'd', 'e']); }); test('returns an unchanged array if the selector does not match', () => { expect(withUpdated(testArray, el => el === 'foo', el => 'x')).toEqual([ 'a', 'b', 'c', 'd', 'e', ]); }); }); describe('withInsertedBefore', () => { test('inserts before every array element', () => { const cases = { a: ['x', 'a', 'b', 'c', 'd', 'e'], b: ['a', 'x', 'b', 'c', 'd', 'e'], c: ['a', 'b', 'x', 'c', 'd', 'e'], d: ['a', 'b', 'c', 'x', 'd', 'e'], e: ['a', 'b', 'c', 'd', 'x', 'e'], }; Object.entries(cases).forEach(([selected, expected]) => { expect(withInsertedBefore(testArray, el => el === selected, 'x')).toEqual( expected ); }); }); test('does not mutate the input array', () => { withInsertedBefore(testArray, el => el === 'c', 'x'); expect(testArray).toEqual(['a', 'b', 'c', 'd', 'e']); }); test('returns an unchanged array if the selector does not match', () => { expect(withInsertedBefore(testArray, el => el === 'foo', 'x')).toEqual([ 'a', 'b', 'c', 'd', 'e', ]); }); }); describe('moveUp', () => { test('moves up every array element', () => { const cases = { a: ['a', 'b', 'c', 'd', 'e'], b: ['b', 'a', 'c', 'd', 'e'], c: ['a', 'c', 'b', 'd', 'e'], d: ['a', 'b', 'd', 'c', 'e'], e: ['a', 'b', 'c', 'e', 'd'], }; Object.entries(cases).forEach(([replace, expected]) => { expect(moveUp(testArray, el => el === replace)).toEqual(expected); }); }); test('does not mutate the input array', () => { moveUp(testArray, el => el === 'c'); expect(testArray).toEqual(['a', 'b', 'c', 'd', 'e']); }); test('returns an unchanged array if the selector does not match', () => { expect(moveUp(testArray, el => el === 'foo')).toEqual([ 'a', 'b', 'c', 'd', 'e', ]); }); }); describe('moveDown', () => { test('moves down every array element', () => { const cases = { //'a': ['b', 'a', 'c', 'd', 'e'], b: ['a', 'c', 'b', 'd', 'e'], c: ['a', 'b', 'd', 'c', 'e'], d: ['a', 'b', 'c', 'e', 'd'], e: ['a', 'b', 'c', 'd', 'e'], }; Object.entries(cases).forEach(([replace, expected]) => { expect(moveDown(testArray, el => el === replace)).toEqual(expected); }); }); test('does not mutate the input array', () => { moveDown(testArray, el => el === 'c'); expect(testArray).toEqual(['a', 'b', 'c', 'd', 'e']); }); test('returns an unchanged array if the selector does not match', () => { expect(moveDown(testArray, el => el === 'foo')).toEqual([ 'a', 'b', 'c', 'd', 'e', ]); }); });
/*! * SWIF-OpenSTC * Copyright 2013-2014 Siclic <contact@siclic.fr> * Licensed under AGPL-3.0 (https://www.gnu.org/licenses/agpl.txt) */ /****************************************** * Require JS Configuration */ requirejs.config({ paths: { // Router // appReservationsRouter : '../app-reservations/js/routers/AppRouter', // Collections // bookingsCollection : '../app-reservations/js/collections/BookingsCollection', bookingLinesCollection : '../app-reservations/js/collections/BookingLinesCollection', bookingRecurrencesCollection : '../app-reservations/js/collections/BookingRecurencesCollection', bookablesCollection : '../app-reservations/js/collections/BookablesCollection', bookablesPartnerCollection : '../app-reservations/js/collections/BookablesPartnerCollection', // Models // bookingModel : '../app-reservations/js/models/BookingModel', bookingModelExtend : '../app-reservations/js/models/BookingModelExtend', bookingLineModel : '../app-reservations/js/models/BookingLineModel', bookingRecurrenceModel : '../app-reservations/js/models/BookingRecurrenceModel', bookableModel : '../app-reservations/js/models/BookableModel', // Views Lists // bookingsListView : '../app-reservations/js/views/lists/BookingsListView', formBookingView : '../app-reservations/js/views/forms/FormBookingView', itemFormBookingLineView : '../app-reservations/js/views/forms/ItemFormBookingLineView', formRecurrenceView : '../app-reservations/js/views/forms/FormRecurrenceView', itemFormBookingOccurrenceView : '../app-reservations/js/views/forms/ItemFormBookingOccurrenceView', planningManagerView : '../app-reservations/js/views/others/PlanningManagerView', // Views Others // planningManagerView : '../app-reservations/js/views/others/PlanningManagerView', sideBarPlanningSelectResourcesView : '../app-reservations/js/views/others/SideBarPlanningSelectResourcesView', calendarPlanningView : '../app-reservations/js/views/others/CalendarPlanningView', // Views Items // itemBookingView : '../app-reservations/js/views/items/ItemBookingView', // Views Modals // modalUpdateBookingView : '../app-reservations/js/views/modals/ModalUpdateBookingView', modalUpdateBookingsListView : '../app-reservations/js/views/modals/ModalUpdateBookingsListView', modalReservationDetailsView : '../app-reservations/js/views/modals/ModalReservationDetailsView', modalDeleteBookingView : '../app-reservations/js/views/modals/ModalDeleteBookingView', //Others View // toolbarButtonsView : '../app-reservations/js/views/others/ToolbarButtonsView', } });
/* See license.txt for terms of usage */ // ************************************************************************************************ // Module var EXPORTED_SYMBOLS = ["CompilationUnit"]; // XXXjjb Modules HACK Components.utils.import("resource://firebug/firebug-trace-service.js"); FBTrace = traceConsoleService.getTracer("extensions.firebug"); // ************************************************************************************************ // Compilation Unit /** * Describes a compilation unit in a browser context. A compilation unit * may originate from a JavaScript source file or a script element in HTML. * * @constructor * @param url compilation unit URL - a {@link String} or <code>null</code> if none * @param context the {@link BrowserContext} this compilation unit is contained in * @type CompilationUnit * @return a new CompilationUnit * @version 1.0 */ function CompilationUnit(url, context) { this.url = url; this.context = context; this.breakpoints = []; this.numberOfLines = 0; this.kind = CompilationUnit.SCRIPT_TAG; } /* * Kinds of Compilation Units */ CompilationUnit.SCRIPT_TAG = "script_tag"; CompilationUnit.EVAL = "eval"; CompilationUnit.BROWSER_GENERATED = "event"; // ************************************************************************************************ // API /** * Returns the Kind of Compilation Unit * <p> * This function does not require communication with * the browser. * </p> */ CompilationUnit.prototype.getKind = function getKind() { return this.kind; } CompilationUnit.prototype.isExecutableLine = function isExecutableLine(lineNo) { return this.sourceFile.isExecutableLine(lineNo); } /** * Returns the URL of this compilation unit. * <p> * This function does not require communication with * the browser. * </p> * * @function * @returns compilation unit identifier as a {@link String} */ CompilationUnit.prototype.getURL = function() { return this.url; }; /** * Returns the browser context this compilation unit was compiled in. * <p> * This function does not require communication with * the browser. * </p> * * @function * @returns a {@link BrowserContext} */ CompilationUnit.prototype.getBrowserContext = function() { return this.context; }; /** * Returns the breakpoints that have been created in this compilation unit and * have not been cleared. * <p> * This function does not require communication with * the browser. * </p> * @function * @returns an array of {@link Breakpoint}'s */ CompilationUnit.prototype.getBreakpoints = function() { // return a copy of scripts so the master copy is not corrupted var bps = []; for ( var i = 0; i < this.breakpoints.length; i++) bps.push(this.breakpoints[i]); return bps; }; /** * Requests the source of this compilation unit asynchronously. Source will be * retrieved from the browser and reported back to the listener function when available. * The handler may be called before or after this function returns. * <p> * TODO: what if the compilation unit no longer exists in the browser * </p> * @function * @param firstLineNumber requested line number starting point; < 1 means from lowest line number * @param lastLineNumber request last line number; < 1 means up to maximum line * @param listener a listener (function) that accepts (compilationUnit, firstLineNumber, lastLineNumber, array of source code lines) */ CompilationUnit.prototype.getSourceLines = function(firstLine, lastLine, listener) { this.lines = this.sourceFile.loadScriptLines(this.context); this.numberOfLines = (this.lines ? this.lines.length : 0); listener(this, 1, this.numberOfLines, this.lines); }; /** * Request the current estimated number of source lines in the entire compilationUnit */ CompilationUnit.prototype.getNumberOfLines = function() { return this.numberOfLines; }; /** * Requests to create a breakpoint in this compilation unit asynchronously. A breakpoint * creation request will be sent to the browser and an <code>onToggleBreakpoint</code> * event will be sent by the browser when the breakpoint is installed. * <p> * <ul> * <li>TODO: onToggleBreakpoint event is not spec'd - is this the intended use?</li> * <li>TODO: line number out of range</li> * <li>TODO: compilation unit no longer exists in the browser</li> * <li>TODO: breakpoint already set</li> * <li>TODO: is line number 0 or 1 based</li> * </ul> * </p> * @function * @param lineNumber the source line number in this compilation unit to set the breakpoint on * @return the {@link Breakpoint} that was created */ CompilationUnit.prototype.setBreakpoint = function(lineNumber) { // TODO: }; // ************************************************************************************************ // Private /** * Adds the specified breakpoint to this compilation unit's collection of breakpoints. * Implementation should call this method when a breakpoint is created in a compilation * unit. * * @param breakpoint the breakpoint that was created * @function */ CompilationUnit.prototype._addBreakpoint = function(breakpoint) { this.breakpoints.push(breakpoint); }; /** * Removes the specified breakpoint from this compilation unit's collection of breakpoints. * Implementation should call this method when a breakpoint is cleared from a compilation * unit. * * @param breakpoint the breakpoint that was removed * @function */ CompilationUnit.prototype._removeBreakpoint = function(breakpoint) { for ( var i = 0; i < this.breakpoints.length; i++) { if (this.breakpoints[i] === breakpoint) { this.breakpoints.splice(i, 1); return; } } }; // ************************************************************************************************ // CommonJS exports = CompilationUnit;
/** * Created with IntelliJ IDEA. * User: wstarcev * Date: 25.08.13 * Time: 17:53 * To change this template use File | Settings | File Templates. */
function DoubleWeapon () { var wait = 0 var maxWait = 9 var distance = 0.014 return { shoot: function (bullets, x, y, angle, speedX, speedY, scale) { if (wait) return wait = maxWait var sideAngle = angle + Math.PI / 2, bulletX = x + Math.cos(sideAngle) * distance bulletY = y + Math.sin(sideAngle) * distance bullets.push(Bullet(bulletX, bulletY, angle, speedX, speedY, scale)) var sideAngle = angle - Math.PI / 2, bulletX = x + Math.cos(sideAngle) * distance, bulletY = y + Math.sin(sideAngle) * distance bullets.push(Bullet(bulletX, bulletY, angle, speedX, speedY, scale)) var multiplier = 0.00006 speedX -= Math.cos(angle) * multiplier speedY -= Math.sin(angle) * multiplier }, tick: function () { if (wait) wait-- }, } }
/** * Base class, paging buttons for datasource.Collection * Assign a paging element to a data source by sending "id" or config object of * the source using the dataSource constructor property * @namespace ludo.paging * @class ludo.paging.Button * @augments ludo.form.Button */ ludo.paging.Button = new Class({ Extends: ludo.form.Button, type : 'grid.paging.Next', width:25, buttonCls : '', tpl:undefined, onLoadMessage:undefined, ludoDOM:function(){ this.parent(); this.$b().addClass(this.buttonCls); }, ludoEvents:function(){ this.parent(); this.dataSourceEvents(); }, dataSourceEvents:function(){ var ds = ludo.get(this.dataSource); if(ds){ this.addDataSourceEvents(); }else{ this.dataSourceEvents.delay(100, this); } }, addDataSourceEvents:function(){}, JSON:function(){} });
function downloadFile(user, url, destinationFolder, fileName, finishedCallback) { var fs = require('fs'); var request = require('request'); var progress = require('request-progress'); if (!fs.existsSync(destinationFolder)) { fs.mkdirSync(destinationFolder); } const path = require("path"); let filePath = path.join(destinationFolder, fileName); var options = { host: 'api.github.com', path: '/users/' + user + '/repos', method: 'GET', headers: {'user-agent': 'node.js'} }; progress(request(url, options)) .on('progress', function (state) { // console.log(state); }) .on('error', function (err) { }) .on('end', function () { finishedCallback(filePath, destinationFolder); }) .pipe(fs.createWriteStream(filePath)); } function downloadAndUnzipFile(packageCoordinates, callback) { downloadPackage(packageCoordinates, function(filePath, folderPath) { unzipFile(filePath, folderPath, function() { renameUnzippedDirectory(packageCoordinates.repo, folderPath, function(newPath) { let fs = require('fs'); fs.unlinkSync(filePath); callback(folderPath); }); }); }); } function downloadPackage(packageCoordinates, finishedCallback) { const path = require("path"); let downloadFolderPath = path.join(process.cwd(), "download." + packageCoordinates.repo); let fs = require("fs-extra"); if (fs.existsSync(downloadFolderPath)) { fs.removeSync(downloadFolderPath); } let releaseUrl = ""; if (packageCoordinates.version === "latest") { releaseUrl = "https://api.github.com/repos/" + packageCoordinates.user + "/" + packageCoordinates.repo + "/zipball"; } else { releaseUrl = "https://github.com/" + packageCoordinates.user + "/" + packageCoordinates.repo + "/archive/" + packageCoordinates.version + ".zip"; } // console.log("Release url is : " + releaseUrl); downloadFile(packageCoordinates.user, releaseUrl, downloadFolderPath, packageCoordinates.repo + ".zip", finishedCallback) } function unzipFile(filePath, folderPath, finishedCallback) { let fs = require('fs-extra'); let unzip = require('unzip'); let stream = fs.createReadStream(filePath).pipe(unzip.Extract({ path: folderPath })); stream.on('close', function() { finishedCallback(); }); } function renameUnzippedDirectory(newName, folderPath, doneCallback) { const subdirectories = require('filehound').create().path(folderPath).directory().findSync(); const path = require("path"); let newPath = path.join(folderPath, newName); for (let i = 0; i < subdirectories.length; i++) { if (subdirectories[i].includes(newName) === true) { let mv = require('mv'); mv(subdirectories[i], newPath, function(err) { if (typeof err !== 'undefined') { console.log("errored: " + err); } else { doneCallback(newPath); } }); } } } module.exports.downloadAndUnzipFile = downloadAndUnzipFile;
var qrcodeine = require('bindings')('qrcodeine.node'); // some convenience consts: // consts for EC level qrcodeine.EC_L = 0; qrcodeine.EC_M = 1; qrcodeine.EC_Q = 2; qrcodeine.EC_H = 3; // consts for mode qrcodeine.MODE_NUM = 0; // numeric qrcodeine.MODE_AN = 1; // alphanumeric qrcodeine.MODE_8 = 2; // 8-bit bytes (binary) qrcodeine.MODE_KANJI = 3; // Kanji module.exports = qrcodeine;
var searchData= [ ['sockettype_0',['SocketType',['../namespaceanch_1_1network.html#aa518b6bd398c963767bf1974e5c113be',1,'anch::network']]] ];
var engine = require('engine.io'); var server = engine.listen(8081); var RpcServer=require('../../index.js').server; var wss=new RpcServer(server); console.log('server started ...'); wss.on('connection', function(ws) { ws.on('test-type', function(message) { console.log('received: %s', message); }); ws.send('test-type','something back'); });
function addBox(str) { var box = document.getElementById('vimrome-box'); var input = document.getElementById('vimrome-input'); if (!box) { box = document.createElement("div"); box.id = "vimrome-box"; input = document.createElement("input"); input.id = "vimrome-input"; box.appendChild(input); document.body.appendChild(box); } box.style.display = 'block'; if (str) input.value=str; input.focus() addInsertShortcut("<Enter>","command_exec"); addInsertShortcut("<Esc>", "command_stop"); addInsertShortcut("C-[", "command_stop"); } function removeBox() { var box = document.getElementById('vimrome-box'); if (box) document.body.removeChild(box); deleteInsertShortcut("<Enter>") addInsertShortcut("<Esc>", "go_cancel"); addInsertShortcut("C-[", "go_cancel"); } function boxExecute() { var input = document.getElementById('vimrome-input'); if (input) execCommandStr(input.value); else alert("input not found!"); removeBox(); } addCommand("command_start", "Start command mode", function (arg) {addBox(arg[0]);}); addCommand("command_stop", "Stop command mode", function (arg) {removeBox();}) addCommand("command_exec", "Execute command", function (arg) {boxExecute();})
import {ModelBase} from 'administration/model-management/model/model-base'; import {ModelControlParam} from 'administration/model-management/model/model-control-param'; import {ModelList} from 'administration/model-management/model/model-list'; /** * Represents a model of a control extending the {@link ModelBase} class. * A model controls are bound to {@link ModelField}. * * @author svelikov */ export class ModelControl extends ModelBase { constructor(id) { super(id); this.controlParams = new ModelList(); } getControlParams() { return this.controlParams.getModels(); } getOwnControlParams() { return this.getOwnModels(this.getControlParams()); } getDirtyControlParams() { return ModelBase.getDirtyModels(this.getOwnControlParams()); } getControlParam(id) { return this.controlParams.getModel(id); } addControlParam(controlParam) { if (controlParam instanceof ModelControlParam) { this.controlParams.insert(controlParam); } return this; } removeControlParam(controlParam) { let id = controlParam.getId(); if (this.getControlParam(id)) { this.controlParams.remove(id); } return this; } isValid() { return super.isValid() && ModelBase.areModelsValid(this.getDirtyControlParams()); } isDirty() { return super.isDirty() || ModelBase.areModelsDirty(this.getOwnControlParams()); } copyFrom(src) { super.copyFrom(src); this.controlParams.copyFrom(src.controlParams); return this; } isOwningModels() { return super.isOwningModels() || !!this.getOwnControlParams().length; } }
(function () { 'use strict'; function noEmbedService($resource) { return { embed: function(url) { var resource = $resource('https://noembed.com/embed?url='+url, {}, { get: { method: 'JSONP' } }); return resource.get().$promise; }, providers: function() { var resource = $resource('https://noembed.com/providers', {}, { query: { method: 'JSONP', isArray: true } }); return resource.query().$promise; } }; } angular.module('noEmbed').service('noEmbedService', ['$resource', noEmbedService]); })();
var searchData= [ ['lastevalstruct',['lastEvalStruct',['../structlastEvalStruct.html',1,'']]], ['legacycmaoutput',['LegacyCMAOutput',['../classLegacyCMAOutput.html',1,'']]], ['linscalingstrategy',['linScalingStrategy',['../classlibcmaes_1_1linScalingStrategy.html',1,'libcmaes']]] ];
import {Converter} from 'common/convert/converter'; describe('Converter', function() { it('should throw error if a converter does not provide a convert function', function () { expect(function () { new DummyConverter() }).to.throw(TypeError); }); class DummyConverter extends Converter { } });
/* ***************************************************************************** qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2014 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Richard Sternagel (rsternagel) ***************************************************************************** */ 'use strict'; // native var fs = require('fs'); var os = require('os'); var path = require('path'); // third party var deepmerge = require('deepmerge'); var common = { "ROOT": ".", "QOOXDOO_PATH": "../../..", "QXTHEME": "<%= common.APPLICATION %>.theme.Theme", "QXICONTHEME": ["Tango"], "TMPDIR": os.tmpdir(), "CACHE": "<%= common.TMPDIR %>/qx<%= common.QOOXDOO_VERSION %>/cache", "CACHE_KEY": { "compile": "<%= common.CACHE %>", "downloads": "<%= common.CACHE %>/downloads", }, "APPLICATION_MAIN_CLASS" : "<%= common.APPLICATION %>.Application", "SOURCE_PATH": "<%= common.ROOT %>/source", "BUILD_PATH": "<%= common.ROOT %>/build", "ENVIRONMENT": { "qx.application": "<%= common.APPLICATION %>.Application", "qx.revision":"", "qx.theme": "<%= common.QXTHEME %>", "qx.version":"<%= common.QOOXDOO_VERSION %>" } }; var getQxVersion = function(relQxPath) { var vers = fs.readFileSync(fs.realpathSync(path.join(path.join(__dirname, relQxPath), 'version.txt')), 'utf-8'); return vers.trim(); }; common.QOOXDOO_VERSION = getQxVersion(common.QOOXDOO_PATH); var getConfig = function() { return { generator_config: { let: {} }, common: common }; }; var mergeConfig = function(config) { return deepmerge(getConfig(), config); }; // exports module.exports.getConfig = getConfig; module.exports.mergeConfig = mergeConfig;
/** * Managers for the theming support. * http://manual.qooxdoo.org/${qxversion}/pages/desktop/ui_theming.html */
(function($) { var cultures = $.global.cultures, en = cultures.en, standard = en.calendars.standard, culture = cultures["bs-Cyrl-BA"] = $.extend(true, {}, en, { name: "bs-Cyrl-BA", englishName: "Bosnian (Cyrillic, Bosnia and Herzegovina)", nativeName: "босански (Босна и Херцеговина)", language: "bs-Cyrl", numberFormat: { ',': ".", '.': ",", percent: { ',': ".", '.': "," }, currency: { pattern: ["-n $","n $"], ',': ".", '.': ",", symbol: "КМ" } }, calendars: { standard: $.extend(true, {}, standard, { '/': ".", firstDay: 1, days: { names: ["недјеља","понедјељак","уторак","сриједа","четвртак","петак","субота"], namesAbbr: ["нед","пон","уто","сре","чет","пет","суб"], namesShort: ["н","п","у","с","ч","п","с"] }, months: { names: ["јануар","фебруар","март","април","мај","јун","јул","август","септембар","октобар","новембар","децембар",""], namesAbbr: ["јан","феб","мар","апр","мај","јун","јул","авг","сеп","окт","нов","дец",""] }, AM: null, PM: null, eras: [{"name":"н.е.","start":null,"offset":0}], patterns: { d: "d.M.yyyy", D: "d. MMMM yyyy", t: "H:mm", T: "H:mm:ss", f: "d. MMMM yyyy H:mm", F: "d. MMMM yyyy H:mm:ss", M: "d. MMMM" } }) } }, cultures["bs-Cyrl-BA"]); culture.calendar = culture.calendars.standard; })(jQuery);
/* Copyright (C) 2012-2013 by Clearcode <http://clearcode.cc> and associates (see AUTHORS). This file is part of cc-gauge-directive. cc-gauge-directive is free software: you can redistribute it and/or modify it under the terms of the Lesser GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. cc-gauge-directive is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with cc-gauge-directive. If not, see <http://www.gnu.org/licenses/>. */ (function (angular) { 'use strict'; angular .module('cc.gauge.directive', []) .directive('gauge', [function () { return { templateUrl: 'partials/directive_gauge.html', replace: true, restrict: 'E', scope: { value: '=input', label: '@', options: '=' } }; }]); })(window.angular);
$.extend(window.lang_az, { "Feedback": "Əlaqə üçün bizə kömək edin!", "niceQuestion": "Gözəl sual!", "badGrammar": "Kötü qrammatika", "vulgarWords": "Vulqar sözlər", "thanksFeedback": "Əlaqə üçün təşəkkür edirik!", });
"use strict"; const conversions = require("webidl-conversions"); const utils = require("./utils.js"); const impl = utils.implSymbol; const ctorRegistry = utils.ctorRegistrySymbol; const interfaceName = "AbortController"; /** * When an interface-module that implements this interface as a mixin is loaded, it will append its own `.is()` * method into this array. It allows objects that directly implements *those* interfaces to be recognized as * implementing this mixin interface. */ exports._mixedIntoPredicates = []; exports.is = function is(obj) { if (obj) { if (utils.hasOwn(obj, impl) && obj[impl] instanceof Impl.implementation) { return true; } for (const isMixedInto of exports._mixedIntoPredicates) { if (isMixedInto(obj)) { return true; } } } return false; }; exports.isImpl = function isImpl(obj) { if (obj) { if (obj instanceof Impl.implementation) { return true; } const wrapper = utils.wrapperForImpl(obj); for (const isMixedInto of exports._mixedIntoPredicates) { if (isMixedInto(wrapper)) { return true; } } } return false; }; exports.convert = function convert(obj, { context = "The provided value" } = {}) { if (exports.is(obj)) { return utils.implForWrapper(obj); } throw new TypeError(`${context} is not of type 'AbortController'.`); }; exports.create = function create(globalObject, constructorArgs, privateData) { if (globalObject[ctorRegistry] === undefined) { throw new Error("Internal error: invalid global object"); } const ctor = globalObject[ctorRegistry]["AbortController"]; if (ctor === undefined) { throw new Error("Internal error: constructor AbortController is not installed on the passed global object"); } let obj = Object.create(ctor.prototype); obj = exports.setup(obj, globalObject, constructorArgs, privateData); return obj; }; exports.createImpl = function createImpl(globalObject, constructorArgs, privateData) { const obj = exports.create(globalObject, constructorArgs, privateData); return utils.implForWrapper(obj); }; exports._internalSetup = function _internalSetup(obj) {}; exports.setup = function setup(obj, globalObject, constructorArgs = [], privateData = {}) { privateData.wrapper = obj; exports._internalSetup(obj); Object.defineProperty(obj, impl, { value: new Impl.implementation(globalObject, constructorArgs, privateData), configurable: true }); obj[impl][utils.wrapperSymbol] = obj; if (Impl.init) { Impl.init(obj[impl], privateData); } return obj; }; exports.install = function install(globalObject) { class AbortController { constructor() { return exports.setup(Object.create(new.target.prototype), globalObject, undefined); } abort() { if (!this || !exports.is(this)) { throw new TypeError("Illegal invocation"); } return this[impl].abort(); } get signal() { if (!this || !exports.is(this)) { throw new TypeError("Illegal invocation"); } return utils.getSameObject(this, "signal", () => { return utils.tryWrapperForImpl(this[impl]["signal"]); }); } } Object.defineProperties(AbortController.prototype, { abort: { enumerable: true }, signal: { enumerable: true }, [Symbol.toStringTag]: { value: "AbortController", configurable: true } }); if (globalObject[ctorRegistry] === undefined) { globalObject[ctorRegistry] = Object.create(null); } globalObject[ctorRegistry][interfaceName] = AbortController; Object.defineProperty(globalObject, interfaceName, { configurable: true, writable: true, value: AbortController }); }; const Impl = require("../aborting/AbortController-impl.js");
console.log((true + false) > 2 + true);
function getCookie(name) { var prefix = name + "="; var cookieStartIndex = document.cookie.indexOf(prefix); if (cookieStartIndex == -1) return null; var cookieEndIndex = document.cookie.indexOf(";", cookieStartIndex + prefix.length); if (cookieEndIndex == -1) cookieEndIndex = document.cookie.length; return unescape(document.cookie.substring(cookieStartIndex + prefix.length, cookieEndIndex)); } function setCookie(name, value) { document.cookie = name + "=" + escape(value) + "; path=/"; } function setCookieElem(name, defv) { var val = getCookie(name); if (val == null) { val = defv; setCookie(name, val); } var f = document.getElementById(name); if(f.type === "checkbox") { f.checked = val == 1 ? true : false; } else if(f.type === "radio") { var f = document.getElementsByName(name); for(var i=0; i<f.length; i++) f[i].checked = f[i].value == val; } else { f.value = val; } } function updCookie(name) { var val; var f = document.getElementById(name); if(f.type === "checkbox") { val = f.checked ? 1 : 0; } else if(f.type === "radio") { var f = document.getElementsByName(name); for(var i=0; i<f.length; i++) if(f[i].checked) { val = f[i].value; break; } } else { val = f.value; } setCookie(name, val); }
module.exports = function (grunt) { 'use strict'; var resolve = require('path').resolve; require('load-grunt-tasks')(grunt); grunt.initConfig({ hapi: { server: { options: { server: resolve('./server/index'), noasync: true } }, async: { options: { server: resolve('./server/index') } } }, watch: { hapi: { files: ['./server/*.js', './Gruntfile.js'], tasks: ['hapi:async'], options: { spawn: true } } } }); grunt.registerTask('default', ['hapi:server']); grunt.registerTask('server', ['hapi:async', 'watch']); };
var searchData= [ ['tasks',['tasks',['../namespaceoption.html#a718f9dc10f6aa27fb9624738cd514c04a771cc52d72ba4da8abf1476926cc1d4b',1,'option']]], ['taus2',['taus2',['../namespaceoption.html#a718f9dc10f6aa27fb9624738cd514c04ac4e22659c5efe7c4b338d59de3eb6d00',1,'option']]], ['temp_5ffiles_5fusage',['temp_files_usage',['../namespaceoption.html#a718f9dc10f6aa27fb9624738cd514c04a901440c3892e5a5a9afbceb4794df19e',1,'option']]], ['timer_5fname',['timer_name',['../namespaceoption.html#a718f9dc10f6aa27fb9624738cd514c04ab07f520c58dab11c2d218efb5409d61e',1,'option']]], ['total',['total',['../namespaceoption.html#a718f9dc10f6aa27fb9624738cd514c04acdbc2814e33f9a73e459cbe264d95b80',1,'option']]], ['translation_5fmode',['translation_mode',['../namespaceoption.html#a718f9dc10f6aa27fb9624738cd514c04af56ab156023330869059340f9436fb4a',1,'option']]] ];
//angular module providing data to calls within HTML body below. app.controller('MainController', ['$scope', function($scope) { $scope.title = 'Best Books of 2017'; $scope.promo = '20% Off Today Only!'; $scope.product = { name: 'The Book of Trees', price: 19, pubdate: new Date('2014', '03', '08') }; }]); <!doctype html> <html> <head> <link href="https://s3.amazonaws.com/codecademy-content/projects/bootstrap.min.css" rel="stylesheet" /> <link href='https://fonts.googleapis.com/css?family=Roboto:500,300,700,400' rel='stylesheet' type='text/css'> <link href="css/main.css" rel="stylesheet" /> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.5/angular.min.js"></script> </head> <body ng-app="myApp"> <div class="header"> <div class="container"> <h1>Book End</h1> </div> </div> <div class="main" ng-controller="MainController"> <div class="container"> <h1>{{ title }}</h1> <h2>{{ promo }}</h2> <div class="col-md-6"> <div class="thumbnail"> <img src="img/the-book-of-trees.jpg"> <p class="title">{{ product.name }}</p> <p class="price">{{ product.price | currency }}</p> <p class="date"> {{ product.pubdate | date }}</p> </div> </div> </div> </div> <div class="footer"> <div class="container"> <h2>Available for iPhone and Android.</h2> <img src="https://s3.amazonaws.com/codecademy-content/projects/shutterbugg/app-store.png" width="120px" /> <img src="https://s3.amazonaws.com/codecademy-content/projects/shutterbugg/google-play.png" width="110px" /> </div> </div> <!-- Modules --> <script src="js/app.js"></script> <!-- Controllers --> <script src="js/controllers/MainController.js"></script> </body> </html>
/** * Copyright © 2013-2017 Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ /*browser:true*/ /*global define*/ define([ 'jquery', 'underscore', 'Magento_Vault/js/view/payment/method-renderer/vault', 'Magento_Ui/js/model/messageList', 'Magento_Checkout/js/model/full-screen-loader' ], function ($, _, VaultComponent, globalMessageList, fullScreenLoader) { 'use strict'; return VaultComponent.extend({ defaults: { template: 'Magento_Braintree/payment/paypal/vault', additionalData: {} }, /** * Get PayPal payer email * @returns {String} */ getPayerEmail: function () { return this.details.payerEmail; }, /** * Get type of payment * @returns {String} */ getPaymentIcon: function () { return window.checkoutConfig.payment['braintree_paypal'].paymentIcon; }, /** * Place order */ beforePlaceOrder: function () { this.getPaymentMethodNonce(); }, /** * Send request to get payment method nonce */ getPaymentMethodNonce: function () { var self = this; fullScreenLoader.startLoader(); $.get(self.nonceUrl, { 'public_hash': self.publicHash }) .done(function (response) { fullScreenLoader.stopLoader(); self.additionalData['payment_method_nonce'] = response.paymentMethodNonce; self.placeOrder(); }) .fail(function (response) { var error = JSON.parse(response.responseText); fullScreenLoader.stopLoader(); globalMessageList.addErrorMessage({ message: error.message }); }); }, /** * Get payment method data * @returns {Object} */ getData: function () { var data = { 'method': this.code, 'additional_data': { 'public_hash': this.publicHash } }; data['additional_data'] = _.extend(data['additional_data'], this.additionalData); return data; } }); });
#!/usr/bin/env node /* jshint node: true */ /* * 46elks samples: Replying to text messages * === * * This example introduces you with how to reply to a received text message. The scenario is * that all people who message this allocated number are interested in what the open hours * are for the day. While that may sound restrictive, the basic idea can be easily expanded * upon later to provide support for various special commands and inquiries. * * Setup * --- * * Allocate phone numbers either via the web dashboard or by using the /Numbers API endpoint. * For the allocated numbers you are going to use, set the `sms_url` value as the endpoint * provided by this example (http://example.com/callback/newsms). */ var core = require(__dirname + '/_core.js'); // JavaScript uses a numeric system that is 0-index and has Sunday as the first element. // We will use this array to transition that over to a string representation. var dayLookup = [ 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat' ]; // This is the object from which we will pick the open hours. var hours = { 'Mon': '08:00 - 17:00', 'Tue': '08:00 - 17:00', 'Wed': '08:00 - 19:00', 'Thu': '08:00 - 17:00', 'Fri': '08:00 - 17:00', 'Sat': '10:00 - 16:00' }; core.listen('/callback/newsms', function listener(page) { /* * This will be executed when a request to /callback/newsms is received. * It will be an automatic POST request as described in the specification. * * To reply to the number that sent the original message, just output content on this page. * The 46elks servers will grab that response and send off a text message automatically. * * Hint: To build commands, check out the value for the "message" key in the POST data! */ var day = dayLookup[new Date().getDay()]; if (typeof hours[day] === 'undefined') { // The open hours for the day are not defined. That means we are closed. page.write('Sorry, but we are closed today.'); } else { // The open hours for the day are defined. That means we are open at some point. page.write('We are open today between ' + hours[day] + '.'); } });
/** * webpack-uni-pages-loader 待重构,需要将平台特有逻辑,收敛到各自包内 * @param {Object} pagesJson * @param {Object} manifestJson */ module.exports = function (pagesJson, manifestJson) { const { app, project } = require('../mp')(pagesJson, manifestJson, require('./project.config.json')) const baseJson = { appType: 'webapp', // 华为IDE V3.0.2+ 需要此属性,否则无法导入 minPlatformVersion: 1070 } manifestJson.name && (baseJson.name = manifestJson.name) manifestJson.versionName && (baseJson.versionName = manifestJson.versionName) manifestJson.versionCode && (baseJson.versionCode = manifestJson.versionCode) const options = Object.assign({}, manifestJson['quickapp-webview'] || {}) if (process.env.UNI_SUB_PLATFORM) { Object.assign(options, manifestJson[process.env.UNI_SUB_PLATFORM] || {}) } Object.assign(app.content, baseJson, options) if (!app.content.package) { app.content.package = manifestJson.name } project.name = 'quickapp.config' return [ app, project ] }
/* * arcus-hubble - A dashboard service to monitor Arcus clusters * Copyright 2012-2014 NAVER Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var winston = require('winston') , conf = require('../../conf/conf-orbiter.json'); var LOG = new winston.Logger({ transports: [ new winston.transports.Console({ level: conf.log.level, timestamp: true }) , new winston.transports.File({ level: conf.log.level, timestamp: true, filename: conf.log.file }) ] }); exports.LOG = LOG;
/* * Copyright 2019 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ const m = require('mithril'); const _ = require('lodash'); const Stream = require('mithril/stream'); function FilterMixin() { const self = this; const internalSearchText = Stream(""); const performSearch = _.debounce(() => { m.route.set(`/${internalSearchText()}`); m.redraw(); }, 200); this._performRouting = performSearch; this.filteredGroups = (filter) => { return this.selectedGroups().select((pipelineName) => { return _.includes(pipelineName.toLowerCase(), internalSearchText()) && filter.acceptsStatusOf(self.dashboard.findPipeline(pipelineName)); }).groups; }; this.searchText = function searchText(searchedBy) { if (arguments.length) { internalSearchText(searchedBy.toLowerCase()); self._performRouting(); } else { return internalSearchText(); } }; } function OperationMessagingMixin() { const MESSAGE_CLEAR_TIMEOUT_IN_MILLISECONDS = 5000; const pipelineFlashMessages = {}; function clearAfterTimeout(name) { setTimeout(() => { delete pipelineFlashMessages[name]; m.redraw(); }, MESSAGE_CLEAR_TIMEOUT_IN_MILLISECONDS); } this.operationMessages = { get: (name) => pipelineFlashMessages[name], success: (name, message) => { pipelineFlashMessages[name] = { message, type: "success" }; clearAfterTimeout(name); }, failure: (name, message) => { pipelineFlashMessages[name] = { message, type: "error" }; clearAfterTimeout(name); } }; } function GroupingMixin() { const scheme = Stream("pipeline_groups"); _.assign(this, { scheme, groupByItems: [ { id: "pipeline_groups", text: "Pipeline Groups" }, { id: "environments", text: "Environments" } ], selectedGroups: () => this.groupByPipelineGroup() ? this.dashboard.getPipelineGroups() : this.dashboard.getEnvironments(), groupByPipelineGroup: function groupByPipelineGroup(bool) { if (!arguments.length) { return "pipeline_groups" === scheme(); } if (bool) { scheme("pipeline_groups"); } }, groupByEnvironment: function groupByEnvironment(bool) { if (!arguments.length) { return "environments" === scheme(); } if (bool) { scheme("environments"); } } }); } function DashboardViewModel(dashboard) { OperationMessagingMixin.call(this); GroupingMixin.call(this); FilterMixin.call(this); let dropdownPipelineName, dropdownPipelineCounter; const self = this; _.assign(this, { dashboard, etag: Stream(null), invalidateEtag: () => self.etag(null), dropdown: { isOpen: (name, instanceCounter) => ((name === dropdownPipelineName) && (instanceCounter === dropdownPipelineCounter)), show: (name, instanceCounter) => { dropdownPipelineName = name; dropdownPipelineCounter = instanceCounter; }, hide: () => { dropdownPipelineName = undefined; dropdownPipelineCounter = undefined; } }, buildCause: Stream() }); } module.exports = DashboardViewModel;
'use strict'; var slayer = require('../index.js'); var path = require('path'); var expect = require("chai").expect; var sinon = require('sinon'); describe('Slayer', function(){ var fixtures = require(path.join(__dirname, 'fixtures', 'default.json')); it('should throw if minPeakHeight is not a number', function(){ expect(function(){ slayer({ minPeakHeight: '25' }) }).to.throw(TypeError); }); describe('.x()', function(){ it('should update the X value accessor', function(){ }); it('should throw if the mapper is not a function', function(){ expect(function(){ slayer().x(''); }).to.throw(TypeError); }); }); describe('.y()', function(){ it('should update the Y value accessor', function(){ }); it('should throw if the mapper is not a function', function(){ expect(function(){ slayer().y(''); }).to.throw(TypeError); }); }); describe('.transform()', function(){ it('should update the item mapper with the provided function', function(){ var spy = sinon.spy(); var s = slayer().transform(spy); expect(s.getItem).to.equal(spy); }); it('should throw if the mapper is not a function', function(){ expect(function(){ slayer().transform(''); }).to.throw(TypeError); }); }); describe('.use()', function(){ it('should load a Node module as an algorithm if the provided argument is a string', function(){ var s = slayer().use('entropy'); expect(s.algorithm.name).to.equal('entropy'); }); it('should use a JavaScript function as an algorithm if the provided argument is a function', function(){ var spy = sinon.spy(); var s = slayer().use(spy); expect(s.algorithm).to.equal(spy); }); it('should throw if the node module cannot be found', function(){ expect(function(){ slayer({ algorithm: 'dummy-module' }); }).to.throw(Error); }); it('should throw if the provided argument is not a function', function(){ expect(function(){ slayer({ algorithm: {} }); }).to.throw(TypeError); }); }); });
/* eslint-env node */ var webpackConfig = require('./webpack.config'); module.exports = function(config) { config.set({ basePath: '../', frameworks: [ 'jasmine' ], files: [ 'test/fixtures/css/disable_animations.css', require.resolve('es6-shim'), 'node_modules/jquery/dist/jquery.js', 'node_modules/@claviska/jquery-offscreen/jquery.offscreen.js', 'node_modules/jasmine-jquery/lib/jasmine-jquery.js', 'node_modules/jasmine-fixture/dist/jasmine-fixture.js', { pattern: 'test/fixtures/images/*.png', watched: false, included: false, served: true, nocache: false }, { pattern: 'icons/*', watched: false, included: false, served: true, nocache: false }, 'test/specs/**/*.js' ], preprocessors: { 'test/specs/**/*.js': ['webpack', 'sourcemap'] }, webpack: webpackConfig, reporters: ['progress', 'coverage'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['PhantomJS'], singleRun: false, concurrency: Infinity, coverageReporter: { reporters: [{ type: 'text-summary' }, { type: 'html', dir: 'coverage/' }] } }); };
goog.module('grrUi.stats.reportListingDirective'); goog.module.declareLegacyNamespace(); const reportDescsService = goog.requireType('grrUi.stats.reportDescsService'); const {upperCaseToTitleCase} = goog.require('grrUi.core.utils'); /** * Parses the stats/reports API call response and converts it to a * jsTree-compatible format. * * @param {Object} reports The server response field response.data.reports, * type-stripped. * @return {!Array} The report listing in a jsTree-compatible structure. */ exports.parseStatsReportsApiResponse = function(reports) { var ret = []; var reportsByType = {}; angular.forEach(reports, function(report) { var desc = report['desc']; var reportType = desc['type']; var typeReportListing; if (angular.isUndefined(reportsByType[reportType])) { typeReportListing = []; reportsByType[reportType] = typeReportListing; ret.push({ text: upperCaseToTitleCase(reportType), children: typeReportListing, state: {opened: true, disabled: true} }); } else { typeReportListing = reportsByType[reportType]; } var leaf = {id: desc['name'], text: desc['title'], desc: desc}; typeReportListing.push(leaf); }); return ret; }; var parseStatsReportsApiResponse = exports.parseStatsReportsApiResponse; /** * Controller for ReportListingDirective. * @unrestricted */ const ReportListingController = class { /** * @param {!angular.Scope} $scope * @param {!angular.jQuery} $element * @param {!reportDescsService.ReportDescsService} * grrReportDescsService * @ngInject */ constructor($scope, $element, grrReportDescsService) { /** @private {!angular.Scope} */ this.scope_ = $scope; /** @private {!angular.jQuery} */ this.element_ = $element; /** @private {!reportDescsService.ReportDescsService} */ this.grrReportDescsService_ = grrReportDescsService; /** @private {!Object} */ this.treeElement_ = this.element_.find('.report-listing-tree'); /** @private {!Object} */ this.tree_; /** @private {string} */ this.selectionName_; /** @private {Object} */ this.reportListing_; this.grrReportDescsService_.getDescs().then(function(reports) { this.reportListing_ = parseStatsReportsApiResponse(reports); this.initTree_(); }.bind(this)); this.scope_.$watch('selectionName', function(selectionName) { if (angular.isUndefined(selectionName)) { return; } this.selectionName_ = selectionName; }.bind(this)); this.scope_.$watch('controller.selectionName_', function() { if (angular.isUndefined(this.selectionName_)) { return; } this.scope_['selectionName'] = this.selectionName_; this.updateTreeSelection_(); }.bind(this)); } /** * Initializes the jsTree instance. * * @private */ initTree_() { this.treeElement_.jstree({'core': {'data': this.reportListing_}}); this.tree_ = this.treeElement_.jstree(true); this.treeElement_.on('loaded.jstree', function(event, data) { this.updateTreeSelection_(); }.bind(this)); this.treeElement_.on('select_node.jstree', function(event, data) { var desc = data['node']['original']['desc']; this.selectionName_ = desc['name']; }.bind(this)); } /** * Selects the jsTree element corresponding to this.selectionName_. If the * tree is not fully loaded this will do nothing and return silently. Note * that this is also what calls to jsTree's methods do. * * @private */ updateTreeSelection_() { if (angular.isUndefined(this.tree_)) { return; } this.tree_['deselect_all'](); this.tree_['select_node'](this.selectionName_); } }; /** * ReportListingDirective definition. * @return {angular.Directive} Directive definition object. */ exports.ReportListingDirective = function() { return { restrict: 'E', scope: {selectionName: '=?'}, templateUrl: '/static/angular-components/stats/report-listing.html', controller: ReportListingController, controllerAs: 'controller', }; }; /** * Name of the directive in Angular. * * @const * @export */ exports.ReportListingDirective.directive_name = 'grrReportListing';
import React from 'react'; import { compose } from 'ramda'; import { withRouter } from 'react-router'; import PropTypes from 'prop-types'; import { withStyles } from 'material-ui/styles'; import Create from 'material-ui-icons/Create'; import IconWithTextButton from '../../../../../components/common/iconWithTextButton'; import withMultipleDialogHandling from '../../../../../components/common/hoc/withMultipleDialogHandling'; import UpdateObservationModal from './updateObservationModal'; const styleSheet = theme => ({ grey: { color: theme.palette.primary[700], '&:hover': { color: theme.palette.primary[900], }, }, }); const update = 'update'; const UpdateObservationButton = (props) => { const { id, classes, dialogOpen, handleDialogClose, handleDialogOpen } = props; return ( <div> <IconWithTextButton id={id} icon={<Create className={classes.grey} />} name="edit" onClick={(e) => { e.stopPropagation(); handleDialogOpen(update); }} /> {dialogOpen[update] && <UpdateObservationModal id={id} dialogOpen={dialogOpen[update]} handleDialogClose={handleDialogClose} />} </div> ); }; UpdateObservationButton.propTypes = { id: PropTypes.number, classes: PropTypes.object.isRequired, dialogOpen: PropTypes.object, handleDialogClose: PropTypes.func, handleDialogOpen: PropTypes.func, }; export default compose( withMultipleDialogHandling, withRouter, withStyles(styleSheet, { name: 'updateObservationButton' }), )(UpdateObservationButton);
sMap.Lang.lang.Popup = { "sv-SE" : { labelText : "Tryck här", minimizeBtn : "Göm popup", rmBtnTxt : "Ta bort" }, en : { labelText : "Press here", minimizeBtn : "Hide popup", rmBtnTxt : "Remove" } };
function sum_rows(col, from, to) { var total = 0; for (var i = from; i < to; i++) { total += get_num(i, col); } return total; } function old_and_new(row, idx) { return { women : [get_num(row, idx + cf_2015), get_num(row, idx + cf_2014)], men : [get_num(row, idx + cm_2015), get_num(row, idx + cm_2014)], } } function getQueryVariable(variable) { var query = window.location.search.substring(1); var vars = query.split('&'); for (var i=0;i<vars.length;i++) { var pair = vars[i].split('='); if(pair[0] == variable){return pair[1];} } return(false); } var row2_template = function(start_row, index_offset) { return [ get_num(start_row, idx + index_offset), 0, get_num(start_row + 1, idx + index_offset) ].reverse() } var row3_template = function(start_row, index_offset) { return [ get_num(start_row, idx + index_offset), get_num(start_row + 1, idx + index_offset), get_num(start_row + 2, idx + index_offset)] } var parse2_template = function(start_row) { var json = { men : { 2014 : row2_template(start_row, cm_2014), 2015 : row2_template(start_row, cm_2015), }, women : { 2014 : row2_template(start_row, cf_2014), 2015 : row2_template(start_row, cf_2015), }, } return json } var parse3_template = function(start_row) { return { men : { 2014 : row3_template(start_row, cm_2014), 2015 : row3_template(start_row, cm_2015), }, women : { 2014 : row3_template(start_row, cf_2014), 2015 : row3_template(start_row, cf_2015), }, } } var place_type1_bar = function(node, data, width_scale, ctx) { var total = d3.sum(data); ctx.width = width_scale(total); ctx.height = 100; ctx.bar_height = big_bar_height; new HorizontalStackedBars(node, data, ctx) node.select('.year').attr('transform', ' translate(' + width_scale(total) + ', 0)'); } var place_type1_bar_small = function(node, data, width_scale, ctx) { var total = d3.sum(data); ctx.width = width_scale(total); ctx.height = small_bar_height; ctx.bar_height = small_bar_height; new HorizontalStackedBars(node, data, ctx) node.selectAll('.barseg text').remove(); node.select('.year').attr('transform', ' translate(' + width_scale(total) + ', 0)'); } var place_type1_question = function(node, data, ctx) { if (ctx == undefined) ctx = {} var wtotal_2015 = d3.sum(data.women['2015']) var wtotal_2014 = d3.sum(data.women['2014']) var mtotal_2015 = d3.sum(data.men['2015']) var mtotal_2014 = d3.sum(data.men['2014']) var width_scale = d3.scale.linear() .domain([0, d3.max([wtotal_2014, wtotal_2015, mtotal_2014, mtotal_2015])]) .range([0, bar_width]) node.selectAll('.demo-contents').remove(); ctx['text'] = '2015' place_type1_bar(node.select('.women-2015'), data.women['2015'], width_scale, ctx); place_type1_bar(node.select('.men-2015'), data.men['2015'], width_scale, ctx); ctx['text'] = '2014' place_type1_bar_small(node.select('.women-2014'), data.women['2014'], width_scale, ctx); place_type1_bar_small(node.select('.men-2014'), data.men['2014'], width_scale, ctx); } var place_type2_bar = function(node, data, height_scale) { var total = d3.sum(data); new VerticalStackedBars(node, data, { height: height_scale(total), width: 100, bar_width: big_bar_width }) } var place_type2_bar_small = function(node, data, height_scale) { var total = d3.sum(data); new VerticalStackedBars(node, data, { height: height_scale(total), width: 100, bar_width: small_bar_width }) node.selectAll('.barseg text').remove(); } var place_type2_question = function(node, data) { var wtotal_2015 = d3.sum(data.women['2015']) var wtotal_2014 = d3.sum(data.women['2014']) var mtotal_2015 = d3.sum(data.men['2015']) var mtotal_2014 = d3.sum(data.men['2014']) var height_scale = d3.scale.linear() .domain([0, d3.max([wtotal_2014, wtotal_2015, mtotal_2014, mtotal_2015])]) .range([0, bar_height]) node.selectAll('.demo-contents').remove(); place_type2_bar(node.select('.women-2015'), data.women['2015'], height_scale); place_type2_bar(node.select('.men-2015'), data.men['2015'], height_scale); place_type2_bar_small(node.select('.women-2014'), data.women['2014'], height_scale); place_type2_bar_small(node.select('.men-2014'), data.men['2014'], height_scale); } var place_type3_question = function(node, data, ctx) { if (!ctx) ctx = {}; height = ctx.height || 32; height1 = ctx.height1 || 22; width = ctx.width || 320; var max_val = d3.max(data, function(d) { return d3.max([ d3.max(d.women), d3.max(d.men) ]) }); node.selectAll('.demo-contents').remove(); x = d3.scale.linear().domain([0, max_val]).range([0, width]); var women_nodes = node.selectAll('g.women') .data(data) var men_nodes = node.selectAll('g.men') .data(data) women_nodes.each(function(d, i) { hb = new HorizontalBars(d3.select(this), d.women, { width: x(d3.max(d.women)), height: height, height1: height1, label_space: 6, flip: false }) }) men_nodes.each(function(d, i) { hb = new HorizontalBars(d3.select(this), d.men, { width: x(d3.max(d.men)), height: height, height1: height1, label_space: 6, flip: true }) }) }
var THREE = require('three'); var ScapeStuff = require('../../stuff'); var M4 = THREE.Matrix4; var ScapeClickable = require('./clickable'); // ------------------------------------------------------------------ /** TODO: work out how to doc these addons * @param {object} treeParts the mesh and clickPoint collection that is a tree * @param {object} options the tree options * @param {object} internals internal calculations make by the tree-maker */ function ScapeDendrometerAddon(treeParts, options, internals) { // start with standard tree meshes var i = internals || { meshNames: [] }; i.diam = i.diam || 1; // transforms we might need: // rotate so it's height is along the Z axis (CylinderGeometry starts lying along the Y axis) var rotate = new THREE.Matrix4().makeRotationX(Math.PI/2); // special convenience: if options.dendrometer is a string, // use that string as the clickData and use defaults for // everything else. if (typeof options.dendrometer === 'string') { options.dendrometer = { clickData: options.dendrometer }; } var d = {}; d.name = options.dendrometer.name || 'dendrometer'; d.bandWidth = options.dendrometer.width || 0.5; d.bandRadius = i.trunkRadius + 0.2 * d.bandWidth; d.bandHeight = Math.min(options.dendrometer.height || 1.5, i.trunkHeight - d.bandWidth/2); d.meterRadius = d.bandWidth; d.meterHeight = d.bandWidth * 3; d.mountRadius = d.meterRadius * 1.1; d.mountWidth = d.meterHeight / 4; d.bandStuff = options.dendrometer.band || ScapeStuff.metal; d.mountStuff = options.dendrometer.mount || ScapeStuff.black; d.meterStuff = options.dendrometer.meter || ScapeStuff.metal; d.clickData = options.dendrometer.clickData || null; // the steel band var bandGeom = new THREE.CylinderGeometry(d.bandRadius, d.bandRadius, d.bandWidth, 12, 1); bandGeom.applyMatrix(new M4().makeTranslation(0, 0, d.bandHeight).multiply(rotate)); var band = new THREE.Mesh(bandGeom, d.bandStuff); i.meshNames.push('dendrometerBand'); treeParts.meshes.push(band); // the meter itself var meterBottomGeom = new THREE.CylinderGeometry(d.meterRadius, d.meterRadius, 0.67 * d.meterHeight, 7, 1); meterBottomGeom.applyMatrix(new M4().makeTranslation(d.bandRadius + d.meterRadius, 0, d.bandHeight + d.meterHeight/6).multiply(rotate)); var meterBottom = new THREE.Mesh(meterBottomGeom, d.meterStuff); i.meshNames.push('dendrometerBottom'); treeParts.meshes.push(meterBottom); var meterTopGeom = new THREE.CylinderGeometry(d.meterRadius/5, d.meterRadius, 0.33 * d.meterHeight, 7, 1); meterTopGeom.applyMatrix(new M4().makeTranslation(d.bandRadius + d.meterRadius, 0, d.bandHeight + d.meterHeight/2 + d.meterHeight/6).multiply(rotate)); var meterTop = new THREE.Mesh(meterTopGeom, d.meterStuff); i.meshNames.push('dendrometerTop'); treeParts.meshes.push(meterTop); // the mount var mountBandGeom = new THREE.CylinderGeometry(d.mountRadius, d.mountRadius, d.mountWidth, 7, 1); mountBandGeom.applyMatrix(new M4().makeTranslation(d.bandRadius + d.meterRadius, 0, d.bandHeight + d.bandWidth/2 + d.mountWidth/2).multiply(rotate)); var mountBand = new THREE.Mesh(mountBandGeom, d.mountStuff); i.meshNames.push('dendrometerMountBand'); treeParts.meshes.push(mountBand); var mountGeom = new THREE.BoxGeometry(d.mountRadius, d.mountRadius/2, d.mountWidth); mountGeom.applyMatrix(new M4().makeTranslation(d.bandRadius, 0, d.bandHeight + d.bandWidth/2 + d.mountWidth/2)); var mount = new THREE.Mesh(mountGeom, d.mountStuff); i.meshNames.push('dendrometerMount'); treeParts.meshes.push(mount); // the dendro should be clickable if (d.clickData) { var dendroClick = ScapeClickable(d.name, d.clickData, d.bandRadius + d.meterRadius, 0, d.bandHeight + d.meterHeight/6); treeParts.clickPoints.push(dendroClick); } i.dendrometer = d; return treeParts; }; // ------------------------------------------------------------------ module.exports = ScapeDendrometerAddon;