text
stringlengths
2
6.14k
const _ = require('lodash'); const utils = require('./utils'); /* * Default key object settings for lando.keys cache */ const keyDefaults = { host: 'lagoon.amazeeio.cloud', port: '32222', user: 'lagoon-pending', date: _.toInteger(_.now() / 1000), }; /* * Generates a new lagoon-pending key. */ exports.generateKey = (lando, method = 'new') => { const cmd = '/helpers/lagoon-generate-key.sh lagoon-pending lando'; return utils.run(lando, cmd, null, false); }; /* * Put keys into inquierer format */ exports.getKeys = (keys = []) => _(keys) .map(key => ({name: key.email, value: key.key})) .thru(keys => keys.concat([{name: 'add a new key', value: 'more'}])) .compact() .value(); // Helper to get preferred key exports.getPreferredKey = answers => { return answers['lagoon-auth-generate'] || answers['auth-generate'] || answers['lagoon-auth'] || answers['auth']; }; /* * Parses a key over defaults to extact key/host/port info */ exports.parseKey = (key = {}) => { // Split the "key" and get it const splitter = key.split('@'); const keyPath = _.first(splitter); // Now handle the host part const lagoon = keyDefaults; // If host part of splitter exists lets update things if (splitter[1]) { const parts = splitter[1].split(':'); if (parts[0]) lagoon.host = parts[0]; if (parts[1]) lagoon.port = parts[1]; } return {keyPath, host: lagoon.host, port: lagoon.port}; }; /* * Sort keys by most recent */ exports.sortKeys = (...sources) => _(_.flatten([...sources])) .filter(key => key !== null) .sortBy('date') .groupBy('key') .map(keys => _.last(keys)) .value();
/* * Languages for annotation Javascript */ /* * Fetch a localized string * This is a function so that it can be replaced with another source of strings if desired * (e.g. in a database). The application uses short English-language strings as keys, so * that if the language source is lacking the key can be returned instead. */ function getLocalized( s ) { return LocalizedAnnotationStrings[ s ]; } LocalizedAnnotationStrings = { 'public annotation' : 'This annotation is public.', 'private annotation' : 'This annotation is private.', 'delete annotation button' : 'Delete this annotation.', 'annotation link button' : 'Link to another document.', 'annotation link label' : 'Select a document to link to.', 'delete annotation link button' : 'Remove this link.', 'annotation expand edit button' : 'Click to display margin note editor', 'annotation collapse edit button' : 'Click to display margin note drop-down list', 'annotation quote button' : 'Quote this annotation in a discussion post.', 'browser support of W3C range required for annotation creation' : 'Your browser does not support the W3C range standard, so you cannot create annotations.', 'select text to annotate' : 'You must select some text to annotate.', 'invalid selection' : 'Selection range is not valid.', 'corrupt XML from service' : 'An attempt to retrieve annotations from the server returned corrupt XML data.', 'note too long' : 'Please limit your margin note to 250 characters.', 'quote too long' : 'The passage you have attempted to highlight is too long. It may not exceed 1000 characters.', 'zero length quote' : 'You must select some text to annotate.', 'quote not found' : 'The highlighted passage could not be found', 'create overlapping edits' : 'You may not create overlapping edits', 'lang' : 'en' };
module.exports = function (app) { // catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); // development error handler // will print stacktrace app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('errors/generic', { message: err.message, error: err }); }); // production error handler // no stacktraces leaked to user // app.use(function(err, req, res, next) { // res.status(err.status || 500); // res.render('partials/error', { // message: err.message, // error: {} // }); // }); }
/* * VITacademics * Copyright (C) 2014-2016 Aneesh Neelam <neelam.aneesh@gmail.com> * Copyright (C) 2014-2016 Ayush Agarwal <agarwalayush161@gmail.com> * * This file is part of VITacademics. * * VITacademics 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. * * VITacademics 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 VITacademics. If not, see <http://www.gnu.org/licenses/>. */ 'use strict'; const path = require('path'); const status = require(path.join(__dirname, '..', 'status')); const handler = function (app) { const onJob = function (job, ack) { job.status = status.toDo; console.log(JSON.stringify(job)); ack(); }; pp.rabbit.queue(app.rabbit.queues.mobile) .consume(onJob, noAck : false ) ; }; module.exports = handler;
/*global require */ 'use strict'; var _ = require('lodash'), utils = require('./../build-utils'), StatementInputBloq = require('./../statementInputBloq'); /** * Bloq name: mbot-ifthereisalotoflight * * Bloq type: Statement-Input * * Description: * * Return type: none */ var bloqMBotIfThereIsALotOfLight = _.merge(_.clone(StatementInputBloq, true), { name: 'mBotIfThereIsALotOfLight', bloqClass: 'bloq-mbot-ifthereisalotoflight', content: [ [{ alias: 'text', value: 'if' }, { id: 'OPERATION', alias: 'staticDropdown', options: [{ label: 'bloq-mbot-ifthereisalotoflight-alot', value: '+' }, { label: 'bloq-mbot-ifthereisalotoflight-low', value: '-' }, { label: 'bloq-mbot-ifthereisalotoflight-operation-nodetect', value: '*' }] }, { alias: 'text', value: 'with-the' }, { id: 'LIGHTSENSOR', alias: 'dynamicDropdown', options: 'mkb_lightsensor' }] ], code: '', arduino: { conditional: { aliasId: 'OPERATION', code: { '+': 'if(¬{LIGHTSENSOR.readSensor} > 200){{STATEMENTS}}', '-': 'if((¬{LIGHTSENSOR.readSensor} > 0) && (¬{LIGHTSENSOR.readSensor} <= 200)){{STATEMENTS}}', '*': 'if(¬{LIGHTSENSOR.readSensor} <= 0){{STATEMENTS}}' } } } }); utils.preprocessBloq(bloqMBotIfThereIsALotOfLight); bloqMBotIfThereIsALotOfLight.connectors[1].acceptedAliases = ['all', 'ifDown']; module.exports = bloqMBotIfThereIsALotOfLight;
angular.module('abastecimentoApp.servicesNotificacoes', []).factory('Notificacao', function ($resource, $http, constantService) { return { query: query, get:get } function query(callback) { $http.get(constantService.baseURL + '/notificacoes') .then(function (response) { if (callback) { callback(response.data); } }); }; function get(id, callback) { $http.get(constantService.baseURL + '/notificacoes/' + id) .then(function (response) { if (callback) { callback(response.data); } }); }; return this.resource; }).service('popupService', function ($window) { this.showPopup = function (message) { return $window.confirm(message); } }).service('constantService', function () { return { baseURL: 'http://localhost:3000/api' } });
import WindowController from "@/modv/window-controller"; import getLargestWindow from "@/modv/get-largest-window"; const state = { windows: [], size: { width: 0, height: 0 } }; // We can't store Window Objects in Vuex because the Observer traversal exceeds the stack size const externalState = []; // getters const getters = { allWindows: state => state.windows, windowReference: () => index => externalState[index], largestWindowSize: state => state.size, largestWindowReference() { return () => getLargestWindow(state.windows).window || externalState[0]; }, largestWindowController() { return () => getLargestWindow(state.windows).controller; }, getWindowById: state => id => state.windows.find(windowController => windowController.id === id), windowIds: state => state.windows.map(windowController => windowController.id) }; // actions const actions = { createWindow({ commit }, { Vue }) { const number = state.windows.length; return new WindowController(Vue, number).then(windowController => { const windowRef = windowController.window; delete windowController.window; commit("addWindow", { windowController, windowRef }); return windowController; }); }, destroyWindow({ commit }, { windowRef }) { commit("removeWindow", { windowRef }); }, resize({ state, commit }, { width, height, dpr }) { state.windows.forEach(windowController => { windowController.resize(width, height, dpr, false); }); commit("setSize", { width, height, dpr }); } }; // mutations const mutations = { addWindow(state, { windowController, windowRef }) { const index = state.windows.length; windowController.window = index; state.windows.push(windowController); externalState.push(windowRef); getters.largestWindowReference(); }, removeWindow(state, { windowRef }) { state.windows.splice(windowRef, 1); externalState.splice(windowRef, 1); getters.largestWindowReference(); }, setSize(state, { width, height, dpr }) { state.size = { width, height, dpr, area: width * height }; } }; export default { namespaced: true, state, getters, actions, mutations };
(function() { 'use strict'; angular.module('pteroWorkflowClient.services', []); })();
/** * Genji Scrum Tool and Issue Tracker * Copyright (C) 2015 Steinbeis GmbH & Co. KG Task Management Solutions * <a href="http://www.trackplus.com">Genji Scrum Tool</a> * * 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/>. */ /* $Id:$ */ Ext.define("com.trackplus.admin.customize.filter.ReportConfigController", { extend: "Ext.app.ViewController", alias: "controller.reportConfig", mixins: { baseController: "com.trackplus.admin.customize.category.CategoryBaseController" }, //used in FieldExpressionAction (not directly here) //issueFilter : true, folderAction: "categoryConfig", baseServerAction: "reportConfig", entityDialog: "com.trackplus.admin.customize.report.ReportEdit", enableDisableToolbarButtons : function(view, arrSelections) { if (CWHF.isNull(arrSelections) || arrSelections.length === 0) { this.getView().actionDeleteGridRow.setDisabled(true); this.getView().actionEditGridRow.setDisabled(true); this.getView().actionExecuteGridRow.setDisabled(true); this.getView().actionDownloadGridRow.setDisabled(true); } else { if (arrSelections.length === 1) { var selectedRecord = arrSelections[0]; var isLeaf = selectedRecord.get("leaf"); var modifiable = selectedRecord.get("modifiable"); this.getView().actionEditGridRow.setDisabled(!modifiable); this.getView().actionExecuteGridRow.setDisabled(!isLeaf); this.getView().actionDownloadGridRow.setDisabled(!isLeaf); } else { // more than one selection this.getView().actionEditGridRow.setDisabled(true); this.getView().actionExecuteGridRow.setDisabled(true); this.getView().actionDownloadGridRow.setDisabled(true); } var allIsDeletable = true; for (var i = 0; i < arrSelections.length; i++) { var selectedRecord = arrSelections[i]; var deletable = selectedRecord.data.deletable; if (!deletable) { allIsDeletable = false; } } this.getView().actionDeleteGridRow.setDisabled(!allIsDeletable); } }, /** * Execute a leaf node */ onExecuteTreeNode: function() { this.onExecute(true); }, /** * Execute a grid row */ onExecuteGridRow: function() { this.onExecute(false); }, /** * Execute a tree node or a grid row */ onExecute: function(fromTree) { var recordData = this.getView().getSingleSelectedRecordData(fromTree); if (recordData ) { var leaf = this.getView().selectedIsLeaf(fromTree); var node = this.getRecordID(recordData, { fromTree : fromTree }); if (leaf) { var lastIndex = node.lastIndexOf("_"); var objectID = node.substring(lastIndex + 1); //customFeature: whether record configuration is needed com.trackplus.admin.Report.executeReport(this, objectID, recordData["customFeature"], false); } } }, /** * Download the report for a tree node */ onDownloadTreeNode : function() { this.downloadReport(true); }, /** * Download the report for the grid row */ onDownloadGridRow : function() { this.downloadReport(false); }, /** * Downloads a report zip */ downloadReport : function(fromTree) { var recordData = this.getView().getSingleSelectedRecordData(fromTree); if (recordData ) { var leaf = this.getView().selectedIsLeaf(fromTree); if (leaf) { var node = this.getRecordID(recordData, { fromTree : fromTree }); attachmentURI = "reportConfig!download.action?node=" + node; window.open(attachmentURI); } } } });
(function() { var StatisticPresenter = function() {}; BH.Presenters.StatisticPresenter = StatisticPresenter; })();
import { moduleFor, test } from 'ember-qunit'; moduleFor('adapter:contacts', 'Unit | Adapter | contacts', { // Specify the other units that are required for this test. // needs: ['serializer:foo'] }); // Replace this with your real tests. test('it exists', function(assert) { let adapter = this.subject(); assert.ok(adapter); });
/** * * Wait for an element (selected by css selector) for the provided amount of * milliseconds to be present within the DOM. Returns true if the selector * matches at least one element that exists in the DOM, otherwise throws an * error. If the reverse flag is true, the command will instead return true * if the selector does not match any elements. * * <example> :waitForExistSyncExample.js it('should display a notification message after successful form submit', function () { var form = $('form'); var notification = $('.notification'); form.submit(); notification.waitForExist(5000); // same as `browser.waitForExist('.notification', 5000)` expect(notification.getText()).to.be.equal('Data transmitted successfully!') }); * </example> * * @alias browser.waitForExist * @param {String} selector element selector to wait for * @param {Number=} ms time in ms (default: 500) * @param {Boolean=} reverse if true it instead waits for the selector to not match any elements (default: false) * @uses utility/waitUntil, state/isExisting * @type utility * */ let waitForExist = function (selector, ms, reverse) { /** * we can't use default values for function parameter here because this would * break the ability to chain the command with an element if reverse is used, like * * ```js * var elem = $('#elem'); * elem.waitForXXX(10000, true); * ``` */ reverse = typeof reverse === 'boolean' ? reverse : false /*! * ensure that ms is set properly */ if (typeof ms !== 'number') { ms = this.options.waitforTimeout } const isReversed = reverse ? '' : 'not ' const errorMsg = `element ("${selector || this.lastResult.selector}") still ${isReversed}existing after ${ms}ms` return this.waitUntil(() => { return this.isExisting(selector).then((isExisting) => { if (!Array.isArray(isExisting)) { return isExisting !== reverse } let result = reverse for (let val of isExisting) { if (!reverse) { result = result || val } else { result = result && val } } return result !== reverse }) }, ms, errorMsg) } export default waitForExist
/*! pl-sql-client - Query many database at once Copyright (C) 2015 Kyle Ilantzis, Pier-Luc Caron St-Pierre 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/>. */ (function(pl) { var gui = require('nw.gui'); var Watcher = require('./backend/watcher.js'); var TAG = "SettingsStore:::"; var NAME = "SettingsStore"; var SettingsStore = { BROADCAST_LOADED: "SettingsStore-BCAST_LOADED", LOAD: "SettingsStore-LOAD", SET_THEME: "SettingsStore-SET_THEME", SET_WINDOW_RECT: "SettingsStore-SET_WINDOW_RECT" }; var DEFAULT_CONFIG = { theme: null, databases: [], windowRect: null }; var config; var watcher; var notify = pl.observable(SettingsStore); var init = function() { loaded = false; config = DEFAULT_CONFIG; if (watcher) { watcher.die(); } watcher = new Watcher(gui.App.dataPath, NAME, DEFAULT_CONFIG, update); notify.init(); }; var load = function() { watcher.watch(update); }; var setTheme = function(theme) { var i = pl.Themes.getThemes().indexOf(theme); config.theme = i >= 0 ? theme : pl.Themes.getDefaultTheme(); watcher.save(config); notify(); }; var setWindowRect = function(x, y, width, height) { config.windowRect = { x: x, y: y, width: width, height: height }; watcher.save(config); notify(); }; var setDatabases = function() { config.databases = pl.DbItemStore.getDatabases(); watcher.save(config); notify(); }; var update = function(newConfig) { config = pl.extend(DEFAULT_CONFIG, newConfig); pl.BroadcastActions.settingsLoaded(); notify(); }; pl.Dispatcher.register(NAME, function(action) { switch (action.actionType) { case pl.DbItemStore.BROADCAST_CHANGED: setDatabases(); break; case SettingsStore.LOAD: load(); break; case SettingsStore.SET_THEME: setTheme(action.theme); break; case SettingsStore.SET_WINDOW_RECT: setWindowRect(action.x, action.y, action.width, action.height); break; } }); pl.SettingsStore = pl.extend(SettingsStore, { _init: init, getTheme: function() { return config.theme || pl.Themes.getDefaultTheme(); }, getDatabases: function() { return config.databases; }, getWindowRect: function() { return config.windowRect; } }); init(); })(pl||{});
var Phaser = Phaser || {}; var Mst = Mst || {}; Mst.BootState = function () { "use strict"; Phaser.State.call(this); }; Mst.prototype = Object.create(Phaser.State.prototype); Mst.prototype.constructor = Mst.BootState; Mst.BootState.prototype.init = function (map_int, usr_id) { "use strict"; var d = new Date(); var n = d.getTime(); this.core_file = "assets/maps/core.json"; this.quest_file = "assets/maps/quest.json"; this.map_int = map_int; this.map_file = "map.php?time="+n+"&uid="+usr_id+"&mapi="+map_int; //this.map_file = "assets/maps/map"+map_int+".json?time="+n+"&uid="+usr_id+"&mapi="+map_int; console.log(this.map_file); this.usr_id = usr_id; }; Mst.BootState.prototype.preload = function () { "use strict"; if (this.usr_id > 0) { this.load.text("core", this.core_file); this.load.text("quest", this.quest_file); this.load.text("map", this.map_file); } else { var a = this.load.image("login", "assets/images/loader2.png"); //console.log(a); } }; Mst.BootState.prototype.create = function () { "use strict"; var map_text, map_data, core_text, core_data, root_data, quest_text, quest_data; if (this.usr_id > 0) { map_text = this.game.cache.getText("map"); var n = map_text.lastIndexOf(">"); if (n > -1) { map_text = map_text.substring(n + 1); } //console.log(map_text); map_data = JSON.parse(map_text); console.log(map_data); core_text = this.game.cache.getText("core"); core_data = JSON.parse(core_text); quest_text = this.game.cache.getText("quest"); quest_data = JSON.parse(quest_text); console.log(quest_data); } root_data = { map_int: this.map_int, usr_id: this.usr_id }; console.log("Boot State"); console.log(root_data); this.game.state.start("LoadingState", true, false, core_data, map_data, root_data, quest_data); };
Simpla CMS 2.3.8 = 0f9e3c6a3ac53725fa229f3620b7ca52
// ========================================================================== // Project: Brochurno // Copyright: @2011 Jason Dooley // ========================================================================== /*globals Brochurno module test ok equals same stop start */ module("Brochurno.SectionView"); // TODO: Replace with real unit test for Brochurno.SectionView test("test description", function() { var expected = "test"; var result = "test"; equals(result, expected, "test should equal test"); });
/** * @author Matthew Foster * @date December 27th 2007 */ var MultiCalendarBase = Class.create(); Object.extend(Object.extend(MultiCalendarBase.prototype, EventDispatcher.prototype), { buildInterface : function(container){ this.container = $(container); this.view = this.container.down(".view"); this.wrap = this.container.down(".wrap"); this.control = this.container.down(".control"); this.nextControl = this.control.down(".next"); this.prevControl = this.control.down(".previous"); }, setItemIncrement : function(num){ this.increment = num; }, getItemIncrement : function(){ return this.increment || 0; }, buildOptions : function(options){ this.options = Object.extend({ rangeOffset : 3, buffer : 25}, options || {}); }, createCalendar : function(element, date){ return new LabeledCalendar(element, date); }, scrollLeft : function(){ this.wrap.scrollLeft -= this.getItemIncrement(); }, scrollRight : function(){ this.wrap.scrollLeft += this.getItemIncrement(); }, insertCalendar : function(element){ try{ this.view.insertBefore(element, this.view.firstChild); } catch(e){ this.appendCalendar(element); } }, appendCalendar : function(element){ this.view.appendChild(element); }, getInitialRange : function(){ var date = new Date(); var start = new GregorianCalendar(date.getFullYear(), date.getMonth() -2); var end = new GregorianCalendar(date.getFullYear(),date.getMonth()+this.options.rangeOffset ); return $A(new GregorianCalendarRange(start, end)); } } );
var request = require("request"); var AuthDetails = require("../../auth.json"); exports.commands = [ "image", //gives top image from google search "rimage", //gives random image from google search "ggif" //gives random gif from google search ]; exports.image = { usage: "<search query>", description: "gets the top matching image from google", process: function(bot, msg, args) { if (!AuthDetails || !AuthDetails.youtube_api_key || !AuthDetails.google_custom_search) { bot.sendMessage(msg.channel, "Image search requires both a YouTube API key and a Google Custom Search key!"); return; } //gets us a random result in first 5 pages var page = 1; //we request 10 items request("https://www.googleapis.com/customsearch/v1?key=" + AuthDetails.youtube_api_key + "&cx=" + AuthDetails.google_custom_search + "&q=" + (args.replace(/\s/g, '+')) + "&searchType=image&alt=json&num=10&start=" + page, function(err, res, body) { var data, error; try { data = JSON.parse(body); } catch (error) { console.log(error) return; } if (!data) { console.log(data); bot.sendMessage(msg.channel, "Error:\n" + JSON.stringify(data)); return; } else if (!data.items || data.items.length == 0) { console.log(data); bot.sendMessage(msg.channel, "No result for '" + args + "'"); return; } var randResult = data.items[0]; bot.sendMessage(msg.channel, randResult.title + '\n' + randResult.link); }); } } exports.rimage = { usage: "<search query>", description: "gets a random image matching tags from google", process: function(bot, msg, args) { if (!AuthDetails || !AuthDetails.youtube_api_key || !AuthDetails.google_custom_search) { bot.sendMessage(msg.channel, "Image search requires both a YouTube API key and a Google Custom Search key!"); return; } //gets us a random result in first 5 pages var page = 1 + Math.floor(Math.random() * 5) * 10; //we request 10 items request("https://www.googleapis.com/customsearch/v1?key=" + AuthDetails.youtube_api_key + "&cx=" + AuthDetails.google_custom_search + "&q=" + (args.replace(/\s/g, '+')) + "&searchType=image&alt=json&num=10&start=" + page, function(err, res, body) { var data, error; try { data = JSON.parse(body); } catch (error) { console.log(error) return; } if (!data) { console.log(data); bot.sendMessage(msg.channel, "Error:\n" + JSON.stringify(data)); return; } else if (!data.items || data.items.length == 0) { console.log(data); bot.sendMessage(msg.channel, "No result for '" + args + "'"); return; } var randResult = data.items[Math.floor(Math.random() * data.items.length)]; bot.sendMessage(msg.channel, randResult.title + '\n' + randResult.link); }); } } exports.ggif = { usage: "<search query>", description: "get random gif matching tags from google", process: function(bot, msg, args) { //gets us a random result in first 5 pages var page = 1 + Math.floor(Math.random() * 5) * 10; //we request 10 items request("https://www.googleapis.com/customsearch/v1?key=" + AuthDetails.youtube_api_key + "&cx=" + AuthDetails.google_custom_search + "&q=" + (args.replace(/\s/g, '+')) + "&searchType=image&alt=json&num=10&start=" + page + "&fileType=gif", function(err, res, body) { var data, error; try { data = JSON.parse(body); } catch (error) { console.log(error) return; } if (!data) { console.log(data); bot.sendMessage(msg.channel, "Error:\n" + JSON.stringify(data)); return; } else if (!data.items || data.items.length == 0) { console.log(data); bot.sendMessage(msg.channel, "No result for '" + args + "'"); return; } var randResult = data.items[Math.floor(Math.random() * data.items.length)]; bot.sendMessage(msg.channel, randResult.title + '\n' + randResult.link); }); } }
export default function * responseTime(next) { /* * A simple middleware to set X response time header */ let start = new Date; yield next let ms = new Date - start this.set('X-Response-Time', ms + 'ms') }
const ajaxurl = window.mc4wp_vars.ajaxurl const m = require('mithril') if (!Element.prototype.matches) { Element.prototype.matches = Element.prototype.msMatchesSelector || Element.prototype.webkitMatchesSelector } function showDetails (evt) { evt.preventDefault() const link = evt.target const next = link.parentElement.parentElement.nextElementSibling const listID = link.getAttribute('data-list-id') const mount = next.querySelector('div') if (next.style.display === 'none') { m.request({ method: 'GET', url: ajaxurl + '?action=mc4wp_get_list_details&ids=' + listID }).then(details => { m.render(mount, view(details.shift())) }) next.style.display = '' } else { next.style.display = 'none' } } function view (data) { return [ m('h3', 'Merge fields'), m('table.widefat.striped', [ m('thead', [ m('tr', [ m('th', 'Name'), m('th', 'Tag'), m('th', 'Type') ]) ]), m('tbody', data.merge_fields.map(f => ( m('tr', [ m('td', [ f.name, f.required && m('span.mc4wp-red', '*') ]), m('td', [ m('code', f.tag) ]), m('td', [ f.type, ' ', f.options && f.options.date_format ? '(' + f.options.date_format + ')' : '', f.options && f.options.choices ? '(' + f.options.choices.join(', ') + ')' : '' ]) ]) ))) ]), data.interest_categories.length > 0 && [ m('h3', 'Interest Categories'), m('table.striped.widefat', [ m('thead', [ m('tr', [ m('th', 'Name'), m('th', 'Type'), m('th', 'Interests') ]) ]), m('tbody', data.interest_categories.map(f => ( m('tr', [ m('td', [ m('strong', f.title), m('br'), m('br'), 'ID: ', m('code', f.id) ]), m('td', f.type), m('td', [ m('div.mc4wp-row', { style: 'margin-bottom: 4px;' }, [ m('div.mc4wp-col.mc4wp-col-3', [ m('strong', { style: 'display: block; border-bottom: 1px solid #eee;' }, 'Name') ]), m('div.mc4wp-col.mc4wp-col-3', [ m('strong', { style: 'display: block; border-bottom: 1px solid #eee;' }, 'ID') ]) ]), Object.keys(f.interests).map((id) => ( m('div.mc4wp-row.mc4wp-margin-s', [ m('div.mc4wp-col.mc4wp-col-3', f.interests[id]), m('div.mc4wp-col.mc4wp-col-3', [ m('code', { title: 'Interest ID' }, id) ]), m('br.clearfix.clear.cf') ]) )) ]) ]) ))) ]) ] ] } const table = document.getElementById('mc4wp-mailchimp-lists-overview') if (table) { table.addEventListener('click', (evt) => { if (!evt.target.matches('.mc4wp-mailchimp-list')) { return } showDetails(evt) }) }
import Ember from 'ember'; import DS from 'ember-data'; export default DS.Transform.extend({ deserialize: function(serialized) { return (Ember.typeOf(serialized) == "array") ? serialized : []; }, serialize: function(deserialized) { var type = Ember.typeOf(deserialized); if (type == 'array') { return deserialized } else if (type == 'string') { return deserialized.split(',').map(function(item) { return Ember.$.trim(item); }); } else { return []; } } });
const protobuf = require('protobufjs') const path = require('path') protobuf.load(path.resolve('../protobuf/meetings.proto')) .then(start) .catch(console.error) function start (root) { const User = root.lookupType('meetings.User') const payload = { firstName: 'Lucas', lastName: 'Santos', addresses: [ { line1: 'Rua X', line2: 3540, type: 0 } ] } const message = User.fromObject(payload) const buffer = User.encode(message).finish() console.log(buffer, message) const decoded = User.decode(buffer) const obj = User.toObject(decoded) console.log(decoded, obj) }
var core__cm_func_8h = [ [ "__CORE_CMFUNC_H", "core__cm_func_8h.html#a50c339231579f3b052ed89428a8a2453", null ] ];
(function(window) { var RectInternalRepresentation = function(primitive) { var me = new ArmContext.InternalRepresentation(primitive); this._width = 10; this._height = 10; me.GetWidth = function() { return this._width; }; me.SetWidth = function(O) { gizmo.Filter(O, "Number"); this.Update({ width: O, height: this.GetHeight() }); }; me.GetHeight = function() { return this._height; }; me.SetHeight = function(O) { gizmo.Filter(O, "Number"); this.UpdatePoints({x: this.GetX(), y: this.GetY(), width: this.GetWidth(), height: O}); }; me.GetPointsOfMatrix = function() { return this._points; }; me.SetPointsOfMatrix = function(O) { gizmo.Filter(O, "Array"); return this._points; }; me.Set = function(O) { for(var name in O) { switch( name ) { case "width" : { this._width = O[name]; if(this._onChanged) { this._onChanged.call(primitive); }; }; break; case "height" : { this._height = O[name]; if(this._onChanged) { this._onChanged.call(primitive); }; }; break; }; }; this._points = new $M( [ [0 ,0 ,1], [this._width,0 ,1], [this._width,this._height,1], [0 ,this._height,1] ] ); }; return me; } ArmContext.RectInternalRepresentation = RectInternalRepresentation; })();
/* url utils @sha0coder */ exports.getUrlDir = function(url) { return url.replace(/\/[^\/]*$/,'/') } exports.getBase = function(url) { var spl = url.split('/'); return spl[0]+'//'+spl[2]; }; exports.getDomain = function(url) { return url.split('/')[2]; }; exports.isDir = function(url) { return (url.charAt(url.length-1) == '/') }; exports.isDirListing = function(html) { return (html.search('<title>Index of /') > 0); }; exports.fixUrl = function(url) { url = url.replace(/\x0d/,'%0d').replace('/./','/'); //.replace(/\/\/$/,'/'); if (url.charAt(0)!='h') url = 'http://'+url; if (url.charAt(url.length-1) != '/') url = url+'/'; return url; }; exports.fixDir = function(dir) { if (dir.charAt(0) == '/') dir = dir.substring(1,dir.length); return dir; };
module.exports = { // Scale for HTML Canvas (1=2kx2k, 2=1kx1k, 4=500x500, ...) scaleFactor: 4, };
var express = require('express'); var routes = function (Page) { var feedbackController = require('../controllers/feedbackController')(Page); var feedbackRouter = express.Router(); feedbackRouter.route('/') .get(feedbackController.findByPage); return feedbackRouter; }; module.exports = routes;
import Ember from 'ember'; var total = 0; export default Ember.Controller.extend({ isShowingHelp: false, isShowingModal: false, actions: { toggleModal: function() { this.toggleProperty('isShowingModal'); }, toggleModal1: function() { this.toggleProperty('isShowingModals'); }, toggleModal2: function() { this.toggleProperty('isShowingModalss'); }, toggleModal3: function() { this.toggleProperty('isShowingModalsss'); }, toggleModal4: function() { this.toggleProperty('isShowingModalssss'); }, toggleModal5: function() { this.toggleProperty('isShowingModalsssss'); }, agreement: function() { this.transitionToRoute('agreement'); }, norewardSelection: function(arg, arg1) { var amount = this.get('amount'); if (amount === null || amount === undefined || amount === "") { this.set('amounterrormessage', "field cannot be empty") return; } var amount = arg; var reward = arg1; console.log(amount); this.set('message', "You have not selected any rewards and you want to contribute Rs "+ amount +" and You will get "+ reward +" reward. Do you want to continue?"); }, rewardSelection: function(arg, arg1) { var amount = arg; var reward = arg1; this.set('message', "You have selected Rs. " + amount + " and You will get " + reward + " reward. Do you want to continue?"); console.log("display"); }, addtocart : function(){ var quantity = this.get("quantity"); var amt = 1000* quantity; total =total + amt; console.log(total); var jsonvariable =Ember.$.getJSON("reward.json"); console.log( Ember.inspect(jsonvariable) ) console.log("jsonvariable",JSON.stringify(jsonvariable)); console.log("ResponseText: " + JSON.stringify(jsonvariable)); // console.log(str.reward[0].rewardamount); // alert(object.toSource(jsonvariable)); this.toggleProperty('isShowingModals'); //var str =JSON.parse(jsonvariable); // console.log(str); var title=""; var array2 = []; console.log("JSON2:before function "+array2); Ember.$.getJSON( "reward.json", function(json) { var array = []; for (var key in json) { if (json.hasOwnProperty(key)) { var item = json[key]; array.push({ rewardtitle: item.rewardtitle, rewardamount: item.rewardamount, rewarddescription: item.rewarddescription }); console.log("rewardtitle"+JSON.stringify(array[0])); /*var item2 =json[key]; array2.push({ rewardtitle: item.rewardtitle, rewardamount: item.rewardamount, rewarddescription: item.rewarddescription }) */ } } console.log("JSON: "+ JSON.stringify(array)); title= JSON.stringify(array[0].rewardtitle); console.log('title :'+title); // this.set('myrewardtitle',title); /* array2=array.slice(); console.log("JSON2: "+ JSON.stringify(array2));*/ // var array2 = array.concat(); for(var i=0;i<array.length;i++){ console.log("1"); array2[i]=array[i]; console.log("2"); } }); this.set('myrewardtitle',title); /* var array3=[]; array3=array.slice(); console.log("JSON3: "+ JSON.stringify(array3));*/ console.log("JSON2: "+ JSON.stringify(array2)); /* var jsstr=JSON.parse(abc); console.log(abc.rewardamount); for(var i=0;i<JSONItems.length;i++){ console.log(JSONItems[i]); }*/ /* var JSONItems1 = []; var strs=Ember.$.get( "reward.json", function( data){ JSONItems1 = JSON.parse(data); console.log(JSONItems1); }); console.log(strs);*/ //console.log(abc.reward[0]); }, payment: function() { alert("Do not Refresh the page...."); window.location.replace("https://www.billdesk.com/savepgi/"); }, showHelp: function() { this.toggleProperty('isShowingHelp'); } } });
'use strict'; angular.module('tucha') .controller('GridCtrl', function ($rootScope, $scope, $location, $http, $timeout, states, columns) { var stateName = $location.path().split('/')[1]; for (var i = 0; i < states.length; i++) { if (states[i].name === stateName) { $scope.state = states[i]; states[i].active = true; $scope.title = states[i].title; } else { states[i].active = false; } } $http.get('/r/' + stateName).then(function (data) { //$scope.data = data.data; var columnDefs = []; if (stateName === 'animal') { columnDefs.push({ field: 'id', name: '', width: 50, cellTemplate: '<div class="grid-image-cell"><img width="50" src="r/animal/{{row.entity.id}}/photo_wh50"/></div>' }); } else if (stateName === 'associate') { $scope.feesDueList = []; $scope.currentYear = new Date().getFullYear(); for (var i = 0; i < data.data.length; i++) { if (!data.data[i].last_paid_fee || data.data[i].last_paid_fee < $scope.currentYear) { $scope.feesDueList.push(data.data[i]); } } } for (var key in data.data[0]) { columnDefs.push(columns[key]); } $scope.gridOptions = { data: data.data, columnDefs: columnDefs, minRowsToShow: data.data.length + 0.1, enableHorizontalScrollbar: 0, enableVerticalScrollbar: 0, enableGridMenu: true, rowTemplate: 'views/directives/rowTemplate.html', rowHeight: 50, onRegisterApi: function (gridApi) { $scope.gridApi = gridApi; }, appScopeProvider: { rowClick: function (row) { if (stateName === 'animal') { // generate current sort ids for the next and previous button to work $rootScope.animalsSequence = []; var rows = $scope.gridApi.core.getVisibleRows(); for (var i = 0; i < rows.length; i++) { $rootScope.animalsSequence.push(rows[i].entity.id); } } else if (stateName === 'volunteer' || stateName === 'associate') { // theese 2 sections are only shortcuts to persons with different filtered lists stateName = 'person'; } $location.path('/' + stateName + '/' + row.entity.id); } } }; }); $scope.add = function () { $location.path('/' + stateName + "/new"); }; });
module.exports = { //--------------------------------------------------------------------- // Action Name // // This is the name of the action displayed in the editor. //--------------------------------------------------------------------- name: "Run Script", //--------------------------------------------------------------------- // Action Section // // This is the section the action will fall into. //--------------------------------------------------------------------- section: "Other Stuff", //--------------------------------------------------------------------- // Action Subtitle // // This function generates the subtitle displayed next to the name. //--------------------------------------------------------------------- subtitle: function(data) { return `${data.code}`; }, //--------------------------------------------------------------------- // Action Storage Function // // Stores the relevant variable info for the editor. //--------------------------------------------------------------------- variableStorage: function(data, varType) { const type = parseInt(data.storage); if(type !== varType) return; return ([data.varName, 'Unknown Type']); }, //--------------------------------------------------------------------- // Action Fields // // These are the fields for the action. These fields are customized // by creating elements with corresponding IDs in the HTML. These // are also the names of the fields stored in the action's JSON data. //--------------------------------------------------------------------- fields: ["behavior", "interpretation", "code", "storage", "varName"], //--------------------------------------------------------------------- // Command HTML // // This function returns a string containing the HTML used for // editting actions. // // The "isEvent" parameter will be true if this action is being used // for an event. Due to their nature, events lack certain information, // so edit the HTML to reflect this. // // The "data" parameter stores constants for select elements to use. // Each is an array: index 0 for commands, index 1 for events. // The names are: sendTargets, members, roles, channels, // messages, servers, variables //--------------------------------------------------------------------- html: function(isEvent, data) { return ` <div> <div style="float: left; width: 45%;"> End Behavior:<br> <select id="behavior" class="round"> <option value="0" selected>Call Next Action Automatically</option> <option value="1">Do Not Call Next Action</option> </select> </div> <div style="padding-left: 5%; float: left; width: 55%;"> Interpretation Style:<br> <select id="interpretation" class="round"> <option value="0" selected>Evaluate Text First</option> <option value="1">Evaluate Text Directly</option> </select> </div> </div><br><br><br> <div style="padding-top: 8px;"> Custom Code:<br> <textarea id="code" rows="9" name="is-eval" style="width: 99%; white-space: nowrap; resize: none;"></textarea> </div><br> <div> <div style="float: left; width: 35%;"> Store In:<br> <select id="storage" class="round" onchange="glob.variableChange(this, 'varNameContainer')"> ${data.variables[0]} </select> </div> <div id="varNameContainer" style="display: none; float: right; width: 60%;"> Variable Name:<br> <input id="varName" class="round" type="text"> </div> </div>` }, //--------------------------------------------------------------------- // Action Editor Init Code // // When the HTML is first applied to the action editor, this code // is also run. This helps add modifications or setup reactionary // functions for the DOM elements. //--------------------------------------------------------------------- init: function() { const {glob, document} = this; glob.variableChange(document.getElementById('storage'), 'varNameContainer'); }, //--------------------------------------------------------------------- // Action Bot Function // // This is the function for the action within the Bot's Action class. // Keep in mind event calls won't have access to the "msg" parameter, // so be sure to provide checks for variable existance. //--------------------------------------------------------------------- action: function(cache) { const data = cache.actions[cache.index]; let code; if(data.interpretation === "0") { code = this.evalMessage(data.code, cache); } else { code = data.code; } const result = this.eval(code, cache); const varName = this.evalMessage(data.varName, cache); const storage = parseInt(data.storage); this.storeValue(result, storage, varName, cache); if(data.behavior === "0") { this.callNextAction(cache); } }, //--------------------------------------------------------------------- // Action Bot Mod // // Upon initialization of the bot, this code is run. Using the bot's // DBM namespace, one can add/modify existing functions if necessary. // In order to reduce conflictions between mods, be sure to alias // functions you wish to overwrite. //--------------------------------------------------------------------- mod: function(DBM) { } }; // End of module
$(function(){ $('#theInput').typed({ strings: ["type a word (e.g. 'website')", "type a word (e.g. 'grammar')", "type a word (e.g. 'paper')"], typeSpeed: 50, startDelay: 150, attr: 'placeholder', backSpeed: 100, backDelay: 500, loop: true, showCursor: false, contentType: 'html', }); });
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); /** * Created by kib357 on 22/01/16. */ class copy { static arrayStructure(target, source, exclude) { if (!Array.isArray(target) || !Array.isArray(source)) { throw new TypeError('copy.arrayStructure cannot be called with not arrays'); } for (let index = 0; index < source.length; index++) { if (typeof source[index] === 'object' && !Array.isArray(source[index])) { target[index] = {}; copy.objectStructure(target[index], source[index], exclude); continue; } if (Array.isArray(source[index])) { target[index] = []; copy.arrayStructure(target[index], source[index], exclude); continue; } target[index] = null; } return target; } static objectStructure(target, source, exclude) { if (target == null || source == null) { throw new TypeError('copy.objectStructure cannot be called with null or undefined'); } for (let key of Object.keys(source)) { if (exclude instanceof RegExp && exclude.test(key)) { continue; } if (typeof source[key] === 'object' && !Array.isArray(source[key])) { target[key] = {}; copy.objectStructure(target[key], source[key], exclude); continue; } if (Array.isArray(source[key])) { target[key] = []; copy.arrayStructure(target[key], source[key], exclude); continue; } target[key] = null; } return target; } } exports.default = copy;
var searchData= [ ['analog',['Analog',['../namespace_d_s_g_1_1_analog.html',1,'DSG']]], ['blit',['BLIT',['../namespace_d_s_g_1_1_b_l_i_t.html',1,'DSG']]], ['dpw',['DPW',['../namespace_d_s_g_1_1_d_p_w.html',1,'DSG']]], ['dsg',['DSG',['../namespace_d_s_g.html',1,'']]], ['eptr',['EPTR',['../namespace_d_s_g_1_1_e_p_t_r.html',1,'DSG']]], ['filter',['Filter',['../namespace_d_s_g_1_1_filter.html',1,'DSG']]], ['fourier',['Fourier',['../namespace_d_s_g_1_1_fourier.html',1,'DSG']]], ['midi',['MIDI',['../namespace_d_s_g_1_1_m_i_d_i.html',1,'DSG']]], ['noise',['Noise',['../namespace_d_s_g_1_1_noise.html',1,'DSG']]], ['window',['Window',['../namespace_d_s_g_1_1_window.html',1,'DSG']]] ];
var http = require('supertest'); var shared = require('../shared'); var server = require('../app'); var app; describe('v2 user#page', function () { before(function (done) { server(function (data) { app = data; done(); }); }); it('should show user index', function (done) { var req = http(app); req.get('/user/page/' + shared.user.username) .expect(200, function (err, res) { var texts = [ '注册时间', '仍然很懒', '最近创建的话题', '无话题', '最近参与的话题', '无话题' ]; texts.forEach(function (text) { res.text.should.containEql(text); }); done(err); }); }); });
import { respond } from "theme/styles/mixins"; export default ` .resource-meta, .resource-meta-mobile { .resource-type { margin-bottom: 14px; ${respond(`margin-bottom: 2px;`, 65)} } /* <ul> */ .meta-list-secondary { margin-bottom: 22px; &:not(:first-child) { margin-top: 10px; } } /* Only shown on mobile */ .meta-list-primary { margin-bottom: 22px; } } `;
/*eslint-env browser */ // main dannybot script const mail = require('./mail'); const storage = require('electron-json-storage'); const fs = require('fs'); const q = require('q'); var readFile = q.nbind(fs.readFile); /* Function to run when DOM loaded */ function ready() { init_tab_handler(); show_counts(); construct_checklist(document.getElementById('checklist')); } window.onload = ready; /* Tab functions */ function init_tab_handler() { var tab_buttons = document.querySelectorAll('#tab-buttons *[data-tab]'); for(var i = 0; i < tab_buttons.length; ++i) { tab_buttons[i].onclick = function () { var active = find_active_tab(tab_buttons); switch_active_tab(active, this); }; } } function find_active_tab(tb) { for(var i = 0; i < tb.length; ++i) { if (tb[i].classList.contains('active')) { return tb[i]; } } } function tab_div(tab) { var div_id = tab.dataset.tab; return document.getElementById(div_id); } function switch_active_tab(last_active, new_active) { tab_div(last_active).style.display = 'none'; tab_div(new_active).style.display = 'block'; last_active.classList.remove('active'); new_active.classList.add('active'); } /* Email count updater */ async function show_counts() { try { var folders = await mail.get_mail_config(); var counts = ''; for (var k in folders) { var f = folders[k]; counts = counts + ' ' + await f.count(); update_mail_count(counts); } } catch (e) { throw e; } } function update_mail_count(s) { document.getElementById('inbox_num').innerHTML = s; } /* Checklist */ async function construct_checklist(hn) { hn.classList.add('checklist-container'); var cl = await read_checklist(); var a_checklist = cl.evening; Object.keys(a_checklist).forEach(function (k) { var item = a_checklist[k]; var div = document.createElement('div'); div.classList.add('checklist-item'); var checkbox = document.createElement('input'); checkbox.type = 'checkbox'; checkbox.id = `evening${k}`; checkbox.name = `evening${k}`; checkbox.value = '1'; if (item.value) { checkbox.checked = true; } checkbox.onchange = function () { item.value = this.checked; write_checklist(cl); }; div.appendChild(checkbox); div.appendChild(document.createTextNode(item.text)); hn.appendChild(div); }); var reset = document.createElement('button'); reset.type = 'reset'; reset.innerText = 'Clear'; reset.onclick = function () { Object.keys(a_checklist).forEach(function (k) { var item = a_checklist[k]; item.value = false; }); var buttons = hn.querySelectorAll('.checklist-container input[type=checkbox]'); for (var i = 0; i < buttons.length; ++i) { buttons[i].checked = false; } write_checklist(cl); }; hn.appendChild(reset); } async function read_checklist() { var url = await storage.get('checklist_url'); if (!url) { var url_json = await readFile('/home/danny/Private/lifehacking/checklist-url.js'); url = JSON.parse(url_json).api; storage.set('checklist_url', url); } var response = await window.fetch(url); var checklist = await response.json(); return checklist; } async function write_checklist(checklist) { var url = await storage.get('checklist_url'); if (!url) { var url_json = await readFile('/home/danny/Private/lifehacking/checklist-url.js'); url = JSON.parse(url_json).api; storage.set('checklist_url', url); } console.log(JSON.stringify(checklist)); var response = await window.fetch(url, { method: 'PUT', headers: { 'Content-Type': 'application/json'}, body: JSON.stringify(checklist)}); console.log(response.status); }
/** * @author alteredq / http://alteredqualia.com/ * * Full-screen textured quad shader */ var THREE = window.THREE || require('three'); THREE.CopyShader = { uniforms: { "tDiffuse": { type: "t", value: null }, "opacity": { type: "f", value: 1.0 } }, vertexShader: [ "varying vec2 vUv;", "void main() {", "vUv = uv;", "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );", "}" ].join("\n"), fragmentShader: [ "uniform float opacity;", "uniform sampler2D tDiffuse;", "varying vec2 vUv;", "void main() {", "vec4 texel = texture2D( tDiffuse, vUv );", "gl_FragColor = opacity * texel;", "}" ].join("\n") };
import { history } from 'byebye'; import React from 'react'; import AltContainer from 'alt-container'; import { MANUAL_LOGOUT } from 'app-constants'; import { loginIfAuthorized as autoFacebookLogin } from 'managers/facebook'; import Analytics from 'instances/analytics'; import parseJWT from 'helpers/parseJWT'; import { decode as decodeBase64 } from 'helpers/base64'; import Auth from 'controllers/auth'; import LoginActions from 'actions/LoginActions'; import LoginStore from 'stores/LoginStore'; import EmailLoginPage from './EmailLoginPage'; import TokenErrorPage from './TokenErrorPage'; export function openTokenLogin(token) { LoginActions.loginWithEmailTokenAndRedirect(token); return ( <AltContainer component={TokenErrorPage} stores={{ LoginStore }} actions={{ LoginActions }} inject={{ data: parseJWT(token), }} /> ); } export function openItemLogin(itemId, token, force) { if (Auth.getId()) { const url = `/item/${itemId}`; history.navigate(url, { trigger: true, replace: false }, { returnUrl: '/' }); return <span />; } Analytics.track('Email login/deeplink landing'); const tokenData = JSON.parse(decodeBase64(token)); const data = { item_id: itemId, user_id: tokenData.id, domain: tokenData.domain, name: tokenData.name, }; // auto login with facebook, and when FB login fails we will send you an email autoFacebookLogin() .then(() => { LoginActions.loginSuccess(null, { login_type: 'facebookautologin', platform: 'facebook', }); }) .catch((err) => { if (err.type === MANUAL_LOGOUT || err.type === 'UnableToLogin') { // Convert the force parameter to a boolean. If `true`, it forces the backend to send the // email, regardless of the default time limit of once a day. LoginActions.sendLoginEmail(data.user_id, data.item_id, data.redirect, !!force); return; } throw err; }); return ( <AltContainer component={EmailLoginPage} stores={{ loginState: LoginStore }} inject={{ data }} /> ); } // WEBPACK FOOTER // // ./src/js/app/modules/emailLogin/module.js
module.exports = function(grunt) { grunt.loadNpmTasks('grunt-ts'); grunt.loadNpmTasks('grunt-karma'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-bump'); grunt.loadNpmTasks('grunt-tslint'); var pkg = grunt.file.readJSON('package.json'); grunt.initConfig({ pkg: pkg, ts: { options: { sourceMap: false, declaration: true, baseDir: '.', comments: true, }, lib: { src: [ 'refs/common.d.ts', 'src/*.ts' ], out: 'dist/<%= pkg.name %>.js' }, tests: { src: [ 'refs/test.d.ts', 'test/*.ts', 'test/**/*.ts' ], out: 'dist/tests.js', options: { declaration: false } } }, karma: { options: { basePath: '.', frameworks: ['jasmine'], singleRun: true, browsers: ['PhantomJS'], reporters: ['progress', 'coverage'], preprocessors: { 'dist/<%= pkg.name %>.js': 'coverage', }, coverageReporter: { type: 'text', dir: 'coverage' }, files: [ 'bower_components/jquery/dist/jquery.js', 'bower_components/jquery-bracket/dist/jquery.bracket.min.js', 'dist/<%= pkg.name %>.js', 'dist/tests.js' ] }, lib: { options: { coverageReporter: { type: 'html', dir: 'coverage' }, frameworks: ['jasmine'] } }, server: { options: { coverageReporter: {}, preprocessors: {}, reporters: ['progress'] }, autoWatch: true, singleRun: false, } }, uglify: { options: { mangle: true, compress: true, wrap: false }, dist: { src: 'dist/<%= pkg.name %>.js', dest: 'dist/<%= pkg.name %>.min.js' } }, bump: { options: { files: ['package.json', 'bower.json'], updateConfigs: [], commit: true, commitMessage: 'Release v%VERSION%', commitFiles: ['package.json', 'bower.json'], createTag: true, tagName: 'v%VERSION%', tagMessage: 'Version %VERSION%', push: false, pushTo: 'upstream', gitDescribeOptions: '--tags --always --abbrev=1 --dirty=-d' } }, tslint: { options: { configuration: grunt.file.readJSON('tslint.json') }, files: { src: ['src/**/*.ts', 'src/**/**/*.ts'] } } }); grunt.registerTask('default', ['ts:lib']); grunt.registerTask('lib', ['ts:lib']); grunt.registerTask('tests', ['ts:tests']); grunt.registerTask('test', ['karma:lib']); grunt.registerTask('dist', [ 'default', 'uglify:dist', ]); grunt.registerTask('all', ['ts', 'dist']); };
export { SavingButton } from './SavingButton';
import 'babel-polyfill'; import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { createStore, applyMiddleware } from 'redux'; import thunk from 'redux-thunk'; import promise from 'redux-promise'; import createLogger from 'redux-logger'; import allReducers from './reducers'; import App from './components/App'; const logger = createLogger(); const store = createStore(allReducers, applyMiddleware(thunk, promise, logger)); ReactDOM.render( <Provider store={store}> <App /> </Provider>, document.getElementById('app') );
var a00250 = [ [ "data_count", "a00250.html#a370358835ed2aa53bcc515894b13eb87", null ], [ "evt_type", "a00250.html#a622197dded7bfa292535944e6870c5f7", null ] ];
jQuery(document).ready(function($) { $('.modalClose').click(function() { $('.Cart66Unavailable').fadeOut(800); }); $('#Cart66CancelPayPalSubscription').click(function() { return confirm('Are you sure you want to cancel your subscription?\n'); }); }); var $pj = jQuery.noConflict(); function getCartButtonFormData(formId) { var theForm = $pj('#' + formId); var str = ''; $pj('input:not([type=checkbox], :radio), input[type=checkbox]:checked, input:radio:checked, select, textarea', theForm).each( function() { var name = $pj(this).attr('name'); var val = $pj(this).val(); str += name + '=' + encodeURIComponent(val) + '&'; } ); return str.substring(0, str.length-1); }
chrome.runtime.onInstalled.addListener(function(details){ if(details.reason == "install"){ console.log("This is a first install!"); }else if(details.reason == "update"){ var thisVersion = chrome.runtime.getManifest().version; console.log("Updated from " + details.previousVersion + " to " + thisVersion + "!"); } }); //Redirect from Valve's version of gamehighlightplayer.js to our stub file. We need this to prevent errors. chrome.webRequest.onBeforeRequest.addListener( function(details) { console.log('this ran'); if( details.url.indexOf("gamehighlightplayer.js")>-1){ return {redirectUrl: "chrome-extension://"+chrome.runtime.id+"/js/gamehighlightplayer_stub.js" }; } }, {urls: ["*://*.steamstatic.com/*"]}, ["blocking"]);
var _ = require('underscore'); var express = require('express'); var router = express.Router(); var Autocomplete = require('autocomplete'); var autocomplete = Autocomplete.connectAutocomplete(); var categoryNames = []; var categories = require('../data/categories.json'); _.each(categories, function (category) { if( category.name!=undefined || category.name!=null ) categoryNames.push(category.name.toLowerCase()); }) autocomplete.initialize(function(onReady) { onReady(categoryNames); }); /* GET categories listing. */ router.get('/autocomplete/', function(req, res, next){ var category = req.query["term"].toLowerCase(); var results = autocomplete.search(category); var categoryResults = _.map(results, function(result){ var found = _.find(categories,function(category){ if( category.name!=undefined || category.name!=null ) return category.name.toLowerCase() === result; else return false }); return {label:found.name, value:found.id}; }) res.send(categoryResults); }); router.get('/', function(req, res, next) { res.setHeader('Content-Type', 'application/json'); res.send(JSON.stringify(categories)); }); module.exports = router;
/* 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/. */ function blockReferer () { if (document.referrer) { // Blocks cross-origin referer var parser = document.createElement('a') parser.href = document.referrer if (parser.origin !== document.location.origin) { window.Document.prototype.__defineGetter__('referrer', () => { return document.location.origin }) } } } function getBlockRefererScript () { return '(' + Function.prototype.toString.call(blockReferer) + '());' } if (chrome.contentSettings.referer != 'allow' && document.location.origin && document.location.origin !== 'https://youtube.googleapis.com') { executeScript(getBlockRefererScript()) }
/* 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', 'lib/localizer' ], function (_, Backbone, Localizer) { 'use strict'; /** * Base class for views that provides common rendering, model presentation, DOM assignment, * subview tracking, and tear-down. * * @class BaseView * * @constructor * * @param {Object} options configuration options passed along to Backbone.View */ var BaseView = Backbone.View.extend({ constructor: function (options) { this.subviews = []; Backbone.View.call(this, options); }, /** * Gets context from model's attributes. Can be overridden to provide custom context for template. * * @method getContext * @return {Object} context */ getContext: function () { var context; if (this.model) { context = this.model.attributes; } else { context = {}; } return context; }, /** * Localizes English input text. * * @method localize * @return {String} localized text */ localize: function (text) { return Localizer.localize(text); }, /** * Renders by combining template and context and inserting into the associated element. * * @method render * @return {BaseView} this * @chainable */ render: function () { this.destroySubviews(); var context = this.getContext(); var self = this; context.l = function () { return function (text, render) { return render(self.localize(text)); }; }; this.$el.html(this.template(context)); this.afterRender(); return this; }, /** * Called after render completes. Provides easy access to custom rendering for subclasses * without having to override render. * * @method afterRender */ afterRender: function () { // Implement in subclasses }, /** * Renders local collection using the provided view and inserts into the provided selector. * * @method renderCollection * @param {Backbone.View} ItemView view for rendering each item in the collection * @param {String} selector jQuery selector to insert the collected elements */ renderCollection: function (ItemView, selector) { var els = this.collection.collect(function (item) { return this.trackSubview(new ItemView({ model: item })).render().el; }.bind(this)); this.$(selector).append(els); }, /** * Assigns view to a selector. * * @method assign * @param {Backbone.View} view to assign * @param {String} selector jQuery selector for the element to be assigned * @return {BaseView} this */ assign: function (view, selector) { view.setElement(this.$(selector)); view.render(); }, /** * Destroys view by stopping Backbone event listeners, disabling jQuery events, and destroying * subviews. * * @method destroy */ destroy: function () { if (this.beforeDestroy) { this.beforeDestroy(); } this.stopListening(); this.destroySubviews(); this.$el.off(); }, /** * Keeps track of a subview so that it can later be destroyed. * * @method trackSubview * @param {BaseView} view to track * @return {BaseView} tracked view */ trackSubview: function (view) { if (!_.contains(this.subviews, view)) { this.subviews.push(view); } return view; }, /** * Destroys all subviews. * * @method destroySubviews */ destroySubviews: function () { _.invoke(this.subviews, 'destroy'); this.subviews = []; } }); return BaseView; } );
// @flow import type { Action, ExpandedSet, ProfileSelection, } from '../actions/types'; import type { Days, StartEndRange } from '../../common/types/units'; import type { IndexIntoFuncTable, Profile, ThreadIndex } from '../../common/types/profile'; import type { TransformStacksPerThread } from '../../common/types/transforms'; import type { TrackedData } from '../../common/types/trackedData'; import type { DateGraph, CategorySummary } from '../../common/types/workers'; export type Reducer<T> = (T, Action) => T; export type RequestedLib = { pdbName: string, breakpadId: string }; export type ThreadViewOptions = { selectedStack: IndexIntoFuncTable[], expandedStacks: Array<IndexIntoFuncTable[]>, }; export type ProfileViewState = { viewOptions: { threadOrder: number[], perThread: ThreadViewOptions[], selection: ProfileSelection, scrollToSelectionGeneration: number, rootRange: StartEndRange, zeroAt: Days, }, profile: Profile, }; export type TrackedDataViewState = { trackedData: TrackedData, }; export type AppState = { view: string, error: string, isURLSetupDone: boolean, }; export type RangeFilterState = { start: number, end: number, }; export type RunnablesViewState = { expanded: Set<number>, runnables: Object[], }; export type CategoriesViewState = { expanded: Set<number> | null, categories: CategorySummary[] | null, }; export type ExploreURLState = { selectedTab: string, rangeFilters: RangeFilterState[], selectedThread: ThreadIndex, callTreeSearchString: string, invertCallstack: boolean, hidePlatformDetails: boolean, historical: boolean, durationSpec: string, runnableFilter: string | null, categoryFilter: string, platformFilter: string, onlyUserInteracting: boolean, payloadID: string | null, mode: string, transforms: TransformStacksPerThread, }; export type TrackURLState = { trackedStat: string, mode: string, }; export type UnknownURLState = { mode: string, }; export type URLState = ExploreURLState | TrackURLState | UnknownURLState; export type IconState = Set<string>; export type State = { app: AppState, profileView: ProfileViewState, trackedDataView: TrackedDataViewState, runnablesView: RunnablesViewState, categoriesView: CategoriesViewState, urlState: URLState, dateGraph: DateGraph, icons: IconState, }; export type IconWithClassName = { icon: string, className: string, };
if (typeof parseRegExp === 'undefined') quit(); load(libdir + "regexp_parse.js"); test_mix("^", no_multiline_flags, Assertion("START_OF_INPUT")); test_mix("^", multiline_flags, Assertion("START_OF_LINE")); test_mix("$", no_multiline_flags, Assertion("END_OF_INPUT")); test_mix("$", multiline_flags, Assertion("END_OF_LINE")); test_mix("\\b", all_flags, Assertion("BOUNDARY")); test_mix("\\B", all_flags, Assertion("NON_BOUNDARY"));
dojo.provide("dojox.charting.widget.Sparkline"); dojo.require("dojox.charting.widget.Chart2D"); dojo.require("dojox.charting.themes.ET.greys"); (function(){ var d = dojo; dojo.declare("dojox.charting.widget.Sparkline", dojox.charting.widget.Chart2D, { theme: dojox.charting.themes.ET.greys, margins: { l: 0, r: 0, t: 0, b: 0 }, type: "Lines", valueFn: "Number(x)", store: "", field: "", query: "", queryOptions: "", start: "0", count: "Infinity", sort: "", data: "", name: "default", buildRendering: function(){ var n = this.srcNodeRef; if( !n.childNodes.length || // shortcut the query !d.query("> .axis, > .plot, > .action, > .series", n).length){ var plot = document.createElement("div"); d.attr(plot, { "class": "plot", "name": "default", "type": this.type }); n.appendChild(plot); var series = document.createElement("div"); d.attr(series, { "class": "series", plot: "default", name: this.name, start: this.start, count: this.count, valueFn: this.valueFn }); d.forEach( ["store", "field", "query", "queryOptions", "sort", "data"], function(i){ if(this[i].length){ d.attr(series, i, this[i]); } }, this ); n.appendChild(series); } this.inherited(arguments); } } ); })();
/* 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/. */ /* eslint-env browser */ "use strict"; const { TAKE_SCREENSHOT_START, TAKE_SCREENSHOT_END, } = require("./index"); const { getFormatStr } = require("../utils/l10n"); const { getToplevelWindow } = require("sdk/window/utils"); const { Task: { spawn } } = require("devtools/shared/task"); const e10s = require("../utils/e10s"); const Services = require("Services"); const CAMERA_AUDIO_URL = "resource://devtools/client/themes/audio/shutter.wav"; const animationFrame = () => new Promise(resolve => { window.requestAnimationFrame(resolve); }); function getFileName() { let date = new Date(); let month = ("0" + (date.getMonth() + 1)).substr(-2); let day = ("0" + date.getDate()).substr(-2); let dateString = [date.getFullYear(), month, day].join("-"); let timeString = date.toTimeString().replace(/:/g, ".").split(" ")[0]; return getFormatStr("responsive.screenshotGeneratedFilename", dateString, timeString); } function createScreenshotFor(node) { let mm = node.frameLoader.messageManager; return e10s.request(mm, "RequestScreenshot"); } function saveToFile(data, filename) { return spawn(function* () { const chromeWindow = getToplevelWindow(window); const chromeDocument = chromeWindow.document; // append .png extension to filename if it doesn't exist filename = filename.replace(/\.png$|$/i, ".png"); chromeWindow.saveURL(data, filename, null, true, true, chromeDocument.documentURIObject, chromeDocument); }); } function simulateCameraEffects(node) { if (Services.prefs.getBoolPref("devtools.screenshot.audio.enabled")) { let cameraAudio = new window.Audio(CAMERA_AUDIO_URL); cameraAudio.play(); } node.animate({ opacity: [ 0, 1 ] }, 500); } module.exports = { takeScreenshot() { return function* (dispatch, getState) { yield dispatch({ type: TAKE_SCREENSHOT_START }); // Waiting the next repaint, to ensure the react components // can be properly render after the action dispatched above yield animationFrame(); let iframe = document.querySelector("iframe"); let data = yield createScreenshotFor(iframe); simulateCameraEffects(iframe); yield saveToFile(data, getFileName()); dispatch({ type: TAKE_SCREENSHOT_END }); }; } };
// Tests. Mocha TDD/assert style. See // http://visionmedia.github.com/mocha/ // http://nodejs.org/docs/latest/api/assert.html var constants = require('constants'); var assert = require('assert'); var sslConfig = require('../index.js'); var log = console.log.bind(console); suite('Checking generated config', function(){ test('modern config', function(done){ var config = sslConfig('modern'); assert.equal(config.ciphers, 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!3DES:!MD5:!PSK'); assert.equal(config.minimumTLSVersion, constants.SSL_OP_NO_TLSv1_1|constants.SSL_OP_NO_TLSv1|constants.SSL_OP_NO_SSLv3|constants.SSL_OP_NO_SSLv2); done(); }); test('intermediate config', function(done){ var config = sslConfig('intermediate'); assert.equal(config.ciphers, 'ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA:ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA256:DHE-RSA-AES256-SHA:ECDHE-ECDSA-DES-CBC3-SHA:ECDHE-RSA-DES-CBC3-SHA:EDH-RSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:DES-CBC3-SHA:!DSS:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA'); assert.equal(config.minimumTLSVersion, constants.SSL_OP_NO_SSLv3|constants.SSL_OP_NO_SSLv2); done(); }); test('old config', function(done){ var config = sslConfig('old'); assert.equal(config.ciphers, 'ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:ECDHE-RSA-DES-CBC3-SHA:ECDHE-ECDSA-DES-CBC3-SHA:EDH-RSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:DES-CBC3-SHA:HIGH:SEED:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!RSAPSK:!aDH:!aECDH:!EDH-DSS-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA:!SRP'); assert.equal(config.minimumTLSVersion, constants.SSL_OP_NO_SSLv2); done(); }); test('non-existent config', function(done){ assert.throws( function() { var config = sslConfig('banana'); }, Error ); done(); }); });
/* 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/. */ const $ = require('jquery'); const _ = require('underscore'); const {assert} = require('chai'); const Account = require('models/account'); const AuthErrors = require('lib/auth-errors'); const Backbone = require('backbone'); const BaseBroker = require('models/auth_brokers/base'); const Metrics = require('lib/metrics'); const Relier = require('models/reliers/relier'); const sinon = require('sinon'); const View = require('views/sign_in_totp_code'); const WindowMock = require('../../mocks/window'); const TOTP_CODE = '123123'; describe('views/sign_in_totp_code', () => { let account; let broker; let metrics; let model; let notifier; let relier; let view; let windowMock; beforeEach(() => { windowMock = new WindowMock(); relier = new Relier({ window: windowMock }); broker = new BaseBroker({ relier: relier, window: windowMock }); account = new Account({ email: 'a@a.com', sessionToken: 'someToken', uid: 'uid' }); model = new Backbone.Model({ account: account, lastPage: 'signin', password: 'password' }); notifier = _.extend({}, Backbone.Events); metrics = new Metrics({ notifier, sentryMetrics: { captureException () {} } }); view = new View({ broker, canGoBack: true, metrics, model, notifier, relier, viewName: 'sign-in-totp-code', window: windowMock }); sinon.stub(view, 'getSignedInAccount').callsFake(() => model.get('account')); $(windowMock.document.body).attr('data-flow-id', '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'); $(windowMock.document.body).attr('data-flow-begin', Date.now()); sinon.spy(view, 'logFlowEvent'); return view.render() .then(() => $('#container').html(view.$el)); }); afterEach(() => { metrics.destroy(); view.remove(); view.destroy(); view = metrics = null; }); describe('render', () => { it('renders the view', () => { assert.lengthOf(view.$('#fxa-totp-code-header'), 1); assert.include(view.$('.verification-totp-message').text(), 'security code'); assert.equal(view.$('#use-recovery-code-link').attr('href'), '/signin_recovery_code'); assert.equal(view.$('.different-account-link').attr('href'), '/signin'); }); describe('without an account', () => { beforeEach(() => { account = model.get('account').unset('sessionToken'); sinon.spy(view, 'navigate'); return view.render(); }); it('redirects to the signin page', () => { assert.isTrue(view.navigate.calledWith('signin')); }); }); }); describe('validateAndSubmit', () => { beforeEach(() => { sinon.stub(view, 'submit').callsFake(() => Promise.resolve()); sinon.spy(view, 'showValidationError'); }); describe('with an empty code', () => { beforeEach(() => { view.$('#totp-code').val(''); return view.validateAndSubmit().then(assert.fail, () => {}); }); it('displays a tooltip, does not call submit', () => { assert.isTrue(view.showValidationError.called); assert.isFalse(view.submit.called); }); }); const validCodes = [ TOTP_CODE, ' ' + TOTP_CODE, TOTP_CODE + ' ', ' ' + TOTP_CODE + ' ', '001-001', '111 111' ]; validCodes.forEach((code) => { describe(`with a valid code: '${code}'`, () => { beforeEach(() => { view.$('.totp-code').val(code); return view.validateAndSubmit(); }); it('calls submit', () => { assert.equal(view.submit.callCount, 1); }); }); }); }); describe('submit', () => { describe('success', () => { beforeEach(() => { sinon.stub(account, 'verifyTotpCode').callsFake(() => Promise.resolve({success: true})); sinon.stub(view, 'invokeBrokerMethod').callsFake(() => Promise.resolve()); view.$('.totp-code').val(TOTP_CODE); return view.submit(); }); it('calls correct broker methods', () => { assert.isTrue(account.verifyTotpCode.calledWith(TOTP_CODE), 'verify with correct code'); assert.isTrue(view.invokeBrokerMethod.calledWith('afterCompleteSignInWithCode', account)); }); it('logs flowEvent', () => { assert.equal(view.logFlowEvent.callCount, 1); }); }); describe('invalid TOTP code', () => { beforeEach(() => { sinon.stub(account, 'verifyTotpCode').callsFake(() => Promise.resolve({success: false})); sinon.spy(view, 'showValidationError'); view.$('.totp-code').val(TOTP_CODE); return view.submit(); }); it('rejects with the error for display', () => { assert.equal(view.showValidationError.args[0][1].errno, 1054, 'correct error thrown'); }); }); describe('errors', () => { beforeEach(() => { sinon.stub(account, 'verifyTotpCode').callsFake(() => Promise.reject(AuthErrors.toError('UNEXPECTED_ERROR'))); sinon.spy(view, 'showValidationError'); view.$('.totp-code').val(TOTP_CODE); return view.submit(); }); it('rejects with the error for display', () => { assert.equal(view.showValidationError.args[0][1].errno, 999, 'correct error thrown'); }); }); }); });
// Copyright 2011-2012 Norbert Lindenberg. All rights reserved. // Copyright 2012 Mozilla Corporation. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /** * @description Tests that the number of fractional digits is determined correctly for currencies. * @author Norbert Lindenberg */ // data from http://www.currency-iso.org/dl_iso_table_a1.xml, 2013-02-25 var currencyDigits = { AED: 2, AFN: 2, ALL: 2, AMD: 2, ANG: 2, AOA: 2, ARS: 2, AUD: 2, AWG: 2, AZN: 2, BAM: 2, BBD: 2, BDT: 2, BGN: 2, BHD: 3, BIF: 0, BMD: 2, BND: 2, BOB: 2, BOV: 2, BRL: 2, BSD: 2, BTN: 2, BWP: 2, BYR: 0, BZD: 2, CAD: 2, CDF: 2, CHE: 2, CHF: 2, CHW: 2, CLF: 4, CLP: 0, CNY: 2, COP: 2, COU: 2, CRC: 2, CUC: 2, CUP: 2, CVE: 2, CZK: 2, DJF: 0, DKK: 2, DOP: 2, DZD: 2, EGP: 2, ERN: 2, ETB: 2, EUR: 2, FJD: 2, FKP: 2, GBP: 2, GEL: 2, GHS: 2, GIP: 2, GMD: 2, GNF: 0, GTQ: 2, GYD: 2, HKD: 2, HNL: 2, HRK: 2, HTG: 2, HUF: 2, IDR: 2, ILS: 2, INR: 2, IQD: 3, IRR: 2, ISK: 0, JMD: 2, JOD: 3, JPY: 0, KES: 2, KGS: 2, KHR: 2, KMF: 0, KPW: 2, KRW: 0, KWD: 3, KYD: 2, KZT: 2, LAK: 2, LBP: 2, LKR: 2, LRD: 2, LSL: 2, LTL: 2, LVL: 2, LYD: 3, MAD: 2, MDL: 2, MGA: 2, MKD: 2, MMK: 2, MNT: 2, MOP: 2, MRO: 2, MUR: 2, MVR: 2, MWK: 2, MXN: 2, MXV: 2, MYR: 2, MZN: 2, NAD: 2, NGN: 2, NIO: 2, NOK: 2, NPR: 2, NZD: 2, OMR: 3, PAB: 2, PEN: 2, PGK: 2, PHP: 2, PKR: 2, PLN: 2, PYG: 0, QAR: 2, RON: 2, RSD: 2, RUB: 2, RWF: 0, SAR: 2, SBD: 2, SCR: 2, SDG: 2, SEK: 2, SGD: 2, SHP: 2, SLL: 2, SOS: 2, SRD: 2, SSP: 2, STD: 2, SVC: 2, SYP: 2, SZL: 2, THB: 2, TJS: 2, TMT: 2, TND: 3, TOP: 2, TRY: 2, TTD: 2, TWD: 2, TZS: 2, UAH: 2, UGX: 0, USD: 2, USN: 2, USS: 2, UYI: 0, UYU: 2, UZS: 2, VEF: 2, VND: 0, VUV: 0, WST: 2, XAF: 0, XCD: 2, XOF: 0, XPF: 0, YER: 2, ZAR: 2, ZMW: 2, ZWL: 2 }; Object.getOwnPropertyNames(currencyDigits).forEach(function (currency) { var digits = currencyDigits[currency]; format = Intl.NumberFormat([], {style: "currency", currency: currency}); var min = format.resolvedOptions().minimumFractionDigits; var max = format.resolvedOptions().maximumFractionDigits; if (min !== digits) { $ERROR("Didn't get correct minimumFractionDigits for currency " + currency + "; expected " + digits + ", got " + min + "."); } if (max !== digits) { $ERROR("Didn't get correct maximumFractionDigits for currency " + currency + "; expected " + digits + ", got " + max + "."); } });
var DB = require('./lib/db.js'); function SQLContext(options) { this.readOnly = options.isReadOnly; this.db = options.db; } function _put(db, key, value, callback) { db.createOrUpdate(key, value, function(err) { if(err) { return callback(err); } callback(); }); } SQLContext.prototype.putObject = function(key, value, callback) { if(this.readOnly) { return callback(new Error('write operation on read-only context.')); } var json = JSON.stringify(value); var buf = new Buffer(json, 'utf8'); _put(this.db, key, buf, callback); }; SQLContext.prototype.putBuffer = function(key, value, callback) { if(this.readOnly) { return callback(new Error('write operation on read-only context.')); } _put(this.db, key, value, callback); }; SQLContext.prototype.delete = function (key, callback) { if(this.readOnly) { return callback(new Error('write operation on read-only context.')); } this.db.remove(key, function(err) { if(err) { return callback(err); } callback(); }); }; SQLContext.prototype.clear = function (callback) { if(this.readOnly) { return callback(new Error('write operation on read-only context.')); } this.db.clearAll(callback); }; function _get(db, key, callback) { db.find(key, callback); } SQLContext.prototype.getObject = function(key, callback) { _get(this.db, key, function(err, data) { if(err) { return callback(err); } if(data) { try { data = JSON.parse(data.toString('utf8')); } catch(e) { return callback(e); } } callback(null, data); }); }; SQLContext.prototype.getBuffer = function(key, callback) { _get(this.db, key, callback); }; function SQLProvider(options) { this.options = options || {}; this.user = options.user; } SQLProvider.isSupported = function() { return (typeof module !== 'undefined' && module.exports); }; SQLProvider.prototype.open = function(callback) { if(!this.user) { return callback(new Error('missing user')); } this.db = new DB(this.options, function(err) { if (err) { return callback(err); } callback(); }); }; SQLProvider.prototype.getReadOnlyContext = function() { return new SQLContext({isReadOnly: true, db: this.db}); }; SQLProvider.prototype.getReadWriteContext = function() { return new SQLContext({isReadOnly: false, db: this.db}); }; // Forward db type constants SQLProvider.MYSQL = DB.MYSQL; SQLProvider.SQLITE = DB.SQLITE; SQLProvider.POSTGRES = DB.POSTGRES; SQLProvider.MARIADB = DB.MARIADB; module.exports = SQLProvider;
/* kJscsspFONT_FACE_RULE */ function jscsspFontFaceRule() { this.type = kJscsspFONT_FACE_RULE; this.parsedCssText = null; this.descriptors = []; this.parentStyleSheet = null; this.parentRule = null; } jscsspFontFaceRule.prototype = { cssText: function() { var rv = gTABS + "@font-face {\n"; var preservedGTABS = gTABS; gTABS += " "; for (var i = 0; i < this.descriptors.length; i++) rv += gTABS + this.descriptors[i].cssText() + "\n"; gTABS = preservedGTABS; return rv + gTABS + "}"; }, setCssText: function(val) { var sheet = {cssRules: []}; var parser = new CSSParser(val); var token = parser.getToken(true, true); if (token.isAtRule("@font-face")) { if (parser.parseFontFaceRule(token, sheet)) { var newRule = sheet.cssRules[0]; this.descriptors = newRule.descriptors; this.parsedCssText = newRule.parsedCssText; return; } } throw DOMException.SYNTAX_ERR; } };
'use strict'; QUnit.module('ellipse', function() { var boundaryOnAngle = function(ellipse, angle) { var a = ellipse.a; var b = ellipse.b; var rad = angle * Math.PI / 180; return g.Point(ellipse.x + a * Math.cos(rad), ellipse.y + b * Math.sin(rad)).round(); }; QUnit.test('validate helper boundaryOnAngle', function(assert) { var a = 150; var b = 50; var c = g.Point(0, 0); var ellipse = g.Ellipse(c, a, b); assert.propEqual(boundaryOnAngle(ellipse, 0), g.Point(150, 0)); assert.propEqual(boundaryOnAngle(ellipse, 90), (g.Point(0, 50))); assert.propEqual(boundaryOnAngle(ellipse, 180), (g.Point(-150, 0))); assert.propEqual(boundaryOnAngle(ellipse, 270), (g.Point(0, -50))); }); QUnit.module('constructor', function() { QUnit.test('creates a new Ellipse object', function(assert) { assert.ok(g.ellipse() instanceof g.ellipse); assert.ok(g.ellipse({ x: 1, y: 2 }, 3, 4) instanceof g.ellipse); assert.equal(g.ellipse({ x: 1, y: 2 }, 3, 4).x, 1); assert.equal(g.ellipse({ x: 1, y: 2 }, 3, 4).y, 2); assert.equal(g.ellipse({ x: 1, y: 2 }, 3, 4).a, 3); assert.equal(g.ellipse({ x: 1, y: 2 }, 3, 4).b, 4); assert.ok(g.ellipse(g.ellipse({ x: 1, y: 2 }, 3, 4)).equals(g.ellipse({ x: 1, y: 2 }, 3, 4))); // default values assert.ok(g.ellipse().equals(g.rect({ x: 0, y: 0 }, 0, 0))); }); }); QUnit.module('fromRect(rect)', function() { QUnit.test('creates a new Ellipse object', function(assert) { assert.ok(g.ellipse.fromRect(g.rect()) instanceof g.ellipse); var r = g.rect(100, 50, 150, 70); assert.ok(g.rect.fromEllipse(g.ellipse.fromRect(r)).equals(r)); }); }); QUnit.module('tangentTheta', function(hooks) { var radiusTangentAngle = function(ellipse, angle) { var theta = ellipse.tangentTheta(boundaryOnAngle(ellipse, angle), angle); return Math.round((theta + angle) % 180); }; QUnit.test('validate on circle', function(assert) { var a = 50; var b = 50; var c = g.Point(0, 0); var ellipse = g.Ellipse(c, a, b); for (var angle = 0; angle <= 360; angle += 10) { var tangentAngle = radiusTangentAngle(ellipse, angle); var tolerance = 2; assert.ok(tangentAngle - 90 < tolerance && tangentAngle - 90 > -tolerance, angle + 'deg, should be 90deg, actual: ' + tangentAngle); } }); QUnit.test('validate helper boundaryOnAngle', function(assert) { function checkTangentThetaOnEllipse(ellipse, message) { assert.equal(ellipse.tangentTheta(boundaryOnAngle(ellipse, 0)), 270, '0 on ' + message); assert.equal(ellipse.tangentTheta(boundaryOnAngle(ellipse, 180)), 90, '180 on ' + message); assert.equal(ellipse.tangentTheta(boundaryOnAngle(ellipse, 90)), 180, '90 on ' + message); assert.equal(ellipse.tangentTheta(boundaryOnAngle(ellipse, 270)), 0, '270 on ' + message); for (var angle = 0; angle <= 360; angle += 5) { var theta = ellipse.tangentTheta(boundaryOnAngle(ellipse, angle), angle); assert.ok(theta >= 0, 'tangent theta is numeric on ' + message); } } checkTangentThetaOnEllipse(g.Ellipse(g.Point(11, 22), 50, 100), 'wide ellipse'); checkTangentThetaOnEllipse(g.Ellipse(g.Point(11, 22), 100, 50), 'tall ellipse'); }); }); QUnit.module('Where is point in space with ellipse', function(hooks) { QUnit.test('normalizedDistance', function(assert) { var tolerance = 0.009; var ellipse = g.Ellipse(g.Point(111, 111), 150, 150); var r1 = ellipse.normalizedDistance(ellipse.center()); assert.ok(r1 < 1 && r1 >= 0); assert.ok(ellipse.normalizedDistance(ellipse.center().offset(500, 500)) > 1); for (var angle = 0; angle < 360; angle += 1) { var b = boundaryOnAngle(ellipse, angle); var x = ellipse.normalizedDistance(b); assert.ok(x - 1 < tolerance && x - 1 > -tolerance, 'point on angle: ' + angle + ' result:' + x); } }); }); QUnit.module('inflate()', function() { QUnit.test('inflate ellipse', function(assert) { assert.ok(g.ellipse({ x: 0, y: 0 }, 1, 1).inflate().equals(g.ellipse({ x: 0, y: 0 }, 1, 1))); assert.ok(g.ellipse({ x: 0, y: 0 }, 1, 1).inflate(2, 1).equals(g.ellipse({ x: 0, y: 0 }, 5, 3))); assert.ok(g.ellipse({ x: 0, y: 0 }, 1, 1).inflate(0, 1).equals(g.ellipse({ x: 0, y: 0 }, 1, 3))); assert.ok(g.ellipse({ x: 0, y: 0 }, 1, 1).inflate(2, 0).equals(g.ellipse({ x: 0, y: 0 }, 5, 1))); assert.ok(g.ellipse({ x: 0, y: 0 }, 1, 1).inflate(5).equals(g.ellipse({ x: 0, y: 0 }, 11, 11))); assert.ok(g.ellipse({ x: 0, y: 0 }, 1, 1).inflate(2).equals( g.ellipse.fromRect(g.rect.fromEllipse(g.ellipse({ x: 0, y: 0 }, 1, 1).inflate(2))) )); }); }); QUnit.module('prototype', function() { QUnit.module('bbox()', function() { }); QUnit.module('clone()', function() { }); QUnit.module('equals(ellipse)', function() { }); QUnit.module('intersectionWithLineFromCenterToPoint(point, angle)', function() { }); QUnit.module('toString()', function() { }); }); });
import { inject as service } from '@ember/service'; import Component from '@ember/component'; import { task } from 'ember-concurrency'; export default Component.extend({ router: service(), controlGroup: service(), store: service(), // public attrs model: null, controlGroupResponse: null, //internal state error: null, unwrapData: null, unwrap: task(function* (token) { let adapter = this.store.adapterFor('tools'); this.set('error', null); try { let response = yield adapter.toolAction('unwrap', null, { clientToken: token }); this.set('unwrapData', response.auth || response.data); this.controlGroup.deleteControlGroupToken(this.model.id); } catch (e) { this.set('error', `Token unwrap failed: ${e.errors[0]}`); } }).drop(), markAndNavigate: task(function* () { this.controlGroup.markTokenForUnwrap(this.model.id); let { url } = this.controlGroupResponse.uiParams; yield this.router.transitionTo(url); }).drop(), });
/* * This program is part of the OpenLMIS logistics management information system platform software. * Copyright © 2017 VillageReach * * This program is free software: you can redistribute it and/or modify it under the terms * of the GNU Affero 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 Affero General Public License for more details. You should have received a copy of * the GNU Affero General Public License along with this program. If not, see * http://www.gnu.org/licenses.  For additional information contact info@OpenLMIS.org.  */ (function() { 'use strict'; /** * @module admin-rejection-reason * * @description * Rejection Reason. */ angular.module('admin-rejection-reason', [ 'openlmis-rights', 'openlmis-admin', 'openlmis-class-extender', 'openlmis-i18n', 'openlmis-repository', 'openlmis-templates', 'openlmis-modal-state', 'ui.router' ]); })();
'use strict'; exports.up = function(knex, Promise) { return knex.schema.table('settings', function(table) { table.integer('next_invoice_number'); }); }; exports.down = function(knex, Promise) { return knex.schema.table('settings', function(t) { t.dropColumn('next_invoice_number'); }); };
import React, { Component, PropTypes } from 'react' import { updateCurrentUser, notify } from '../actions' import ListItemTagInput from './ListItemTagInput' export default class ProfileSkillsModule extends Component { static propTypes = { person: PropTypes.object } static contextTypes = { dispatch: PropTypes.func } constructor (props) { super(props) this.state = { tags: [], valid: false } } update = (type, tags) => { const valid = tags.length > 0 return this.setState({ tags, valid }) } save = () => { const { tags } = this.state const { dispatch } = this.context return Promise.all([ dispatch(updateCurrentUser({tags})), dispatch(notify('Skills added successfully.', {type: 'info'})) ]) } render () { const { update, save } = this const { person } = this.props const { valid } = this.state const firstName = person.name.split(' ')[0] return <div className='feed-module profile-skills'> <h2> Welcome {firstName}! Are there any skills, passions or interests you’d like to be known for in the community? </h2> <p> Pick “tags” to describe yourself and to find people and opportunities that match your interests. </p> <ListItemTagInput type='tags' className='modal-input' person={person} update={update} context='feed-module' /> <div className='meta'> Press Enter (Return) after each tag. Use a dash (-) between words in a tag. </div> <button type='button' className='btn-primary' disabled={!valid} onClick={save}> Save </button> </div> } }
var Password = require('../../lib/Interactor/Password.js'); var should = require('should'); describe('Password test', function() { var crypted = ''; it('should crypt a password', function() { crypted = Password.generate('testpass'); }); it('should fail with wrong password', function() { Password.verify('testpasds', crypted).should.be.false; }); it('should success with right password', function() { Password.verify('testpass', crypted).should.be.true; }); });
(function ($, undefined) { $.widget("ui.HarvesterInlineEditor", $.ui.CiteInlineEditor, { options: { }, _refreshView: function () { this._super(); //var item = this.option('item'); this.element.empty(); this.initEditor(); //this.showData(item); //this.setCurrentDisplayModeAndApply($.ui.CiteBaseControl.DisplayMode.Edit); }, initEditor: function () { var self = this; var definitionTable = $('<table></table>'); this.element.append(definitionTable); { var r = $('<tr></tr>'); var c = $('<td></td>'); this.sveEndpoint = $('<div id="' + $.ui.CiteBaseControl.generateControlId() + '"></div>'); c.append(this.sveEndpoint); var c2 = $('<td></td>'); var lbl = $('<label class="formFieldLabel" for="' + this.sveEndpoint[0].id + '">' + 'Endpoint' +'</label>'); c2.append(lbl); r.append(c2); r.append(c); definitionTable.append(r); this.sveEndpoint.CiteStringValueEditor({ currentDisplayMode: $.ui.CiteBaseControl.DisplayMode.Edit, autoInitialize: true }); } { var r = $('<tr></tr>'); var c = $('<td></td>'); this.sveEndpointAlias = $('<div id="' + $.ui.CiteBaseControl.generateControlId() + '"></div>'); c.append(this.sveEndpointAlias); var c2 = $('<td></td>'); var lbl = $('<label class="formFieldLabel" for="' + this.sveEndpointAlias[0].id + '">' + 'Endpoint Alias' +'</label>'); c2.append(lbl); r.append(c2); r.append(c); definitionTable.append(r); this.sveEndpointAlias.CiteStringValueEditor({ currentDisplayMode: $.ui.CiteBaseControl.DisplayMode.Edit, autoInitialize: true }); } { var r = $('<tr></tr>'); var c = $('<td></td>'); this.svePeriod = $('<div id="' + $.ui.CiteBaseControl.generateControlId() + '"></div>'); c.append(this.svePeriod); var c2 = $('<td></td>'); var lbl = $('<label class="formFieldLabel" for="' + this.svePeriod[0].id + '">' + 'Period' +'</label>'); c2.append(lbl); r.append(c2); r.append(c); definitionTable.append(r); this.svePeriod.CiteStringValueEditor({ currentDisplayMode: $.ui.CiteBaseControl.DisplayMode.Edit, autoInitialize: true }); } { var r = $('<tr></tr>'); var c = $('<td></td>'); this.asgPeriodType = $('<div id="' + $.ui.CiteBaseControl.generateControlId() + '"></div>'); c.append(this.asgPeriodType); var c2 = $('<td></td>'); var lbl = $('<label class="formFieldLabel" for="' + this.asgPeriodType[0].id + '">' + 'Period Type' +'</label>'); c2.append(lbl); r.append(c2); r.append(c); definitionTable.append(r); var suggestions = [{ 'Text': 'Seconds' , 'Value': 'SECONDS' }, { 'Text': 'Minutes' , 'Value': 'MINUTES' }, { 'Text': 'Hours' , 'Value': 'HOURS' }, { 'Text': 'Days' , 'Value': 'DAYS' }]; this.asgPeriodType.CiteAutoSuggest({ currentDisplayMode: $.ui.CiteBaseControl.DisplayMode.Edit, suggestionMode: $.ui.CiteAutoSuggest.SuggestionMode.Static, uiMode: $.ui.CiteAutoSuggest.UIMode.DropDown, selectionNameProperty: 'Text', selectionValueProperty: 'Value', staticSuggestions: suggestions, autoInitialize: true }); } { var r = $('<tr></tr>'); var c1 = $('<td></td>'); this.saveButton = $('<button id="cancel" name="save" class="btn btn-default" value="1">Save</button>'); c1.append(this.saveButton); var c2 = $('<td></td>'); this.cancelButton = $('<button id="cancel" name="cancel" class="btn btn-default" value="1">Cancel</button>'); c2.append(this.cancelButton); r.append(c1); r.append(c2); definitionTable.append(r); this.saveButton.on('click', function() { eval(self.options.saveCallback)(); }) this.cancelButton.on('click', function() { eval(self.options.cancelCallback)(); }) } }, getData: function () { var result = {}; result.endpoint = this.sveEndpoint.CiteStringValueEditor('getValue'); result.endpointAlias = this.sveEndpointAlias.CiteStringValueEditor('getValue'); result.period = this.svePeriod.CiteStringValueEditor('getValue'); var values = this.asgPeriodType.CiteAutoSuggest('getSelectedValues'); result.periodType = (values.length == 0) ? '' : values[0]; console.log(result); return result; } }) }(jQuery));
module.exports = (app) => { let Base58 = {}; Base58.alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'; Base58.alphabetMap = {}; for(let i = 0; i < Base58.alphabet.length; i++) { Base58.alphabetMap[Base58.alphabet.charAt(i)] = i } Base58.encode = function(buffer) { if (buffer.length === 0) return ''; let i, j, digits = [0]; for (i = 0; i < buffer.length; i++) { for (j = 0; j < digits.length; j++) digits[j] <<= 8 digits[digits.length - 1] += buffer[i]; let carry = 0; for (j = digits.length - 1; j >= 0; j--){ digits[j] += carry; carry = (digits[j] / 58) | 0; digits[j] %= 58 } while (carry) { digits.unshift(carry); carry = (digits[0] / 58) | 0; digits[0] %= 58 } } // deal with leading zeros for (i = 0; i < buffer.length - 1 && buffer[i] == 0; i++) digits.unshift(0) return digits.map(function(digit) { return Base58.alphabet[digit] }).join('') }; Base58.decode = function(string) { if (string.length === 0) return (new Uint8Array()); let input = string.split('').map(function(c){ return Base58.alphabetMap[c] }); let i, j, bytes = [0]; for (i = 0; i < input.length; i++) { for (j = 0; j < bytes.length; j++) bytes[j] *= 58 bytes[bytes.length - 1] += input[i]; let carry = 0; for (j = bytes.length - 1; j >= 0; j--){ bytes[j] += carry; carry = bytes[j] >> 8; bytes[j] &= 0xff } while (carry) { bytes.unshift(carry); carry = bytes[0] >> 8; bytes[0] &= 0xff } } // deal with leading zeros for (i = 0; i < input.length - 1 && input[i] == 0; i++) bytes.unshift(0) return (new Uint8Array(bytes)) }; app.factory('Base58', function() { return { encode: Base58.encode, decode: Base58.decode }; }); };
import React from 'react'; import SPELLS from 'common/SPELLS/index'; import { formatDuration } from 'common/format'; import StatisticBox, { STATISTIC_ORDER } from 'interface/others/StatisticBox'; import STATISTIC_CATEGORY from 'interface/others/STATISTIC_CATEGORY'; import SpellLink from 'common/SpellLink'; import SpellIcon from 'common/SpellIcon'; import Events from 'parser/core/Events'; import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer'; import SpellUsable from 'parser/shared/modules/SpellUsable'; import EventEmitter from 'parser/core/modules/EventEmitter'; import indexById from 'common/indexById'; import safeMerge from 'common/safeMerge'; import T_DEATH_KNIGHT from 'common/SPELLS/talents/deathknight'; import T_DEMON_HUNTER from 'common/SPELLS/talents/demonhunter'; import T_DRUID from 'common/SPELLS/talents/druid'; import T_HUNTER from 'common/SPELLS/talents/hunter'; import T_MAGE from 'common/SPELLS/talents/mage'; import T_MONK from 'common/SPELLS/talents/monk'; import T_PALADIN from 'common/SPELLS/talents/paladin'; import T_PRIEST from 'common/SPELLS/talents/priest'; import T_ROGUE from 'common/SPELLS/talents/rogue'; import T_SHAMAN from 'common/SPELLS/talents/shaman'; import T_WARLOCK from 'common/SPELLS/talents/warlock'; import T_WARRIOR from 'common/SPELLS/talents/warrior'; import DEATH_KNIGHT from 'common/SPELLS/deathknight'; import DEMON_HUNTER from 'common/SPELLS/demonhunter'; import DRUID from 'common/SPELLS/druid'; import HUNTER from 'common/SPELLS/hunter'; import MAGE from 'common/SPELLS/mage'; import MONK from 'common/SPELLS/monk'; import PALADIN from 'common/SPELLS/paladin'; import PRIEST from 'common/SPELLS/priest'; import ROGUE from 'common/SPELLS/rogue'; import SHAMAN from 'common/SPELLS/shaman'; import WARLOCK from 'common/SPELLS/warlock'; import WARRIOR from 'common/SPELLS/warrior'; const CLASS_ABILITIES = { ...safeMerge(T_DEATH_KNIGHT, T_DEMON_HUNTER, T_DRUID, T_HUNTER, T_MAGE, T_MONK, T_PALADIN, T_PRIEST, T_ROGUE, T_SHAMAN, T_WARLOCK, T_WARRIOR), ...safeMerge(DEATH_KNIGHT, DEMON_HUNTER, DRUID, HUNTER, MAGE, MONK, PALADIN, PRIEST, ROGUE, SHAMAN, WARLOCK, WARRIOR), }; indexById(CLASS_ABILITIES); const SMALL_TRUTH = 0.3; const BIG_TRUTH = 0.5; const debug = false; class IneffableTruth extends Analyzer { static dependencies = { spellUsable: SpellUsable, }; buffActive = false; lastTimestamp = 0; reducedDuration = []; reductionPercent = 0; constructor(...args) { super(...args); this.active = this.selectedCombatant.hasCorruptionByName("Ineffable Truth"); if (!this.active) { return; } this.reductionPercent += this.selectedCombatant.getCorruptionCount(SPELLS.INEFFABLE_TRUTH_T1.id) * SMALL_TRUTH; this.reductionPercent += this.selectedCombatant.getCorruptionCount(SPELLS.INEFFABLE_TRUTH_T2.id) * BIG_TRUTH; this.addEventListener(Events.applybuff.by(SELECTED_PLAYER).spell(SPELLS.INEFFABLE_TRUTH_BUFF), this.setBuffActive); this.addEventListener(Events.removebuff.by(SELECTED_PLAYER).spell(SPELLS.INEFFABLE_TRUTH_BUFF), this.setBuffInactive); this.addEventListener(EventEmitter.catchAll, this.reduceCooldowns); } setBuffActive(event) { this.buffActive = true; this.lastTimestamp = event.timestamp; } setBuffInactive() { this.buffActive = false; debug && this.log(this.reducedDuration); } reduceCooldowns(event) { if (!this.buffActive) { return; } /** * This is assuming that stacking this corruption works additive, might need adjustment in the future * 1x 50%: For every 1 second of elapsed time, reduce cooldowns for another 50% of that (0.5 seconds) * 1x 30% 1x 50%: For every 1 second of elapsed time, reduce cooldowns for another 80% of that (0.8 seconds) * 2x 50%: For every 1 second of elapsed time, reduce cooldowns for another 100% of that (1.0 seconds) */ const reduction = (event.timestamp - this.lastTimestamp) * this.reductionPercent; Object.keys(this.spellUsable._currentCooldowns) .filter(cd => CLASS_ABILITIES[cd]) .forEach(cooldown => { debug && this.log(cooldown); this.spellUsable.reduceCooldown(cooldown, reduction, event.timestamp); if (!this.reducedDuration[cooldown]) { this.reducedDuration[cooldown] = reduction; } else { this.reducedDuration[cooldown] += reduction; } }); this.lastTimestamp = event.timestamp; } get totalReduction() { return this.reducedDuration.reduce((acc, curr) => acc + curr, 0) / 1000; } statistic() { return ( <StatisticBox icon={<SpellIcon id={SPELLS.INEFFABLE_TRUTH_BUFF.id} />} value={`${formatDuration(this.totalReduction)} min reduction`} category={STATISTIC_CATEGORY.ITEMS} position={STATISTIC_ORDER.OPTIONAL(60)} label="Ineffable Truth" > <table className="table table-condensed"> <thead> <tr> <th /> <th>Spell</th> <th>Reduction</th> </tr> </thead> <tbody> { Object.entries(this.reducedDuration).map((cd) => ( <tr key={cd[0]}> <td><SpellIcon id={cd[0]} /></td> <td><SpellLink id={cd[0]} icon={false} /></td> <td>{formatDuration(cd[1] / 1000)}</td> </tr> ))} </tbody> </table> </StatisticBox> ); } } export default IneffableTruth;
var hook = require("../lib/resources/hook"); var hooks = require("hook.io-hooks"); var bodyParser = require('body-parser'); var mergeParams = require('merge-params'); var config = require('../config'); var themes = require('../lib/resources/themes'); var hooks = require('hook.io-hooks'); module['exports'] = function view (opts, callback) { var req = opts.request, res = opts.response; var $ = this.$, self = this; if (!req.isAuthenticated()) { req.session.redirectTo = "/new"; return res.redirect('/login'); } var user = req.session.user; var boot = { owner: user }; bodyParser()(req, res, function bodyParsed(){ mergeParams(req, res, function(){}); var params = req.resource.params; var gist = params.gist; if (req.method === "POST") { if (params.name.length === 0) { return res.end('Hook name is required!'); } // do not recreate hooks that already exist with that name params.owner = user || "Marak"; // hardcode Marak for testing if (typeof params.theme === 'string' && params.theme.length === 0) { delete params.theme; } if (typeof params.presenter === 'string' && params.presenter.length === 0) { delete params.presenter; } var query = { name: params.name, owner: req.session.user }; return hook.find(query, function(err, results){ if (results.length > 0) { var h = results[0]; return res.end('Hook already exists ' + '/' + h.owner + "/" + h.name); //return res.redirect('/' + h.owner + "/" + h.name + "?alreadyExists=true"); } params.cron = params.cronString; if (params.hookSource === "editor") { delete params.gist; params.source = params.codeEditor; } // TODO: filter params for only specified resource fields? return hook.create(params, function(err, result){ if (err) { return callback(null, err.message); } var h = result; req.hook = h; if (params.hookSource === "editor") { // the source of the hook is coming from the code editor return res.redirect('/' + h.owner + "/" + h.name + ""); } else { // the source of the hook is coming from a github gist opts.gist = gist; opts.req = opts.request; opts.res = opts.response; // fetch the hook from github and check if it has a schema / theme // if so, attach it to the hook document // TODO: can we remove this? it seems like this logic should be in the Hook.runHook execution chain... hook.fetchHookSourceCode(opts, function(err, code){ if (err) { return opts.res.end(err.message); } hook.attemptToRequireUntrustedHook(opts, function(err, _module){ if (err) { return opts.res.end(err.message) } h.mschema = _module.schema; h.theme = _module.theme; h.presenter = _module.presenter; h.save(function(){ // redirect to new hook friendly page return res.redirect('/' + h.owner + "/" + h.name + ""); //return callback(null, JSON.stringify(result, true, 2)); }); }); }); } }); }); } if (typeof req.session.gistLink === 'string') { // todo: after created, unset gistSource so it doesn't keep popping up $('.gist').attr('value', req.session.gistLink); } else { $('.gistStatus').remove(); } var services = hooks.services; var examples = {}; // pull out helloworld examples for every langauge hook.languages.forEach(function(l){ examples[l] = services['examples-' + l + '-helloworld']; }); boot.examples = examples; /* for (var e in examples) { for (var code in examples[e]) { // $('.services').append(examples[e][code]); } } */ self.parent.components.themeSelector.present({}, function(err, html){ var el = $('.themeSelector') el.html(html); var out = $.html(); out = out.replace('{{hook}}', JSON.stringify(boot, true, 2)); callback(null, out); }) }); };
'use strict'; /** * @ngdoc directive * @name FlyveMDM.directive:loggedUserMenu * @description * # loggedUserMenu */ angular.module('FlyveMDM') .directive('loggedUserMenu', function () { return { templateUrl: 'views/loggedusermenu.html', restrict: 'E', link: function postLink(scope) { scope.opened = false; scope.fabModOpened = false; angular.element(document.querySelector('nav > ul.menu')).css({ }); scope.$watch('fabModOpened', function (opened) { if (opened) { angular.element(document.querySelector('nav > ul.menu')).removeClass('fab-usermenu-closed'); } else { angular.element(document.querySelector('nav > ul.menu')).addClass('fab-usermenu-closed'); } }); }, scope: {}, controller: function ($scope, AuthProvider) { var handleClickOutside = function () { $scope.$apply(function () { $scope.forceClose(); }); }; $scope.toggleOpened = function ($event) { $event.stopPropagation(); $scope.opened = !$scope.opened; if ($scope.opened) { angular.element(document.querySelector('html')).on('click', handleClickOutside); } }; $scope.forceClose = function () { $scope.opened = false; angular.element(document.querySelector('html')).off('click', handleClickOutside); return true; }; $scope.disconnect = function () { AuthProvider.logout().then(function () { AuthProvider.showLogin(); }); }; $scope.$on('$destroy', function () { angular.element(document.querySelector('html')).off('click', handleClickOutside); }); } }; });
import React from 'react'; import reactCSS from 'reactcss'; import { Swatch } from 'react-color/lib/components/common'; export const SwatchesColor = ({ color, onClick = () => {}, onSwatchHover, first, last, active, }) => { const styles = reactCSS( { default: { color: { width: '40px', height: '24px', cursor: 'pointer', background: color, marginBottom: '1px', }, check: { fill: '#fff', marginLeft: '8px', display: 'none', }, }, first: { color: { overflow: 'hidden', borderRadius: '2px 2px 0 0', }, }, last: { color: { overflow: 'hidden', borderRadius: '0 0 2px 2px', }, }, active: { check: { display: 'block', }, }, 'color-#FFFFFF': { color: { boxShadow: 'inset 0 0 0 1px #ddd', }, check: { fill: '#333', }, }, transparent: { check: { fill: '#333', }, }, }, { first, last, active, 'color-#FFFFFF': color === '#FFFFFF', transparent: color === 'transparent', }, ); return ( <Swatch color={color} style={styles.color} onClick={onClick} onHover={onSwatchHover} focusStyle={{ boxShadow: `0 0 4px ${color}` }} > <div style={styles.check}> <svg style={{ width: '24px', height: '24px' }} viewBox="0 0 24 24"> <path d="M21,7L9,19L3.5,13.5L4.91,12.09L9,16.17L19.59,5.59L21,7Z" /> </svg> </div> </Swatch> ); }; export default SwatchesColor;
function handleRace(data_races) { var ch_race; var ch_side; for (var ra in data_races.races) { if (data_races.races[ra].id === character_data.race) { ch_race = data_races.races[ra].name; ch_side = data_races.races[ra].side; } else { } } document.querySelector('div.info_image span.rac').textContent = ch_race; //$('div.info_image span.rac').text(ch_race); //document.querySelector('div.info_image div.sid').textContent = ch_side; //$('div.info_image div.sid').text(ch_side); } function handleClass(data_classes) { var ch_class; for (var cl in data_classes.classes) { if (data_classes.classes[cl].id === character_data.class) { ch_class = data_classes.classes[cl].name; } else { } } document.querySelector('div.info_image span.clss'). textContent = ch_class; //$('div.info_image span.clss').text(ch_class); } var character_data; function fetch_char(data) { character_data = data; // fetch image - card format var region = document.querySelector('input[name=region]:checked').value; var str = data.thumbnail; var pieces = []; pieces = str.split('-a'); var card = 'http://' + region + '.battle.net/static-render/' + region + '/' + pieces[0] + '-card.jpg'; // type of images: -avarar, -card, -profilemain, -inset document.querySelector('div.info_image').style.backgroundImage = 'url("' + card + '")'; // character data var ch_name = data.name; document.querySelector('div.info_image span.titl').textContent = ''; for (var tit in data.titles) { if (data.titles[tit].selected) { var my_title = data.titles[tit].name; my_title = my_title.replace('%s', ''); document.querySelector('div.info_image span.titl').textContent = my_title; } } document.querySelector('div.info_image span.nam').textContent = ch_name; url = 'http://' + region + '.battle.net/api/wow/data/character/races'; jsonp_request(url, 'handleRace'); url2 = 'http://' + region + '.battle.net/api/wow/data/character/classes'; jsonp_request(url2, 'handleClass'); var ch_gender = (data.gender === 0) ? 'Male' : 'Female'; var ch_level = data.level; document.querySelector('div.info_image span.levl').textContent = ch_level; var ch_guild = (data.guild) ? data.guild.name : ''; document.querySelector('div.info_image div.gld').textContent = ch_guild; var ch_server = data.realm; document.querySelector('div.info_image div.srv').textContent = ch_server; var ch_achiv = data.achievementPoints; document.querySelector('div.info_image div.achiv').innerHTML = ('<div class="achiv_icon"></div> ' + ch_achiv); // create character history var history_li = document.createElement('li'); history_li.dataset.name = ch_name; history_li.dataset.server = ch_server; history_li.dataset.region = region; history_li.innerHTML = '<aside>' + '<img src="' + 'http://' + region + '.battle.net/static-render/' + region + '/' + data.thumbnail + '"></img>' + '</aside>' + '<p>' + ch_name + '</p>' + '<p>' + ch_server + ' - ' + region.toUpperCase() + '</p>'; document.querySelector('ul.history').insertBefore(history_li, document.querySelector('ul.history').firstChild); // recall character form history [].forEach.call(document.querySelectorAll('ul.history > li'), function(li) { li.addEventListener('click', function() { document.querySelector('input[name=region][value=' + this.dataset.region + ']').checked = true; document.querySelector('input[name=server_name]').value = this.dataset.server; document.querySelector('input[name=char_name]').value = this.dataset.name; }); }); } // ON CLICK FUNCTION TO FETCH CHARACTER PETS (function() { document.getElementById('char_button').addEventListener('click', function() { var region = document.querySelector('input[name=region]:checked').value; var server_name = document.querySelector('input[name=server_name]').value; var char_name = document.querySelector('input[name=char_name]').value; var url = 'http://' + region + '.battle.net/api/wow/character/' + server_name + '/' + char_name + '?fields=guild,titles'; jsonp_request(url, 'fetch_char'); document.getElementById('general_panel').style.display = 'block'; document.getElementById('home_panel').style.display = 'none'; }); })(); //////////////////////////////////
/* * Copyright 2015 Trim-marks Inc. * * This file is part of Vivliostyle UI. * * Vivliostyle UI is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Vivliostyle UI 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 Vivliostyle UI. If not, see <http://www.gnu.org/licenses/>. */ import vivliostyle from "../../../src/vivliostyle"; import PageViewMode from "../../../src/models/page-view-mode"; import ViewerOptions from "../../../src/models/viewer-options"; import ZoomOptions from "../../../src/models/zoom-options"; import urlParameters from "../../../src/stores/url-parameters"; import vivliostyleMock from "../../mock/models/vivliostyle"; describe("ViewerOptions", function () { let history, location; vivliostyleMock(); beforeEach(function () { history = urlParameters.history; urlParameters.history = {}; location = urlParameters.location; }); afterEach(function () { urlParameters.history = history; urlParameters.location = location; }); describe("constructor", function () { it("retrieves parameters from URL", function () { urlParameters.location = { href: "http://example.com#spread=true" }; let options = new ViewerOptions(); expect(options.pageViewMode()).toEqual(PageViewMode.SPREAD); urlParameters.location = { href: "http://example.com#spread=false" }; options = new ViewerOptions(); expect(options.pageViewMode()).toBe(PageViewMode.SINGLE_PAGE); urlParameters.location = { href: "http://example.com#spread=auto" }; options = new ViewerOptions(); expect(options.pageViewMode()).toBe(PageViewMode.AUTO_SPREAD); }); it("copies parameters from the argument", function () { const other = new ViewerOptions(); other.pageViewMode(PageViewMode.SINGLE_PAGE); other.fontSize(20); other.zoom(ZoomOptions.createFromZoomFactor(1.2)); const options = new ViewerOptions(other); expect(options.pageViewMode()).toBe(PageViewMode.SINGLE_PAGE); expect(options.fontSize()).toBe(20); expect(options.zoom().zoom).toBe(1.2); expect(options.zoom().fitToScreen).toBe(false); }); }); it("write spread option back to URL when update if it is constructed with no argument", function () { urlParameters.location = { href: "http://example.com#spread=true" }; let options = new ViewerOptions(); options.pageViewMode(PageViewMode.SINGLE_PAGE); expect(urlParameters.location.href).toBe("http://example.com#spread=false"); options.pageViewMode(PageViewMode.SPREAD); expect(urlParameters.location.href).toBe("http://example.com#spread=true"); // options.pageViewMode(PageViewMode.AUTO_SPREAD); // expect(urlParameters.location.href).toBe("http://example.com#spread=auto"); // not write back if it is constructed with another ViewerOptions const other = new ViewerOptions(); other.pageViewMode(PageViewMode.SINGLE_PAGE); other.fontSize(20); other.zoom(ZoomOptions.createFromZoomFactor(1.2)); options = new ViewerOptions(other); options.pageViewMode(PageViewMode.SPREAD); expect(urlParameters.location.href).toBe("http://example.com#spread=false"); }); describe("copyFrom", function () { it("copies parameters from the argument to itself", function () { const options = new ViewerOptions(); options.pageViewMode(PageViewMode.SPREAD); options.fontSize(10); options.zoom(ZoomOptions.createFromZoomFactor(1.4)); const other = new ViewerOptions(); other.pageViewMode(PageViewMode.SINGLE_PAGE); other.fontSize(20); other.zoom(ZoomOptions.createFromZoomFactor(1.2)); options.copyFrom(other); expect(options.pageViewMode()).toBe(PageViewMode.SINGLE_PAGE); expect(options.fontSize()).toBe(20); expect(options.zoom().zoom).toBe(1.2); expect(options.zoom().fitToScreen).toBe(false); }); }); describe("toObject", function () { it("converts parameters to an object", function () { const options = new ViewerOptions(); options.pageViewMode(PageViewMode.SPREAD); options.fontSize(20); options.zoom(ZoomOptions.createFromZoomFactor(1.2)); expect(options.toObject()).toEqual({ fontSize: 20, pageViewMode: vivliostyle.viewer.PageViewMode.SPREAD, zoom: 1.2, fitToScreen: false, renderAllPages: true, }); }); }); });
const express = require('express'); const feedr = require('feedr').create(); const router = express.Router(); router.get('/', (req, res) => { feedr.readFeed('https://blog.schul-cloud.org/rss', { requestOptions: { timeout: 2000 }, }, (err, data) => { let blogFeed; try { blogFeed = data.rss.channel[0].item .filter((item) => (item['media:content'] || []).length && (item.link || []).length) .slice(0, 3) .map((e) => { const date = new Date(e.pubDate); const locale = 'en-us'; const month = date.toLocaleString(locale, { month: 'long' }); e.pubDate = `${date.getDate()}. ${month}`; e.description = e.description.join(' '); e.url = e.link[0]; e.img = { src: e['media:content'][0].$.url, alt: e.title, }; return e; }); } catch (e) { blogFeed = []; } res.send({ blogFeed, }); }); }); module.exports = router;
/* test/auth_route_spec.js -- test Authentication helper * Copyright 2014 Sergei Ianovich * * Licensed under AGPL-3.0 or later, see LICENSE * Process Control Service Web Interface */ var expect = require('expect.js'); var Routes = require('../routes/_auth'); var User = require('../models/user'); describe('Authentication helper', function() { describe("#authenticate", function() { describe("when request for not html page", function() { it("should send 401 if session is not inited", function(done) { var req = { session: {}, url: "someurl", headers: {accept: 'application/json'} }, res = { send: function(code) { expect(code).to.eql(401); done(); }}; Routes.authenticate(req, res, null); }); it("should send 401 if user is not found", function(done) { var req = { session: { operator: 2220 }, headers: {accept: 'application/json'} }, res = { send: function(code) { expect(code).to.eql(401); done(); }}; Routes.authenticate(req, res, null); }); }); describe("when request for html page", function() { it("should redirect to signin if session is not inited", function(done) { var req = { session: {}, url: "someurl", headers: {accept: 'application/html'} }, res = { redirect: function(url) { expect(url).to.eql("/signin"); done(); }}; Routes.authenticate(req, res, null); }); it("should reload if user is not found", function(done) { var req = { session: { operator: 2220 }, headers: {accept: 'application/html'} }, res = { redirect: function(url) { expect(url).to.eql('/signin'); done(); }}; Routes.authenticate(req, res, null); }); }); it("should assign operator", function(done) { var user = null; var userAttrs = { name: "Example User", email: "user@example.com", password: 'password', confirmation: 'password', }; (new User(userAttrs)).save(function(err, user) { var req = { session: { operator: user.email } }, res = { locals: { } }, next = function() { expect(res.locals.operator.toJSON()).to.eql(user.toJSON()); expect(req.operator.toJSON()).to.eql(user.toJSON()); done(); }; Routes.authenticate(req, res, next); }); }); }); });
/** * Model for Devices */ Ext.define('FHEM.model.DeviceModel', { extend: 'Ext.data.Model', fields: [ { name: 'DEVICE', type: 'text' } ] });
/* Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'image2', 'sq', { alt: 'Tekst Alternativ', btnUpload: 'Dërgo në server', captioned: 'Captioned image', // MISSING captionPlaceholder: 'Caption', // MISSING infoTab: 'Informacione mbi Fotografinë', lockRatio: 'Mbyll Racionin', menu: 'Karakteristikat e Fotografisë', pathName: 'foto', pathNameCaption: 'caption', // MISSING resetSize: 'Rikthe Madhësinë', resizer: 'Click and drag to resize', // MISSING title: 'Karakteristikat e Fotografisë', uploadTab: 'Ngarko', urlMissing: 'Mungon URL e burimit të fotografisë.', altMissing: 'Alternative text is missing.' // MISSING } );
/* * This file is part of huborcid. * * huborcid is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * huborcid 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 huborcid. If not, see <http://www.gnu.org/licenses/>. */ // GamePad API // https://dvcs.w3.org/hg/gamepad/raw-file/default/gamepad.html // By Eric Bidelman // FF has Gamepad API support only in special builds, but not in any release (even behind a flag) // Their current implementation has no way to feature detect, only events to bind to. // http://www.html5rocks.com/en/tutorials/doodles/gamepad/#toc-featuredetect // but a patch will bring them up to date with the spec when it lands (and they'll pass this test) // https://bugzilla.mozilla.org/show_bug.cgi?id=690935 Modernizr.addTest('gamepads', !!Modernizr.prefixed('getGamepads', navigator));
define(function(require) { 'use strict'; var _ = require('underscore'); var PIXI = require('pixi'); var ArrowView = require('common/v3/pixi/view/arrow'); var Constants = require('constants'); var EFieldDetectorArrowView = ArrowView.extend({ initialize: function(options) { options = _.extend({ label: 'An Arrow', tailWidth: 8, headWidth: 20, headLength: 20, fillColor: Constants.EFieldDetectorView.DISPLAY_COLOR }, options); this.label = options.label; this.model = new ArrowView.ArrowViewModel({ originX: 0, originY: 0, targetX: 0, targetY: 0, minLength: null }); this.scale = 1; this.value = 0; ArrowView.prototype.initialize.apply(this, [ options ]); }, initGraphics: function() { ArrowView.prototype.initGraphics.apply(this, arguments); var textStyle = { font: '11px Helvetica Neue', fill: Constants.EFieldDetectorView.DISPLAY_COLOR }; var label = new PIXI.Text(this.label, textStyle); var value = new PIXI.Text('10 V/m', textStyle); label.resolution = this.getResolution(); value.resolution = this.getResolution(); value.y = 12; this.text = new PIXI.Container(); this.text.addChild(label); this.text.addChild(value); this.displayObject.addChild(this.text); this.labelText = label; this.valueText = value; this.update(); this.drawArrow(); }, update: function() { var length = this.value * this.scale; this.model.set('targetY', this.model.get('originY') + length); this.updateText(); }, updateText: function(defaultDirection) { var length = this.value * this.scale; if (length === 0 && !defaultDirection) this.text.y = Math.round(-this.text.height / 2); else if (length > 0 || (defaultDirection && defaultDirection < 0)) this.text.y = Math.round(-this.text.height + 4); else this.text.y = 4; this.labelText.x = Math.round(-this.labelText.width / 2); this.valueText.x = Math.round(-this.valueText.width / 2); this.valueText.text = Math.abs(Math.round(this.value)) + ' V/m'; }, setScale: function(scale) { this.scale = scale; this.update(); }, setValue: function(value) { this.value = value; this.update(); }, alignTextAbove: function() { this.updateText(-1); }, alignTextBelow: function() { this.updateText(1); }, centerOn: function(x, y) { this.model.centerOn(x, y); this.updateText(); }, moveToY: function(y) { this.model.moveTo(this.model.get('originX'), y); }, getTotalHeight: function() { return this.displayObject.height; }, getArrowHeight: function() { return Math.abs(Math.round(this.value)); }, getTextHeight: function() { return this.text.height; }, getOriginY: function() { return this.model.get('originY'); }, getTargetY: function() { return this.model.get('targetY'); }, showValue: function() { this.valueText.visible = true; }, hideValue: function() { this.valueText.visible = false; } }); return EFieldDetectorArrowView; });
import * as R from 'ramda'; import { getPatchPath } from 'xod-project'; import { isAmong } from 'xod-func-tools'; import { def } from './types'; import { CHANGE_TYPES } from './constants'; const isEqualPatchPaths = def( 'isEqualPatchPaths :: Patch -> Patch -> Boolean', R.useWith(R.equals, [getPatchPath, getPatchPath]) ); const createPatchChange = def( 'createPatchChange :: AnyChangeType -> Patch -> AnyPatchChange', (changeType, patch) => R.compose( R.when( () => changeType === CHANGE_TYPES.ADDED || changeType === CHANGE_TYPES.MODIFIED, R.assoc('data', patch) ), R.applySpec({ path: getPatchPath, changeType: R.always(changeType), }) )(patch) ); export const calculateAdded = def( 'calculateAdded :: [Patch] -> [Patch] -> [AddedPatchChange]', R.compose( R.map(createPatchChange(CHANGE_TYPES.ADDED)), R.flip(R.differenceWith(isEqualPatchPaths)) ) ); export const calculateModified = def( 'calculateModified :: [Patch] -> [Patch] -> [ModifiedPatchChange]', (before, after) => { const beforeIds = R.map(getPatchPath, before); return R.compose( R.map(createPatchChange(CHANGE_TYPES.MODIFIED)), R.difference(R.__, before), R.filter(R.compose(isAmong(beforeIds), getPatchPath)) )(after); } ); export const calculateDeleted = def( 'calculateDeleted :: [Patch] -> [Patch] -> [DeletedPatchChange]', R.compose( R.map(createPatchChange(CHANGE_TYPES.DELETED)), R.differenceWith(isEqualPatchPaths) ) ); export const calculateDiff = def( 'calculateDiff :: [Patch] -> [Patch] -> [AnyPatchChange]', R.converge(R.unapply(R.unnest), [ calculateAdded, calculateModified, calculateDeleted, ]) );
import 'mad/model/model'; import 'mad/model/serializer/cake_serializer'; /** * @inherits {mad.Model} * @parent index * * The GroupUser model * * @constructor * Creates a groupUser * @param {array} options * @return {passbolt.model.GroupUser} */ var GroupUser = passbolt.model.GroupUser = mad.Model.extend('passbolt.model.GroupUser', /** @static */ { /* ************************************************************** */ /* MODEL DEFINITION */ /* ************************************************************** */ validateRules: { }, attributes: { id: 'string', group_id: 'string', user_id: 'string', User: 'passbolt.model.User.model', Group: 'passbolt.model.Group.model' }, membershipType: { 0 : __('Member'), 1 : __('Group manager') }, /* ************************************************************** */ /* CRUD FUNCTION */ /* ************************************************************** */ /** * Create a new groupUser * @param {array} attrs Attributes of the new groupUser * @return {jQuery.Deferred) */ create : function (attrs, success, error) { var self = this; var params = mad.model.serializer.CakeSerializer.to(attrs, this); return mad.net.Ajax.request({ url: APP_URL + 'groupsUsers', type: 'POST', params: params, success: success, error: error }).pipe(function (data, textStatus, jqXHR) { // pipe the result to convert cakephp response format into can format // else the new attribute are not well placed var def = $.Deferred(); def.resolveWith(this, [mad.model.serializer.CakeSerializer.from(data, self)]); return def; }); }, /** * Destroy a groupUser following the given parameter * @params {string} id the id of the instance to remove * @return {jQuery.Deferred) */ destroy : function (id, success, error) { var params = {id:id}; return mad.net.Ajax.request({ url: APP_URL + 'groupsUsers/{id}', type: 'DELETE', params: params, success: success, error: error }); }, /** * Find a groupUser following the given parameter * @param {array} params Optional parameters * @return {jQuery.Deferred) */ findOne: function (params, success, error) { params.children = params.children || false; return mad.net.Ajax.request({ url: APP_URL + 'groupsUsers/{id}.json', type: 'GET', params: params, success: success, error: error }); }, /** * Find a bunch of groupsUsers following the given parameters * @param {array} params Optional parameters * @return {jQuery.Deferred) */ findAll: function (params, success, error) { return mad.net.Ajax.request({ url: APP_URL + 'groupsUsers.json', type: 'GET', params: params, success: success, error: error }); }, update : function(id, attrs, success, error) { var self = this; // remove not desired attributes delete attrs.created; delete attrs.modified; // format data as expected by cakePHP var params = mad.model.serializer.CakeSerializer.to(attrs, this); // add the root of the params, it will be used in the url template params.id = id; return mad.net.Ajax.request({ url: APP_URL + 'groupsUsers/{id}', type: 'PUT', params: params, success: success, error: error }).pipe(function (data, textStatus, jqXHR) { // pipe the result to convert cakephp response format into can format var def = $.Deferred(); def.resolveWith(this, [mad.model.serializer.CakeSerializer.from(data, self)]); return def; }); } }, /** @prototype */ { }); export default GroupUser;
// Xiongxiong // Bearer token codec // AGPLv3 or later // Copyright (c) 2014, 2015 Genome Research Limited var crypto = require('crypto'); module.exports = function(/* privateKey, lifetime, algorithm OR hash */) { var privateKey, lifetime, algorithm, xiongxiong; // Parse arguments if (arguments.length) { // Try to get options from hash first, then fallback to positional // and finally, where appropriate, to defaults privateKey = arguments[0].privateKey || arguments[0]; lifetime = parseInt(arguments[0].lifetime || arguments[1], 10) || 3600; algorithm = arguments[0].algorithm || arguments[2] || 'sha1'; // Private key must be a string or a buffer if (!(typeof privateKey == 'string' || privateKey instanceof Buffer)) { throw new TypeError('Invalid arguments: Private key must be a string or buffer'); } } else { // Need at least a private key throw new Error('No private key specified'); } var getHMAC = (function() { // Check algorithm is supported if (crypto.getHashes().indexOf(algorithm) < 0) { throw new Error('Unsupported hash algorithm \'' + algorithm + '\''); } return function(message) { var hmac = crypto.createHmac(algorithm, privateKey); hmac.setEncoding('base64'); hmac.end(message); return hmac.read(); }; })(); // Return value xiongxiong = { encode: function(data, callback) { // Flatten array if (Array.isArray(data)) { data = data.join(':'); } if (typeof data != 'string') { callback(new TypeError('Invalid arguments: Seed data must be a string or array of strings'), null); } else { // Create a 48-bit salt crypto.randomBytes(6, function(err, salt) { if (err) { callback(err, null); } else { var expiration = Math.floor(Date.now() / 1000) + lifetime, message = [data, expiration, salt.toString('base64')].join(':'), // Generate HMAC of data:expiration:salt password = getHMAC(message); // Return token and basic authentication pair callback(null, Object.freeze({ expiration: expiration, // Unix epoch accessToken: (new Buffer([message, password].join(':'))).toString('base64'), basicLogin: (new Buffer(message)).toString('base64'), basicPassword: password })); } }); } }, decode: function(/* bearer/basic auth data */) { var output = {}; switch (arguments.length) { case 1: // Split bearer token and decode as basic auth var accessToken = (new Buffer(arguments[0], 'base64')).toString().split(':'); var basicPassword = accessToken.pop(), basicLogin = (new Buffer(accessToken.join(':'))).toString('base64'); output = this.decode(basicLogin, basicPassword); break; case 2: // Basic authentication data var basicLogin = (new Buffer(arguments[0], 'base64')).toString(), extracted = basicLogin.split(':'), basicPassword = arguments[1]; // Pass the salt extracted.pop(); // Expiration is penultimate element // n.b., JavaScript Date in ms, hence x1000 on Unix epoch Object.defineProperty(output, 'expiration', { configurable: false, writable: false, enumerable: true, value: new Date(parseInt(extracted.pop(), 10) * 1000) }); // Convert to string if we only have one element remaining Object.defineProperty(output, 'data', { configurable: false, writable: false, enumerable: true, value: extracted.length == 1 ? extracted[0] : extracted, }); // Validity check Object.defineProperty(output, 'valid', { configurable: false, enumerable: true, get: (function() { if (basicPassword == getHMAC(basicLogin)) { return function() { // Match: Valid until expiration return Date.now() <= this.expiration; }; } else { // No match: Invalid return function() { return false; } } })() }); break; default: Object.defineProperty(output, 'valid', { configurable: false, writable: false, enumerable: true, value: false }); break; } return Object.freeze(output); } }; // Set aliases (legacy API) xiongxiong.create = xiongxiong.encode; xiongxiong.extract = xiongxiong.decode; return Object.freeze(xiongxiong); };
// Generated by CoffeeScript 1.7.1 var Application, Manifest, americano; americano = require('americano-cozy'); Manifest = require('../lib/manifest').Manifest; module.exports = Application = americano.getModel('Application', { name: String, displayName: String, description: String, slug: String, state: String, isStoppable: { type: Boolean, "default": false }, date: { type: Date, "default": Date.now }, icon: String, iconPath: String, git: String, errormsg: String, branch: String, port: Number, permissions: Object, password: String, homeposition: Object, widget: String, version: String, needsUpdate: { type: Boolean, "default": false }, _attachments: Object }); Application.all = function(params, callback) { return Application.request("bySlug", params, callback); }; Application.destroyAll = function(params, callback) { return Application.requestDestroy("all", params, callback); }; Application.prototype.checkForUpdate = function(callback) { var manifest, setFlag; setFlag = (function(_this) { return function() { _this.needsUpdate = true; return _this.save(function(err) { if (err) { return callback(err); } else { return callback(null, true); } }); }; })(this); if (this.needsUpdate) { return callback(null, false); } else { manifest = new Manifest(); return manifest.download(this, (function(_this) { return function(err) { var repoVersion; if (err) { return callback(err); } else { repoVersion = manifest.getVersion(); if (repoVersion == null) { return callback(null, false); } else if (_this.version == null) { return setFlag(); } else if (_this.version !== repoVersion) { return setFlag(); } else { return callback(null, false); } } }; })(this)); } }; Application.prototype.getHaibuDescriptor = function() { var descriptor; descriptor = { user: this.slug, name: this.slug, domain: "127.0.0.1", repository: { type: "git", url: this.git }, scripts: { start: "server.coffee" }, password: this.password }; if ((this.branch != null) && this.branch !== "null") { descriptor.repository.branch = this.branch; } return descriptor; };
'use strict'; angular.module('BattleShipApp.directives', []). directive('appVersion', ['version', function (version) { return function (scope, elm, attrs) { elm.text(version); }; }]);
define('jst/ExternalTools/ExternalToolsCollectionView', ["compiled/handlebars_helpers"], function (Handlebars) { var template = Handlebars.template, templates = Handlebars.templates = Handlebars.templates || {}; templates['ExternalTools/ExternalToolsCollectionView'] = template(function (Handlebars,depth0,helpers,partials,data) { helpers = helpers || Handlebars.helpers; var foundHelper, self=this; return "<table class=\"table table-striped\">\n <thead>\n <tr>\n <th>Name</th>\n <th>Extensions</th>\n <th>&nbsp;</th>\n </tr>\n </thead>\n <tbody class=\"collectionViewItems\"></tbody>\n</table>\n<div class=\"paginatedLoadingIndicator\" style=\"display: none\"></div>\n";}); return templates['ExternalTools/ExternalToolsCollectionView']; });
import React from 'react'; import Head from '../components/head'; import '../styles/custom.css'; const Resume = () => ( <div className="resume-page"> <Head /> <iframe frameBorder="0" className="resume-frame" src="https://souvik.me/resume.pdf"></iframe> <style jsx>{` .resume-frame { width: 100%; height: 100%; min-height: 100%; display: block; } .resume-page { width: 100%; height: 100vh; } `}</style> </div> ); export default Resume;
/* This file is part of Aaron Rest Server. Aaron Rest Server is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Aaron Rest Server 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 Aaron Rest Server. If not, see <http://www.gnu.org/licenses/>. */ 'use strict'; var util = require('util'); var permissionLog = util.debuglog('permission'); var config = require('../config'); var pool = null; function updatePermissions(req, res) { permissionLog('update request!'); pool.getConnection(function(err, connection) { if(err) { console.error(err); return res.send(500, new Error('mysql')); } var post = {}; if(typeof req.params.email !== 'string') { console.error('updatePermissions: invalid-input-data'); return res.send(400, new Error('invalid-input-data')); } else if(!config.r.email.test(req.params.email)) { console.error('updatePermissions: invalid-input-formatting'); return res.send(400, new Error('invalid-input-formatting')); } /*if(Object.keys(post).length === 0) { console.error('updatePermissions: invalid-input-data'); return res.send(400, new Error('no-data-inputted')); }*/ return res.send(500, new Error('not implemented yet!')); // TODO - not implemented yet! var query = connection.query(';', [], function(err, results) { connection.release(); if(err) { console.error(err, query.sql); return res.send(500, new Error('mysql')); } console.log(results); res.send(200, {message: 'success'}); }); }); } function getPermissions(req, res) { permissionLog('get request!'); pool.getConnection(function(err, connection) { if(err) { console.error(err); return res.send(500, new Error('mysql')); } var query = connection.query( 'SELECT p.*, ghp.* '+ 'FROM users u '+ 'INNER JOIN users_has_groups uhg ON u.user_id = uhg.users_user_id '+ 'INNER JOIN groups g ON g.group_id = uhg.groups_group_id '+ 'INNER JOIN groups_has_permissions ghp ON g.group_id = ghp.groups_group_id '+ 'INNER JOIN permissions p ON p.permission_id = ghp.permissions_permission_id '+ 'INNER JOIN permissions_has_applications pha ON p.permission_id = pha.permissions_permission_id '+ 'INNER JOIN applications a ON a.application_shortname = pha.applications_application_shortname '+ 'WHERE user_email = ?;', [req.params.email], function(err, results) { connection.release(); if(err) { console.error(err, query.sql); return res.send(500, new Error('mysql')); } console.log(results); res.send(200, {data: 'here'}); } ); }); } function activateRoute(server, mysqlPool, checkAuth) { pool = mysqlPool; server.post('/permissions/user/:email', checkAuth, updatePermissions); server.get('/permissions/user/:email', checkAuth, getPermissions); } module.exports.activateRoute = activateRoute;
var assert = require('assert') , FeedParser = require('../') , feedparser = new FeedParser() , feed = __dirname + '/feeds/unknown-namespace.atom' , meta = {} , articles = {} ; describe('feedparser', function(){ describe('nondefaultnamespace Test case 3: default namespace Atom; XHTML namespace mapped to a prefix; FooML namespace default in the namespace DIV', function(){ before(function(done){ feedparser.parseFile(feed, function (error, _meta, _articles) { assert.ifError(error); meta = _meta; articles = _articles; done(); }); }); describe('article', function(){ it('should have the expected title', function() { assert.equal(articles[0].title, 'This entry contains XHTML-looking markup that is not XHTML'); }); it('should have the expected description', function(){ assert.ok(articles[0].description.match(/^<h:div xmlns="http:\/\/hsivonen.iki.fi\/FooML">/)); assert.ok(articles[0].description.match(/<h:li>This is an XHTML list item./)); assert.ok(articles[0].description.match(/<li>This is not an XHTML list item./)); }); }); }); describe('nondefaultnamespace using static methods Test case 3: default namespace Atom; XHTML namespace mapped to a prefix; FooML namespace default in the namespace DIV', function(){ before(function(done){ FeedParser.parseFile(feed, function (error, _meta, _articles) { assert.ifError(error); meta = _meta; articles = _articles; done(); }); }); describe('article', function(){ it('should have the expected title', function() { assert.equal(articles[0].title, 'This entry contains XHTML-looking markup that is not XHTML'); }); it('should have the expected description', function(){ assert.ok(articles[0].description.match(/^<h:div xmlns="http:\/\/hsivonen.iki.fi\/FooML">/)); assert.ok(articles[0].description.match(/<h:li>This is an XHTML list item./)); assert.ok(articles[0].description.match(/<li>This is not an XHTML list item./)); }); }); }); });
$(document).ready(function() { // Hide GNU-cat $('#loading').hide(); // jQuery cycle plugin usage for screenshot slideshow $('.slideshow').cycle({ fx: 'fade', speed: 1000, timeout: 6000, }); // Show GNU-cat when the submit button is pressed $('input#submit').click(function() { $('#loading').fadeIn(1000); }); // Assign account form fields to variables // (was doing this to do some logic with the below keyup function // to make it so that a field did not react to a master form change if // it was altered by the user. Unfortunately, the JS cannot seem to react // quickly enough to handle anything but slow typing. May attempt rewrite // later. var master_field = $('input#master'); var ohloh_field = $('input#ohloh'); var coderwall_field = $('input#coderwall'); // Have master account input field update all other field master_field.keyup(function () { ohloh_field.val($(this).val()); coderwall_field.val($(this).val()); }); }); $(window).on('unload', function() { // Re-hide GNU-cat when we leave. $('loading').hide(); });
(function($){ $.fn.extend({ renderChart: function() { return this.each(function() { var $chart = $(this); if ($chart.children().length > 0) return; var data = $.parseJSON($chart.html()); var saveHTML = $chart.html(); $chart.html('').show().parent(); var chartID = 'chart' + $.fluxx.visualizations.counter++; if (data) { var $card; if (typeof $chart.fluxxCard == 'function') { $card = $chart.fluxxCard(); } else { $card = $('#hand'); } if (data.hasOwnProperty('class')) $card.fluxxCardDetail().addClass(data['class']); if (data.hasOwnProperty('width')) $card.fluxxCardDetail().width(data.width); $chart.html("").append('<div id="' + chartID + '"></div>'); $.jqplot.config.enablePlugins = true; if (data.type == 'bar') { if (!data.seriesDefaults) data.seriesDefaults = {}; data.seriesDefaults.renderer = $.jqplot.BarRenderer; } if (data.series) { $.each(data.series, function(i, s) { if (s.renderer) { s.renderer = eval(s.renderer); } }); } if (data.axes && data.axes.xaxis && data.axes.xaxis.ticks.length > 0 && !$.isArray(data.axes.xaxis.ticks[0])) data.axes.xaxis.renderer = $.jqplot.CategoryAxisRenderer; var error = false; try { plot = $.jqplot(chartID, data.data, { axesDefaults: { tickRenderer: $.jqplot.CanvasAxisTickRenderer , tickOptions: { fontSize: '10pt' } }, title: {show: false}, width: $chart.css('width'), stackSeries: data.stackSeries, // grid:{background:'#fefbf3', borderWidth:2.5}, grid:{background:'#ffffff', borderWidth:0, gridLineColor: '#ffffff', shadow: false}, seriesDefaults: data.seriesDefaults, axes: data.axes, series: data.series }); } catch(e) { // $.fluxx.log('error', e); $chart.html('<h4>No data available</h4>').height(50).css({"text-align": "center"}); error = true; } if (!error) { var legend = {}; $.each(plot.series, function(index, key) { legend[key.label] = key; }); var $table = $('.legend table.legend-table', $card); if ($table.hasClass('single-row-legend')) { $table.find('.category').each(function () { var $cat = $(this); var l = legend[$.trim($cat.text())]; if (l) $cat.prepend('<span class="legend-color-swatch" style="background-color: ' + l.color + '"/>'); }); } else { $table.find('tr').each(function() { var $td = $('td:first', $(this)); if ($td.length) { var l = legend[$.trim($td.text())]; if (l) $td.prepend('<span class="legend-color-swatch" style="background-color: ' + l.color + '"/>'); } }) .hover(function(e) { var $td = $('td:first', $(this)); if (legend[$.trim($td.text())]) legend[$.trim($td.text())].canvas._elem.css('opacity', '.5'); }, function(e) { var $td = $('td:first', $(this)); if (legend[$.trim($td.text())]) legend[$.trim($td.text())].canvas._elem.css('opacity', '1'); }); } } } }); } }); $.extend(true, { fluxx: { visualizations: { counter: 0 } } }); })(jQuery);
import { expect } from 'chai'; import semverCompare from './semverCompare'; describe('semverCompare', () => { const chaos = [ '2.5.10.4159', '0.5', '0.4.1', '1', '1.1', '2.5.0', '2', '2.5.10', '10.5', '1.25.4', '1.2.15', ]; const order = [ '0.4.1', '0.5', '1', '1.1', '1.2.15', '1.25.4', '2', '2.5.0', '2.5.10', '2.5.10.4159', '10.5', ]; it('sorts arrays correctly', () => { expect(chaos.sort(semverCompare)).to.deep.equal(order); }); it('leaves equal version numbers in place', () => { expect(['1', '1.0.0'].sort(semverCompare)).to.deep.equal(['1', '1.0.0']); expect(['1.0.0', '1'].sort(semverCompare)).to.deep.equal(['1.0.0', '1']); }); });
var clover = new Object(); // JSON: {classes : [{name, id, sl, el, methods : [{sl, el}, ...]}, ...]} clover.pageData = {"classes":[{"el":70,"id":245172,"methods":[{"el":61,"sc":2,"sl":48},{"el":65,"sc":2,"sl":63},{"el":69,"sc":2,"sl":67}],"name":"ResourceLabel","sl":33}]} // JSON: {test_ID : {"methods": [ID1, ID2, ID3...], "name" : "testXXX() void"}, ...}; clover.testTargets = {} // JSON: { lines : [{tests : [testid1, testid2, testid3, ...]}, ...]}; clover.srcFileLines = [[], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], []]
import { toArray, exists, stringToBoolean } from '../../../utils/utils' import { head } from 'ramda' export default function intent (addressbar, params) { const setAppMode$ = addressbar.get('appMode') .map(d => d.pop()) // what mode is the app in ? ("editor" or "viewer" only for now) const setToolsets$ = addressbar.get('tools') .map(d => d.pop()) .filter(data => data.length > 0) .map(function (data) { if (data.indexOf(',') > -1) { return data.split(',').filter(d => d.length > 0) } else { return data } }) .map(toArray) const setAutoSave$ = addressbar.get('autoSave') .map(data => head(data)) .filter(exists) .map(stringToBoolean) const setAutoLoad$ = addressbar.get('autoLoad') .map(data => head(data)) .filter(exists) .map(stringToBoolean) return { setAppMode$, setToolsets$, setAutoSave$, setAutoLoad$ } }
/* * Copyright (C) 2017 - present Instructure, Inc. * * This file is part of Canvas. * * Canvas is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, version 3 of the License. * * Canvas 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 program. If not, see <http://www.gnu.org/licenses/>. */ import axios from 'axios'; import Fixtures from 'spec/jsx/gradebook-history/Fixtures'; import HistoryApi from 'jsx/gradebook-history/api/HistoryApi'; QUnit.module('HistoryApi', { setup () { this.courseId = 123; this.getStub = this.stub(axios, 'get') .returns(Promise.resolve({ status: 200, response: Fixtures.historyResponse() })); } }); test('getGradebookHistory sends a request to the grade change audit url', function () { const url = `/api/v1/audit/grade_change/courses/${this.courseId}`; HistoryApi.getGradebookHistory(this.courseId, {}); strictEqual(this.getStub.callCount, 1); strictEqual(this.getStub.getCall(0).args[0], url); }); test('getGradebookHistory requests with course and assignment', function () { const assignment = '21'; const url = `/api/v1/audit/grade_change/courses/${this.courseId}/assignments/${assignment}`; HistoryApi.getGradebookHistory(this.courseId, { assignment }); strictEqual(this.getStub.callCount, 1); strictEqual(this.getStub.getCall(0).args[0], url); }); test('getGradebookHistory requests with course and grader', function () { const grader = '22'; const url = `/api/v1/audit/grade_change/courses/${this.courseId}/graders/${grader}`; HistoryApi.getGradebookHistory(this.courseId, { grader }); strictEqual(this.getStub.callCount, 1); strictEqual(this.getStub.getCall(0).args[0], url); }); test('getGradebookHistory requests with course and student', function () { const student = '23'; const url = `/api/v1/audit/grade_change/courses/${this.courseId}/students/${student}`; HistoryApi.getGradebookHistory(this.courseId, { student }); strictEqual(this.getStub.callCount, 1); strictEqual(this.getStub.getCall(0).args[0], url); }); test('getGradebookHistory requests with course, assignment, and grader', function () { const grader = '22'; const assignment = '210'; const url = `/api/v1/audit/grade_change/courses/${this.courseId}/assignments/${assignment}/graders/${grader}`; HistoryApi.getGradebookHistory(this.courseId, { assignment, grader }); strictEqual(this.getStub.callCount, 1); strictEqual(this.getStub.getCall(0).args[0], url); }); test('getGradebookHistory requests with course, assignment, and student', function () { const student = '23'; const assignment = '210'; const url = `/api/v1/audit/grade_change/courses/${this.courseId}/assignments/${assignment}/students/${student}`; HistoryApi.getGradebookHistory(this.courseId, { assignment, student }); strictEqual(this.getStub.callCount, 1); strictEqual(this.getStub.getCall(0).args[0], url); }); test('getGradebookHistory requests with course, grader, and student', function () { const grader = '23'; const student = '230'; const url = `/api/v1/audit/grade_change/courses/${this.courseId}/graders/${grader}/students/${student}`; HistoryApi.getGradebookHistory(this.courseId, { grader, student }); strictEqual(this.getStub.callCount, 1); strictEqual(this.getStub.getCall(0).args[0], url); }); test('getGradebookHistory requests with course, assignment, grader, and student', function () { const grader = '22'; const assignment = '220'; const student = '2200' const url = `/api/v1/audit/grade_change/courses/${this.courseId}/assignments/${assignment}/graders/${grader}/students/${student}`; HistoryApi.getGradebookHistory(this.courseId, { assignment, grader, student }); strictEqual(this.getStub.callCount, 1); strictEqual(this.getStub.getCall(0).args[0], url); }); test('getNextPage makes an axios get request', function () { const url = encodeURI('http://example.com/grades?include[]=current_grade&page=42&per_page=100000000'); HistoryApi.getNextPage(url); strictEqual(this.getStub.callCount, 1); strictEqual(this.getStub.getCall(0).args[0], url); });
function fetchData{{ id }}() { function onDataReceived(series) { data = [series]; $.plot("#{{ id }}", data, { series: { shadowSize: 0, }, bars: { show: true, barWidth: series.barWidth, align: "center" }, xaxis: { tickDecimals: 0, mode: "time", timezone: "browser", }, yaxis: { tickDecimals: 0, min: 0, }, }); $("#{{ id }}loading").hide(); }; $.ajax({ url: '{% url id %}', type: "GET", dataType: "json", success: onDataReceived, }); }; {% include 'pages/refreshbutton.js' %} $('#{{ id }}remove').click(function(){ var url = "{% url 'usersprofiledash' 'off' id %}"; $.ajax({ url: url, type: "GET", }); });
/* INPUT: * workspaceId * contactId DESCRIPTION An editable list of phone numbers (`workspacesContactsPhoneNumbers`) owned by contactId. */ define([ "dojo/_base/declare" , "dijit/form/ValidationTextBox" , "put-selector/put" , "hotplate/hotClientDojo/dgridWidgets/commonMixins" , "hotplate/hotClientDojo/widgets/EditingWidget" , "hotplate/hotClientDojo/widgets/SharedValidationTextBox" , "hotplate/hotClientDojo/widgets/widgets" , "hotplate/hotClientDojo/dgridWidgets/EditableList" , "hotplate/hotClientDojo/widgets/BusyButton" , "hotplate/hotClientDojo/stores/stores" , "hotplate/hotClientDojo/globals/globals" , "hotplate/hotClientDojo/storeConfig/ConfigVars" ], function( declare , ValidationTextBox , put , commonMixins , EditingWidget , SharedValidationTextBox , widgets , EditableList , BusyButton , stores , globals , ConfigVars ){ var templateString = '' + '<div>\n' + ' <div class="inline-form">\n' + ' <form data-dojo-type="dijit/form/Form" data-dojo-attach-point="formWidget" method="POST">\n' + ' <input class="dial-code" id="${id}_dialCode" name="dialCode" data-dojo-type="hotplate/hotClientDojo/widgets/SharedValidationTextBox" maxlength="4" data-dojo-props="value: this.countryDialCodeDefault, placeHolder:this.countryDialCodeDefault, required: true, sharedValidator: \'dialCode\'" data-dojo-attach-point="dialCodeWidget" />\n' + ' <input class="number" id="${id}_number" name="number" data-dojo-type="hotplate/hotClientDojo/widgets/SharedValidationTextBox" maxlength="20" data-dojo-props="placeHolder:\'Type a phone number...\', required: true, sharedValidator: \'phoneNumber\'" data-dojo-attach-point="numberWidget" />\n' + ' <input class="form-submit" type="submit" data-dojo-attach-point="buttonWidget" data-dojo-type="hotplate/hotClientDojo/widgets/BusyButton" label="Save" />' + ' </form>\n'+ ' </div>\n'+ '</div>\n'+ ''; return declare( [ EditableList ], { closeDialogAfterSubmit: true, ownClass: 'workspaces-contacts-phone-numbers', postMixInProperties: function(){ this.inherited(arguments); this.storeParameters = { workspaceId: this.workspaceId, contactId: this.contactId }; }, ListConstructor: declare( [ commonMixins.FullOnDemandList ], { renderRow: function(object, options){ if( object.dialCode ) var row = put('div.row', '+' + object.dialCode + ' ' + object.number ); else var row = put('div.row', object.number ); return row; }, dndParams: { selfAccept: true }, refresh: function(){ this.inherited( arguments ); }, }), EditingWidgetConstructor: declare([ EditingWidget ], { templateString: templateString, alertBarDomPlacement: 'last', resetOnSuccess: true, buildRendering: function(){ this.countryDialCodeDefault = ConfigVars.workspacesInfo.countryDialCodeDefault; this.inherited( arguments ); }, manipulateValuesBeforeSubmit: function( values ){ //console.log(values); //values.orderByNameDefault = values.orderByNameDefault.indexOf( 'on' ) !== -1; }, }), storeName: 'workspacesContactsPhoneNumbers', editingWidgetPlacement: 'inline', multipleEditingAllowed: false, addingWidgetPosition: 'top', gutters: false, buttonsPosition: 'after', // or "top" or "bottom" } ); }); /* var countryOptions = []; var countryDialCodes = sharedFunctions.bd.countryDialCodes(); for( var code in countryDialCodes ){ var country = countryDialCodes[ code ]; console.log( country, code ); countryOptions.push( { label: country + ' (+' + code + ')', value: code }); console.log( "OPTIONS: ", countryOptions ); } var CountrySelect = declare( 'bd/DialCode', Select, { name: "dialCode", options: countryOptions }); */
var webpack = require('webpack'); var dotenv = require('dotenv').load(); module.exports = exports = require('./webpack.config'); exports.plugins = [ new webpack.DefinePlugin({ __API_URL__: JSON.stringify(process.env.LANDLINE_API_URL), __PROD__: false, __S3_BUCKET__: JSON.stringify('landline-dev') }), new webpack.NoErrorsPlugin() ]; exports.output = Object.create(exports.output); exports.output.filename = exports.output.filename.replace(/\.js$/, ".dev.js"); exports.devtool = 'source-map';
var root2 = { "name": "flare", "children": [ { "name": "analytics", "children": [ { "name": "cluster", "children": [ {"name": "AgglomerativeCluster", "size": 3938}, {"name": "CommunityStructure", "size": 3812}, {"name": "MergeEdge", "size": 743} ] }, { "name": "graph", "children": [ {"name": "BetweennessCentrality", "size": 3534}, {"name": "LinkDistance", "size": 5731} ] } ] } ] }
/* http://www.kryogenix.org/code/browser/searchhi/ */ /* Modified 20021006 to fix query string parsing and add case insensitivity */ /* Modified 20030227 by sgala@hisitech.com to skip words with "-" and cut %2B (+) preceding pages */ function highlightWord(node,word) { // Iterate into this nodes childNodes if (node.hasChildNodes) { var hi_cn; for (hi_cn=0;hi_cn<node.childNodes.length;hi_cn++) { highlightWord(node.childNodes[hi_cn],word); } } // And do this node itself if (node.nodeType == 3) { // text node tempNodeVal = node.nodeValue.toLowerCase(); tempWordVal = word.toLowerCase(); if (tempNodeVal.indexOf(tempWordVal) != -1) { pn = node.parentNode; if (pn.className != "searchword") { // word has not already been highlighted! nv = node.nodeValue; ni = tempNodeVal.indexOf(tempWordVal); // Create a load of replacement nodes before = document.createTextNode(nv.substr(0,ni)); docWordVal = nv.substr(ni,word.length); // alert( "Found: " + docWordVal ); after = document.createTextNode(nv.substr(ni+word.length)); hiwordtext = document.createTextNode(docWordVal); hiword = document.createElement("span"); hiword.className = "searchword"; hiword.appendChild(hiwordtext); pn.insertBefore(before,node); pn.insertBefore(hiword,node); pn.insertBefore(after,node); pn.removeChild(node); } } } } function googleSearchHighlight() { if (!document.createElement) return; ref = document.referrer; //or URL for highlighting in place if (ref.indexOf('?') == -1) return; qs = ref.substr(ref.indexOf('?')+1); qsa = qs.split('&'); for (i=0;i<qsa.length;i++) { qsip = qsa[i].split('='); if (qsip.length == 1) continue; // q= for Google, p= for Yahoo // query= for JSPWiki if (qsip[0] == 'query' || qsip[0] == 'q') { words = qsip[1].replace(/%2B/g,''); words = words.replace(/-\S+\s/g,''); words = unescape(words.replace(/\+/g,' ')).split(/\s+/); for (w=0;w<words.length;w++) { highlightWord(document.getElementsByTagName("body")[0],words[w]); } } } } window.onload = googleSearchHighlight;
var interface_c_p_event = [ [ "buttonNumber", "interface_c_p_event.html#a95f060acf8268fe7f3a16c42ea121466", null ], [ "characters", "interface_c_p_event.html#a1bf8cbf0c017151070a99236c957fc94", null ], [ "charactersIgnoringModifiers", "interface_c_p_event.html#aa1b99c685842a415f6736d776c8aba90", null ], [ "clickCount", "interface_c_p_event.html#a21ba312feb01ac26df9cab0eae85cdcc", null ], [ "currentTimestamp", "interface_c_p_event.html#a0370261e16fa1b67388c1a027efff02a", null ], [ "data1", "interface_c_p_event.html#a2129df252602ed408c8e9241d8e89aad", null ], [ "data2", "interface_c_p_event.html#a5a9e2ed2d7faffaef4648da3257ac31b", null ], [ "deltaX", "interface_c_p_event.html#a8bcf33e092b83a9bf10fc2aabae6c249", null ], [ "deltaY", "interface_c_p_event.html#a1804678959cc324a1af7386b71720cf2", null ], [ "deltaZ", "interface_c_p_event.html#adb216a38817ab6a03fc50276fb7abad9", null ], [ "description", "interface_c_p_event.html#af262b1f3b4aced3b2bd3044bd15af565", null ], [ "globalLocation", "interface_c_p_event.html#ad464fd6df3bf20110075dc81ce662a44", null ], [ "isARepeat", "interface_c_p_event.html#a0d6e1d0c4afa0c4231bedcdd9401ba87", null ], [ "keyCode", "interface_c_p_event.html#a5ecd01fadd6c4bc25a8508dc4bb7cca7", null ], [ "keyEventWithType:location:modifierFlags:timestamp:windowNumber:context:characters:charactersIgnoringModifiers:isARepeat:keyCode:", "interface_c_p_event.html#af5f96235d926dc455c492ece4d907744", null ], [ "locationInWindow", "interface_c_p_event.html#a5a57f4fa909de5d83e5402a8d8af4b94", null ], [ "modifierFlags", "interface_c_p_event.html#ae1990580a2f73b19009f30f27ff1e396", null ], [ "mouseEventWithType:location:modifierFlags:timestamp:windowNumber:context:eventNumber:clickCount:pressure:", "interface_c_p_event.html#ad6bbef973e2dd36732fe8b51be55e3e7", null ], [ "mouseLocation", "interface_c_p_event.html#a91d4b5abd148e3976056714f6cf658fc", null ], [ "otherEventWithType:location:modifierFlags:timestamp:windowNumber:context:subtype:data1:data2:", "interface_c_p_event.html#a90910bafcdc04fe2641c9350669d9810", null ], [ "pressure", "interface_c_p_event.html#acac4af271cc9cbeb999d0c148767fc99", null ], [ "startPeriodicEventsAfterDelay:withPeriod:", "interface_c_p_event.html#a474ff767ceaf957fbde1a662d01b4788", null ], [ "stopPeriodicEvents", "interface_c_p_event.html#a5071c8f5ce8fd7d8a08e6ae4756b1d2d", null ], [ "timestamp", "interface_c_p_event.html#ab290762686ceda8bb462e0e989f62e04", null ], [ "type", "interface_c_p_event.html#abbbd5ff6550996fa3ef524ef27a1ef80", null ], [ "window", "interface_c_p_event.html#af9a0e45bbaba9bc6587a222e74bf0703", null ], [ "windowNumber", "interface_c_p_event.html#a15734c6e53f37894f69326ac46ec3600", null ] ];
#!/usr/bin/env node // requires var webcredits = require('../lib/webcredits.js'); var program = require('commander'); /** * version as a command */ function bin(argv) { // setup config var config = require('../config/dbconfig.js'); program .option('-c, --currency <currency>', 'Currency') .option('-d, --database <database>', 'Database') .option('-w, --wallet <wallet>', 'Wallet') .parse(argv); var defaultCurrency = 'https://w3id.org/cc#bit'; var defaultDatabase = 'webcredits'; var defaultWallet = 'https://localhost/wallet/test#this'; config.currency = program.currency || config.currency || defaultCurrency; config.database = program.database || config.database || defaultDatabase; config.wallet = program.wallet || config.wallet || defaultWallet; webcredits.createDB(config, function(err, ret) { if (err) { console.error(err); } else { console.log(ret); } }); } // If one import this file, this is a module, otherwise a library if (require.main === module) { bin(process.argv); } module.exports = bin;
export default [ { name: 'hello-wold-functional', displayName: 'Hello World (functional)', directory: 'hello-world', files: ['hello-world-functional.js'] }, { name: 'hello-wold-class', displayName: 'Hello World (class component)', directory: 'hello-world', files: ['hello-world-class.js'] }, { name: 'clock', displayName: 'Clock', directory: 'clock', files: ['clock.js'] }, { name: 'simple-counter', displayName: 'Simple Counter', directory: 'counter', files: ['simple-counter.js'] }, { name: 'complex-counter', displayName: 'Complex Counter', directory: 'counter', files: ['complex-counter.js'] }, { name: 'injection', displayName: 'Injection', directory: 'injection', files: ['injection.js'] }, { name: 'i18n', displayName: 'Internationalization', directory: 'i18n', files: ['i18n.js'] } ];
var structshyft_1_1timeseries_1_1d__ref__t_3_01_t_00_01typename_01enable__if_3_01is__shared__ptr_3_0a96d8130ed21daa23ed2d27c0d825333 = [ [ "type", "structshyft_1_1timeseries_1_1d__ref__t_3_01_t_00_01typename_01enable__if_3_01is__shared__ptr_3_0a96d8130ed21daa23ed2d27c0d825333.html#a88ec5a232f62e1394dc393ac07b0096c", null ] ];