text
stringlengths
2
6.14k
/** * A class to hold a person. * Please note that the Trove API does not currently support People * except as a result of a search. * @class * * @param {Object} options The options object for the Person. * @param {(number|string)} options.init The Person identifier for which * to retrieve data on construction. * @param {function} options.done The callback on receipt of data * (optional). * @param {function} options.fail The callback on failure (optional). * @param {RECLEVEL} options.reclevel Whether to return the brief * or full record. * @param {INCLUDES[]} options.includes * * @property {string} id The Trove identifier for the person * @property {string} troveUrl The full URL for the person * @property {string} url The relative URL for the person * */ export class Person { constructor (options) { // console.log('Creating Person'); // Save and remove init from options. var init; if (options.init !== undefined) { init = options.init; delete options.init; } // Save all other options in this object. $.extend(this, options); // If we know the identifier, get the data if (init !== undefined) { this.get({id: init}); } } process_done (data) { $.extend(this, data.people); if (this.done !== undefined) { this.done(this); } } process_fail (jqXHR, textStatus, errorThrown) { console.error('Error getting person:', textStatus); if (this.fail !== undefined) { this.fail(this); } } /** * Get the Person metadata from the Trove server. * Currently not supported by Trove. * @param {Object} options The options object for the query. * @param {(number|string)} options.id The person ID for which * to retrieve data. * @param {function} options.done The callback on receipt of data * (optional). * @param {function} options.fail The callback on failure (optional). * @param {RECLEVEL} options.reclevel Whether to return the brief * or full record. * @param {INCLUDES[]} options.includes */ get (options) { // console.log('Getting person'); // Override reclevel, includes, done and fail if specified if (options) { this.id = options.id || this.id; this.reclevel = options.reclevel || this.reclevel; this.includes = options.includes || this.includes; this.done = options.done || this.done; this.fail = options.fail || this.fail; } var query_data = { key: Trove.trove_key, encoding: 'json' }; // Full or brief if (this.reclevel !== undefined) { query_data.reclevel = this.reclevel; } // What to include if ((this.includes !== undefined) && (Array.isArray(this.includes)) && (this.includes.length > 0)) { query_data.include = this.includes.join(','); } $.ajax({ dataType: "jsonp", url: Trove.API.PEOPLE + this.id, data: query_data, context: this }).done(this.process_done).fail(this.process_fail); } }
function addItem() { let [text, value, menu] = [ document.getElementById('newItemText'), document.getElementById('newItemValue'), document.getElementById('menu') ]; let item = document.createElement('option'); item.text = text.value; item.value = value.value; menu.add(item); text.value = ''; value.value = ''; }
/** * Change table failedlogin to include a primary key on column id */ exports.up = function(knex) { return knex.schema.alterTable('failedlogin', (table) => { table.primary('id'); table.dropUnique('id'); }); }; exports.down = function(knex) { return null; };
var Gpio = require('pigpio').Gpio; var x = new Gpio(17, {mode: Gpio.INPUT}); var y = new Gpio(18, {mode: Gpio.INPUT}); var button = new Gpio(27, {mode: Gpio.INPUT, pullUpDown: Gpio.PUD_DOWN, edge: Gpio.RISING_EDGE}); console.log('Warning: no analog inputs on the Raspberry Pi!\nThis program just reads the button on pin GPIO27.'); button.on('interrupt', function (level) { console.log('button pressed.'); });
import Adapt from 'core/js/adapt'; /** * Controller for managing accessibilty logging, specifically used for * controlling the display of removed or deprecated API warnings. */ export default class Log extends Backbone.Controller { initialize() { this._warned = {}; } _hasWarned(args) { const config = Adapt.a11y.config; if (!config._options._warnFirstOnly) { return false; } const hash = args.map(String).join(':'); if (this._warned[hash]) { return true; } this._warned[hash] = true; return false; } _canWarn() { const config = Adapt.a11y.config; return Boolean(config._options._warn); } removed(...args) { if (!this._canWarn) { return; } args = ['A11Y'].concat(args); if (this._hasWarned(args)) { return; } Adapt.log.removed(...args); return this; } deprecated(...args) { if (!this._canWarn) { return; } args = ['A11Y'].concat(args); if (this._hasWarned(args)) { return; } Adapt.log.deprecated(...args); return this; } }
import SpellEffect from '../../base/SpellEffect'; export default class Heal extends SpellEffect { apply(target) { if(target.stats.hp.atMin()) return `${target.name} is currently dead and can't be healed!`; target.stats.hp.add(this.statBuff); return `${target.name} was healed for ${this.statBuff} HP!`; } }
/** * @name UserView */ function UserView(){ var self = this, model = self.model, form = P.loadForm(this.constructor.name, model); var changePassView = new ChangePassView(); var rolesForm = new RolesForm(); function setControlsEnabled() { form.btnSave.enabled = model.modified; } function refreshUsers() { var cur = model.dsMtdUsers.usr_id; if (model.modified && confirm('Сохранить изменения?', self.title)) model.save(); model.requery(); } form.onWindowOpened = function(evt) {//GEN-FIRST:event_formWindowOpened setControlsEnabled(); };//GEN-LAST:event_formWindowOpened form.onWindowClosing = function(evt) {//GEN-FIRST:event_formWindowClosing if(model.modified && confirm("Сохранить?", self.title)) model.save(); };//GEN-LAST:event_formWindowClosing form.USR_ROLE.onSelectValue = function(aEditor) {//GEN-FIRST:event_USR_ROLESelectValue model.save(); rolesForm.setUserName(model.dsMtdUsers.cursor.usr_name); rolesForm.showModal(function(user){ if(user){ model.dsMtdUsers.cursor.usr_roles = user.usr_role; model.dsMtdUsers.cursor.usr_form = user.usr_form; model.save(); model.requery(); } }); };//GEN-LAST:event_USR_ROLESelectValue form.USR_PASSWD.onSelect = function(aEditor) { model.save(); changePassView.setUserId(self.dsMtdUsers.usr_name); changePassView.showModal(function(aResult){ if (aResult) { refreshUsers(); setControlsEnabled(); } }); }; form.btnReq.onActionPerformed = function(evt) { refreshUsers(); setControlsEnabled(); }; form.btnSave.onActionPerformed = function(evt) { model.save(); refreshUsers(); setControlsEnabled(); }; form.tbSetEdit.onActionPerformed = function(evt) { //isEditable = self.tbSetEdit.selected; setEdit(); }; model.dsMtdUsers.onChanged = function(evt) { setControlsEnabled(); }; form.btnAdd.onActionPerformed = function(evt) { model.dsMtdUsers.insert(); }; form.btnDel.onActionPerformed = function(evt) { if (confirm("Удалить текущего пользователя")){ model.dsMtdUsers.usr_passwd = 'false'; model.save(); refreshUsers(); } }; form.btnFind.onActionPerformed = function(evt) { form.grdUsers.findSomething(); }; self.show = function() { form.show(); }; self.getView = function(){ return form.view; }; }
/** * */ Ext.define('Hrproject.view.logalarm.LogAlarmMainView', { extend : 'Ext.form.Panel', xtype : 'logAlarmMainView', requires : [ 'Hrproject.view.logalarm.LogAlarmMainViewController', 'Hrproject.view.logalarm.tree.LogAlarmTreePanel', 'Hrproject.view.logalarm.mainscreen.LogAlarmMainViewTabPanel', 'Ext.layout.container.Column','Ext.form.field.Hidden' ], controller : 'logAlarmMainViewController', layout : 'column', autoScroll : true, defaults : { margin : 10, }, items : [ { columnWidth : '0.3', xtype : 'logAlarmTreePanel', itemId : 'logAlarmTreePanel', }, { columnWidth : '0.7', xtype : 'logAlarmMainViewTabPanel', itemId : 'logAlarmMainViewTabPanel' }], buttons : [ { text : 'Clear', itemId : 'clearButton', handler : 'onClearButton', }, { text : 'Update Module', itemId : 'saveButton', formBind : true, handler : 'onSaveButton', } ] });
Meteor.subscribe('keywords'); Template.keywordInputType.helpers({ keywords: function() { let keywordDoc=Collections.Keywords.findOne(Collections.Keywords.KEYWORD_DOCUMENT_ID); if(keywordDoc===undefined) return undefined; return keywordDoc.keywords; } }); Template.keywordInputType.onRendered(function() { $('.keywordEditor') .dropdown({ allowAdditions: true }); }); AutoForm.addInputType('keywords',{ template: 'keywordInputType', valueIn:function(value,typeFieldInfo) { if(value.join===undefined) return value; return value.join(','); }, valueOut:function() { try { //console.log(this.val()); var keywords=this.val().split(','); if(this.val().trim()=='') return []; let keywordDoc=Collections.Keywords.findOne(Collections.Keywords.KEYWORD_DOCUMENT_ID); if(keywordDoc.keywords===undefined) keywordDoc.keywords=[]; //console.log('keywordDoc',keywordDoc); //console.log('keywords',keywords); let newKeywords=[]; for(let i=0;i<keywords.length;i++) { let originalKeyword=keywords[i].trim(); let keyword=originalKeyword.toLowerCase(); let found=false; for(let j=0;j<keywordDoc.keywords.length;j++) { if(keywordDoc.keywords[j]!==null && keywordDoc.keywords[j].toLowerCase()===keyword) { found=true; break; } } if(!found) newKeywords[newKeywords.length]=originalKeyword; } //console.log(newKeywords); if(newKeywords.length!==0) ConnectionManager.call("addKeywords", newKeywords); return keywords; } catch(e) { console.log(e); } } });
$(document).ready(function () { $("#owl-demo").owlCarousel({ navigation: true, navigationText: ['&lsaquo;','&rsaquo;'], slideSpeed: 300, paginationSpeed: 400, singleItem: true, afterInit: makePages, afterUpdate: makePages }); function makePages() { $.each(this.owl.userItems, function(i) { $('.owl-controls .owl-page').eq(i) .css({ 'background': 'url(' + $(this).find('img').attr('src') + ')', 'background-size': 'cover' }) }); } });
var path = require('path'); var router = require('express')(); var security = require('../middlewares/security'); require('express-reverse')(router); router.disable('x-powered-by'); router.set('views',path.join(__dirname, '../../app/views/countries')); var countries = require('../controllers/Countries'); router.get('countries.index','/countries', security.csrf, countries.index ); router.post('countries.create','/countries', security.csrf, countries.create ); router.put('countries.update','/countries', security.csrf, countries.update ); router.delete('countries.delete','/countries', security.csrf, countries.delete ); module.exports = router;
var searchData= [ ['macros_2edox',['macros.dox',['../da/dd9/macros_8dox.html',1,'']]], ['macros_2eh',['macros.h',['../de/d3c/macros_8h.html',1,'']]], ['mainpage_2edox',['mainpage.dox',['../d5/d4d/mainpage_8dox.html',1,'']]], ['makefile_2ecpp',['makefile.cpp',['../de/d36/makefile_8cpp.html',1,'']]], ['makefile_2edox',['makefile.dox',['../d6/d3b/makefile_8dox.html',1,'']]], ['makefile_2eh',['makefile.h',['../d1/d9e/makefile_8h.html',1,'']]] ];
import {Observable, Subscriber} from 'rxjs'; import {mergeStatic} from 'rxjs/operator/merge'; import {MessageBus} from 'chromium-port-bus'; import createNamespace from 'namespace-proxy'; import Container from './../Container'; const ns = createNamespace(); export default class ActionDispatcher { messageBus: MessageBus /** * Initializes the action dispatcher. */ constructor (container: Container, messageBus: MessageBus) { /** * The container instance. * @type {Container} */ ns(this).container = container; /** * The handler class object. * @type {{key: string: Class<string>[]}} */ ns(this).handlerClassesByActionType = {}; /** * The message bus instance. * @type {MessageBus} */ this.messageBus = messageBus; } /** * Mount handler classes. * * @param {Object} handlerClasses The handler classes * @return {this} */ mount (handlerClasses: {}): this { for (let handlerClassName in handlerClasses) { let handlerClass = handlerClasses[handlerClassName]; handlerClass.subscribedActionTypes.forEach(actionType => { if (ns(this).handlerClassesByActionType[actionType]) { ns(this).handlerClassesByActionType[actionType].push(handlerClass); } else { ns(this).handlerClassesByActionType[actionType] = [handlerClass]; } }); } return this; } /** * Dispatch an action. * * @param {String} actionType The action type * @param {Object} input The message data * @return {Observable<*>} */ dispatch (actionType: string, input: ?{}): Observable<*> { const handlerClasses = ns(this).handlerClassesByActionType[actionType]; if (handlerClasses) { console.log(`Dispatch action type "${actionType}"`); const observables = handlerClasses.map(handlerClass => { return new Observable(async (observer: Subscriber) => { console.log(`Handle action type "${actionType}"`); await handlerClass.handle({ dispatch: ::this.dispatch, messageBus: { send: ::this.messageBus.send }, next: (event) => observer.next(event), input, ...ns(this).container.instance }).then(() => observer.complete()) .catch(error => observer.error(error)); }); }); return mergeStatic(...observables).toPromise(); } throw new Error(`Undefined action type "${actionType}"`); } }
/************************************************************************** * bPortal is a SuiteCRM portal written using django project. * Copyright (C) 2017-2018 BTACTIC, SCCL * Copyright (C) 2017-2018 Marc Sanchez Fauste * 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 updateDynamicEnum(field, subfield) { if (document.getElementById(subfield) != null) { var de_key = document.getElementById(field).value; var selector = document.getElementById(subfield); var current = []; for (var i = 0; i < selector.length; i++) { if (selector.options[i].selected) { current.push(selector.options[i].value); } } document.getElementById(subfield).innerHTML = ""; for (var key in de_entries[subfield]) { if (key.indexOf(de_key + "_") === 0 || key === "") { selector.options[selector.options.length] = new Option( de_entries[subfield][key], key ); } } for (var item in current) { for (var k = 0; k < selector.length; k++) { if (selector.options[k].value === current[item]) { selector[k].selected = true; } } } } }
'use strict'; var test = require("unit.js"), morse = require("../lib/_morselib.js"); var converter = new morse.Converter(), machine, // five = require("johnny-five"), // board = new five.Board(), timeline = morse.timeline; function translate(mes) { if (machine != null) { console.log("Check out your Arduino - it tells you:\n" + mes); machine.sendMessage(converter.engToMorse(mes)); timeline.execute(); } else console.log("Please wait a second, it seems like the board isn't ready yet!"); } /* Test the Translation mechanism first */ describe("morse", function() { describe("Converter.engToMorse()", function() { it("should get valid values from the ABC", function() { var valid = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", " ", "\n", "\t"]; // each one has an entry in the ABC valid.map(function(i) { test.assert.notEqual(converter.engToMorse(i), ""); // should be equal to the entry in the ABC, because i is always one character // it always add one space at the end, so it's easier to read test.assert.equal(converter.engToMorse(i), morse.ABC[i] + " "); }); }); it("should skip invalid values", function() { var invalid = [":", ";", "<", "=", ">", "?", "@", "[", "\\", "]", "^", "_", "`", "|", "!", ".", ","]; var count = 0; invalid.map(function(i) { test.assert.equal(converter.engToMorse(i), ""); }); }); }); });
/* eslint-env node */ /* eslint-disable quotes */ /* eslint-disable comma-dangle */ const path = require('path'); const webpack = require('webpack'); const BundleTracker = require('webpack-bundle-tracker'); const ip = 'localhost'; module.exports = { context: __dirname, entry: { App: [ 'webpack-dev-server/client?http://' + ip + ':8080', 'webpack/hot/only-dev-server', './src/main.jsx', ], vendors: [ 'react', 'react-dom', 'react-dropzone', 'react-redux', 'material-ui', ], }, plugins: [ new webpack.HotModuleReplacementPlugin(), new webpack.NoEmitOnErrorsPlugin(), new webpack.optimize.CommonsChunkPlugin({ name: 'vendors', filename: 'vendors.js' }), new BundleTracker({ filename: './webpack-stats-local.json' }), ], output: { path: path.resolve('./bundles/'), filename: '[name]-[hash].js', publicPath: 'http://' + ip + ':8080' + '/assets/bundles/', }, module: { loaders: [ { test: /\.html$/, loader: 'file?name=[name].[ext]' }, { test: /.css$/, loader: 'file?name=[name].[ext]' }, { test: /\.jsx?$/, exclude: /node_modules/, loaders: ['react-hot-loader','babel-loader'] }, ], }, resolve: { extensions: ['.js', '.jsx'], }, devtool: '#eval-source-map', devServer: { historyApiFallback: true, watchOptions: { aggregateTimeout: 300, poll: 1000 }, headers: { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS", "Access-Control-Allow-Headers": "X-Requested-With, content-type, Authorization" } }, };
const Highscore = require("../../models/highscore"); module.exports = (req, res) => { Highscore.findById(req.params.highscoreId, function (err, highscore) { if (err) res.sendStatus(404); res.json(highscore); }); };
var searchData= [ ['widget',['Widget',['../classsfg_1_1Widget.html#a7a85471a7906e7de686c781b8d9788e3',1,'sfg::Widget']]], ['window',['Window',['../classsfg_1_1Window.html#a580b72ad982ef7534783b6477c4e90bf',1,'sfg::Window']]], ['wipestatecache',['WipeStateCache',['../classsfg_1_1Renderer.html#aad5587332fc70c3b7520cbd7246cb490',1,'sfg::Renderer']]] ];
/** * @license Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang( 'uicolor', 'eu', { title: 'EI kolore-hautatzailea', options: 'Color Options', // MISSING highlight: 'Highlight', // MISSING selected: 'Selected Color', // MISSING predefined: 'Aurrez definitutako kolore multzoak', config: 'Itsatsi kate hau zure config.js fitxategian' } );
class QTable { constructor(initialQ, numActions) { this.map = new Map(); this.initialQ = initialQ; this.numActions = numActions; } get(obs, action) { let val = this.map.get(obs * this.numActions + action); if (val == undefined) { return this.initialQ; } return val; } set(obs, action, value) { this.map.set(obs * this.numActions + action, value); } copy() { let res = new QTable(); for (let [key, value] of this.map) { res.map.set(key, value); } return res; } }
/** * Copyright «©» 2014, FOCUS CONSULTORES ASOCIADOS SAC. All rights reserved. * * This file is part of FocusSeguridadApp. * * FocusSeguridadApp 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. * * FocusSeguridadApp 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 FocusSeguridadApp. If not, see <http://www.gnu.org/licenses/>. */ /** * GENERATOR CRUD EXT JS 5 * BY FOCUS CONSULTORES ASOCIADOS SAC * DATE CREATE : 20/12/2014 23:29:59 * VERSION : 1.0 */ Ext.define('MyApp.store.GestionarFuncionalidad.MainStore', { extend: 'Ext.data.Store', model: 'MyApp.model.GestionarFuncionalidad.MainModel', // autoLoad: true, // remoteSort:true, // remoteFilter:true, // pageSize: 20, // autoLoad: {start: 0, limit: 20}, proxy: { type: 'ajax', api: { read : 'GestionarFuncionalidadView.action', create : 'GestionarFuncionalidadCreate.action', update: 'GestionarFuncionalidadSave.action', destroy: 'GestionarFuncionalidadRemove.action' }, reader: { type: 'json', rootProperty: 'data', successProperty: 'success', totalProperty: 'total', messageProperty: 'message' }, writer: { type: 'json', writeAllFields: true, encode: false, rootProperty: 'data' }, listeners: { exception: function(proxy, response, operation){ Ext.MessageBox.show({ title: 'REMOTE EXCEPTION', msg: operation.getError(), icon: Ext.MessageBox.ERROR, buttons: Ext.Msg.OK }); } } } });
'use strict'; const fs = require('fs'), zmq = require('zmq'), filename = process.argv[2], requester = zmq.socket('req'); requester.on('message', function (data) { let response = JSON.parse(data); console.log('Received response: ', response); }); requester.connect('tcp://localhost:5433'); console.log('Sending request for ' + filename); requester.send(JSON.stringify({ path: filename }));
import _get from 'lodash/get'; import React from 'react'; import { createBottomTabNavigator } from 'react-navigation-tabs'; import CharacterStackNavigator from './CharacterStackNavigator'; import TeamStackNavigator from './TeamStackNavigator'; import SettingsStackNavigator from './SettingsStackNavigator'; import TabIcon from '../components/TabIcon'; import TabIconBadged from '../components/TabIconBadged'; import { colors } from '../styles'; const routeConfiguration = { Characters: { screen: CharacterStackNavigator, path: 'characters', }, Teams: { screen: TeamStackNavigator, path: 'teams', }, Settings: { screen: SettingsStackNavigator, path: 'settings', }, }; const tabNavigatorConfig = { initialRouteName: 'Characters', backBehavior: 'none', defaultNavigationOptions: ({ navigation }) => ({ tabBarIcon: ({ focused, horizontal, tintColor }) => { const { routeName } = navigation.state; if (routeName === 'Teams') { return ( <TabIconBadged iconName={'list'} size={24} color={tintColor} selected={focused} horizontal={horizontal} /> ); } let iconName; if (routeName === 'Characters') { iconName = 'documents'; } else if (routeName === 'Settings') { iconName = 'cog'; } return ( <TabIcon iconName={iconName} size={24} color={tintColor} selected={focused} horizontal={horizontal} /> ); }, tabBarOnPress: ({ navigation: tabNavigation, defaultHandler }) => { if (tabNavigation.isFocused() && tabNavigation.state.index === 0) { const stackNavigation = _get(tabNavigation, 'state.routes[0]'); if ( stackNavigation && stackNavigation.params && stackNavigation.params.resetScreen ) { stackNavigation.params.resetScreen(); } } else { defaultHandler(); } }, }), tabBarOptions: { activeTintColor: colors.tabActiveTint, inactiveTintColor: colors.tabInactiveTint, labelStyle: { fontSize: 13, }, }, }; const TabNavigator = createBottomTabNavigator( routeConfiguration, tabNavigatorConfig, ); export default TabNavigator;
vti_encoding:SR|utf8-nl vti_timelastmodified:TW|14 Aug 2014 12:39:17 -0000 vti_extenderversion:SR|12.0.0.0 vti_author:SR|Office-PC\\Rafael vti_modifiedby:SR|Office-PC\\Rafael vti_timecreated:TR|01 Nov 2014 09:08:24 -0000 vti_backlinkinfo:VX| vti_nexttolasttimemodified:TW|14 Aug 2014 12:39:17 -0000 vti_cacheddtm:TX|03 Nov 2015 21:07:00 -0000 vti_filesize:IR|7034 vti_syncofs_mydatalogger.de\:22/%2fvar/www/vhosts/s16851491.onlinehome-server.info/kaufreund.de:TW|14 Aug 2014 12:39:17 -0000 vti_syncwith_mydatalogger.de\:22/%2fvar/www/vhosts/s16851491.onlinehome-server.info/kaufreund.de:TW|03 Nov 2015 21:07:00 -0000
const Actions = require('./Actions'); export const ACTION_SEND_REQUEST = Actions.register('requests-send'); export const sendRequest = Actions.registerActionCreator( ACTION_SEND_REQUEST, /* * If more than one request with this id is made, the previous request will be aborted. * @returns {Function} Returns a thunk that runs the given functions * in the following order: * 1. begin() (optional) - returns the action to be sent initially * 2. makeRequest(getState) - returns a thenable representing the request that was made * 3. success(response) (optional) - returns the action to be sent on success based on the response * 4. failure(error) (optional) - returns the action to be sent on failure */ ({ id, makeRequest, begin = () => {}, success = () => {}, failure = () => {}, }) => { return (dispatch, getState) => { const maybeDispatch = (action) => action ? dispatch(action) : null; maybeDispatch(begin()); const request = makeRequest(getState); dispatch(Actions.createAction(ACTION_SEND_REQUEST, { id, request, })); const requestNumber = getState().requests.getRequestNumber(id); return request.then((response) => { if (getState().requests.getRequestNumber(id) === requestNumber) { maybeDispatch(success(response)); } }).catch((error) => { if (getState().requests.getRequestNumber(id) === requestNumber) { maybeDispatch(failure(error)); } }); }; } );
var dir_26f86437d447a114ddfe6b1e8d3d8da9 = [ [ "batches.h", "batches_8h_source.html", null ], [ "cache.h", "cache_8h_source.html", null ], [ "control.h", "control_8h_source.html", null ], [ "cycle.h", "cycle_8h_source.html", null ], [ "debug.h", "debug_8h_source.html", null ], [ "util.h", "util_8h_source.html", null ] ];
/* Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang( 'stylescombo', 'mk', { label: 'Styles', panelTitle: 'Formatting Styles', // MISSING panelTitle1: 'Block Styles', // MISSING panelTitle2: 'Inline Styles', // MISSING panelTitle3: 'Object Styles' // MISSING } );
'use strict'; const Role = require('./role'); class Commissar extends Role { constructor(wolf, player) { super(wolf, player); this.id = 'commissar'; this.name = this.i18n.job_name('commissar'); this.priority = 2; this.allowEvents = [ 'vote', 'isparty' ]; } action(ev, target, queue) { if (ev === 'isparty') { // killed if (target.role.id === 'partymember') { target.role.endOfLife(ev, this.player, queue); // message target this.ba.sendMessage({ chat_id: this.user_id, text: this.i18n.__('commissar.found_partymember', { name: this.i18n.player_name(target) }) }, (err, r) => { if (err) console.log(err); }); } else { this.ba.sendMessage({ chat_id: this.user_id, text: this.i18n.__('commissar.notfound', { name: this.i18n.player_name(target) }) }, (err, r) => { if (err) console.log(err); }); } } } eventNight(queue) { let players = this.wolf.players; let keyboard = []; for (let u of players) { if (u.role.dead || u.id === this.user_id) { continue; } let pname = this.wolf.i18n.player_name(u, true); // \/[evname] [user_id] [chat_id] keyboard.push([{ text: pname, callback_data: this.makeCommand('isparty', u.id, this.chat_id) }]); } // skip keyboard.push([{ text: 'Skip', callback_data: this.makeCommand('isparty', 0, this.chat_id) }]); var self = this; queue.addVoter(this.player); this.event_message_id = null; this.ba.sendMessage({ chat_id: this.user_id, text: this.i18n.__('commissar.choose'), reply_markup: JSON.stringify({ inline_keyboard: keyboard }), }, (err, r) => { if (err) { console.log(err); } else { self.event_message_id = r.message_id; } }); } nightTimeUp() { if (this.event_message_id) { this.ba.editMessageText({ chat_id: this.user_id, message_id: this.event_message_id, text: this.i18n.__('common.timeup') }); } } eventNightCallback(queue, upd, data) { super.eventNightCallback(queue, upd, data); // update message let cq = upd.callback_query; this.ba.editMessageText({ chat_id: cq.message.chat.id, message_id: cq.message.message_id, text: this.i18n.__('common.selected', { name: data.name }) }); } }; module.exports = Commissar;
'use strict'; var exec = require('child_process').execSync; setInterval(function () { console.log('A message'); }, 500); setInterval(function () { console.log('A second message'); }, 500); setInterval(function () { console.log('Running a thread blocking process'); if (process.platform == 'win32') { exec('PING -n 3 -w 1000 127.1 >NUL'); } else { exec('sleep 3'); } }, 5000);
$('#zgzsTable').datagrid({ fitColumns:true, url:'contect/list1', singleSelect:true, columns:[[ {field:'cid',title:'编号',width:20,align:'center'}, {field:'cconcrete',title:'资质证书',width:150,align:'center', formatter:function(value,row,index){ var str = '<img width="300" height="150" alt="资质证书长腿了??" src="'+value+'"/>'; return str; } }, {field:'operator',title:'操作',width:50,align:'center', formatter:function(value,row,index){ var str = '<a class="operatorBtn" href="javaScript:void(0)" onClick="delC('+row.cid+')">删除</a>' +'<script>$(".operatorBtn").linkbutton({iconCls: "icon-edit"});</script>'; return str; } }, ]] }); function delC(cid){ $.messager.confirm('确认对话框', '您确认删除吗?', function(r){ if (r){ $.get("contect/delZzzs?cid="+cid,function(data){ if(data){ $.messager.alert('消息提示','恭喜您,删除成功...','info'); $('#zgzsTable').datagrid('reload'); }else{ $.messager.alert('消息提示','抱歉,可能由于网络原因删除失败...','info'); } },"json") } }); }
/* As in the rest parameters exercise, your goal is to write a Node module whose default export is a function. This time it will take two arguments: a lower bound and an upper bound. Your function should return the midpoint between those two bounds. However, your function should have sensible defaults. The lower bound should default to 0, and the upper bound should default to 1. As before, you don't need to print anything to the console. Your solution should look something like: */ module.exports = (lower=0, upper=1)=> (upper+lower)/2; /* We'll test your module by passing it a few different sets of arguments: sometimes none, sometimes one, sometimes two. Sometimes we'll pass in an explicit undefined, and you should be sure to treat that as the default. */
$(document).ready(function() { $('ul.block-filtered-items li').each(function(index, element) { $(this).attr('data-type',$(this).attr('title')).attr('data-id','item'+index).removeAttr('title'); }); // get the action filter option item on page load var $filterType = $('#filter-cats a.active').attr('href'); // get and assign the ourHolder element to the // $holder varible for use later var $holder = $('ul.block-filtered-items'); // clone all items within the pre-assigned $holder element var $data =$holder.clone() // attempt to call Quicksand when a filter option // item is clicked $('#filter-cats a').click(function(e) { // reset the active class on all the buttons $('#filter-cats a').removeClass('active'); // assign the class of the clicked filter option // element to our $filterType variable var $filterType = $(this).attr('href'); $(this).addClass('active'); if ($filterType == 'all') { // assign all li items to the $filteredData var when // the 'All' filter option is clicked var $filteredData = $data.find('li'); } else { // find all li elements that have our required $filterType // values for the data-type element var $filteredData = $data.find('li[data-type=' + $filterType + ']'); } // call quicksand and assign transition parameters $holder.quicksand($filteredData, { duration: 800, easing: 'easeInOutQuad' },function(){$('.block-filtered-items').removeAttr('style');}) return false; }); });
import { graphql } from 'react-relay'; import commitMutation from '../utils/commitMutation'; const mutation = graphql` mutation UpdateViewerMutation($input: UpdateViewerInput!) { updateViewer(input: $input) { viewer { id email pseudo description hasPrivateProfile } } } `; const updateViewer = input => commitMutation({ mutation, variables: { input: { ...input, clientMutationId: Math.random().toString().slice(2), }, }, }); export default updateViewer;
var fs = require('fs'); var express = require('express'); var cookie = require('cookie'); var util = require('../util'); var uglify = require('uglify-js'); var browserify = require('browserify'); var generateClientSourceCode = function(debug) { return browserify(__dirname + '/../browserify.js', { debug : debug }).bundle() + fs.readFileSync(__dirname + '/../../node_modules/ace/build/src/ace.js'); }; module.exports = function(app, logger, cfg, t) { fs.writeFileSync(__dirname + '/../client/cfg.js', 'module.exports=' + JSON.stringify(cfg.client) + ';'); var srcdebug = generateClientSourceCode(true); var src = generateClientSourceCode(false); var ast = uglify.parser.parse(src); ast = uglify.uglify.ast_mangle(ast, { mangle : true, toplevel : false, defines : {}, except : null, no_functions : false }); ast = uglify.uglify.ast_squeeze(ast, { make_seqs : true, dead_code : true, keep_comps : true, unsafe : false }); src = uglify.uglify.gen_code(ast, { ascii_only: false, beautify: false, indent_level: 4, indent_start: 0, quote_keys: false, space_colon: false, inline_script: false }); app.configure(function() { logger.info('app.use'); app.use(function(req, res, next) { res.removeHeader('X-Powered-By'); req.url = req.path; next(); }); app.use(express.compress()); app.use(express['static'](__dirname + '/../../public_html')); app.use(express.bodyParser({ // client needs to send bare strings and even nulls strict : false })); app.use(function(req, res, next) { req.cookies = req.header('Cookie'); if(typeof req.cookies === 'string') { try { req.cookies = cookie.parse(req.cookies); } catch(e) { req.cookies = {}; } } else { req.cookies = {}; } next(); }); app.use(function(req, res, next) { logger.info('REQUEST', req.method, req.url, req.cookies); req.sessionId = typeof req.cookies.sessionId === 'undefined' ? null : req.cookies.sessionId; next(); }); app.use(function(req, res, next) { if(util.startsWith(req.url, '/script')) { if(util.startsWith(req.url, '/script/index.js')) { res.statusCode = 200; res.setHeader('content-type', 'text/javascript'); if(typeof req.cookies.debug === 'undefined') { res.setHeader('last-modified', cfg.client.version.date); res.end(src); } else { res.setHeader('last-modified', new Date()); res.end(srcdebug); } } else if(typeof req.cookies.script === 'undefined') { res.send(t.cookies({ baseurl : cfg.client.baseurl })); } else { res.header('Set-Cookie', cookie.serialize('script', req.url.charAt('/script/'.length), { path : '/' })); res.redirect(req.url.substr('/script/0'.length)); } } else { if(typeof req.cookies.script === 'string') { next(); } else { res.header('Set-Cookie', cookie.serialize('script', 'testing', { path : '/' })); res.send(t.script({ baseurl : cfg.client.baseurl, path : req.url })); } } }); }); };
/** * @file fieldMutateState.js * @copyright Copyright 2016 Clay Freeman. All rights reserved * @license GNU General Public License v3 (GPL-3.0) * * Responsible for form validation control and field status indicators */ function fieldMutateState(field, enabled, indicateState) { // Select the icon and form from the field var icon = field.siblings('i'); var form = field.closest('form'); // Remove the icon's classes icon.removeClass(function(index, css) { return (css.match(/(^|\s)uk-icon-\S+/g) || []).join(' '); }); if (enabled) { // Update the state of the field to show success field.removeAttr('unverified'); field.removeClass('uk-form-danger'); field.addClass('uk-form-success'); icon.addClass('uk-icon-check'); // Enable form submission if appropriate if (form.find('input[unverified]').length == 0) form.find('button').prop('disabled', false); } else { // Update the state of the field to show failure field.attr('unverified', true); field.removeClass('uk-form-success'); if (indicateState) { field.addClass('uk-form-danger'); icon.addClass('uk-icon-close'); } else { field.removeClass('uk-form-danger'); } // Disable form submission form.find('button').prop('disabled', true); } }
////////////////////////////////////////////////////////////////////////////// // // This file is part of Geotagger: A tool for geotagging photographs // Copyright (C) 2007 Kaz Okuda (http://notions.okuda.ca) // // Geotagger 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/>. // ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// // Object for interfacing the GeoTagger application with Bing Maps. ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// // Create Singleton BMapInterface as Bing Map interface to geotagger. var BMapInterface = new function() { ////////////////////////////////////////////////////////////////////////// // Public members this.mMap = null; this.mGeocoder = null; ////////////////////////////////////////////////////////////////////////// // Check the availability of Bing Maps this.IsAvailable = function() { return true; } ////////////////////////////////////////////////////////////////////////// // Initialize BMapInterface with the Bing Map this.Initialize = function(map) { try { mMap = new VEMap(map); mMap.LoadMap(new VELatLong(49.2, -123), 10); var draggingElement = null; var dragging = false; var clickX = null; var clickY = null; var mouseHandler = function(e) { if (e.eventName == "onmousedown" && e.elementID != null) { var shape = mMap.GetShapeByID(e.elementID); if (shape.GetType() == VEShapeType.Pushpin) { draggingElement = shape; dragging = false; // Sticky clickX = e.mapX; clickY = e.mapY; return true; } } else if (e.eventName == "onmouseup" && draggingElement != null) { if (dragging) { var points = draggingElement.GetPoints(); GTMInterface.MarkerDrop(draggingElement.myID, points[0].Latitude, points[0].Longitude); } else { GTMInterface.MarkerClick(draggingElement.myID); } draggingElement = null; } else if (e.eventName == "onmousemove" && draggingElement != null) { if (!dragging) { // If we have moved sufficiently then we can begin dragging. if (Math.abs(clickX - e.mapX) > 10 || Math.abs(clickY - e.mapY) > 10) { // Unstick. dragging = true; } } else { var point = mMap.PixelToLatLong(new VEPixel(e.mapX, e.mapY)); draggingElement.SetPoints(point); return true; } } } // Handle the map click event. mMap.AttachEvent("onmousedown", mouseHandler); mMap.AttachEvent("onmouseup", mouseHandler); mMap.AttachEvent("onmousemove", mouseHandler); } catch (e) { alert(e.message); } }; ////////////////////////////////////////////////////////////////////////// // ClearTrack: Removes all track points from the map. this.ClearTrack = function () { mMap.DeleteAllShapes(); }; ////////////////////////////////////////////////////////////////////////// // StartTrack: Indicates the begining of a track point list. this.StartTrack = function () { var pointarray = []; // Temporarily add a new function for adding the track points. this.AddTrackPoint = function (lat, lng) { var latlng = new VELatLong(lat, lng); pointarray.push(latlng) } this.EndTrack = function () { // Remove the temporary functions this.AddTrackPoint = null; this.EndTrack = null; var polyline = new VEShape(VEShapeType.Polyline, pointarray); polyline.HideIcon(); mMap.AddShape(polyline); }; }; ////////////////////////////////////////////////////////////////////////// // CreateMarker: Create a marker on the map (probably for a photo this.CreateMarker = function (id, lat, lng) { var marker = new VEShape(VEShapeType.Pushpin, new VELatLong(lat, lng)); marker.myID = id; //GEvent.addListener(marker, "dragend", // function() // { // var latlng = marker.getLatLng(); // GTMInterface.MarkerDrop(id, latlng.lat(), latlng.lng()); // } //); mMap.AddShape(marker); return marker; } ////////////////////////////////////////////////////////////////////////// // MoveMarker: Moves a marker to a new location. this.MoveMarker = function (marker, lat, lng) { marker.SetPoints([new VELatLong(lat, lng)]); } ////////////////////////////////////////////////////////////////////////// // Search: Find the given address and navigate the map to it. this.Search = function (address) { try { mMap.Find(null, address); } catch(e) { GTMInterface.Alert(e); } } }
/*eslint-env applescript*/ /*eslint-env builtins*/ /*eslint eqeqeq:0, quotes:0, space-infix-ops:0, curly:0*/ "use strict"; var photosTab, photos = {url: 'https://photos.google.com'}, photosAlt = {url: 'https://photos.google.com/u/1'}; $.browser.tabSelected = photosTab = new $.WebView(photos); var delegate = {}; // our delegate to receive events from the webview app function search(query) { photosTab.loadURL("https://photos.google.com/search/"+query); // FIXME: do this in JS } delegate.launchURL = function(url) { console.log("app.js: launching " + url); var comps = url.split(':'), scheme = comps.shift(), addr = comps.shift(); switch (scheme) { case 'http': case 'https': case 'file': // prompt to do upload photosTab.evalJS('confirm("Upload '+url+'?");'); // http://stackoverflow.com/a/30565302/3878712 // document.querySelector("input[type='file']").click() // document.querySelector("div[aria-label='Upload photos']").click() break; case 'googlephotos': case 'gphotos': search(addr); break; default: $.browser.tabSelected = new $.WebView({url: url}); } }; delegate.handleUserInputtedInvalidURL = function(query) { // assuming the invalid url is a search request search(encodeURI(query)); if ($.app.pathExists(query)) this.launchURL('file://' + query); else search(encodeURI(query)); // assuming the invalid url is a search request return true; // tell MacPin to stop validating the URL }; // handles all URLs drag-and-dropped into NON-html5 parts of Photos and Dock icon. delegate.handleDragAndDroppedURLs = function(urls) { console.log(urls); for (var url of urls) { this.launchURL(url); //$.browser.tabSelected = new $.WebView({url: url}); } return true; } delegate.AppFinishedLaunching = function() { $.app.registerURLScheme('googlephotos'); //IOS? $.app.registerURLScheme('gphotos'); $.browser.addShortcut('Google Photos', photos); $.browser.addShortcut('Google Photos (using secondary account)', photosAlt); $.browser.addShortcut('Picasa Web Albums', 'http://picasaweb.google.com/lh/myphotos?noredirect=1'); if ($.launchedWithURL != '') { // app was launched with a feed url this.launchURL($.launchedWithURL); $.launchedWithURL = ''; } }; delegate; //return this to macpin
Ext.define('PM.view.NorthPanel', { extend: 'Ext.panel.Panel', alias : 'widget.northpanel', layout: { type: 'hbox', pack: 'start', align: 'middle' }, defaults:{ margin: '2, 4, 2, 4' }, items:[{ xtype: 'component', html: '<div id="title">Div@ter</div>' }, { xtype:'tbfill' },{ xtype: 'component', name: 'welcomeMsg', html: '<div>Benvenuto Nome Cognome</div>' },{ xtype: 'button', text: 'Logout' }], openWindow: function(){ this.win=Ext.create('PM.view.SettingsWindow').show(); }, closeWindow: function(){ this.win.destroy(); } });
let $pageButton = $('#page-list-button'); let $pageList = $('#page-list'); let $main = $('.main'); let $mainButton = $('#main-button'); let $history = $('.history'); let $historyButton = $('#history-button'); let $laws = $('.laws'); let $lawsButton = $('#laws-button'); let $title = $('#web-title'); $pageList.hide(); $history.hide(); $laws.hide(); console.log("Ready"); $(document).ready(() => { $pageButton.on('click', () => { $pageList.fadeToggle(); }) $mainButton.on('click', () => { $history.fadeOut(); $laws.fadeOut(); setTimeout(function(){$main.fadeIn(); document.getElementById(title).innerHTML = "The Book Kingdom";}, 402); console.log("Main page refreshed"); }) $historyButton.on('click', () => { $main.fadeOut(); $laws.fadeOut(); setTimeout(function(){$history.fadeIn(); document.getElementById(title).innerHTML = "History - The Book Kingdom";}, 402); console.log("History page opened"); }) $lawsButton.on('click', () => { $history.fadeOut(); $main.fadeOut(); setTimeout(function(){$laws.fadeIn(); document.getElementById(title).innerHTML = "Laws - The Book Kingdom";}, 402); console.log("Laws page opened"); }) })
let Frecuencia = 100; let Tiempo = 0; let P1, P2; let L1, L2; let Panel1, Panel2; let Grosor; function setup() { createCanvas(500, 500); background(0); } function draw() { if (Tiempo + Frecuencia < millis()) { Tiempo = millis(); EscojerLina(); EscojerPanel(); ActualizarPanel(); ActualizarLinea(); } } function ActualizarPanel() { let Vector = p5.Vector.sub(P1, P2); print(Vector); let Angulo1 = p5.Vector.fromAngle(Vector.heading() + PI/2); Angulo1 = Angulo1.mult(Grosor/2); let Angulo2 = p5.Vector.fromAngle(Vector.heading() + PI/2); Angulo2 = Angulo2.mult(-Grosor/2); print(Angulo1.x); push(); translate(Angulo1.x, Angulo1.y); image(Panel1, 0, 0); pop(); push(); translate(Angulo2.x, Angulo2.y); image(Panel2, 0, 0); pop() } function EscojerPanel() { Panel1 = get(); Panel2 = get(); Panel1.loadPixels(); Panel2.loadPixels(); let Vector = p5.Vector.sub(P1, P2); let Angulo = Vector.heading(); let P; for (let x = 0; x < Panel1.width; x++) { for (let y = 0; y < Panel2.height; y++) { P = createVector(x, y); let PM = p5.Vector.sub(P1, P); let PAngulo = PM.heading(); if (Angulo < PAngulo) { Panel1.set(x, y, color(0, 0, 0, 0)); } else { Panel2.set(x, y, color(0, 0, 0, 0)); } } } Panel1.updatePixels(); Panel2.updatePixels(); } function ActualizarLinea() { strokeWeight(Grosor/3); stroke(255); DibujarLineaGrosor(Grosor/2); DibujarLineaGrosor(-Grosor/2); strokeWeight(Grosor); stroke(random(255), random(255), random(255)); DibujarLinea(); } function DibujarLineaGrosor(G) { push(); translate(P1.x, P1.y); let Vector = p5.Vector.sub(P2, P1); let VectorInicial = p5.Vector.fromAngle(Vector.heading() + PI/2); VectorInicial=VectorInicial.mult(G); translate(VectorInicial.x, VectorInicial.y); line(0, 0, Vector.x, Vector.y); pop(); } function DibujarLinea() { line(P1.x, P1.y, P2.x, P2.y); } function EscojerLina() { L1 = int(random(0, 4)); do { L2 = int(random(0, 4)); } while (L1 == L2); if (L2 > L1) { let Ltmp= L2; L2 = L1; L1 = Ltmp; } print("L1 " + L1); P1 = EscojerLado(L1); P2 = EscojerLado(L2); Grosor = random(5, 30); } function EscojerLado(l) { let V = createVector(0, 0); switch(l) { case 0: V.x = 0; V.y = random(height); break; case 1: V.x = random(width); V.y = 0; break; case 2: V.x = width; V.y = random(height); break; case 3: V.x = random(width); V.y = height; break; } return V; } let EstadoLoop = true; function mousePressed() { if (EstadoLoop) { noLoop(); } else { loop(); } EstadoLoop= !EstadoLoop; }
var mysql = require("mysql"); var logger = require("./logger"); var pool = mysql.createPool({ host: "localhost", port: 3306, database: "agitodo", user: "agitodo", password: "PASSWORD", charset: "utf8_bin", connectionLimit: 4 }); function logError(err) { logger.error(err); } function execute(template, values, stream, callback) { pool.getConnection(function(err, connection) { if (err) { logError(err); return callback ? callback(err) : undefined; } values = values ? values : []; console.log(template + " , " + values); var result = []; var error = null; var query = connection.query(template, values); query.on("error", function(err) { // Handle error, an "end" event will be emitted after this as well logError(err); error = err; }).on("fields", function(fields) { // the field packets for the rows to follow }).on("result", function(row) { if (stream) { return callback ? callback(error, row) : undefined; } result.push(row); }).on("end", function() { connection.release(); return callback ? callback(error, stream ? undefined : result) : undefined; }); }); } function valueToSql(value) { if (typeof value === "object" && value !== null) { if (Object.prototype.toString.call(value) === "[object Date]") { value = value.toISOString(); } else { value = JSON.stringify(value); } } return value; } function objToSql(dict, join) { var placeholders = []; var values = []; for (var k in dict) { placeholders.push(k + " = ?"); values.push(valueToSql(dict[k])); } return { sql: placeholders.join(join ? join : ""), values: values } } function update(table, setColumns, conditions, callback) { if (!setColumns) { return callback ? callback() : undefined; } var sql = "UPDATE `" + table + "`"; var s = objToSql(setColumns, ", "); sql += (" SET " + s.sql); var values = s.values; if (conditions) { var s = objToSql(conditions, " AND "); sql += (" WHERE " + s.sql); Array.prototype.push.apply(values, s.values); } execute(sql, values, false, callback); } function insert(table, setColumns, onDuplicate, callback) { if (!setColumns) { return callback ? callback() : undefined; } var sql = "INSERT INTO `" + table + "`"; var s = objToSql(setColumns, ", "); sql += (" SET " + s.sql); var values = s.values; if (onDuplicate) { var s = objToSql(onDuplicate, ", "); sql += (" ON DUPLICATE KEY UPDATE " + s.sql); Array.prototype.push.apply(values, s.values); } execute(sql, values, false, callback); } function select(table, conditions, callback) { var sql = "SELECT * FROM `" + table + "`"; var values = []; if (conditions) { var s = objToSql(conditions, " AND "); sql += (" WHERE " + s.sql); Array.prototype.push.apply(values, s.values); } execute(sql, values, false, callback); } function remove(table, conditions, callback) { if (!conditions) { return callback ? callback() : undefined; } var sql = "DELETE FROM `" + table + "`"; var s = objToSql(conditions, " AND "); execute(sql + " WHERE " + s.sql, s.values, false, callback); } module.exports = { "execute": execute, "select": select, "insert": insert, "update": update, "remove": remove };
// This file is part of Moodle - http://moodle.org/ // // Moodle 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. // // Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>. /** * JavaScript code for the gapfill question type. * * @package qtype * @subpackage gapfill * @copyright 2012 Marcus Green * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ /* This should be called script.js and go through the Moodle minify process but that seems to break it */ $(function () { readonly = document.querySelectorAll('.readonly'); if (readonly.length > 0) { return; } $(".draggable").draggable({ revert: false, helper: 'clone', cursor: 'pointer', scroll: 'false', start: function (event, ui) { $(this).fadeTo('fast', 0.5); }, stop: function (event, ui) { $(this).fadeTo(0, 1); } }); $(".droptarget").droppable({ hoverClass: 'active', drop: function (event, ui) { this.value = $(ui.draggable).text(); $(this).css("background-color", "white"); } }); });
"use strict"; const roleHauler = { /** @param {Creep} creep */ run: function(creep) { if (creep.memory.pickingUp === undefined || (creep.memory.pickingUp === false && creep.carry.energy === 0)) { creep.memory.pickingUp = true; getRandomDroppedEnergy(creep); } else if (creep.memory.pickingUp === true && creep.carry.energy === creep.carryCapacity) { creep.memory.pickingUp = false; creep.say("\u{1F69B}", true); getUncappedStruct(creep); } /* STATE EXECUTION ***************************************************/ if (creep.memory.pickingUp === true) { // If there's dropped energy in the room, pick it up, if (creep.memory.pickupId !== null && creep.pickup(Game.getObjectById(creep.memory.pickupId)) === ERR_NOT_IN_RANGE) { creep.moveTo(Game.getObjectById(creep.memory.pickupId), {visualizePathStyle: {stroke: "#ff0000"}}); } // and, if still not at max carry capacity, else if (creep.carry.energy < creep.carryCapacity) { // get the nearest dropped energy. getNearestDroppedEnergy(creep); } } // If there are available dump sites, dump energy. else if (creep.memory.dropoffId !== null && creep.transfer(Game.getObjectById(creep.memory.dropoffId), RESOURCE_ENERGY) === ERR_NOT_IN_RANGE) { creep.moveTo(Game.getObjectById(creep.memory.dropoffId), {visualizePathStyle: {stroke: "#0000ff"}}); } // Otherwise, else { // stand by creep.moveTo(Game.flags[creep.room.name + " Tavern"]); // and keep seeking dump sites. getUncappedStruct(creep); } } }; /** * Assigns the ID of a random mass of dropped energy in the room to the creep's memory.pickupId field * @param {Creep} creep */ function getRandomDroppedEnergy(creep) { // Probe all dropped energy in the room. let droppedEnergy = creep.room.find(FIND_DROPPED_RESOURCES, { filter: (resource) => { return resource.resourceType === RESOURCE_ENERGY; } }); // If there's dropped energy in the room, if (droppedEnergy !== null && droppedEnergy.length > 0) { // pick a random deposit. creep.memory.pickupId = droppedEnergy[Math.floor(Math.random() * droppedEnergy.length)].id; } // Otherwise, else { // set deliverId to null. creep.memory.pickupId = null; } } /** * Assigns the ID of the nearest mass of dropped energy in the room to the creep's memory.pickupId field * @param {Creep} creep */ function getNearestDroppedEnergy(creep) { creep.memory.pickupId = creep.pos.findClosestByRange(FIND_DROPPED_RESOURCES, { filter: (resource) => { return resource.resourceType === RESOURCE_ENERGY; } }); if (creep.memory.pickupId !== null) { creep.memory.pickupId = creep.memory.pickupId.id; } } /** * Sets the nearest energy bearing structure with as much or more energy than the creep can carry to * the creep's memory.dropoffId field, prioritizing extensions, spawns, and towers over containers and storages * @param {Creep} creep */ function getUncappedStruct(creep) { // Probe for available extensions, spawns, and towers. creep.memory.dropoffId = creep.pos.findClosestByRange(FIND_MY_STRUCTURES, { filter: (structure) => { return (structure.structureType === STRUCTURE_EXTENSION || structure.structureType === STRUCTURE_SPAWN || structure.structureType === STRUCTURE_TOWER) && (structure.energy < structure.energyCapacity); } }); if (creep.memory.dropoffId !== null) { creep.memory.dropoffId = creep.memory.dropoffId.id; } // If none, else { // probe for available containers and storages. creep.memory.dropoffId = creep.pos.findClosestByRange(FIND_MY_STRUCTURES, { filter: (structure) => { return (structure.structureType === STRUCTURE_CONTAINER || structure.structureType === STRUCTURE_STORAGE) && structure.store[RESOURCE_ENERGY] < structure.storeCapacity; } }); if (creep.memory.dropoffId !== null) { creep.memory.dropoffId = creep.memory.dropoffId.id; } } } module.exports = roleHauler;
import { getButton } from './../button.js' export const domain = 'streamable'; export const resource = { buttonDidAppear: function() { const progressBar = document.getElementById('player-progress'); const progressBarStyle = window.getComputedStyle(progressBar); getButton().style.right = progressBarStyle.right; progressBar.style.right = (parseInt(progressBarStyle.right, 10) + 40) + 'px'; }, buttonElementType: 'div', buttonHoverStyle: /** CSS */ (`opacity: 1 !important`), buttonParent: function() { return document.querySelector('.player-controls-right'); }, buttonStyle: /** CSS */ (` position: absolute; bottom: 10px; height: 26px; width: 26px; cursor: pointer; opacity: 0.9; filter: drop-shadow(rgba(0, 0, 0, 0.5) 0px 0px 2px); `), videoElement: function() { return document.getElementById('video-player-tag'); }, };
import React, { Component } from 'react'; export default class NotFoundPage extends Component { render() { return ( <div> <div className="container paddingTopBottom15"> <img width="100%" height="100%" src="/assets/images/404.jpg" style={{ position: 'relative' }} /> <h1 style={{ position: 'absolute', bottom: '53%', backgroundColor: '#4F3A2C', color: 'white' }}> Ups, Seite und Baum kaputt. <br /> <a style={{ color: 'white' }} href="/"> Pflanz doch hier einen neuen Baum. </a> </h1> </div> </div> ); } }
(function() { NAinfo.requireApiVersion(0, 2); var TIME = sluchch(3, 99); var remain = sluchch(10,99); var time_izm = [['секундах', 'сек', 'секунд'],['минутах', 'мин', 'минут'],['часах', 'ч', 'часов']].iz(); var g_mg = ['г', 'мг'].iz(); var step = sluchch(1,5); var m_null = remain * Math.pow(2, step); var time = TIME * step; NAtask.setTask({ text: 'В ходе распада радиоактивного изотопа его масса уменьшается по закону ' + '$m(t) = m_02^{-t/T}$' + ', где ' + '$m_0$' + ' — начальная масса изотопа, ' + '$t$' + ' (' + time_izm[1] + ') — прошедшее от начального момента время, ' + '$T$' + ' — период полураспада в ' + time_izm[0] + '. В ' + ['лаборатории', 'результате опыта', 'результате эксперимента'].iz() + ' получили вещество, содержащее в начальный момент времени ' + '$m (t) =' + ' ' + m_null + '$ ' + g_mg + ' изотопа Z' + ', период полураспада которого ' + '$T =' + ' ' + TIME + '$ ' + time_izm[1] + '. В течение скольких ' + time_izm[2] + ' масса изотопа будет ' + ['не меньше', 'больше'].iz() + ' '+ remain +' ' + g_mg + '?', answers: time, }); })(); //https://matematikalegko.ru/prikladnie/v-hode-raspada-radiaktivnogo-izotopa.html //Aisse-258
import assert from 'power-assert'; export function getWebGL2Context (canvas) { const gl = canvas.getContext('webgl2'); assert.ok(gl); return gl; } export function createStaticVbo (gl, data) { const vbo = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, vbo); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(data), gl.STATIC_DRAW); gl.bindBuffer(gl.ARRAY_BUFFER, null); return vbo; } const SQUARE = [ -1, -1, -1, 1, 1, -1, 1, 1, ]; export function createSquareVbo (gl) { return createStaticVbo(gl, SQUARE); } export function linkProgram (gl, program) { gl.linkProgram(program); assert.ok(gl.getProgramParameter(program, gl.LINK_STATUS), 'Link Program Error'); gl.useProgram(program); } export function attachShader (gl, shaderStr, program, shaderType) { const shader = gl.createShader(shaderType); gl.shaderSource(shader, shaderStr); gl.compileShader(shader); assert.ok(gl.getShaderParameter(shader, gl.COMPILE_STATUS), `Shader Compilation Error\n${gl.getShaderInfoLog(shader)}`); gl.attachShader(program, shader); } export function createTexture2D (gl, width, height, internalFormat, format, type) { const texture = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, texture); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, width, height, 0, gl.RGB, type, null); gl.bindTexture(gl.TEXTURE_2D, null); return texture; } export function createRGBTextures (gl, width, height, num) { const textures = []; for (let i = 0; i < num; i++) { textures.push(createTexture2D(gl, width, height, gl.RGB, gl.RGB, gl.UNSIGNED_BYTE, num)); } return textures; } export function createRGBATextures (gl, width, height, num) { const textures = []; for (let i = 0; i < num; i++) { textures.push(createTexture2D(gl, width, height, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, num)); } return textures; }
import React from 'react'; import FormControl from 'react-bootstrap/lib/FormControl'; import FormGroup from 'react-bootstrap/lib/FormGroup'; import Glyphicon from 'react-bootstrap/lib/Glyphicon'; import { browserHistory } from 'react-router' export default class BigSearchBox extends React.Component { constructor(props) { super(props); this.onKeywordChange = this._onKeywordChange.bind(this); this.onLinkInputKeyDown = this._onLinkInputKeyDown.bind(this); } _onKeywordChange(e) { //console.log(this); //let keyword = this._slugify(e.target.value); } _onLinkInputKeyDown(e) { //console.log(e.which); if (e.which === 13) { e.preventDefault(); let slug = this._slugify(e.target.value); if(slug.length){ browserHistory.push(`/search/${slug}/`) } } } _slugify(text) { return text.toString().toLowerCase() .replace(/\s+/g, '-') // Replace spaces with - .replace(/[^\w\-]+/g, '') // Remove all non-word chars .replace(/\-\-+/g, '-') // Replace multiple - with single - .replace(/^-+/, '') // Trim - from start of text .replace(/-+$/, '') // Trim - from end of text .replace(/[\s_-]+/g, '-'); } render() { return ( <form> <FormGroup controlId="searchNyaayaText" bsSize="large"> <FormControl type="text" placeholder="Search Nyaaya" onChange={this.onKeywordChange} onKeyDown={this.onLinkInputKeyDown} //value={textValue} /> <FormControl.Feedback> <Glyphicon glyph="search" /> </FormControl.Feedback> </FormGroup> </form> ); } } BigSearchBox.propTypes = { };
/* global prefs */ window.enabled = false; if (typeof prefs === 'object') { prefs.enabled = window.enabled; }
/* * 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/. */ /* * Copyright 2020 Joyent, Inc. */ const util = require('util'); const ldap = require('ldapjs'); const Validator = require('../lib/schema/validator'); var ID_RE = /^\w+$/; // --- API function AccessKey() { Validator.call(this, { name: 'accesskey', required: { accesskeyid: 1, accesskeysecret: 1 }, optional: { created: 1 }, strict: true }); } util.inherits(AccessKey, Validator); AccessKey.prototype.validate = function validate(entry, config, changes, callback) { var attrs = entry.attributes; var errors = []; // Skip validation when importing legacy entries: if (!config.ufds_is_master) { callback(); return; } const id = attrs.accesskeyid[0]; if (!ID_RE.test(id) || id.length < 16 || id.length > 128) { errors.push('accesskeyid: ' + id + ' is invalid'); } if (changes && changes.some(function (c) { const fixedAttrs = ['acceskeyid', 'accesskeysecret', 'created']; return (fixedAttrs.indexOf(c._modification.type) !== -1); })) { errors.push('only status can be modified'); } if (errors.length) { callback(new ldap.ConstraintViolationError(errors.join('\n'))); return; } callback(); }; // --- Exports module.exports = { createInstance: function createInstance() { return new AccessKey(); } };
import Model, { attr } from '@ember-data/model'; import { alias } from '@ember/object/computed'; import { set, get, computed } from '@ember/object'; import clamp from 'vault/utils/clamp'; import lazyCapabilities, { apiPath } from 'vault/macros/lazy-capabilities'; const ACTION_VALUES = { encrypt: { isSupported: 'supportsEncryption', description: 'Looks up wrapping properties for the given token', glyph: 'lock-fill', }, decrypt: { isSupported: 'supportsDecryption', description: 'Decrypts the provided ciphertext using this key', glyph: 'mail-open', }, datakey: { isSupported: 'supportsEncryption', description: 'Generates a new key and value encrypted with this key', glyph: 'key', }, rewrap: { isSupported: 'supportsEncryption', description: 'Rewraps the ciphertext using the latest version of the named key', glyph: 'reload', }, sign: { isSupported: 'supportsSigning', description: 'Get the cryptographic signature of the given data', glyph: 'pencil-tool', }, hmac: { isSupported: true, description: 'Generate a data digest using a hash algorithm', glyph: 'shuffle', }, verify: { isSupported: true, description: 'Validate the provided signature for the given data', glyph: 'check-circle', }, export: { isSupported: 'exportable', description: 'Get the named key', glyph: 'external-link', }, }; export default Model.extend({ type: attr('string', { defaultValue: 'aes256-gcm96', }), name: attr('string', { label: 'Name', fieldValue: 'id', readOnly: true, }), autoRotatePeriod: attr({ defaultValue: '0', defaultShown: 'Key is not automatically rotated', editType: 'ttl', label: 'Auto-rotation period', }), deletionAllowed: attr('boolean'), derived: attr('boolean'), exportable: attr('boolean'), minDecryptionVersion: attr('number', { defaultValue: 1, }), minEncryptionVersion: attr('number', { defaultValue: 0, }), latestVersion: attr('number'), keys: attr('object'), convergentEncryption: attr('boolean'), convergentEncryptionVersion: attr('number'), supportsSigning: attr('boolean'), supportsEncryption: attr('boolean'), supportsDecryption: attr('boolean'), supportsDerivation: attr('boolean'), setConvergentEncryption(val) { if (val === true) { set(this, 'derived', val); } set(this, 'convergentEncryption', val); }, setDerived(val) { if (val === false) { set(this, 'convergentEncryption', val); } set(this, 'derived', val); }, supportedActions: computed('type', function () { return Object.keys(ACTION_VALUES) .filter((name) => { const { isSupported } = ACTION_VALUES[name]; return typeof isSupported === 'boolean' || get(this, isSupported); }) .map((name) => { const { description, glyph } = ACTION_VALUES[name]; return { name, description, glyph }; }); }), canDelete: computed('deletionAllowed', 'lastLoadTS', function () { const deleteAttrChanged = Boolean(this.changedAttributes().deletionAllowed); return this.deletionAllowed && deleteAttrChanged === false; }), keyVersions: computed('validKeyVersions', function () { let maxVersion = Math.max(...this.validKeyVersions); let versions = []; while (maxVersion > 0) { versions.unshift(maxVersion); maxVersion--; } return versions; }), encryptionKeyVersions: computed( 'keyVerisons', 'keyVersions', 'latestVersion', 'minDecryptionVersion', function () { const { keyVersions, minDecryptionVersion } = this; return keyVersions .filter((version) => { return version >= minDecryptionVersion; }) .reverse(); } ), keysForEncryption: computed('minEncryptionVersion', 'latestVersion', function () { let { minEncryptionVersion, latestVersion } = this; let minVersion = clamp(minEncryptionVersion - 1, 0, latestVersion); let versions = []; while (latestVersion > minVersion) { versions.push(latestVersion); latestVersion--; } return versions; }), validKeyVersions: computed('keys', function () { return Object.keys(this.keys); }), exportKeyTypes: computed('exportable', 'supportsEncryption', 'supportsSigning', 'type', function () { let types = ['hmac']; if (this.supportsSigning) { types.unshift('signing'); } if (this.supportsEncryption) { types.unshift('encryption'); } return types; }), backend: attr('string'), rotatePath: lazyCapabilities(apiPath`${'backend'}/keys/${'id'}/rotate`, 'backend', 'id'), canRotate: alias('rotatePath.canUpdate'), secretPath: lazyCapabilities(apiPath`${'backend'}/keys/${'id'}`, 'backend', 'id'), canRead: alias('secretPath.canUpdate'), canEdit: alias('secretPath.canUpdate'), });
/* -*- Mode: javascript; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ gTestfile = '12.6.3-1.js'; /** File Name: 12.6.3-1.js ECMA Section: 12.6.3 The for...in Statement Description: Author: christine@netscape.com Date: 11 september 1997 */ var SECTION = "12.6.3-1"; var VERSION = "ECMA_1"; startTest(); var TITLE = "The for..in statement"; writeHeaderToLog( SECTION + " "+ TITLE); new TestCase( SECTION, "var x; Number.prototype.foo = 34; for ( j in 7 ) x = j; x", "foo", eval("var x; Number.prototype.foo = 34; for ( j in 7 ){x = j;} x") ); test();
"use strict"; let _=require("lodash") module.exports = function(backend,config, req, res, next) { var connection = backend.connect(); var doc = connection.get('assets', req.query.id); let callback = function () { "use strict"; console.error(doc.data.data) res.send((doc.data.data)) } doc.fetch(function (err) { if (err) throw err; if (doc.type === null) { doc.create({data: ""}, callback); return; } callback(); }); };
Components.utils.import("resource://gre/modules/Services.jsm"); var cmdMarkdownCommand = { isCommandEnabled: function(aCommand, dummy) { return (EditorUtils.getCurrentEditorElement() && EditorUtils.isDocumentEditable() && EditorUtils.isEditingRenderedHTML() && EditorUtils.isWysiwygMode()); }, getCommandStateParams: function(aCommand, aParams, aRefCon) {}, doCommandParams: function(aCommand, aParams, aRefCon) {}, doCommand: function(aCommand) { window.openDialog('chrome://markdown/content/markdown.xul',"_blank", "chrome,resizable,modal,dialog=no,scrollbars=yes"); } }; var MarkdownHelper = { startup: function() { window.removeEventListener("load", MarkdownHelper.startup, false); var commandTable = ComposerCommands.getComposerCommandTable(); commandTable.registerCommand("cmd_insertMarkdown", cmdMarkdownCommand); } }; window.addEventListener("load", MarkdownHelper.startup, false);
/** * Farm Overview View controller * Hosts a tab bar and nested view */ var module = angular.module( 'ngMoogle.farm', [ 'ui.router', 'ngMoogle.farm.herds', 'ngMoogle.farm.animals', 'ngMoogle.farm.measurementsView', 'ngMoogle.farm.members', 'ngMoogle.farm.paddocks' ]); module.config(function config( $stateProvider, $urlRouterProvider ) { $stateProvider .state( 'home.farm', { //abstract: true, //MDB: if ui-router #27 is fixed we should be able to get default state change for abstract states redirectTo: 'home.farm.members', // This abstract state will prepend '/contacts' onto the urls of all its children. url: "/farm/:farmId", views: { "home-content": { controller: 'FarmCtrl', templateUrl: 'farm/farm.tpl.html'} }, data:{ pageTitle: 'Farm Overview' } }); $urlRouterProvider // The `when` method says if the url is ever the 1st param, then redirect to the 2nd param // Here we are just setting up some convenience urls. .when('', '/members') // If the url is ever invalid, e.g. '/asdf', then redirect to members page .otherwise('/members'); }); module.controller( 'FarmCtrl', function FarmController( $log, $scope, $state, $stateParams,$ag, $filter, UserService, FarmService, HerdService, FarmPermissionService, AnimalService,FarmRoleService, NgTableParams, $sce ) { console.log("loaded farm controller"); $scope.farmId = parseInt($stateParams.farmId,10); $log.debug("farm id: " + $scope.farmId); UserService.getUserFarms().then(function(farms){ var farm = $ag.findByIdIn($scope.farmId,farms); $scope.farm = farm; //TODO: !MDB - I think this information is already in scope, perhaps it should be persistent in UserService FarmPermissionService.find($scope.user.id, $scope.farmId, true,true, true, function (err, data) { if (err) { console.log(err); return; } if (data.length > 0) { $scope.userPermissions = data.length > 0 ? data[0].role : null; $scope.userPermissions.editFarmPermissions = $scope.userPermissions.editFarmPermissions || $scope.user.role.editFarmPermissions; $scope.userPermissions.editFarmHerds = $scope.userPermissions.editFarmHerds || $scope.user.role.editHerds; $scope.userPermissions.editFarmAnimals = $scope.userPermissions.editFarmAnimals || $scope.user.role.editAnimals; $scope.userPermissions.editFarmMeasurements = $scope.userPermissions.editFarmMeasurements || $scope.user.role.editMeasurements; } }); }); $scope.$state = $state; });
/* 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 https://mozilla.org/MPL/2.0/. */ 'use strict'; const path = require('path'); const fs = require('fs'); const os = require('os'); const ExifReader = require('../../dist/exif-reader'); const exifErrors = ExifReader.errors; if (process.argv.length < 3) { console.log(`Usage: node ${path.basename(__filename)} <filename>`); process.exit(); } const filePath = process.argv[2]; ExifReader.load(filePath, {expanded: true}).then(function (tags) { // The MakerNote tag can be really large. Remove it to lower memory // usage if you're parsing a lot of files and saving the tags. if (tags.exif) { delete tags.exif['MakerNote']; } // If you want to extract the thumbnail you can save it like this: if (tags['Thumbnail'] && tags['Thumbnail'].image) { fs.writeFileSync(path.join(os.tmpdir(), 'thumbnail.jpg'), Buffer.from(tags['Thumbnail'].image)); } // If you want to extract images from the multi-picture metadata (MPF) you can save them like this: if (tags['mpf'] && tags['mpf']['Images']) { for (let i = 0; i < tags['mpf']['Images'].length; i++) { fs.writeFileSync(path.join(os.tmpdir(), `mpf-image-${i}.jpg`), Buffer.from(tags['mpf']['Images'][i].image)); // You can also read the metadata from each of these images too: // ExifReader.load(tags['mpf']['Images'][i].image, {expanded: true}); } } listTags(tags); }).catch(function (error) { if (error instanceof exifErrors.MetadataMissingError) { console.log('No Exif data found'); } console.error(error); process.exit(1); }); function listTags(tags) { for (const group in tags) { for (const name in tags[group]) { if (group === 'gps') { console.log(`${group}:${name}: ${tags[group][name]}`); } else if ((group === 'Thumbnail') && (name === 'type')) { console.log(`${group}:${name}: ${tags[group][name]}`); } else if ((group === 'Thumbnail') && (name === 'image')) { console.log(`${group}:${name}: <image>`); } else if ((group === 'Thumbnail') && (name === 'base64')) { console.log(`${group}:${name}: <base64 encoded image>`); } else if ((group === 'mpf') && (name === 'Images')) { console.log(`${group}:${name}: ${getMpfImagesDescription(tags[group][name])}`); } else if (Array.isArray(tags[group][name])) { console.log(`${group}:${name}: ${tags[group][name].map((item) => item.description).join(', ')}`); } else { console.log(`${group}:${name}: ${typeof tags[group][name].description === 'string' ? tags[group][name].description.trim() : tags[group][name].description}`); } } } } function getMpfImagesDescription(images) { return images.map( (image, index) => `(${index}) ` + Object.keys(image).map((key) => { if (key === 'image') { return `${key}: <image>`; } if (key === 'base64') { return `${key}: <base64 encoded image>`; } return `${key}: ${image[key].description}`; }).join(', ') ).join('; '); }
//Design:liangguichang $(document).ready(function(){ $("#add").click(function(){ $("#select1 option:selected").appendTo("#select2"); }); $("#add_all").click(function(){ $("#select1 option").appendTo("#select2"); }); $("#remove").click(function(){ $("#select2 option:selected").appendTo("#select1"); }); $("#remove_all").click(function(){ $("#select2 option").appendTo("#select1"); }); $("#select1").dblclick(function(){ $("#select1 option:selected").appendTo("#select2"); }); $("#select2").dblclick(function(){ $("#select2 option:selected").appendTo("#select1"); }); });
import ApplicationAdapter from './application'; import { encodePath } from 'vault/utils/path-encoding-helpers'; export default ApplicationAdapter.extend({ revokePrefix(prefix) { let url = this.buildURL() + '/leases/revoke-prefix/' + encodePath(prefix); url = url.replace(/\/$/, ''); return this.ajax(url, 'PUT'); }, forceRevokePrefix(prefix) { let url = this.buildURL() + '/leases/revoke-prefix/' + encodePath(prefix); url = url.replace(/\/$/, ''); return this.ajax(url, 'PUT'); }, renew(lease_id, increment) { let url = this.buildURL() + '/leases/renew'; return this.ajax(url, 'PUT', { data: { lease_id, increment, }, }); }, deleteRecord(store, type, snapshot) { const lease_id = snapshot.id; return this.ajax(this.buildURL() + '/leases/revoke', 'PUT', { data: { lease_id, }, }); }, queryRecord(store, type, query) { const { lease_id } = query; return this.ajax(this.buildURL() + '/leases/lookup', 'PUT', { data: { lease_id, }, }); }, query(store, type, query) { const prefix = query.prefix || ''; return this.ajax(this.buildURL() + '/leases/lookup/' + encodePath(prefix), 'GET', { data: { list: true, }, }).then((resp) => { if (prefix) { resp.prefix = prefix; } return resp; }); }, });
/*! * Copyright 2002 - 2015 Webdetails, a Pentaho company. All rights reserved. * * This software was developed by Webdetails and is provided under the terms * of the Mozilla Public License, Version 2.0, or any later version. You may not use * this file except in compliance with the license. If you need a copy of the license, * please go to http://mozilla.org/MPL/2.0/. The Initial Developer is Webdetails. * * Software distributed under the Mozilla Public License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to * the license for the specific language governing your rights and limitations. */ define([ './dashboard/Dashboard', './dashboard/Dashboard.context', './dashboard/Dashboard.addIns', './dashboard/Dashboard.bookmarkable', './dashboard/Dashboard.components', './dashboard/Dashboard.i18n', './dashboard/Dashboard.legacy', './dashboard/Dashboard.lifecycle', './dashboard/Dashboard.notifications', './dashboard/Dashboard.parameters', './dashboard/Dashboard.storage', './dashboard/Dashboard.query', './dashboard/Dashboard.views', './queries/BaseQuery', './queries/CpkQuery', './queries/CdaQuery', './queries/LegacyQuery', './components/BaseComponent', './components/UnmanagedComponent', 'css!./Dashboard'], function(Dashboard) { return Dashboard; });
/* vim: set ts=2 et sw=2 tw=80: */ /* Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ */ "use strict"; // https rather than chrome to improve coverage const TESTCASE_URI = TEST_BASE_HTTPS + "sourcemaps-inline.html"; const PREF = "devtools.styleeditor.source-maps-enabled"; const sassContent = `body { background-color: black; & > h1 { color: white; } } `; const cssContent = `body { background-color: black; } body > h1 { color: white; } ` + "/*# sourceMappingURL=data:application/json;base64,ewoidmVyc2lvbiI6IDMsCiJtY" + "XBwaW5ncyI6ICJBQUFBLElBQUs7RUFDSCxnQkFBZ0IsRUFBRSxLQUFLO0VBQ3ZCLFNBQU87SUFD" + "TCxLQUFLLEVBQUUsS0FBSyIsCiJzb3VyY2VzIjogWyJ0ZXN0LnNjc3MiXSwKInNvdXJjZXNDb25" + "0ZW50IjogWyJib2R5IHtcbiAgYmFja2dyb3VuZC1jb2xvcjogYmxhY2s7XG4gICYgPiBoMSB7XG" + "4gICAgY29sb3I6IHdoaXRlO1xuICB9XG59XG4iXSwKIm5hbWVzIjogW10sCiJmaWxlIjogInRlc" + "3QuY3NzIgp9Cg== */"; add_task(function* () { let {ui} = yield openStyleEditorForURL(TESTCASE_URI); is(ui.editors.length, 1, "correct number of editors with source maps enabled"); yield testEditor(ui.editors[0], "test.scss", sassContent); // Test disabling original sources yield togglePref(ui); is(ui.editors.length, 1, "correct number of editors after pref toggled"); // Test CSS editors yield testEditor(ui.editors[0], "<inline style sheet #1>", cssContent); Services.prefs.clearUserPref(PREF); }); function* testEditor(editor, expectedName, expectedText) { let name = getStylesheetNameFor(editor); is(expectedName, name, name + " editor name is correct"); yield openEditor(editor); let text = editor.sourceEditor.getText(); is(text, expectedText, name + " editor contains expected text"); } /* Helpers */ function togglePref(UI) { let editorsPromise = UI.once("stylesheets-reset"); let selectedPromise = UI.once("editor-selected"); Services.prefs.setBoolPref(PREF, false); return promise.all([editorsPromise, selectedPromise]); } function openEditor(editor) { getLinkFor(editor).click(); return editor.getSourceEditor(); } function getLinkFor(editor) { return editor.summary.querySelector(".stylesheet-name"); } function getStylesheetNameFor(editor) { return editor.summary.querySelector(".stylesheet-name > label") .getAttribute("value"); }
/* This file is a part of libertysoil.org website Copyright (C) 2016 Loki Education (Social Enterprise) 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/>. */ /* eslint-env node, mocha */ /* global $dbConfig */ import React from 'react'; import { mount } from 'enzyme'; import initBookshelf from '../../../src/api/db'; import expect from '../../../test-helpers/expect'; import { waitForChange } from '../../../test-helpers/wait'; import HashtagFactory from '../../../test-helpers/factories/hashtag'; import GeotagFactory from '../../../test-helpers/factories/geotag'; import HashtagSelect from '../../../src/components/add-tag-modal/form/hashtag/select'; import GeotagSelect from '../../../src/components/add-tag-modal/form/geotag/select'; const bookshelf = initBookshelf($dbConfig); const Hashtag = bookshelf.model('Hashtag'); const Geotag = bookshelf.model('Geotag'); describe('AddTagModal', () => { describe('HashtagSelect', () => { const hashtags = Array(3); const names = ['knowledge', 'know', 'fox']; before(async () => { for (let i = 0; i < hashtags.length; ++i) { hashtags[i] = await new Hashtag( HashtagFactory.build({ name: names[i] }) ).save(null, { method: 'insert' }); } }); after(async () => { for (let i = 0; i < hashtags.length; ++i) { await hashtags[i].destroy(); } }); it('shows suggestions', async () => { const wrapper = mount(<HashtagSelect />); const query = 'kno'; const suggestionsLength = waitForChange(() => wrapper.state('suggestions').length); wrapper.find('.autosuggest__input').simulate('change', { target: { value: query } }); expect(await suggestionsLength, 'to equal', 2); }); }); describe('GeotagSelect', () => { const geotags = Array(3); const names = ['New York City', 'New Orleans', 'Chicago']; before(async () => { for (let i = 0; i < geotags.length; ++i) { geotags[i] = await new Geotag( GeotagFactory.build({ name: names[i] }) ).save(null, { method: 'insert' }); } await bookshelf.knex.raw(`UPDATE geotags SET tsv = setweight(to_tsvector(coalesce(geotags.name, '')), 'A')`); // build index }); after(async () => { for (let i = 0; i < geotags.length; ++i) { await geotags[i].destroy(); } }); it('shows suggestions', async () => { const wrapper = mount(<GeotagSelect />); const query = 'New'; const suggestionsLength = waitForChange(() => wrapper.state('suggestions').length); wrapper.find('.autosuggest__input').simulate('change', { target: { value: query } }); expect(await suggestionsLength, 'to equal', 2); }); }); });
import SPELLS from 'common/SPELLS'; import CombatLogParser from './CombatLogParser'; describe('Paladin/Holy/CombatLogParser', () => { const reorderScenarios = [ { test: 'doesn\'t re-order LoD when it\'s already in order', events: [ { testid: 1, timestamp: 0, sourceID: 1, ability: { guid: SPELLS.LIGHT_OF_DAWN_CAST.id }, type: 'cast' }, { testid: 2, timestamp: 0, sourceID: 1, ability: { guid: SPELLS.LIGHT_OF_DAWN_HEAL.id }, type: 'heal' }, { testid: 3, timestamp: 0, sourceID: 2, ability: { guid: SPELLS.LIGHT_OF_DAWN_HEAL.id }, type: 'heal' }, ], result: [1, 2, 3], }, { test: 'moves the cast before the heal when it\'s misordered', events: [ { testid: 1, timestamp: 0, sourceID: 1, ability: { guid: SPELLS.LIGHT_OF_DAWN_HEAL.id }, type: 'heal' }, { testid: 2, timestamp: 0, sourceID: 1, ability: { guid: SPELLS.LIGHT_OF_DAWN_CAST.id }, type: 'cast' }, ], result: [2, 1], }, { test: 'ignores irrelevant spells', events: [ { testid: 1, timestamp: 0, sourceID: 1, ability: { guid: SPELLS.LIGHT_OF_DAWN_HEAL.id }, type: 'heal' }, { testid: 2, timestamp: 0, sourceID: 1, ability: { guid: SPELLS.REJUVENATION.id }, type: 'heal' }, { testid: 3, timestamp: 0, sourceID: 1, ability: { guid: SPELLS.LIGHT_OF_DAWN_CAST.id }, type: 'cast' }, { testid: 4, timestamp: 0, sourceID: 1, ability: { guid: SPELLS.REJUVENATION_GERMINATION.id }, type: 'heal' }, ], result: [2, 3, 1, 4], }, { test: 'does not move more than 1 heal (this is assumed to be of a previous LoD)', events: [ { testid: 1, timestamp: -5, sourceID: 1, ability: { guid: SPELLS.LIGHT_OF_DAWN_HEAL.id }, type: 'heal' }, { testid: 2, timestamp: -5, sourceID: 1, ability: { guid: SPELLS.LIGHT_OF_DAWN_HEAL.id }, type: 'heal' }, { testid: 3, timestamp: 0, sourceID: 1, ability: { guid: SPELLS.LIGHT_OF_DAWN_HEAL.id }, type: 'heal' }, { testid: 4, timestamp: 0, sourceID: 1, ability: { guid: SPELLS.LIGHT_OF_DAWN_CAST.id }, type: 'cast' }, ], result: [1, 2, 4, 3], }, { test: 'does not move heals that are too old (and likely from a previous LoD)', events: [ { testid: 1, timestamp: 0, sourceID: 1, ability: { guid: SPELLS.LIGHT_OF_DAWN_HEAL.id }, type: 'heal' }, { testid: 2, timestamp: 64, sourceID: 1, ability: { guid: SPELLS.LIGHT_OF_DAWN_CAST.id }, type: 'cast' }, ], result: [1, 2], }, { test: 'only moves events of the same player', events: [ { testid: 1, timestamp: 0, sourceID: 1, ability: { guid: SPELLS.LIGHT_OF_DAWN_HEAL.id }, type: 'heal' }, { testid: 2, timestamp: 0, sourceID: 2, ability: { guid: SPELLS.LIGHT_OF_DAWN_HEAL.id }, type: 'heal' }, { testid: 3, timestamp: 0, sourceID: 1, ability: { guid: SPELLS.LIGHT_OF_DAWN_CAST.id }, type: 'cast' }, ], result: [2, 3, 1], }, { test: 'can move multiple around', events: [ { testid: 1, timestamp: 1, sourceID: 1, ability: { guid: SPELLS.LIGHT_OF_DAWN_HEAL.id }, type: 'heal' }, { testid: 2, timestamp: 1, sourceID: 1, ability: { guid: SPELLS.LIGHT_OF_DAWN_CAST.id }, type: 'cast' }, { testid: 3, timestamp: 2, sourceID: 1, ability: { guid: SPELLS.LIGHT_OF_DAWN_HEAL.id }, type: 'heal' }, { testid: 4, timestamp: 2, sourceID: 1, ability: { guid: SPELLS.LIGHT_OF_DAWN_CAST.id }, type: 'cast' }, { testid: 5, timestamp: 3, sourceID: 2, ability: { guid: SPELLS.LIGHT_OF_DAWN_HEAL.id }, type: 'heal' }, { testid: 6, timestamp: 3, sourceID: 2, ability: { guid: SPELLS.LIGHT_OF_DAWN_CAST.id }, type: 'cast' }, ], result: [2, 1, 4, 3, 6, 5], }, ]; reorderScenarios.forEach((scenario) => { it(scenario.test, () => { const player = { id: 1, }; const parser = new CombatLogParser({ friendlies: [player], }, player); expect(parser.normalize(scenario.events).map(event => event.testid)).toEqual(scenario.result); }); }); });
const ActionButton = require('./action_button') const utils = require('./_utils') module.exports = { id: 'builtin_card', group: 'Built-in Messages', title: 'card', jsonSchema: { description: 'module.builtin.types.card.description', type: 'object', required: ['title'], properties: { title: { type: 'string', title: 'title' }, subtitle: { type: 'string', title: 'subtitle' }, image: { type: 'string', $subtype: 'image', $filter: '.jpg, .png, .jpeg, .gif, .bmp, .tif, .tiff|image/*', title: 'image' }, actions: { type: 'array', title: 'module.builtin.actionButton', items: ActionButton.jsonSchema } } }, uiSchema: {}, computePreviewText: formData => formData.title && `Card: ${formData.title}`, renderElement: (data, channel) => { return utils.extractPayload('card', data) } }
$p.templates = function ($control) { $p.send($control, 'SitesForm'); } $p.setTemplate = function () { var selector = '.template-selectable .control-selectable'; $('#TemplateTabsContainer:not(.applied)').tabs({ beforeActivate: function (event, ui) { $p.setTemplateData(ui.newPanel.find(selector)); } }).addClass('applied'); $(selector).selectable({ selected: function (event, ui) { $(ui.selected) .addClass("ui-selected") .siblings() .removeClass("ui-selected") .each(function (key, value) { $(value).find('*').removeClass("ui-selected"); }); }, stop: function () { $p.setTemplateData($(this)); } }); } $p.setTemplateData = function ($control) { var selected = $control.find('li.ui-selected'); var show = selected.length === 1; $p.setData($control); $p.send($control); $('#OpenSiteTitleDialog') .removeClass('hidden') .toggle(show); $('#SiteTitle').val(show ? selected[0].innerText : ''); $('#TemplateId').val(show ? selected[0].getAttribute('data-value') : ''); } $p.setTemplateViewer = function () { $('.template-tab-container').tabs().addClass('applied'); } $p.openSiteTitleDialog = function ($control) { $('#SiteTitleDialog').dialog({ modal: true, width: '370px', appendTo: '#Application' }); }
/* Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'removeformat', 'id', { toolbar: 'Hapus Format' } );
var Team = Object.freeze({ enemy: 1, ally: 2, same: 3, both: 4 }); function isTeam(creature1, creature2, team) { switch (team) { case Team.enemy: return creature1.team % 2 !== creature2.team % 2; case Team.ally: return creaSource.team % 2 === creaTarget.team % 2; case Team.same: return creaSource.team === creaTarget.team; case Team.both: return true; } }
/* * Copyright 2015 Paradone * * This file is part of Paradone <https://paradone.github.io> * * Paradone 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. * * Paradone 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 Paradone. If not, see <http://www.gnu.org/licenses/>. * * @flow weak */ /** * Wrapper setting handlers of a RTCDatachannel from a given PeerConnection * @module datachannel */ /** * @typedef DataChannel * @desc Augmented RTCDataChannel with configured callbacks used to transmit * information to other peers and relay received data to the * PeerConnection instance it is attached to * @augments external:RTCDataChannel * @see http://w3c.github.io/webrtc-pc/#idl-def-RTCDataChannel * @see https://developer.mozilla.org/en-US/docs/Web/API/RTCDataChannel */ /** * Options used for the creation of a DataChannel * * @const {Object} options * @inner * @memberof module:datachannel * @property {Array.<Object>} [optional] */ export const options = {} /** * When a peer disconnect the channel is closed. We update the connection's * status of the Peer */ var onclose = function(peer, peerConnection, remotePeer, event) { peer.dispatchMessage({ type: 'disconnected', to: peer.id, from: remotePeer, data: event }) } /** An error has been thrown by the DataChannel */ var onerror = function(error) { console.error('Channel error:', error) } /** * When a message is received through the channel we send it to the Peer * onmessage handler. This allows us to handle data recevied through both the * signaling system and the mesh network with the same functions * * @param {Peer} peer - Messages will be forwarded to this Peer * @param {Event} event - Contains the message sent by the remote peer */ var onmessage = function(peer, event) { var message = JSON.parse(event.data) if(-1 === message.to || peer.id === message.to) { peer.dispatchMessage(message) } else if(message.ttl > 0) { peer.forward(message) } } /** * Relay to the Peer instance the initialization of the data channel and save * it in the PeerConnection * * @param {Event} event */ var onopen = function(peer, peerConnection, remotePeer, event) { var channel = event.target if('open' === channel.readyState.toLowerCase()) { peerConnection.channel = channel peer.dispatchMessage({ type: 'connected', from: remotePeer, to: peer.id, data: event }) } } /** * Set all the callbacks of a newly created DataChannel * * @function module:datachannel~setHandlers * @param {RTCDataChannel} channel - Channel to be configured * @param {Peer} peer - Events must be forwarded to this Peer * @param {PeerConnection} peerConnection - PeerConnection where the DataChannel * will be stored * @param {string} id - Id of the remote peer * @return {DataChannel} Some {@link DataChannel} */ export function setHandlers(channel, peer, peerConnection, remotePeer) { channel.onclose = onclose.bind(null, peer, peerConnection, remotePeer) channel.onerror = onerror channel.onmessage = onmessage.bind(null, peer) channel.onopen = onopen.bind(null, peer, peerConnection, remotePeer) return channel } /** * Creates a new DataChannel from a PeerConnection object and add the callbacks * needed to forward events to the Peer and PeerConnection objects (like a * connection/disconnection, error and reception of messages) * * @function module:datachannel~create * @param {Peer} peer - Events will be forwarded to this Peer * @param {PeerConnection} peerConnection - PeerConnection where the * DataChannel will be stored * @param {string} id - Id of the remote peer * @return {DataChannel} */ export function create(peer, peerConnection, remotePeer) { var channel = peerConnection.createDataChannel( peer.id + '-' + remotePeer, this.options) return setHandlers(channel, peer, peerConnection, remotePeer) }
OC.L10N.register( "gallery", { "Gallery" : "相册", "No pictures found" : "没有找到图片", "Upload pictures in the files app to display them here" : "上传图片文件后您可以在这里查看它们", "Nothing in here" : "无内容", "No media files found in this folder" : "此文件夹中没有媒体文件", "Aborting preview. Could not find the file" : "预览异常,无法找到文件。", "No ownCloud installation (7 or higher) found at {remote}" : "未发现 {remote} 安装有ownCloud (7 或更高版本 ) ", "Invalid ownCloud url" : "无效的 ownCloud 网址", "Gallery view" : "查看相册", "Could not load the description" : "无法载入描述", "Could not load the description: " : "无法载入描述", "Copyright" : "版权", "Could not load the copyright notice: " : "无法载入版权信息", "Copyright notice" : "版权信息", "Link to copyright document" : "版权信息链接", "This application may not work properly on your browser." : "该应用可能无法在您的浏览器内正常运行", "For an improved experience, please install one of the following alternatives" : "为了更好地使用体验,请使用以下推荐的浏览器", "Your browser is not supported!" : "您的浏览器对此不支持!", "please install one of the following alternatives" : "请使用推荐的浏览器", "Configuration error" : "配置错误", "Error loading slideshow template" : "加载幻灯片模板错误", "Next" : "下一个", "Play" : "播放", "Pause" : "暂停", "Previous" : "上一个", "Close" : "关闭", "Download" : "下载", "Error" : "错误", "Error while sharing" : "共享时出错", "Error while unsharing" : "取消共享时出错", "Error while changing permissions" : "修改权限时出错", "Shared with you and the group {group} by {owner}" : "{owner} 共享给您及 {group} 组", "Shared with you by {owner}" : "{owner} 与您共享", "Share with users or groups …" : "分享给其他用户或组 ...", "Share with users, groups or remote users …" : "分享给其他用户、组或远程用户 ...", "Share" : "共享", "Share with people on other ownClouds using the syntax username@example.com/owncloud" : "使用语法 username@example.com/owncloud 分享给其他 ownCloud 上的用户", "Share link" : "分享链接", "The public link will expire no later than {days} days after it is created" : "这个共享链接将在创建后 {days} 天失效", "Link" : "链接", "Password protect" : "密码保护", "Password" : "密码", "Choose a password for the public link" : "为共享链接设置密码", "Allow editing" : "允许编辑", "Email link to person" : "发送链接到个人", "Send" : "发送", "Set expiration date" : "设置过期日期", "Expiration" : "过期", "Expiration date" : "过期日期", "An error occured. Please try again" : "发生了一个错误请重新尝试", "Adding user..." : "添加用户中...", "group" : "群组", "remote" : "远程", "Resharing is not allowed" : "不允许二次共享", "Unshare" : "取消共享", "notify by email" : "以邮件通知", "can share" : "可共享", "can edit" : "可编辑", "access control" : "访问控制", "create" : "创建", "change" : "更改", "delete" : "删除", "Password protected" : "密码已受保护", "Error unsetting expiration date" : "取消设置过期日期时出错", "Error setting expiration date" : "设置过期日期时出错", "Sending ..." : "正在发送...", "Email sent" : "邮件已发送", "Warning" : "警告", "This share is password-protected" : "这是一个密码保护的共享", "The password is wrong. Try again." : "用户名或密码错误!请重试", "Sort by date" : "按日期排序", "Sort by name" : "按名称排序", "Album information" : "专辑信息", "File list" : "文件列表", "Sorry, this file could not be found." : "抱歉,无法找到该文件。", "Reasons might be:" : "可能原因是:", "the wrong file ID was provided" : "文件ID错误", "the file was removed" : "文件已移除", "the file is corrupt" : "文件已损坏", "Sorry, but the server could not fulfill your request." : "抱歉,服务器无法完成您的请求。", "Possible reasons for the problem:" : "可能的原因:", "a conflicting app was installed" : "已安装了一个会引发冲突的应用", "a required component is missing or was disconnected" : "必要的部件丢失,或者与服务器的连接已断开", "the filesystem is not readable" : "该文件无法打开", "Sorry, this link doesn't seem to work anymore." : "抱歉,此链接已失效", "the item was removed" : "此项已移除", "the link has expired" : "链接已过期", "sharing is disabled" : "共享已禁用", "For more information, please ask the person who has sent you this link." : "欲知详情,请联系共享链接给你的人。", "Add to your ownCloud" : "添加到您的云空间", "Picture view" : "查看图片" }, "nplurals=1; plural=0;");
import _ from 'intl' import React, { Component } from 'react' import SortedTable from 'sorted-table' import { connectStore } from 'utils' import { createGetObjectMessages } from 'selectors' import { FormattedRelative, FormattedTime } from 'react-intl' import { deleteMessage, deleteMessages } from 'xo' const LOG_COLUMNS = [ { itemRenderer: log => ( <span> <FormattedTime value={log.time * 1000} minute='numeric' hour='numeric' day='numeric' month='long' year='numeric' />{' '} (<FormattedRelative value={log.time * 1000} />) </span> ), name: _('logDate'), sortCriteria: 'time', sortOrder: 'desc', }, { itemRenderer: log => log.name, name: _('logName'), sortCriteria: 'name', }, { itemRenderer: log => log.body, name: _('logContent'), sortCriteria: 'body', }, ] const INDIVIDUAL_ACTIONS = [ { handler: deleteMessage, icon: 'delete', label: _('logDelete'), level: 'danger', }, ] const GROUPED_ACTIONS = [ { handler: deleteMessages, icon: 'delete', label: _('logsDelete'), level: 'danger', }, ] @connectStore(() => { const logs = createGetObjectMessages((_, props) => props.vm) return (state, props) => ({ logs: logs(state, props), }) }) export default class TabLogs extends Component { render() { return ( <SortedTable collection={this.props.logs} columns={LOG_COLUMNS} groupedActions={GROUPED_ACTIONS} individualActions={INDIVIDUAL_ACTIONS} stateUrlParam='s' /> ) } }
export { DestinationDirective } from './DestinationDirective'; export { SubscribersDirective } from './SubscribersDirective';
// libs var async = require('async'); var colors = require('colors'); var crypto = require('crypto'); var uuid = require('node-uuid'); var mongoose = require('mongoose'); var _ = require('lodash'); var fs = require('fs'); var Table = require('easy-table'); // database schemas var Project = require('../models/project'); var Clientel = require('../models/client'); // weird name cause 'Client' is restricted name var User = require('../models/user'); var File = require('../models/file'); var Layer = require('../models/layer'); var Hash = require('../models/hash'); var Role = require('../models/role'); var Group = require('../models/group'); // config var config = require('../config.js').serverConfig; // connect to our database mongoose.connect(config.mongo.url); User .find() .exec(function (err, users) { var t = new Table; // console.log(err, users) users.forEach(function (u, i) { // columns t.cell('#', i); t.cell('Username', u.username); t.cell('First Name', u.firstName); t.cell('Last Name', u.lastName); t.cell('Email', u.local.email); t.cell('ID', u.id); t.cell('Super', (u.access.super ? 'YES' : '')) t.newRow(); }); t.sort(); console.log('\n'); console.log(t.toString()); process.exit(0); });
"use strict"; var ST = ST || {}; ST.main = {}; ST.main.view = {}; // Main NavBar ST.main.view.NavBar = Backbone.View.extend({ el: "#divContainerMainNavBar", events: { "click #aLinkNavBarNewTale": "newTale", "click #aLinkNavBarHelp": "showHelp" }, initialize: function () { //ST.util.setLayoutBackgroundColors(".layoutBG"); }, // new tale button newTale: function () { $("#divDarkenScreen").show(); new ST.dialog.view.NewTaleDialog(function (result) { // hide dialog $("#divDarkenScreen").hide(); $("#divDialogContainer").empty(); $("#divDialogContainer").unbind(); // go to new tale if (result.success === true) { ST.router.navigate("/edit-tale/" + result.idTale, { trigger: true }); } }); }, // help button showHelp: function () { ST.main.view.help = new ST.main.view.Help(ST.router.lastName); }, // show different buttons if logged in or out toggleLogout: function (loggedIn) { if (loggedIn === true) { $("#aLinkNavBarNewTale").show(); $("#aLinkNavBarLogout").show(); $("#aLinkNavBarAccount").show(); $("#aLinkNavBarLogin").hide(); $("#aLinkNavBarTryItOut").hide(); } else { $("#aLinkNavBarNewTale").hide(); $("#aLinkNavBarLogout").hide(); $("#aLinkNavBarAccount").hide(); $("#aLinkNavBarLogin").show(); $("#aLinkNavBarTryItOut").show(); } } }); // Help drawer sidebar thing ST.main.view.Help = Backbone.View.extend({ el: "#divHelp", events: { "click #buttonCloseHelp": "close" }, initialize: function (page) { this.render(page); }, render: function (page) { this.template = null; this.$el.empty(); switch(page) { case "search": this.template = _.template($("#templateHelpSearch").html()); break; case "editTale" : case "tryItOut" : this.template = _.template($("#templateHelpEditTale").html()); break; case "editItem": this.template = _.template($("#templateHelpEditItem").html()); break; case "about" : this.template = _.template($("#templateHelpAbout").html()); break; case "account" : this.template = _.template($("#templateHelpAccount").html()); break; } if (this.template !== null) { $("#divHelp").show(); this.$el.html(this.template()); } return this; }, close: function () { $("#divHelp").hide(); } });
OC.L10N.register( "federation", { "Added to the list of trusted servers" : "Bætt á lista yfir treysta þjóna", "Server is already in the list of trusted servers." : "Þjónninn er nú þegar á listanum yfir treysta þjóna.", "No server to federate with found" : "Enginn þjónn sem hæfur er til skýjasambands fannst", "Could not add server" : "Gat ekki bætt við þjóni", "Trusted servers" : "Treystir þjónar", "Federation allows you to connect with other trusted servers to exchange the user directory. For example this will be used to auto-complete external users for federated sharing." : "Þjónasamband (federation) gerir þér kleift að tengjast öðrum treystum skýjum til að skiptast á notendaskrám. Þetta er til dæmis notað til að sjálfklára nöfn ytri notenda við deilingu sambandssameigna.", "Add server automatically once a federated share was created successfully" : "Bæta þjóni við sjálfkrafa, hafi tekist að búa til sambandssameign", "+ Add trusted server" : "+ Bæta við treystum þjóni", "Trusted server" : "Treystur þjónn", "Add" : "Bæta við" }, "nplurals=2; plural=(n % 10 != 1 || n % 100 == 11);");
module.exports = { "id": { FIXTURES: "fixtures", CONTAINER: "container", STRUCTURE: "structure", CENTER_DIV: "centerdiv", STATS: "stats" }, "class" : { DATE: 'date', FOLLOWED: 'followed', FOLLOW_TEAM: 'follow-team', MATCH_SELECT: 'match-select', MATCH_SELECTED: 'match-selected' }, "type" : { LEAGUE: "league" }, FINISH: "finished", LEAGUE_SORTORDER: [[8,1],[7,1], [5,1],[0,0]], //pts, goal difference, goals for and name TOPSCORERS: "topscorers", FIXTURES: "fixtures" };
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // the compiled file. // // WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD // GO AFTER THE REQUIRES BELOW. // //= require jquery //= require jquery_ujs //= require jquery.cookie //= require json/json2 //= require bootstrap //= require checkin //= require cowork //= require purchase //= require user_edit // $.browser fallback for jQuery 1.9+. if ($.browser === undefined) { jQuery.browser = function () { var ua_match = function (ua) { ua = ua.toLowerCase(); var match = /(chrome)[ \/]([\w.]+)/.exec(ua) || /(webkit)[ \/]([\w.]+)/.exec(ua) || /(opera)(?:.*version|)[ \/]([\w.]+)/.exec(ua) || /(msie) ([\w.]+)/.exec(ua) || ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec(ua) || []; return { browser:match[ 1 ] || "", version:match[ 2 ] || "0" }; }, matched = ua_match(navigator.userAgent), browser = {}; if (matched.browser) { browser[ matched.browser ] = true; browser.version = matched.version; } if (browser.chrome) { browser.webkit = true; } else if (browser.webkit) { browser.safari = true; } return browser; } }
/** * Special endpoints to access TVML/TVJS files with versioning support: * * /tvos/v{version}/{type}/{filepath} * OR * /tvos/{type}/{filepath} * * Where: * {version} - a version of the TVML/TVJS. If omitted then defaults to 1. * {type} - either 'tvml' or 'tvjs'. * {filepath} - path to the file. * * E.g.: * /tvos/v1/tvml/root.tvml * /tvos/v2/tvjs/app.js */ var fs = Meteor.npmRequire('fs'); function redirectToDefault() { this.response.writeHead(302, { 'Location': `/tvos/v1${this.url}` }); this.response.end(); } function serveTvosFile() { var tvosClientPath = `${process.env.TVOS_CLIENT_PATH}/${this.params.version}`, fileType = this.params.type, fileName = this.params.name, filePath = null, fileStatus = null, contentType = null; switch (fileType) { case 'tvml': filePath = `${tvosClientPath}/public/tvml/${fileName}`; contentType = 'application/xml'; break; case 'tvjs': filePath = `${tvosClientPath}/dist/${fileName}`; contentType = 'application/javascript'; break; default: console.log(`Error getting Apple TV client file: type ${fileType} is not supported!`); this.response.statusCode = 404; this.response.end(); return; } try { fileStatus = fs.statSync(filePath); } catch (error) { console.log(`Error getting Apple TV client file: ${error}`); this.response.statusCode = 404; this.response.end(); return; } this.response.writeHead(200, { 'Content-Type': contentType, 'Content-Disposition': 'attachment; filename=' + fileName, 'Content-Length': fileStatus.size }); fs.createReadStream(filePath).pipe(this.response); } Router.route('/tvml/:name', redirectToDefault, { where: 'server' }); Router.route('/tvjs/:name', redirectToDefault, { where: 'server' }); Router.route('/tvos/:version/:type/:name', serveTvosFile, { where: 'server' });
var Document = dejavu.Class.declare({ department: "", editor: null, initialize : function(){ $('#docEdit').html($('#docContent').val()); CKEDITOR.disableAutoInline = true; //document.getElementById('docEdit').innerHTML = $('#extraText').val(); this.editor = CKEDITOR.inline( 'docEdit', { format_tags : 'p;h2;h3;h4;h5;h6;pre;address', allowedContent : true, removePlugins : 'dragdrop,basket', disableNativeSpellChecker : false, language : 'pl', toolbar: [ { name: 'document', items: [ 'Sourcedialog' ] }, { name: 'basicstyles', items: [ 'Bold','Italic','Underline','Strike','Subscript','Superscript','-','RemoveFormat' ]}, { name: 'edit', items: [ 'Cut','Copy','Paste','PasteText','PasteFromWord','-','Undo','Redo' ] }, { name: 'extraedit', items: [ 'Find','Replace','SelectAll' ]}, { name: 'paragraph', items: [ 'NumberedList','BulletedList','-','Outdent','Indent','-', 'Blockquote','JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock', 'BidiLtr','BidiRtl' ] }, '/',{ name: 'links', items: [ 'Link', 'Unlink', 'Anchor' ] }, { name: 'insert', items: [ 'CodeSnippet', 'Mathjax', 'AddFile', 'AddImage', 'Table', 'Youtube','SpecialChar'] }, { name: 'styles', items: [ 'Format', 'Styles', 'FontSize', 'Styles', 'TextColor','BGColor'] } ], extraPlugins: 'codesnippet,mathjax,youtube,addFile,addImage,sourcedialog,specialchar', mathJaxLib : 'https://cdn.mathjax.org/mathjax/2.6-latest/MathJax.js?config=TeX-AMS_HTML' }); this.department = $('#subjectAndDepartment').children('big').text().trim(); $('#subjectChoice').val(this.department); }, deleteDoc: function() { return confirm("Jesteś pewien, że chcesz skasować cały dokument?"); }, saveDoc : function() { $('#docContent').val(this.editor.getData()); return true; } });
define(['order!libs/backbone/backbone-min'], function(){ _.noConflict(); $.noConflict(); return Backbone.noConflict(); });
openerp.web_remove_quick_create = function(openerp) { var _t = openerp.web._t, _lt = openerp.web._lt; var QWeb = openerp.web.qweb; openerp.web.form.FieldMany2One = openerp.web.form.FieldMany2One.extend({ // autocomplete component content handling get_search_result: function(request, response) { var search_val = request.term; var self = this; if (this.abort_last) { this.abort_last(); delete this.abort_last; } var dataset = new openerp.web.DataSetStatic(this, this.field.relation, self.build_context()); dataset.name_search(search_val, self.build_domain(), 'ilike', this.limit + 1, function(data) { self.last_search = data; // possible selections for the m2o var values = _.map(data, function(x) { return { label: _.str.escapeHTML(x[1]), value:x[1], name:x[1], id:x[0] }; }); // search more... if more results than max if (values.length > self.limit) { var open_search_popup = function(data) { self._change_int_value(null); self._search_create_popup("search", data); }; values = values.slice(0, self.limit); values.push({label: _t("<em>   Search More...</em>"), action: function() { if (!search_val) { // search optimisation - in case user didn't enter any text we // do not need to prefilter records; for big datasets (ex: more // that 10.000 records) calling name_search() could be very very // expensive! open_search_popup(); return; } dataset.name_search(search_val, self.build_domain(), 'ilike', false, open_search_popup); }}); } response(values); }); this.abort_last = dataset.abort_last; } })}
/* Copyright (c) 2006 Yahoo! Inc. All rights reserved. */ /** * A menu-specific implementation that differs from TextNode in that only * one sibling can be expanded at a time. * @extends YAHOO.widget.TextNode * @constructor */ YAHOO.widget.MenuNode = function(oData, oParent, expanded) { if (oParent) { this.init(oData, oParent, expanded); this.setUpLabel(oData); } /** * Menus usually allow only one branch to be open at a time. * @type boolean */ this.multiExpand = false; }; YAHOO.widget.MenuNode.prototype = new YAHOO.widget.TextNode();
import { module, test } from 'qunit'; import { setupTest } from 'ember-qunit'; import { blocklyWorkspaceMock } from '../../helpers/mocks'; import { findBlockByTypeIn, assertNotDisabled, assertNotAvailable, setUpTestLocale } from '../../helpers/utils'; module('Unit | Service | available-blocks-validator', function (hooks) { setupTest(hooks); setUpTestLocale(hooks) var validator hooks.beforeEach(function () { validator = this.owner.lookup('service:available-blocks-validator'); this.blocksGallery = this.owner.lookup('service:blocksGallery'); blocklyWorkspaceMock() this.blocksGallery.start(); }); let simpleProgram = `<block type="al_empezar_a_ejecutar" deletable="false" movable="false" editable="false" x="269" y="15"> <statement name="program"> <block type="MoverACasillaDerecha"> <next> <block type="MoverACasillaIzquierda"></block> </next> </block> </statement> </block>` test('Should not disable global available blocks', function (assert) { let program = Blockly.textToBlock(simpleProgram) validator.disableNotAvailableBlocksInWorkspace([]) assertNotDisabled(assert, program) }); test('Should disable not available activity blocks', function (assert) { let program = Blockly.textToBlock(simpleProgram) let moveLeft = findBlockByTypeIn(program, "MoverACasillaIzquierda") validator.disableNotAvailableBlocksInWorkspace(["MoverACasillaDerecha"]) assertNotAvailable(assert, moveLeft) }); test('Should not disable available activity blocks', function (assert) { let program = Blockly.textToBlock(simpleProgram) let moveRight = findBlockByTypeIn(program, "MoverACasillaDerecha") validator.disableNotAvailableBlocksInWorkspace(["MoverACasillaDerecha"]) assertNotDisabled(assert, moveRight) }); let procedureDefinition = `<block type="procedures_defnoreturn" id="whpKBVIV.;:t%=8XN+E_" x="778" y="185"> <mutation> <arg name="param"></arg> </mutation> <field name="NAME">Hacer algo</field> <field name="ARG0">param</field> <statement name="STACK"> <block type="GirarGrados" id=";qf!gXUI;'/BUa0nx#y]"> <value name="grados"> <block type="variables_get" id="wAE7-:@m*P0G[x'Uf$Hv"> <mutation var="param" parent="whpKBVIV.;:t%=8XN+E_"></mutation> </block> </value> </block> </statement> </block>` let procedureCallProgram = `<block type="al_empezar_a_ejecutar" deletable="false" movable="false" editable="false" x="0" y="0"> <statement name="program"> <block type="procedures_callnoreturn"> <mutation name="Hacer algo"></mutation> </block> </statement> </block>` test('Should disable procedure blocks when they are not available', function (assert) { let procedure = Blockly.textToBlock(procedureDefinition) let variable = findBlockByTypeIn(procedure, "variables_get") let program = Blockly.textToBlock(procedureCallProgram) let procedureCall = findBlockByTypeIn(program, "procedures_callnoreturn") validator.disableNotAvailableBlocksInWorkspace(["GirarGrados"]) assertNotAvailable(assert, procedure) assertNotAvailable(assert, variable) assertNotAvailable(assert, procedureCall) }); test('Should not disable procedure blocks when they are available', function (assert) { let procedure = Blockly.textToBlock(procedureDefinition) let variable = findBlockByTypeIn(procedure, "variables_get") let program = Blockly.textToBlock(procedureCallProgram) let procedureCall = findBlockByTypeIn(program, "procedures_callnoreturn") validator.disableNotAvailableBlocksInWorkspace(["GirarGrados", "Procedimiento"]) assertNotDisabled(assert, procedure) assertNotDisabled(assert, variable) assertNotDisabled(assert, procedureCall) }); let mathArithmeticProgram = `<block type="al_empezar_a_ejecutar" deletable="false" movable="false" editable="false" x="15" y="15"> <statement name="program"> <block type="GirarGrados"> <value name="grados"> <block type="math_arithmetic"> <field name="OP">ADD</field> <value name="A"> <block type="math_number"> <field name="NUM">90</field> </block> </value> <value name="B"> <block type="math_number"> <field name="NUM">90</field> </block> </value> </block> </value> </block> </statement> </block>` test('Should works for original blocks with alias', function (assert) { let program = Blockly.textToBlock(mathArithmeticProgram) let mathArithmetic = findBlockByTypeIn(program, "math_arithmetic") validator.disableNotAvailableBlocksInWorkspace(["GirarGrados", "OpAritmetica"]) assertNotDisabled(assert, mathArithmetic) }); });
// Temporarily import Ractive first to keep it from detecting ie8's object.defineProperty shim, which it misuses (ractivejs/ractive#2343). import Ractive from 'ractive' Ractive.DEBUG = /minified/.test(() => {/* minified */}) import 'ie8' import 'babel-polyfill' import 'dom4' import 'html5shiv' // Extend the Math builtin with our own utilities. Object.assign(Math, require('util/math')) // Set up the initialize function. This is either called below if JSON is provided // inline, or called by the server if it was not. import TGUI from 'tgui.ract' // This thing was a part of an old index.html window.update = window.initialize = dataString => { const data = JSON.parse(dataString); // Initialize if (!window.tgui) { window.tgui = new TGUI({ el: '#container', data () { const initial = data; return { constants: require('util/constants'), text: require('util/text'), config: initial.config, data: initial.data, adata: initial.data, }; }, }); } // Update if (window.tgui) { window.tgui.set('config', data.config); if (typeof data.data !== 'undefined') { window.tgui.set('data', data.data); window.tgui.animate('adata', data.data); } } }; // Try to find data in the page. If the JSON was inlined, load it. const holder = document.getElementById('data') const data = holder.textContent const ref = holder.getAttribute('data-ref') if (data !== '{}') { window.initialize(data) holder.remove() } // Let the server know we're set up. // This also sends data if it was not inlined. // NOTE: This is currently handled by tgui-next. Only initialize if // we were loaded by tgui-fallback.html. import { act } from 'util/byond'; import { loadCSS } from 'fg-loadcss'; if (window.tguiFallback) { act(ref, 'tgui:initialize'); // Load fonts. loadCSS('v4shim.css') loadCSS('font-awesome.css') } else { act(ref, 'tgui:update'); }
/* * 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'; angular.module('stock-add-products-modal', [ 'openlmis-modal', 'stock-orderable-group', 'stockmanagement' ]); })();
import axios from 'axios' let FD_API_URL if (window.location.host === 'fd-vue-webapp.herokuapp.com') { FD_API_URL = 'http://165.227.172.191:9111/v3' } else { FD_API_URL = 'http://' + window.location.hostname + ':9111/v3' } export default axios.create({ baseURL: FD_API_URL, withCredentials: true, headers: { 'Content-Type': 'application/json' } })
frappe.ui.form.on("Appointment", "validate", function(frm,doc) { if(frm.doc.starts_on && frm.doc.ends_on){ if(frm.doc.starts_on >frm.doc.ends_on){ msgprint(__("Start Time should be greater than End Time")); validated = false; } } }); frappe.ui.form.on("Appointment", "starts_on", function(frm,doc) { if(frm.doc.starts_on){ frm.doc.starts = frm.doc.starts_on } }); frappe.ui.form.on("Appointment", "refresh", function(frm,doc) { if((frm.doc.status=='Cancel') || (frm.doc.status=='Completed')){ cur_frm.set_df_property('customer', 'read_only', 1); cur_frm.set_df_property('starts_on', 'read_only', 1); cur_frm.set_df_property('ends_on', 'read_only', 1); cur_frm.set_df_property('employee', 'read_only', 1); cur_frm.set_df_property('company', 'read_only', 1); cur_frm.set_df_property('service', 'read_only', 1); cur_frm.set_df_property('status', 'read_only', 1); cur_frm.set_df_property('appointment_type', 'read_only', 1); refresh_field("customer") refresh_field("starts_on") refresh_field("ends_on") refresh_field("employee") refresh_field("company") refresh_field("service") refresh_field("status") refresh_field("appointment_type") } }); cur_frm.fields_dict.customer.get_query = function(doc) { return { query: "erpnext.crm.doctype.appointment.appointment.get_mob_no" } } frappe.ui.form.on("Appointment", "customer", function(frm,doc) { frappe.call({ method: "erpnext.crm.doctype.appointment.appointment.get_customer_mobile", args: { "customer": frm.doc.customer }, callback: function(r) { if(r.message) { if (frm.doc.appointment_type=='Home Service'){ frm.doc.customer_mobile_no = r.message[0][0] refresh_field("customer_mobile_no") } else{ frm.doc.customer_mobile_no = '' refresh_field("customer_mobile_no") } } else{ frm.doc.customer_mobile_no = '' refresh_field("customer_mobile_no") } } }); frappe.call({ method: "erpnext.crm.doctype.appointment.appointment.get_address", args: { "customer": frm.doc.customer }, callback: function(r) { if(r.message) { if (frm.doc.appointment_type=='Home Service'){ frm.doc.address_display = r.message refresh_field("address_display") } else{ frm.doc.address_display = '' refresh_field("address_display") } } else{ frm.doc.address_display = '' refresh_field("address_display") } } }); }); frappe.ui.form.on("Appointment", "appointment_type", function(frm,doc) { frappe.call({ method: "erpnext.crm.doctype.appointment.appointment.get_customer_mobile", args: { "customer": frm.doc.customer }, callback: function(r) { if(r.message) { if (frm.doc.appointment_type=='Home Service'){ frm.doc.customer_mobile_no = r.message[0][0] refresh_field("customer_mobile_no") } else{ frm.doc.customer_mobile_no = '' refresh_field("customer_mobile_no") } } } }); frappe.call({ method: "erpnext.crm.doctype.appointment.appointment.get_address", args: { "customer": frm.doc.customer }, callback: function(r) { if(r.message) { if (frm.doc.appointment_type=='Home Service'){ frm.doc.address_display = r.message refresh_field("address_display") } else{ frm.doc.address_display = '' refresh_field("address_display") } } } }); });
/** * * News module for yode-server * * controller * ver 0.0.1 * * Copyright 2013 * */ Ext.define('MyDesktop.modules.news.controller.News', { extend: 'MyDesktop.core.Controller' ,id:'news-win' // If you specify a window identifier, it only appears in one copy ,launcher: { text: D.t('News'), iconCls:'news' } ,addFormControls: function(win) { var me = this me.control(win,{ '[action=upload]':{change: function(th, val) {me.upload(win, th)}}, '[action=removePhoto]':{click: function(th, val) {me.delPhoto(win)}} }) me.callParent(arguments) } ,delPhoto: function(win) { var g = win.down('grid') ,sm = g.getSelectionModel() g.getStore().remove(sm.selected.items) } ,upload: function(win, inp) { var me = this if(inp.fileInputEl.dom.files.length>0) { Core.Ajax.uploadFiles(inp.fileInputEl.dom.files, '/admin.models.fileOperations:upload/', function(data) { if(data && data.length) { var s = win.down('grid').getStore(); for(var i=0;i<data.length;i++) { s.add({preview: '/tmp/'+data[i].name+'_small', img: data[i].name}); } } }) } } ,beforeSave: function(form, data) { var stor = form.down("grid").getStore() data.photos = [] stor.each(function(r) { data.photos.push(r.data) }) return data } ,beforeModify: function(form, data) { var store = form.down('grid').getStore() store.removeAll(); if(data.photos) { for(var i=0;i<data.photos.length;i++) { store.add({preview:data.photos[i].preview, img: null, num: i}) } } } ,detailFormReconfig: function(cnf) { cnf.layout = 'border' cnf.width = 800 cnf.height = 350 cnf.tools = null return cnf } });
/* Script: Drag.Move.js Contains <Drag.Move>, <Element.makeDraggable> License: MIT-style license. */ /* Class: Drag.Move Extends <Drag.Base>, has additional functionality for dragging an element, support snapping and droppables. Drag.move supports either position absolute or relative. If no position is found, absolute will be set. Inherits methods, properties, options and events from <Drag.Base>. Note: Drag.Move requires an XHTML doctype. Arguments: el - the $(element) to apply the drag to. options - optional. see Options below. Options: all the drag.Base options, plus: container - an element, will fill automatically limiting options based on the $(element) size and position. defaults to false (no limiting) droppables - an array of elements you can drop your draggable to. overflown - an array of nested scrolling containers, see Element::getPosition */ Drag.Move = Drag.Base.extend({ options: { droppables: [], container: false, overflown: [] }, initialize: function(el, options){ this.setOptions(options); this.element = $(el); this.droppables = $$(this.options.droppables); this.container = $(this.options.container); this.position = {'element': this.element.getStyle('position'), 'container': false}; if (this.container) this.position.container = this.container.getStyle('position'); if (!['relative', 'absolute', 'fixed'].contains(this.position.element)) this.position.element = 'absolute'; var top = this.element.getStyle('top').toInt(); var left = this.element.getStyle('left').toInt(); if (this.position.element == 'absolute' && !['relative', 'absolute', 'fixed'].contains(this.position.container)){ top = $chk(top) ? top : this.element.getTop(this.options.overflown); left = $chk(left) ? left : this.element.getLeft(this.options.overflown); } else { top = $chk(top) ? top : 0; left = $chk(left) ? left : 0; } this.element.setStyles({'top': top, 'left': left, 'position': this.position.element}); this.parent(this.element); }, start: function(event){ this.overed = null; if (this.container){ var cont = this.container.getCoordinates(); var el = this.element.getCoordinates(); if (this.position.element == 'absolute' && !['relative', 'absolute', 'fixed'].contains(this.position.container)){ this.options.limit = { 'x': [cont.left, cont.right - el.width], 'y': [cont.top, cont.bottom - el.height] }; } else { this.options.limit = { 'y': [0, cont.height - el.height], 'x': [0, cont.width - el.width] }; } } this.parent(event); }, drag: function(event){ this.parent(event); var overed = this.out ? false : this.droppables.filter(this.checkAgainst, this).getLast(); if (this.overed != overed){ if (this.overed) this.overed.fireEvent('leave', [this.element, this]); this.overed = overed ? overed.fireEvent('over', [this.element, this]) : null; } else if (overed) overed.fireEvent('drag', [this.element, this]); return this; }, checkAgainst: function(el){ el = el.getCoordinates(this.options.overflown); var now = this.mouse.now; return (now.x > el.left && now.x < el.right && now.y < el.bottom && now.y > el.top); }, stop: function(){ if (this.overed && !this.out) this.overed.fireEvent('drop', [this.element, this]); else this.element.fireEvent('emptydrop', this); this.parent(); return this; } }); /* Class: Element Custom class to allow all of its methods to be used with any DOM element via the dollar function <$>. */ Element.extend({ /* Property: makeDraggable Makes an element draggable with the supplied options. Arguments: options - see <Drag.Move> and <Drag.Base> for acceptable options. */ makeDraggable: function(options){ return new Drag.Move(this, options); } });
'use strict'; // Test setting details exports.seed = async database => { // Insert test settings await database('settings').insert([ { id: 'publicReadAccess', value: JSON.stringify(false) }, { id: 'setupComplete', value: JSON.stringify(true) } ]); };
/** * layerPanelCtrl class handles rendering of left hand side layer reports * @module controllers * @class layerPanelCtrl * */ allControllers.controller('layerPanelCtrl', ['$scope','GetCSWRecordService','RenderStatusService','$timeout','GoogleMapService','QuerierPanelService', function ($scope,GetCSWRecordService,RenderStatusService,$timeout,GoogleMapService,QuerierPanelService) { $scope.cswRecords={}; GetCSWRecordService.getCSWKnownLayers().then(function(data){ $scope.cswRecords=data; }); $scope.status = {}; $scope.renderStatus = RenderStatusService.getRenderStatus(); RenderStatusService.onUpdate($scope, function (newRenderStatus) { //VT: Inconsistent API (Sync/Async): https://docs.angularjs.org/error/$rootScope/inprog?p0=$digest $timeout(function() { $scope.renderStatus = newRenderStatus; },0); }); /** * remove the cswLayer * @method removeLayer * */ $scope.removeLayer = function(filterPanelCsw){ GoogleMapService.removeActiveLayer(filterPanelCsw); QuerierPanelService.deregisterLayer(filterPanelCsw); }; /** * @method getCswRecords * @return cswRecords - csw records that match the search, or all known layer csw records if search is empty */ this.getCswRecords = function() { // if there was a search, return search result $scope.cswRecords = GetCSWRecordService.getSearchedLayers(); return $scope.cswRecords; }; /** * @method togglePanels * @param panelType type of panel * @param group group * @param cswRecordId record identifier */ $scope.togglePanels = function(panelType,group,cswRecordId){ //VT: we only want 1 panel open at a time var closeOtherPanels = function(){ for (var showPanelType in $scope.status[group][cswRecordId].panels) { if(showPanelType != panelType){ $scope.status[group][cswRecordId].panels[showPanelType]=false; } } }; if($scope.status[group]===undefined){ $scope.status[group]={}; } if($scope.status[group][cswRecordId]===undefined){ $scope.status[group][cswRecordId]={}; $scope.status[group][cswRecordId].panels={}; } $scope.status[group][cswRecordId].panels[panelType] = !$scope.status[group][cswRecordId].panels[panelType]; if($scope.status[group][cswRecordId].panels[panelType] == true){ $scope.status[group][cswRecordId].isExpanded = true; toggleLayers(group,cswRecordId); }else{ $scope.status[group][cswRecordId].isExpanded = false; } closeOtherPanels(); return; }; /** * @method toggleLayers * @param group group * @param cswRecordId record identifier */ var toggleLayers = function(group,cswRecordId){ //VT: we only want 1 layer open at a time for(var cswRecord in $scope.status[group]){ if(cswRecord != cswRecordId){ if(cswRecord == "isOpen"){ continue; } for (var panelType in $scope.status[group][cswRecord].panels) { $scope.status[group][cswRecord].panels[panelType]=false; } $scope.status[group][cswRecord].isExpanded = false; } } }; }]);
export * from './changeJobsOrProjectStatus'
var express = require('express'); var session = require('express-session'); var bodyParser = require('body-parser'); var fs = require('fs'); var xml2js = require('xml2js'); var SAPRestService = require('./model/SAPRestService.js'); var bo = require('./model/bo.js'); var log4js = require('log4js'); var log = log4js.getLogger("Web server"); log.setLevel("DEBUG"); var port = process.env.port || process.argv[2] || 1338 ; var app = express(); app.use(log4js.connectLogger(log4js.getLogger("http"), { level: 'auto', format: ':method :url'})); app.use(bodyParser.urlencoded({extended: false})); app.use(bodyParser.json()); app.use(express.static('public')); //app.listen(port); var os = require("os"); app.listen(8081, os.hostname()); //------------------------------------------------------------------- //Remove below comments in case you want to enable cross domain call //And give the URL of domain from where you are expecting the call. //------------------------------------------------------------------- //var allowCrossDomain = function (req, res, next) { // res.header('Access-Control-Allow-Origin', 'http://amit-pc:8000'); // res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE'); // res.header('Access-Control-Allow-Headers', 'Content-Type'); // next(); //} //app.use(allowCrossDomain); var selectedObjects; // TODO: some kind of persistent data containing username and password. var userName = "boUserName"; var password = "boPassword"; // TODO: some kind of persistent data containing accepted username and passwords for authentication to WDC. var acceptedUsers = { "kbui" : "kbui", "skalki" : "skalki", "kritiv" : "kritiv" } app.get('/', function (request, response) { response.sendFile("views/BOT.html", {root: __dirname}); }); app.post('/api/cms', async function (req, response) { serverIP = req.body["Server"]; cmsName = req.body["CMS"]; universeName = req.body["UnxName"]; universeId = req.body["UnxId"]; if (acceptedUsers[req.body["UserName"]] == req.body["Password"]) { var metadataFile = "./UniverseMetdata/" + universeName + ".json"; fs.access(metadataFile, fs.R_OK, function(e) { if (!e) { response.sendStatus(200); } else { log.error("Couldn't access metadata file " + metadataFile); response.sendStatus(500); } }); } else { log.error("Invalid username or password"); response.statusMessage = "Invalid username or password"; response.sendStatus(500); } }); app.get('/api/bo-fav/:favName', function(req, response) { selectedObjects = bo.getFavorite(req.params.favName); response.send(selectedObjects); }); app.post('/api/bo-fav', function(req, response) { var favName = req.body["favName"]; selectedObjects = JSON.parse(req.body.data); bo.addToFavorite(favName, selectedObjects); response.send(true); }); app.get('/api/bo-metadata', function (req, response) { console.log("get api/bo metadata:"); var metadataFile = "./UniverseMetdata/" + universeName + ".json"; var universeMetadata = JSON.parse(fs.readFileSync(metadataFile)); var metadataResponse = bo.getBOData(universeMetadata); response.json(metadataResponse); }); app.post('/api/bo-ids', function (req, response) { selectedObjects = JSON.parse(req.body.data); response.send(true); }); app.get('/api/bo-schema', async function (req, response) { var sapRestSvc = new SAPRestService(userName, password, serverIP, cmsName, universeId, selectedObjects); try { // node.js closes socket after 2 minutes, causing browser to resend ajax. This is to prevent it from resubmitting ajax call. response.setTimeout(0); await sapRestSvc.logon(); var queryId = await sapRestSvc.createQuery(); var schemas = await sapRestSvc.getQuerySchema(queryId); response.send(schemas); // not really understan await sapRestSvc.logoff(); } catch (err) { handleError(err, response); await sapRestSvc.logoff(); } }); app.get('/api/bo-data', async function (req, response) { var sapRestSvc = new SAPRestService(userName, password, serverIP, cmsName, universeId, selectedObjects); try { // node.js closes socket after 2 minutes, causing browser to resend ajax. This is to prevent it from resubmitting ajax call. response.setTimeout(0); await sapRestSvc.logon(); var queryId = await sapRestSvc.createQuery(); var data = await sapRestSvc.getQueryData(queryId); response.send(data); await sapRestSvc.logoff(); } catch (err) { console.log((err.response ? err.response.data.message : err.message)); await sapRestSvc.logoff(); } }); function handleError(err, response) { var errMsg; var status = 500; // default generic code if (err.response) { status = err.response.status; if (err.response.data.message) { errMsg = err.response.data.message; } else { errMsg = err.response.data; } } else { errMsg = err.message; } response.statusMessage = errMsg; response.status(status).end(); }
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function hd(arr) { return arr[0]; } exports.hd = hd; function tl(arr) { return arr.slice(1); } exports.tl = tl; function last(arr) { return arr[arr.length - 1]; } exports.last = last; //# sourceMappingURL=data:application/json;charset=utf8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uL3NyYy91dGlsL2ZuLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBQ0EsWUFBc0IsR0FBUTtJQUMxQixNQUFNLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxDQUFDO0FBQ2xCLENBQUM7QUFGRCxnQkFFQztBQUVELFlBQXNCLEdBQVE7SUFDMUIsTUFBTSxDQUFDLEdBQUcsQ0FBQyxLQUFLLENBQUMsQ0FBQyxDQUFDLENBQUM7QUFDeEIsQ0FBQztBQUZELGdCQUVDO0FBRUQsY0FBd0IsR0FBUTtJQUM1QixNQUFNLENBQUMsR0FBRyxDQUFDLEdBQUcsQ0FBQyxNQUFNLEdBQUcsQ0FBQyxDQUFDLENBQUM7QUFDL0IsQ0FBQztBQUZELG9CQUVDIiwiZmlsZSI6InV0aWwvZm4uanMiLCJzb3VyY2VSb290Ijoic3JjLyJ9
/* * Copyright (c) 2005-2016 Vincent Vandenschrick. All rights reserved. * * This file is part of the Jspresso framework. * * Jspresso is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Jspresso 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Jspresso. If not, see <http://www.gnu.org/licenses/>. */ /** * Copyright (c) 2005-2013 Vincent Vandenschrick. All rights reserved. * <p> * This file is part of the Jspresso framework. Jspresso is free software: you * can redistribute it and/or modify it under the terms of the GNU Lesser * General Public License as published by the Free Software Foundation, either * version 3 of the License, or (at your option) any later version. Jspresso 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 Lesser General Public License for more * details. You should have received a copy of the GNU Lesser General Public * License along with Jspresso. If not, see <http://www.gnu.org/licenses/>. */ qx.Class.define("org.jspresso.framework.gui.remote.mobile.RMobilePageAwareContainer", { extend: org.jspresso.framework.gui.remote.mobile.RMobilePageAware, construct: function () { this.base(arguments); }, properties: { content: { check: "org.jspresso.framework.gui.remote.RComponent", nullable: true } }, members: { getPosition: function () { return this.getContent().getPosition(); } } });
/* * Module: Front-End Development Certification * Section: Basic Algorithm Scripting * Challenge: Factorialize a Number * https://www.freecodecamp.com/challenges/factorialize-a-number * * Return the factorial of the provided integer. * * If the integer is represented with the letter n, a factorial is the product of * all positive integers less than or equal to n. * * Factorials are often represented with the shorthand notation n! * * For example: 5! = 1 * 2 * 3 * 4 * 5 = 120 */ 'use strict'; function fact (x) { return x == 0 ? 1 : x * fact (x - 1); } module.exports = fact;
isc.Canvas.create({ ID: "container", width: "100%", height: "100%" }); isc.RPCManager.loadScreen("formRules",function (screen) { container.addChild(screen); });
/** * This file automatically adds the CSRF token as an input for every form submission, and as a header for every ajax * request **/ $(document).ready(function() { var token = $("meta[name='_csrf']").attr("content"); var header = $("meta[name='_csrf_header']").attr("content"); var parameter = $("meta[name='_csrf_parameter']").attr("content"); $(document).ajaxSend(function(e, xhr, options) { xhr.setRequestHeader(header, token); }); })
import {ToCVirtualTree} from 'idoc/idoc-toc/idoc-toc-virtual-tree'; let hasChild = function (children, child) { return children.indexOf(child) > -1; }; describe('Tests for the idoc table of contents : virtual tree', () => { it('Test if moveSection(sectionID, to, nextSiblingID) moves a main section and makes it subsection', () => { let tocTree = new ToCVirtualTree(); tocTree.createSection('mock1', null); tocTree.createSection('mock2', null); tocTree.moveSection('mock1', 'mock2'); expect(hasChild(tocTree.tree.get('mock2'), 'mock1')).to.be.true; }); it('Test if moveSection(sectionID, to, nextSiblingID) moves a main section to subsection', () => { let tocTree = new ToCVirtualTree(); tocTree.createSection('mock2', 'mock1'); tocTree.createSection('mock3', null); tocTree.moveSection('mock3', 'mock2'); expect(hasChild(tocTree.tree.get('mock2'), 'mock3')).to.be.true; }); it('Test if moveSection(sectionID, to, nextSiblingID) makes a subsection main', () => { let tocTree = new ToCVirtualTree(); tocTree.createSection('mock2', 'mock1'); tocTree.createSection('mock3', null); tocTree.moveSection('mock3', 'mock2'); tocTree.moveSection('mock2', null); expect(tocTree.parents.get('mock2')).to.be.equal('mock2'); expect(hasChild(tocTree.tree.get('mock2'), 'mock3')).to.be.true; }); it('Test if moveSection(sectionID, to, nextSiblingID) makes "sectionID" child of "to" moves "sectionID" just before "nextSiblingID"',()=>{ let tocTree = new ToCVirtualTree(); tocTree.createSection('mock',null); tocTree.createSection('mock1','mock'); tocTree.createSection('test',null); tocTree.moveSection('test','mock','mock1'); let children = tocTree.tree.get('mock'); let childIndex = children.indexOf('test'); expect(children[childIndex+1]).to.equal('mock1'); }); it('Test the creation of main section', () => { let toCVirtualTree = new ToCVirtualTree(); let mockSectionID = 'mockSectionID'; toCVirtualTree.createSection(mockSectionID, null); expect(toCVirtualTree.tree.has(mockSectionID)).to.be.true; }); it('Test the creation of sub section', () => { let toCVirtualTree = new ToCVirtualTree(); let mockParentSectionID = 'mockParentID'; toCVirtualTree.createSection(mockParentSectionID, null); let mockSectionID = 'mockSectionID'; toCVirtualTree.createSection(mockSectionID, mockParentSectionID); expect(hasChild(toCVirtualTree.tree.get(mockParentSectionID), mockSectionID)).to.be.true; }); it('Test the creation of sub sub section', () => { let toCVirtualTree = new ToCVirtualTree(); let mockParentSubSection = 'mockParentSubSection'; let mockSection = 'mockSubSub'; toCVirtualTree.createSection(mockSection, mockParentSubSection); expect(hasChild(toCVirtualTree.tree.get(mockParentSubSection), mockSection)).to.be.true; }); it('Test the deletion of main section', () => { let toCVirtualTree = new ToCVirtualTree(); let mockSectionID = 'mockSectionID'; toCVirtualTree.createSection(mockSectionID, null); let result = toCVirtualTree.deleteSection(mockSectionID); expect(toCVirtualTree.tree.has(mockSectionID)).to.be.false; expect(result).to.be.true; }); it('Test the deletion of subsection', () => { let toCVirtualTree = new ToCVirtualTree(); let mockSectionID = 'mockSectionID'; let mockParentID = 'mockParent'; toCVirtualTree.createSection(mockSectionID, mockParentID); let result = toCVirtualTree.deleteSection(mockSectionID); expect(hasChild(toCVirtualTree.tree.get(mockParentID), mockSectionID)).to.be.false; expect(result).to.be.true; }); it('Test the deletion of subsection which is parent of other sections', () => { let toCVirtualTree = new ToCVirtualTree(); let mockSectionID = 'mockSectionID'; let mockSubSectionID = 'mockSubSectionID'; let mockParentID = 'mockParent'; toCVirtualTree.createSection(mockSectionID, mockParentID); toCVirtualTree.createSection(mockSubSectionID, mockSectionID); let result = toCVirtualTree.deleteSection(mockSectionID); expect(hasChild(toCVirtualTree.tree.get(mockParentID), mockSectionID)).to.be.false; expect(toCVirtualTree.tree.has(mockSectionID)).to.be.false; expect(result).to.be.true; }); it('Test the deletion of whole subTree', ()=> { let tocVirtualTree = new ToCVirtualTree(); tocVirtualTree.createSection('b', 'a'); tocVirtualTree.createSection('b1', 'b'); tocVirtualTree.createSection('c', 'a'); tocVirtualTree.deleteSubTree('a'); expect(tocVirtualTree.tree.length).to.be.zero; }); it('Test the tree full traversal', ()=> { let virtualTree = new ToCVirtualTree(); virtualTree.createSection('a', null); virtualTree.createSection('a1', 'a'); virtualTree.createSection('b', null); virtualTree.createSection('b1', 'b'); let result = ''; let mockDecorator = function () { this.decorateRoots = function (roots) { return roots; }; this.decorateNode = function (node) { }; this.decorateNodeChild = function (node, child) { result += (node + '->' + child + ' '); } }; virtualTree.fullTraversal(new mockDecorator()); expect(result).to.equal('a->a1 b->b1 '); }); });
var namespace_b_w_a_p_i_1_1_damage_types = [ [ "allDamageTypes", "namespace_b_w_a_p_i_1_1_damage_types.html#a406fdd4cf35667c4353a71989cbfaeca", null ], [ "Independent", "namespace_b_w_a_p_i_1_1_damage_types.html#aa21b2df99a55b109ab5897de462640ef", null ], [ "Explosive", "namespace_b_w_a_p_i_1_1_damage_types.html#a5779aeb5c5556fd7fec022fe5ca671ea", null ], [ "Concussive", "namespace_b_w_a_p_i_1_1_damage_types.html#a7d298fbc94fa426dead1aebf20bf258e", null ], [ "Normal", "namespace_b_w_a_p_i_1_1_damage_types.html#a5210cb07e6edd8795ed3ff572ca909cd", null ], [ "Ignore_Armor", "namespace_b_w_a_p_i_1_1_damage_types.html#ad04c48c976375576ea981fbbf9e34168", null ], [ "None", "namespace_b_w_a_p_i_1_1_damage_types.html#a58c1f6b836bea4acf05abcc63f9b38a5", null ], [ "Unknown", "namespace_b_w_a_p_i_1_1_damage_types.html#a3104774b5c6deeeb8485becf24141e66", null ] ];
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.editorConfig = function( config ) { config.toolbar = 'Full'; config.toolbar_Full = [ { name: 'document', items : [ 'Source',] }, { name: 'clipboard', items : [ 'Cut','Copy','Paste','PasteText','PasteFromWord','-','Undo','Redo' ] }, { name: 'editing', items : [ 'Find','Replace','-','SelectAll'] }, '/', { name: 'basicstyles', items : [ 'Bold','Italic','Underline','Strike','Subscript','Superscript','-','RemoveFormat' ] }, { name: 'paragraph', items : [ 'NumberedList','BulletedList','-','Outdent','Indent','-','Blockquote','CreateDiv','-','JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'] }, { name: 'links', items : [ 'Link','Unlink','Anchor' ] }, { name: 'insert', items : [ 'Image','Flash','Table'] }, '/', { name: 'styles', items : [ 'Format','Font','FontSize' ] }, { name: 'colors', items : [ 'TextColor','BGColor' ] }, ]; config.filebrowserBrowseUrl = GCore.DESIGN_PATH + '_js_libs/ckeditor/kcfinder/browse.php?type=files'; config.filebrowserImageBrowseUrl = GCore.DESIGN_PATH + '_js_libs/ckeditor/kcfinder/browse.php?type=images'; config.filebrowserFlashBrowseUrl = GCore.DESIGN_PATH + '_js_libs/ckeditor/kcfinder/browse.php?type=flash'; config.filebrowserUploadUrl = GCore.DESIGN_PATH + '_js_libs/ckeditor/kcfinder/upload.php?type=files'; config.filebrowserImageUploadUrl = GCore.DESIGN_PATH + '_js_libs/ckeditor/kcfinder/upload.php?type=images'; config.filebrowserFlashUploadUrl = GCore.DESIGN_PATH + '_js_libs/ckeditor/kcfinder/upload.php?type=flash'; };
import { Dispatcher } from 'consus-core/flux'; import StudentStore from '../../../.dist/store/student-store'; import { assert } from 'chai'; describe('StudentStore', () => { beforeEach(() => { return Dispatcher.handleAction('CLEAR_ALL_DATA'); }); it('should instantiate without a student', () => { assert.isNull(StudentStore.getStudent()); }); it('should get the student', () => { Dispatcher.handleAction('STUDENT_FOUND',{ id: 432345, name: 'Poe', items: [] }); let student = StudentStore.getStudent(); assert.strictEqual(student.id, 432345); assert.strictEqual(student.name,'Poe'); }); it('should get student by Id', () => { Dispatcher.handleAction('STUDENT_FOUND',{ id: 432345, name: 'Poe', items: [] }); let student = StudentStore.getStudentById(432345); assert.strictEqual(student.id, 432345); assert.strictEqual(student.name,'Poe'); }); it('should get all students', () => { Dispatcher.handleAction("STUDENTS_FOUND", [ { id: 432432, name: "Sporf Bigby", items: [] }, { id:654321, name: "Bruce Glasgow", items: [] } ]); let students = StudentStore.getAllStudents(); assert.lengthOf(Object.keys(students), 2); assert.isDefined(students[432432]); assert.isDefined(students[654321]); }); it('should know if students have overdue items', () => { Dispatcher.handleAction("STUDENTS_FOUND", [ { id: 432432, name: "Sporf Bigby", items: [{ timestamp : 0 }] }, { id:654321, name: "Bruce Glasgow", items: [] } ]); let students = StudentStore.getAllStudents(); assert.lengthOf(Object.keys(students), 2); assert.isDefined(students[432432]); assert.isDefined(students[654321]); assert.isTrue(students[432432].hasOverdueItem); assert.isFalse(students[654321].hasOverdueItem); }); it('should know which students are delinquents', () => { Dispatcher.handleAction("STUDENTS_FOUND", [ { id: 432432, name: "Sporf Bigby", items: [{ timestamp : 0 }], overdueCheckins:[] }, { id:654321, name: "Bruce Glasgow", items: [], overdueCheckins:[] }, { id:321321, name: "Derk Bigums", items: [], overdueCheckins:[{}] } ]); let students = StudentStore.getAllDelinquents(); assert.lengthOf(Object.keys(students), 2); }); it('should handle a student not being found', () => { Dispatcher.handleAction('NO_STUDENT_FOUND'); assert.strictEqual(StudentStore.getStudent(), null); }); it("should remove an item from a student's list when it's checked in", () =>{ //Set Up Test State Dispatcher.handleAction('STUDENT_FOUND',{ id: 432345, name: 'Poe', items: [{address:1},{address:2},{address:3},{address:4}] }); let student = StudentStore.getStudent(); //validate test state assert.strictEqual(student.items.length,4); Dispatcher.handleAction('CHECKIN_SUCCESS',{ itemAddress: 4 }); student = StudentStore.getStudent(); assert.strictEqual(student.items.length, 3); assert.strictEqual(student.items.indexOf(4), -1); }); it("should add item to student's list on checkout success", () => { Dispatcher.handleAction("STUDENT_FOUND", { id: 32423, name: "Poe", items: [] }); Dispatcher.handleAction("CHECKOUT_ITEM_FOUND", { address: "123", status: "AVAILABLE" }); Dispatcher.handleAction("CHECKOUT_SUCCESS"); let student = StudentStore.getStudent(); assert.strictEqual(student.items[0].address, "123"); }); it("Should know if the student has an overdue item", () => { //Test that it will find an overdue item Dispatcher.handleAction('STUDENT_FOUND',{ id: 432432432423432432432432432, name: 'Poe', items: [{ address: 1, timestamp: 0 }] }); let student = StudentStore.getStudent(); assert.strictEqual(student.items.length, 1); assert(student.hasOverdueItem); //Test that it will not say an item is overdue if it's not. Dispatcher.handleAction('STUDENT_FOUND',{ id: 432432432423432432432432432, name: 'Poe', items: [{ address: 1, timestamp: new Date().getTime() + 100000 }] }); student = StudentStore.getStudent(); assert.strictEqual(student.items.length, 1); assert.isFalse(student.hasOverdueItem); }); it("Should update the student", () => { Dispatcher.handleAction("STUDENTS_FOUND", [ { "id":111111, "name":"Boaty McBoatface", "status":"C - Current", "email":"mcboatfaceb@msoe.edu", "major":"Hyperdimensional Nautical Machines Engineering", "items":[] } ]); assert.lengthOf(Object.keys(StudentStore.getAllStudents()), 1); Dispatcher.handleAction("STUDENT_UPDATED", {id: 111111, name:"Sporf McDougal"}) assert.strictEqual(StudentStore.getStudentById(111111).name, "Sporf McDougal"); }); });