text
stringlengths
2
6.14k
'use strict'; var ko = require('knockout'); var bootbox = require('bootbox'); var $osf = require('osf-helpers'); function FolderCreatorViewModel(url) { var self = this; self.url = url; self.title = ko.observable('').extend({ maxLength: 200 }); self.formErrorText = ko.observable(''); self.createFolder = function () { $osf.postJSON( self.url, self.serialize() ).done( self.createSuccess ).fail( self.createFailure ); }; self.createSuccess = function (data) { window.location = data.projectUrl; }; self.createFailure = function () { $osf.growl('Could not create a new folder.', 'Please try again. If the problem persists, email <a href="mailto:[email protected].">[email protected]</a>'); }; self.serialize = function () { return { title: self.title() }; }; self.verifyTitle = function () { if (self.title() === ''){ self.formErrorText('We need a title for your folder.'); } else { self.createFolder(); } }; } function FolderCreator(selector, url) { var viewModel = new FolderCreatorViewModel(url); // Uncomment for debugging // window.viewModel = viewModel; $osf.applyBindings(viewModel, selector); } module.exports = FolderCreator;
/** * Utility functions. * @module util */ (function () { 'use strict'; /** * Determine whether a variable is an integer. * @param {mixed} n The variable to test. * @returns {boolean} * @public */ var isInteger = function (n) { return ( Object.prototype.toString.call(n) === '[object Number]' && n % 1 === 0 && isNaN(n) === false ); }; /** * Determine if n is a prime number * @param {integer} n The integer to test * @returns {boolean} * @public */ var isPrime = function (n) { if (!isInteger(n) || !isFinite(n) || n % 1 || n < 2) { return false; } if (n % 2 === 0) { return n === 2; } var m = Math.sqrt(n); for (var i = 3; i <= m; i += 2) { if (n % i === 0) { return false; } } return true; }; module.exports = { isInteger: isInteger, isPrime: isPrime, }; })();
// notice_start /* * Copyright 2015 Dev Shop Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // notice_end import Guard from '../Guard'; export default class DisposableWrapper { constructor(disposable) { Guard.isDefined(disposable, "disposable must be defined"); var innerDisposable; if(typeof disposable === 'function') { innerDisposable = { dispose: function() { disposable(); } }; } else if(disposable.dispose && typeof disposable.dispose === 'function') { innerDisposable = { dispose: () => { // at this point if something has deleted the dispose or it's not a function we just ignore it. if (disposable.dispose && typeof disposable.dispose === 'function') { disposable.dispose(); } } }; } else { throw new Error('Item to dispose was neither a function nor had a dispose method.'); } this._isDisposed = false; this._disposable = innerDisposable; } get isDisposed() { return this._isDisposed; } dispose() { if(!this._isDisposed && this._disposable) { this._isDisposed = true; this._disposable.dispose(); } } }
/* * Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ define("ace/mode/asyncapi", ["require", "exports", "module"], function (require, exports, module) { "use strict"; // JS strict mode var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var AsyncAPIHighlightRules = require("./asyncapi_highlight_rules").AsyncAPIHighlightRules; var AsyncAPIFoldMode = require("./folding/asyncapi").AsyncAPIFoldMode; var Mode = function () { this.HighlightRules = AsyncAPIHighlightRules; this.foldingRules = new AsyncAPIFoldMode(); }; oop.inherits(Mode, TextMode); (function () { this.lineCommentStart = "--"; this.$id = "ace/mode/siddhi"; }).call(Mode.prototype); exports.Mode = Mode; });
/** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var betaln = require( '@stdlib/math/base/special/betaln' ); var isnan = require( '@stdlib/math/base/assert/is-nan' ); var log1p = require( '@stdlib/math/base/special/log1p' ); var exp = require( '@stdlib/math/base/special/exp' ); var ln = require( '@stdlib/math/base/special/ln' ); var PINF = require( '@stdlib/constants/float64/pinf' ); // MAIN // /** * Evaluates the probability density function (PDF) for a beta distribution with first shape parameter `alpha` and second shape parameter `beta` at a value `x`. * * @param {number} x - input value * @param {PositiveNumber} alpha - first shape parameter * @param {PositiveNumber} beta - second shape parameter * @returns {number} evaluated PDF * * @example * var y = pdf( 0.5, 1.0, 1.0 ); * // returns 1.0 * * @example * var y = pdf( 0.5, 2.0, 4.0 ); * // returns 1.25 * * @example * var y = pdf( 0.2, 2.0, 2.0 ); * // returns ~0.96 * * @example * var y = pdf( 0.8, 4.0, 4.0 ); * // returns ~0.573 * * @example * var y = pdf( -0.5, 4.0, 2.0 ); * // returns 0.0 * * @example * var y = pdf( 1.5, 4.0, 2.0 ); * // returns 0.0 * * @example * var y = pdf( 0.5, -1.0, 0.5 ); * // returns NaN * * @example * var y = pdf( 0.5, 0.5, -1.0 ); * // returns NaN * * @example * var y = pdf( NaN, 1.0, 1.0 ); * // returns NaN * * @example * var y = pdf( 0.5, NaN, 1.0 ); * // returns NaN * * @example * var y = pdf( 0.5, 1.0, NaN ); * // returns NaN */ function pdf( x, alpha, beta ) { var out; if ( isnan( x ) || isnan( alpha ) || isnan( beta ) || alpha <= 0.0 || beta <= 0.0 ) { return NaN; } if ( x < 0.0 || x > 1.0 ) { // Support of the Beta distribution: [0,1] return 0.0; } if ( x === 0.0 ) { if ( alpha < 1.0 ) { return PINF; } if ( alpha > 1.0 ) { return 0.0; } return beta; } if ( x === 1.0 ) { if ( beta < 1.0 ) { return PINF; } if ( beta > 1.0 ) { return 0.0; } return alpha; } out = ( alpha-1.0 ) * ln( x ); out += ( beta-1.0 ) * log1p( -x ); out -= betaln( alpha, beta ); return exp( out ); } // EXPORTS // module.exports = pdf;
'use strict'; /** * @ngdoc function * @name MaterialApp.controller:MainCtrl * @description * # MainCtrl * Controller of MaterialApp */ angular.module('MaterialApp').controller('PaginationDemoCtrl', function ($scope, $log) { $scope.totalItems = 64; $scope.currentPage = 4; $scope.setPage = function (pageNo) { $scope.currentPage = pageNo; }; $scope.pageChanged = function() { $log.log('Page changed to: ' + $scope.currentPage); }; $scope.maxSize = 5; $scope.bigTotalItems = 175; $scope.bigCurrentPage = 1; });
/** * Copyright (c) 2015-2017 Guyon Roche * LICENCE: MIT - please refer to LICENCE file included with this module * or https://github.com/guyonroche/exceljs/blob/master/LICENSE */ 'use strict'; var events = require('events'); var Sax = require('sax'); var utils = require('../../utils/utils'); var Enums = require('../../doc/enums'); var RelType = require('../../xlsx/rel-type'); var HyperlinkReader = module.exports = function(workbook, id) { // in a workbook, each sheet will have a number this.id = id; this._workbook = workbook; }; utils.inherits(HyperlinkReader, events.EventEmitter, { get count() { return (this.hyperlinks && this.hyperlinks.length) || 0; }, each: function(fn) { return this.hyperlinks.forEach(fn); }, read: function(entry, options) { var self = this; var emitHyperlinks = false; var hyperlinks = null; switch (options.hyperlinks) { case 'emit': emitHyperlinks = true; break; case 'cache': this.hyperlinks = hyperlinks = {}; break; default: break; } if (!emitHyperlinks && !hyperlinks) { entry.autodrain(); self.emit('finished'); return; } var parser = Sax.createStream(true, {}); parser.on('opentag', function(node) { if (node.name === 'Relationship') { var rId = node.attributes.Id; switch (node.attributes.Type) { case RelType.Hyperlink: var relationship = { type: Enums.RelationshipType.Styles, rId: rId, target: node.attributes.Target, targetMode: node.attributes.TargetMode }; if (emitHyperlinks) { self.emit('hyperlink', relationship); } else { hyperlinks[relationship.rId] = relationship; } break; default: break; } } }); parser.on('end', function() { self.emit('finished'); }); // create a down-stream flow-control to regulate the stream var flowControl = this.workbook.flowControl.createChild(); flowControl.pipe(parser, {sync: true}); entry.pipe(flowControl); } });
/* Copyright (c) 2004-2016, The JS Foundation All Rights Reserved. Available via Academic Free License >= 2.1 OR the modified BSD license. see: http://dojotoolkit.org/license for details */ //>>built define("dojo/cldr/nls/de/currency",{HKD_displayName:"Hongkong-Dollar",CHF_displayName:"Schweizer Franken",JPY_symbol:"\u00a5",CAD_displayName:"Kanadischer Dollar",HKD_symbol:"HK$",CNY_displayName:"Renminbi Yuan",USD_symbol:"$",AUD_displayName:"Australischer Dollar",JPY_displayName:"Japanischer Yen",CAD_symbol:"CA$",USD_displayName:"US-Dollar",EUR_symbol:"\u20ac",CNY_symbol:"CN\u00a5",GBP_displayName:"Britisches Pfund",GBP_symbol:"\u00a3",AUD_symbol:"AU$",EUR_displayName:"Euro"});
/** * Copyright 2017 HUAWEI. All Rights Reserved. * * SPDX-License-Identifier: Apache-2.0 * * @file, definition of the Fabric class, which implements the caliper's NBI for hyperledger fabric */ 'use strict' var txType = { // commands ADD_ASSET_QUANTITY : {type:'command', fn:'addAssetQuantity', argslen: 3}, ADD_PEER : {type:'command', fn:'addPeer', argslen: 2}, ADD_SIGNATORY : {type:'command', fn:'addSignatory', argslen: 2}, APPEND_ROLE : {type:'command', fn:'appendRole', argslen: 2}, CREATE_ACCOUNT : {type:'command', fn:'createAccount', argslen: 3}, CREATE_ASSET : {type:'command', fn:'createAsset', argslen: 3}, CREATE_DOMAIN : {type:'command', fn:'createDomain', argslen: 2}, CREATE_ROLE : {type:'command', fn:'createRole', argslen: 2}, DETACH_ROLE : {type:'command', fn:'detachRole', argslen: 2}, GRANT_PERMISSION : {type:'command', fn:'grantPermission', argslen: 2}, REMOVE_SIGNATORY : {type:'command', fn:'removeSignatory', argslen: 2}, REVOKE_PERMISSION : {type:'command', fn:'revokePermission', argslen: 2}, SET_ACCOUNT_DETAIL : {type:'command', fn:'setAccountDetail', argslen: 3}, SET_ACCOUNT_QUORUM : {type:'command', fn:'setAccountQuorum', argslen: 2}, SUBTRACT_ASSET_QUANTITY : {type:'command', fn:'subtractAssetQuantity', argslen: 3}, TRANSFER_ASSET : {type:'command', fn:'transferAsset', argslen: 5}, // query, started from 100 GET_ACCOUNT : {type:'query', fn:'getAccount', argslen: 1}, GET_SIGNATORIES : {type:'query', fn:'getSignatories', argslen: 1}, GET_ACCOUNT_TRANSACTIONS : {type:'query', fn:'getAccountTransactions', argslen: 1}, GET_ACCOUNT_ASSERT_TRANSACTIONS : {type:'query', fn:'getAccountAssetTransactions', argslen: 2}, GET_TRANSACTIONS : {type:'query', fn:'getTransactions', argslen: 1}, GET_ACCOUNT_ASSETS : {type:'query', fn:'getAccountAssets', argslen: 2}, GET_ASSET_INFO : {type:'query', fn:'getAssetInfo', argslen: 1}, GET_ROLES : {type:'query', fn:'getRoles ', argslen: 0}, GET_ROLE_PERMISSIONS : {type:'query', fn:'GetRolePermissions ', argslen: 1} }; module.exports.txType = txType; /** * judge whether the type is a command type or query type * @type {Number} * @return {Number}, 0: command; 1: query */ module.exports.commandOrQuery = function (tx) { if(tx.type === 'command') { return 0; } else { return 1; } }
/** * Survey Component Stories. * * Site Kit by Google, Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * External dependencies */ import fetchMock from 'fetch-mock'; /** * Internal dependencies */ import WithRegistrySetup from '../../../../tests/js/WithRegistrySetup'; import { provideCurrentSurvey } from '../../../../tests/js/utils'; import { CORE_FORMS } from '../../googlesitekit/datastore/forms/constants'; import CurrentSurvey from './CurrentSurvey'; import { multiQuestionConditionalSurvey, multiQuestionSurvey, singleQuestionSurvey, singleQuestionSurveyWithNoFollowUp, } from './__fixtures__'; function Template( { setupRegistry, ...args } ) { return ( <WithRegistrySetup func={ setupRegistry }> <CurrentSurvey { ...args } /> </WithRegistrySetup> ); } export const SurveySingleQuestionStory = Template.bind( {} ); SurveySingleQuestionStory.storyName = 'Single question'; SurveySingleQuestionStory.args = { setupRegistry: ( registry ) => { fetchMock.post( /google-site-kit\/v1\/core\/user\/data\/survey-event/, { body: {}, } ); provideCurrentSurvey( registry, singleQuestionSurvey ); }, }; SurveySingleQuestionStory.scenario = { label: 'Global/Current Survey/Single question', delay: 250, }; export const SurveyMultipleQuestionsStory = Template.bind( {} ); SurveyMultipleQuestionsStory.storyName = 'Multiple questions'; SurveyMultipleQuestionsStory.args = { setupRegistry: ( registry ) => { fetchMock.post( /google-site-kit\/v1\/core\/user\/data\/survey-event/, { body: {}, } ); provideCurrentSurvey( registry, multiQuestionSurvey ); }, }; export const SurveyMultipleQuestionsConditionalStory = Template.bind( {} ); SurveyMultipleQuestionsConditionalStory.storyName = 'Conditional'; SurveyMultipleQuestionsConditionalStory.args = { setupRegistry: ( registry ) => { fetchMock.post( /google-site-kit\/v1\/core\/user\/data\/survey-event/, { body: {}, } ); provideCurrentSurvey( registry, multiQuestionConditionalSurvey ); }, }; export const SurveyNotAnsweredNoFollowUpStory = Template.bind( {} ); SurveyNotAnsweredNoFollowUpStory.storyName = 'New survey (no follow-up CTA)'; SurveyNotAnsweredNoFollowUpStory.args = { setupRegistry: ( registry ) => { fetchMock.post( /google-site-kit\/v1\/core\/user\/data\/survey-event/, { body: {}, } ); provideCurrentSurvey( registry, singleQuestionSurveyWithNoFollowUp ); }, }; export const SurveyAnsweredPositiveStory = Template.bind( {} ); SurveyAnsweredPositiveStory.storyName = 'Completed'; SurveyAnsweredPositiveStory.args = { setupRegistry: ( registry ) => { const answer = { question_ordinal: 1, answer: { answer: { answer_ordinal: 5 }, }, }; fetchMock.post( /google-site-kit\/v1\/core\/user\/data\/survey-event/, { body: {}, } ); provideCurrentSurvey( registry, singleQuestionSurvey ); registry .dispatch( CORE_FORMS ) .setValues( `survey-${ singleQuestionSurvey.session.session_id }`, { answers: [ answer ], } ); }, }; export const SurveyWithTermsStory = Template.bind( {} ); SurveyWithTermsStory.storyName = 'With Terms'; SurveyWithTermsStory.args = { setupRegistry: ( registry ) => { fetchMock.post( /google-site-kit\/v1\/core\/user\/data\/survey-event/, { body: {}, } ); provideCurrentSurvey( registry, singleQuestionSurvey, { trackingEnabled: false, } ); }, }; export default { title: 'Components/Surveys/CurrentSurvey', };
const React = require('react-native'); const { StyleSheet } = React; export default { container: { backgroundColor: '#fff', }, pinBoxList: { flex: -1, flexDirection: 'row', justifyContent: 'space-between', marginBottom: 20, }, };
const { mix } = require('laravel-mix'); /* |-------------------------------------------------------------------------- | Mix Asset Management |-------------------------------------------------------------------------- | | Mix provides a clean, fluent API for defining some Webpack build steps | for your Laravel application. By default, we are compiling the Sass | file for the application as well as bundling up all the JS files. | */ // Do not Autoload Jquery as we're already including it via `plugins.js` mix.autoload({}) var pluginPath = 'resources/assets/plugins/'; mix.combine([ // ** Required Plugins ** pluginPath + 'jquery/jquery.js', pluginPath + 'bootstrap/tether.js', pluginPath + 'bootstrap/bootstrap.js', pluginPath + 'customScrollBar/customScrollBar.js', // ** Additional Plugins ** pluginPath + 'ladda/spin.js', pluginPath + 'ladda/ladda.js', pluginPath + 'toastr/toastr.js', pluginPath + 'notie/notie.js', pluginPath + 'jquery-validate/jquery.validate.js', pluginPath + 'jquery-validate/additional-methods.js', pluginPath + 'clockpicker/bootstrap-clockpicker.js', pluginPath + 'switchery/switchery.js', pluginPath + 'select2/select2.js', pluginPath + 'datatables/dataTables.min.js', pluginPath + 'datatables/dataTables.bootstrap.js', pluginPath + 'multiselect/jquery.multi-select.js', pluginPath + 'bootstrapSelect/bootstrap-select.js', pluginPath + 'bootstrap-datepicker/bootstrap-datepicker.js', pluginPath + 'timepicker/jquery.timepicker.js', pluginPath + 'summernote/summernote.js', pluginPath + 'simplemde/simplemde.min.js', pluginPath + 'Chartjs/Chart.js', pluginPath + 'alertify/alertify.js', pluginPath + 'easypiecharts/jquery.easypiechart.js', pluginPath + 'metisMenu/metisMenu.js', ],'public/assets/js/core/plugins.js') .js('resources/assets/js/app.js','public/assets/js/') .sass('resources/assets/sass/laraspace.scss', 'public/assets/css/') // .version();
๏ปฟangular.module('main') .controller('MainController', ['$scope', function ($scope) { }]);
describe('BrickSlopes When Page', function() { it('should have an when section', function() { browser.get('http://mybrickslopes.com'); var link = element(by.id('whenLink')).click(); var greeting = element(by.id('splashTextWhen')); expect(greeting.getText()).toContain('Ticket'); }); });
/* # ---------------------------------------------------------------------- # COLLECTION - EDIT: JAVASCRIPT # ---------------------------------------------------------------------- */ var base_url = $('#id-global-url').val(); function openBrowser(){ document.getElementById("id-color-image").click(); } function readURL(input) { if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function (e) { $('#id-image').removeClass("hidden"); $('#id-image').attr('src', e.target.result); } reader.readAsDataURL(input.files[0]); } } function validation(){ var name = $('#id-name').val(); $('#id-row-name').removeClass('has-error'); if(name == ''){ $('#id-row-name').addClass('has-error'); }else{ $('#btn-submit').click(); } } $(document).ready(function(e) { activeNAvbar('products'); $('#btn-alias-submit').click(function(){ validation(); }); });
/*! * Angular Material Design * https://github.com/angular/material * @license MIT * v0.10.1-rc5-master-f5a9101 */ (function( window, angular, undefined ){ "use strict"; (function() { 'use strict'; angular .module('material.components.fabActions', ['material.core']) .directive('mdFabActions', MdFabActionsDirective); /** * @ngdoc directive * @name mdFabActions * @module material.components.fabSpeedDial * * @restrict E * * @description * The `<md-fab-actions>` directive is used inside of a `<md-fab-speed-dial>` or * `<md-fab-toolbar>` directive to mark the an element (or elements) as the actions and setup the * proper event listeners. * * @usage * See the `<md-fab-speed-dial>` or `<md-fab-toolbar>` directives for example usage. */ function MdFabActionsDirective() { return { restrict: 'E', require: ['^?mdFabSpeedDial', '^?mdFabToolbar'], compile: function(element, attributes) { var children = element.children(); // Support both ng-repat and static content if (children.attr('ng-repeat')) { children.addClass('md-fab-action-item'); } else { // Wrap every child in a new div and add a class that we can scale/fling independently children.wrap('<div class="md-fab-action-item">'); } return function postLink(scope, element, attributes, controllers) { // Grab whichever parent controller is used var controller = controllers[0] || controllers[1]; // Make the children open/close their parent directive if (controller) { angular.forEach(element.children(), function(child) { // Attach listeners to the `md-fab-action-item` child = angular.element(child).children()[0]; angular.element(child).on('focus', controller.open); angular.element(child).on('blur', controller.close); }); } } } } } })(); })(window, window.angular);
goog.provide('recoil.ui.widgets.TextWidget'); goog.require('goog.events'); goog.require('goog.events.InputHandler'); goog.require('goog.ui.Component'); goog.require('goog.ui.Textarea'); goog.require('recoil.frp.Util'); goog.require('recoil.ui.Widget'); /** * * @param {!recoil.ui.WidgetScope} scope * @constructor * @implements recoil.ui.Widget */ recoil.ui.widgets.TextWidget = function(scope) { this.component_ = new goog.ui.Textarea(''); }; /** * @return {!goog.ui.Component} */ recoil.ui.widgets.TextWidget.prototype.getComponent = function() { return this.component_; }; /** * all widgets should not allow themselves to be flatterned * * @type {!Object} */ recoil.ui.widgets.TextWidget.prototype.flatten = recoil.frp.struct.NO_FLATTEN;
/* * Copyright (C) 2013 salesforce.com, inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ function lib() { //eslint-disable-line no-unused-vars // -- Utils function getElement(item) { var cmp = $A.util.isString(item) ? $A.getCmp(item) : $A.util.isComponent(item) ? item : null; item = item instanceof HTMLElement ? item : cmp && cmp.getElement(); $A.assert(item, 'Invalid type of element to stack'); return item; } function isPosAndHasZindex(el) { return el.style.zIndex !== 'auto' && !isNaN(parseInt(el.style.zIndex, 10)); } function doesStyleCreateStackingCtx(el) { var styles = el.style; return styles.opacity < 1 || styles.transform !== 'none' || styles.transformStyle === 'preserve-3d' || styles.perspective !== 'none' || styles.position === 'fixed' || (styles.flowFrom !== 'none' && styles.content !== 'normal') || false; } function isStackingCtx(el) { return el.nodeType === 11 || el.tagName === 'HTML' || el._stackContextRoot || (isPosAndHasZindex(el) && doesStyleCreateStackingCtx(el)); } function findElAncestor(el, ancestorEl, stackingCtxEl) { var parentNode = el.parentNode; if (stackingCtxEl === parentNode || parentNode.tagName === 'BODY') { return el; } while (parentNode.parentNode.tagName !== 'BODY') { parentNode = parentNode.parentNode; } return parentNode; } // -- Private internal methods function getStackingCtx(el) { var parentNode = el.parentNode; while (!isStackingCtx(parentNode)) { parentNode = parentNode.parentNode; } return parentNode; } function modifyZindex(el, increment) { var stackingCtxEl = getStackingCtx(el); var siblings; var siblingsMaxMinZindex = increment ? 0 : -1; var elAncestor = el; var siblingZindex; var i = 0; stackingCtxEl = stackingCtxEl.tagName === 'HTML' ? document.getElementsByTagName('body')[0] : stackingCtxEl; siblings = stackingCtxEl.childNodes; if (stackingCtxEl !== el.parentNode) { for (i; i < siblings.length; i++) { elAncestor = findElAncestor(el, siblings[i], stackingCtxEl); } } for (i = 0; i < siblings.length; i++) { if (siblings[i].nodeType === 1 && isPosAndHasZindex(siblings[i]) && siblings[i] !== elAncestor) { siblingZindex = parseInt(siblings[i].style.zIndex, 10); if (isNaN(siblingZindex)) { continue; } if (increment) { siblingsMaxMinZindex = siblingZindex > siblingsMaxMinZindex ? siblingZindex : siblingsMaxMinZindex; } else { siblingsMaxMinZindex = siblingsMaxMinZindex < 0 || siblingZindex < siblingsMaxMinZindex ? siblingZindex : siblingsMaxMinZindex; } } } // adjusted z-index is 0 and sending to back then bump all other elements up by 1 if (!siblingsMaxMinZindex && !increment) { for (i = 0; i < siblings.length; i++) { if (siblings[i].nodeType === 1 && siblings[i] !== el) { siblingZindex = parseInt(siblings[i].style.zIndex, 10); if (isNaN(siblingZindex)) { continue; } siblings[i].style.zIndex = ++siblingZindex; } } } elAncestor.style.zIndex = increment ? siblingsMaxMinZindex + 1 : (siblingsMaxMinZindex > 0 ? siblingsMaxMinZindex - 1 : 0); } function moveUpOrDown(el, forceCreateStackingCtx, increment) { var stackingCtxEl = getStackingCtx(el); if (forceCreateStackingCtx && stackingCtxEl !== el.parentNode) { if ($A.util.isFunction(forceCreateStackingCtx)) { forceCreateStackingCtx(el.parentNode); } else { el.parentNode.style.position = 'relative'; el.parentNode.style.zIndex = 0; } } return modifyZindex(el, increment); } return { bringToFront: function (element, forceCreateStackingCtx) { element = getElement(element); return moveUpOrDown(element, forceCreateStackingCtx, true); }, sendToBack: function (element, forceCreateStackingCtx) { element = getElement(element); return moveUpOrDown(element, forceCreateStackingCtx, false); }, setStackingContextRoot: function (element) { element = getElement(element); element._stackContextRoot = true; } }; }
import { create, _delete, execute, fetch, query } from 'reducers/rest' import DirectoryOperations from 'operations/DirectoryOperations' import { FV_PHRASES_SHARED_FETCH_START, FV_PHRASES_SHARED_FETCH_SUCCESS, FV_PHRASES_SHARED_FETCH_ERROR, FV_PHRASE_FETCH_ALL_START, FV_PHRASE_FETCH_ALL_SUCCESS, FV_PHRASE_FETCH_ALL_ERROR, FV_PHRASES_USER_MODIFIED_QUERY_START, FV_PHRASES_USER_MODIFIED_QUERY_SUCCESS, FV_PHRASES_USER_MODIFIED_QUERY_ERROR, FV_PHRASES_USER_CREATED_QUERY_START, FV_PHRASES_USER_CREATED_QUERY_SUCCESS, FV_PHRASES_USER_CREATED_QUERY_ERROR, } from './actionTypes' export const fetchSharedPhrases = function fetchSharedPhrases(pageProvider, headers = {}, params = {}) { return (dispatch) => { dispatch({ type: FV_PHRASES_SHARED_FETCH_START }) return DirectoryOperations.getDocumentsViaPageProvider(pageProvider, 'FVPhrase', headers, params) .then((response) => { dispatch({ type: FV_PHRASES_SHARED_FETCH_SUCCESS, documents: response }) }) .catch((error) => { dispatch({ type: FV_PHRASES_SHARED_FETCH_ERROR, error: error }) }) } } export const fetchPhrasesAll = function fetchPhrasesAll(path /*, type*/) { return (dispatch) => { dispatch({ type: FV_PHRASE_FETCH_ALL_START }) return DirectoryOperations.getDocuments(path, 'FVPhrase', '', { headers: { 'enrichers.document': 'ancestry,phrase,permissions' }, }) .then((response) => { dispatch({ type: FV_PHRASE_FETCH_ALL_SUCCESS, documents: response }) }) .catch((error) => { dispatch({ type: FV_PHRASE_FETCH_ALL_ERROR, error: error }) }) } } export const fetchPhrase = fetch('FV_PHRASE', 'FVPhrase', { headers: { 'enrichers.document': 'ancestry,phrase,permissions,draft' }, }) export const fetchPhrases = query('FV_PHRASES', 'FVPhrase', { headers: { 'enrichers.document': 'phrase,draft' } }) export const fetchDrafts = query('FV_PHRASES_DRAFTS', 'FVPhrase', { headers: { 'enrichers.document': 'phrase,draft', properties: 'dublincore, fv-phrase, fvcore, fvproxy', }, }) export const createPhrase = create('FV_PHRASE', 'FVPhrase', {}) export const createAndPublishPhrase = create('FV_PHRASE', 'FVPhrase', { headers: { 'fv-publish': true }, }) export const deletePhrase = _delete('FV_PHRASE', 'FVPhrase', {}) export const createDraft = execute('FV_CREATE_DRAFT', 'Document.CreateDraftForRecorder', { headers: { 'enrichers.document': 'ancestry,phrase,permissions,draft' }, }) export const queryModifiedPhrases = query('FV_MODIFIED_PHRASES', 'FVPhrase', { queryAppend: '&sortBy=dc:modified&sortOrder=DESC&pageSize=4', headers: { properties: 'dublincore' }, }) export const queryCreatedPhrases = query('FV_CREATED_PHRASES', 'FVPhrase', { queryAppend: '&sortBy=dc:created&sortOrder=DESC&pageSize=4', headers: { properties: 'dublincore' }, }) export const queryUserModifiedPhrases = function queryUserModifiedPhrases(pathOrId, user) { return (dispatch) => { dispatch({ type: FV_PHRASES_USER_MODIFIED_QUERY_START }) return DirectoryOperations.getDocuments( pathOrId, 'FVPhrase', " AND dc:lastContributor='" + user + "'&sortBy=dc:modified&sortOrder=DESC&pageSize=4", { properties: 'dublincore' } ) .then((response) => { dispatch({ type: FV_PHRASES_USER_MODIFIED_QUERY_SUCCESS, document: response }) }) .catch((error) => { dispatch({ type: FV_PHRASES_USER_MODIFIED_QUERY_ERROR, error: error }) }) } } export const queryUserCreatedPhrases = function queryUserCreatedPhrases(pathOrId, user) { return (dispatch) => { dispatch({ type: FV_PHRASES_USER_CREATED_QUERY_START }) return DirectoryOperations.getDocuments( pathOrId, 'FVPhrase', " AND dc:lastContributor='" + user + "'&sortBy=dc:created&sortOrder=DESC&pageSize=4", { properties: 'dublincore' } ) .then((response) => { dispatch({ type: FV_PHRASES_USER_CREATED_QUERY_SUCCESS, document: response }) }) .catch((error) => { dispatch({ type: FV_PHRASES_USER_CREATED_QUERY_ERROR, error: error }) }) } }
/*! * SAP UI development toolkit for HTML5 (SAPUI5/OpenUI5) * (c) Copyright 2009-2014 SAP AG or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ // Provides an abstraction for model bindings sap.ui.define(['jquery.sap.global', 'sap/ui/base/EventProvider'], function(jQuery, EventProvider) { "use strict"; /** * Constructor for Context class. * * @class * The Context is a pointer to an object in the model data, which is used to * allow definition of relative bindings, which are resolved relative to the * defined object. * Context elements are created either by the ListBinding for each list entry * or by using createBindingContext. * * @param {sap.ui.model.Model} oModel the model * @param {String} sPath the path * @param {Object} oContext the context object * @abstract * @public * @name sap.ui.model.Context */ var Context = sap.ui.base.Object.extend("sap.ui.model.Context", /** @lends sap.ui.model.Context.prototype */ { constructor : function(oModel, sPath){ sap.ui.base.Object.apply(this); this.oModel = oModel; this.sPath = sPath; }, metadata : { "abstract" : true, publicMethods : [ "getModel", "getPath", "getProperty", "getObject" ] } }); /** * Creates a new subclass of class sap.ui.model.Context with name <code>sClassName</code> * and enriches it with the information contained in <code>oClassInfo</code>. * * For a detailed description of <code>oClassInfo</code> or <code>FNMetaImpl</code> * see {@link sap.ui.base.C.extend Object.extend}. * * @param {string} sClassName name of the class to be created * @param {object} [oClassInfo] object literal with informations about the class * @param {function} [FNMetaImpl] alternative constructor for a metadata object * @return {function} the created class / constructor function * @public * @static * @name sap.ui.model.Context.extend * @function */ // Getter /** * Getter for model * @public * @return {sap.ui.core.Model} the model * @name sap.ui.model.Context#getModel * @function */ Context.prototype.getModel = function() { return this.oModel; }; /** * Getter for path * @public * @return {String} the binding path * @name sap.ui.model.Context#getPath * @function */ Context.prototype.getPath = function() { return this.sPath; }; /** * Gets the property with the given relative binding path * @public * @param {String} sPath the binding path * @return {any} the property value * @name sap.ui.model.Context#getProperty * @function */ Context.prototype.getProperty = function(sPath) { return this.oModel.getProperty(sPath, this); }; /** * Gets the (model dependent) object the context points to * @public * @return {object} the context object * @name sap.ui.model.Context#getObject * @function */ Context.prototype.getObject = function() { return this.oModel.getObject(this.sPath); }; /** * toString method returns path for compatbility * @name sap.ui.model.Context#toString * @function */ Context.prototype.toString = function() { return this.sPath; }; return Context; }, /* bExport= */ true);
export const UP_ARROW_KEY = 38 export const DOWN_ARROW_KEY = 40 export const ENTER_KEY = 13 export const RESULT_SIZE = 5
/* deploy-button: defines how the deploy button should act */ define(function () { /* in case we want to change the Semantic UI colour scheme later - http://semantic-ui.com/elements/button.html#colored */ var colourClass = 'teal'; var setButtonAsDeploying = function ($this) { // revert label state $this.mouseout(); // showing the deploying state $this.closest('form').hide().next('.buttons').show(); // add a class to the button to track state $this.closest('tr').addClass('deploying'); }; var init = function () { $('body').on('click', '.deploy .button', function (e) { // prevent the form from submitting e.preventDefault(); var $this = $(this); var $deploy = $this.closest('.deploy'); var $prev = $deploy.prev('.stage'); var $form = $this.closest('form'); setButtonAsDeploying($this, $prev.find('.label').text()); $.ajax({ type: 'POST', url: '/deploy', data: $form.serialize(), success: function (data) { /* we maybe don't want to do anything here? the /deploy POST should push updates to all UIs to say the button was clicked, and a deployment is in progress */ }, error: function (error) { console.log("deploy button hit an arror - ", error); /* it's more likely we'll need to handle errors relating to the deploy e.g. if the version is invalid, or communication error */ } }); }); $('body').on('mouseover', '.deploy .button', function () { var $this = $(this); var $deploy = $this.closest('.deploy'); var $prev = $deploy.prev('.stage'); var $row = $this.closest('tr'); // highlight the version that will be deployed if ($row.hasClass('deploying')) return false; $prev.find('.label').addClass(colourClass); }); $('body').on('mouseout', '.deploy .button', function () { var $this = $(this); var $deploy = $this.closest('.deploy'); var $prev = $deploy.prev('.stage'); // remove the highlight from the to-be-deployed version $prev.find('.label').removeClass(colourClass); }); }; // expose publics return { init: init }; });
import { scheduleOnce, later } from '@ember/runloop'; import { inject as service } from '@ember/service'; import Component from '@ember/component'; import C from 'ui/utils/constants'; import { loadScript } from 'ui/utils/load-script'; import ModalBase from 'shared/mixins/modal-base'; import layout from './template'; export default Component.extend(ModalBase, { layout, classNames: ['span-8', 'offset-2', 'modal-telemetry'], settings: service(), prefs: service(), access: service(), loading: true, init() { this._super(...arguments); let self = this; let opt = JSON.parse(this.get(`settings.${C.SETTING.FEEDBACK_FORM}`)||'{}'); scheduleOnce('afterRender', this, function() { loadScript('//js.hsforms.net/forms/v2.js').then(() => { window['hbspt'].forms.create({ css: '', portalId: opt.portalId, // '468859', formId: opt.formId, // 'bfca2d1d-ed50-4ed7-a582-3f0440f236ca', target: '#feedback-form', errorClass: 'form-control', onFormReady: function() { self.styleForm(); $('INPUT[name=rancher_account_id]')[0].value = self.get('access.principal.id'); $('INPUT[name=github_username]')[0].value = self.get('access.identity.login'); self.set('loading',false); }, onFormSubmit: function() { self.styleForm(); later(() => { self.send('sent'); }, 1000); }, }); }); }); }, styleForm() { var self = this; let form = $('#feedback-form'); form.find('.field').not('.hs_sandbox_acknowledgement').addClass('col-md-6'); form.find('.field.hs_sandbox_acknowledgement').addClass('span-12'); form.find('INPUT[type=text],INPUT[type=email],SELECT').addClass('form-control'); form.find('LABEL').addClass('pt-10'); form.find('INPUT[type=submit]').addClass('hide'); form.find('UL').addClass('list-unstyled'); form.find('INPUT[type=checkbox]').addClass('mr-10'); form.find('.hs-form-booleancheckbox-display').css('font-weight', 'normal'); form.find('SELECT').on('change', function() { self.styleForm(); }); }, actions: { submit() { let form = $('#feedback-form'); form.find('INPUT[type=submit]').click(); }, sent() { this.set(`prefs.${C.PREFS.FEEDBACK}`,'sent'); this.send('cancel'); }, }, });
var http = require('http'), should = require('should'), sysInfo = require('../lib/sysinfo.js'), keyProcessor = require('../lib/keyprocessor.js'), hock = require('hock'); describe('node-env/sdk/environment', function (done) { var context = {}; before(function (done) { done(); }), it("Can list system environment variables", function () { var env = sysInfo.sysInfo(); should.exist(env); env.length.should.be.equal(5); }); it("Key processor leaves values unchanged", function () { var result = keyProcessor.procKey('Name', 'VALUE'); result.should.be.equal('VALUE'); }); it("Key processor replaces \\r with an empty space", function () { var result = keyProcessor.procKey('Name', 'VALUE\r'); result.should.be.equal('VALUE'); }); it("Key processor replaces \\n with a <br/> tag", function () { var result = keyProcessor.procKey('Name', 'VALUE\n'); result.should.be.equal('VALUE<br/>'); }); it("Key processor generates a <span> tag for the path variable", function () { var result = keyProcessor.procKey('path', 'VALUE'); result.should.not.be.equal('VALUE'); }); it("Key processor generates a <span> tag for the path variable", function () { var result = keyProcessor.procKey('vmc_app_instance', '{"app_name" : "VALUE"}'); result.should.not.be.equal('VALUE'); }); });
//Require Module var log4js = require('log4js'); var logger = log4js.getLogger('Logging'); var moment = require('moment-timezone'); var fs = require('fs'); /** * Check time format "hh:mm" * @param{String} time * @return{Boolean} true * */ function checkTimeFormat(time){ //If the time format is wrong, throw error. var checking = time.match(/^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/); if(!checking){ return false; } return true; } /** * Convert time to ms * @param{String} time * @return{Number} totalMs */ function getTimeMs(time){ //Call checkTimeFormat to make sure the format is right. var format = checkTimeFormat(time); if(format == true){ //Split the time and convert it to ms var splitedTime = time.split(':'); var hour = splitedTime[0]; var minute = splitedTime[1]; var hourMs = hour * 60 * 60 * 1000; var minMs = minute * 60 *1000; var totalMs = hourMs + minMs; return totalMs; } return; } /** * Get the date of today with init time (00:00:00) * @param{string} timeZone * @return {Object(Date)} newCurrentDate */ function getInitTime(timeZone){ if(timeZone == '' || timeZone == null){ //Get the date of today, and set the time to 00:00:00 var currentDate = new Date(); currentDate.setHours(0); currentDate.setMinutes(0); currentDate.setSeconds(0); currentDate.setMilliseconds(0); return currentDate; } //If user setted timezone, using moment to convert the date with timezone var currentDate = new Date(); var currentDateTz = new moment.tz(new Date(),timeZone); //Make sure the month and date of converted date is same of currentDate //After that, set it to 00:00:00 currentDateTz.month(currentDate.getMonth()); currentDateTz.date(currentDate.getDate()); currentDateTz.hours(0); currentDateTz.minutes(0); currentDateTz.seconds(0); currentDateTz.milliseconds(0); //Get the ms and convert it to date object. var currentDateMs = currentDateTz.valueOf(); var newCurrentDate = new Date(currentDateMs) return newCurrentDate; } /** * Check the success time is match keepAliveTime and lastAliveTime. * It will return the date which convent from totalKeepAliveTimeMs, * it mean the script can send alive mail. Otherwise if it return null, * it should not send any mail. * * @param {Number[]} keepAliveTimes (Timestamp, in ms) * @param {Number} lastAliveTime (Timestamp, in ms) * @param {Number} lastSuccessTime (Timestamp, in ms) * @param {String} timeZone * @return {Date} Date, null for mismatch */ function checkKeepAliveTime(keepAliveTimes,lastAliveTime,lastSuccessTime,timeZone){ //Get a initDate by calling the getInitTime function var currentDateInited = getInitTime(timeZone).getTime(); //Convert lastSuccessTime,lastAliveTime(If it is not null) and keepAliveTime to ms. for(var i =0; i < keepAliveTimes.length; i++){ var keepAliveTimeMs1 = keepAliveTimes[i]; var keepAliveTimeMs2 = keepAliveTimes[i+1]; //Convert the KeepAliveTime to be a timestamp of current Date. var totalKeepAliveTimeMs1 = keepAliveTimeMs1 + currentDateInited; var totalKeepAliveTimeMs2 = keepAliveTimeMs2 + currentDateInited; //logger.debug('keepAliveTimes: ', new Date(totalKeepAliveTimeMs1)); //logger.debug('lastSuccessTime: ', new Date(lastSuccessTime)); /*If the keepAliveTimeMs2 is NaN, *lastSuccessTimeMs is bigger than totalKeepAliveTimeMs1, *return a date object of totalKeepAliveTime. */ if(isNaN(keepAliveTimeMs2) && lastSuccessTime >= totalKeepAliveTimeMs1){ if(lastAliveTime == null){ return new Date(totalKeepAliveTimeMs1); } /*If the keepAliveTimeMs2 is NaN, *lastSuccessTimeMs is bigger than totalKeepAliveTimeMs1, *but lastAliveTimeMs is bigger than totalKeepAliveTimeMs1, *it will return undefined. */ if(lastAliveTime >= totalKeepAliveTimeMs1){ return null; } return new Date(totalKeepAliveTimeMs1); } /*If the keepAliveTimeMs2 is not NaN, *lastSuccessTimeMs is bigger than totalKeepAliveTimeMs1 *and smaller than totalKeepAliveTimeMs2, *it will return a date object of totalKeepAliveTime. */ if(lastSuccessTime >= totalKeepAliveTimeMs1 && lastSuccessTime < totalKeepAliveTimeMs2){ if(lastAliveTime == null){ return new Date(totalKeepAliveTimeMs1); } /*If the keepAliveTimeMs2 is not NaN, *lastSuccessTimeMs is bigger than totalKeepAliveTimeMs1, *but lastAliveTimeMs is bigger than totalKeepAliveTimeMs1, *it will be skip. */ if(lastAliveTime >= totalKeepAliveTimeMs1){ continue; } return new Date(totalKeepAliveTimeMs1); } } } module.exports = { checkTimeFormat:checkTimeFormat, getTimeMs:getTimeMs, getInitTime:getInitTime, checkKeepAliveTime:checkKeepAliveTime }
๏ปฟType.registerNamespace("_u"); _u.ExtensibilityStrings = function() { }; _u.ExtensibilityStrings.registerClass("_u.ExtensibilityStrings"); _u.ExtensibilityStrings.l_DeleteAttachmentDoesNotExist_Text = "Ek dizini bulunamadฤฑฤŸฤฑ iรงin ek silinemiyor."; _u.ExtensibilityStrings.l_EwsRequestOversized_Text = "ฤฐstek, 1 MB'lฤฑk boyut sฤฑnฤฑrฤฑnฤฑ aลŸฤฑyor. Lรผtfen EWS isteฤŸinizi deฤŸiลŸtirin."; _u.ExtensibilityStrings.l_ElevatedPermissionNeededForMethod_Text = "ลžu yรถntemi รงaฤŸฤฑrmak iรงin yรผkseltilmiลŸ izin gerekir: '{0}'."; _u.ExtensibilityStrings.l_AttachmentErrorName_Text = "Ek Hatasฤฑ"; _u.ExtensibilityStrings.l_InvalidEventDates_Text = "BitiลŸ tarihi baลŸlangฤฑรง tarihinden รถnce girilmiลŸ."; _u.ExtensibilityStrings.l_DisplayNameTooLong_Text = "SaฤŸlanan bir veya daha fazla sayฤฑda gรถrรผnen ad รงok uzun."; _u.ExtensibilityStrings.l_NumberOfRecipientsExceeded_Text = "Alana eklenen toplam alฤฑcฤฑ sayฤฑsฤฑ {0} deฤŸerinden fazla olamaz."; _u.ExtensibilityStrings.l_HtmlSanitizationFailure_Text = "HTML temizlemesi baลŸarฤฑsฤฑz oldu."; _u.ExtensibilityStrings.l_DataWriteErrorName_Text = "Veri Yazma Hatasฤฑ"; _u.ExtensibilityStrings.l_ElevatedPermissionNeeded_Text = "Office iรงin JavaScript API'sinin korumalฤฑ รผyelerine eriลŸmek amacฤฑyla yรผkseltilmiลŸ izinler gerekir:."; _u.ExtensibilityStrings.l_ExceededMaxNumberOfAttachments_Text = "ฤฐletide izin verilen en fazla ek sayฤฑsฤฑna ulaลŸฤฑldฤฑฤŸฤฑ iรงin ek eklenemez"; _u.ExtensibilityStrings.l_InternalProtocolError_Text = "ฤฐรง protokol hatasฤฑ: '{0}'."; _u.ExtensibilityStrings.l_AttachmentDeletedBeforeUploadCompletes_Text = "Kullanฤฑcฤฑ yรผkleme tamamlanmadan รถnce eki kaldฤฑrdฤฑ."; _u.ExtensibilityStrings.l_OffsetNotfound_Text = "Bu zaman damgasฤฑ iรงin bir uzaklฤฑk bulunamadฤฑ."; _u.ExtensibilityStrings.l_AttachmentExceededSize_Text = "Ek รงok bรผyรผk olduฤŸu iรงin eklenemiyor."; _u.ExtensibilityStrings.l_InvalidEndTime_Text = "BitiลŸ saati baลŸlangฤฑรง saatinden รถnce olamaz."; _u.ExtensibilityStrings.l_ParametersNotAsExpected_Text = "Belirtilen parametreler beklenen biรงimle eลŸleลŸmiyor."; _u.ExtensibilityStrings.l_AttachmentUploadGeneralFailure_Text = "ร–ฤŸeye ek eklenemiyor."; _u.ExtensibilityStrings.l_NoValidRecipientsProvided_Text = "Geรงerli alฤฑcฤฑ bilgisi saฤŸlanmadฤฑ."; _u.ExtensibilityStrings.l_InvalidAttachmentId_Text = "Ek kimliฤŸi geรงersiz."; _u.ExtensibilityStrings.l_CannotAddAttachmentBeforeUpgrade_Text = "Sunucudan tam yanฤฑt veya ilet metni alฤฑnฤฑrken ek eklenemez."; _u.ExtensibilityStrings.l_EmailAddressTooLong_Text = "SaฤŸlanan bir veya daha fazla e-posta adresi รงok uzun."; _u.ExtensibilityStrings.l_InvalidAttachmentPath_Text = "Ek yolu geรงersiz."; _u.ExtensibilityStrings.l_AttachmentDeleteGeneralFailure_Text = "Ek รถฤŸeden silinemiyor."; _u.ExtensibilityStrings.l_InternalFormatError_Text = "Dahili biรงim hatasฤฑ oluลŸtu."; _u.ExtensibilityStrings.l_InvalidDate_Text = "GiriลŸ, geรงerli bir tarihe รงรถzรผmlenemiyor."; _u.ExtensibilityStrings.l_CursorPositionChanged_Text = "Kullanฤฑcฤฑ, veriler eklenirken imlecin yerini deฤŸiลŸtirdi."
/* * Copyright 2019 EPAM Systems * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ export { RolesRow } from './rolesRow';
const React = require('react'); const CompLibrary = require('../../core/CompLibrary.js'); const Container = CompLibrary.Container; const CWD = process.cwd(); const releases = require(`${CWD}/releases.json`); class PulsarAdminCli extends React.Component { render() { const latestVersion = releases[0]; const url = "../js/getCliByVersion.js?latestVersion=" + latestVersion; return ( <div className="pageContainer"> <Container className="mainContainer documentContainer postContainer" > <span id="latestVersion" style={{display:'none'}}>{latestVersion}</span> <script src={url}></script> </Container> </div> ); } } module.exports = PulsarAdminCli;
function C() { this.f = 0; } C.prototype = { m1: function () { return this.f+1; } }; function D() { this.f = 0; } D.prototype = new C(); // override m1 method D.prototype.m1 = function() { return this.f-1; };
var followReference = require("./followReference"); var onValueType = require("./onValueType"); var isExpired = require("./util/isExpired"); var iterateKeySet = require("falcor-path-utils").iterateKeySet; var $ref = require("./../types/ref"); module.exports = function walkPath(model, root, curr, path, depthArg, seed, outerResults, requestedPath, optimizedPathArg, isJSONG, fromReferenceArg) { var depth = depthArg; var fromReference = fromReferenceArg; var optimizedPath = optimizedPathArg; // If there is not a value in the current cache position or its a // value type, then we are at the end of the getWalk. if ((!curr || curr && curr.$type) || depth === path.length) { onValueType(model, curr, path, depth, seed, outerResults, requestedPath, optimizedPath, isJSONG, fromReference); return; } var keySet, i; keySet = path[depth]; var isKeySet = typeof keySet === 'object'; var optimizedLength = optimizedPath.length; var previousOptimizedPath = optimizedPath; var nextDepth = depth + 1; var iteratorNote = false; var key = keySet; if (isKeySet) { iteratorNote = {}; key = iterateKeySet(keySet, iteratorNote); } // The key can be undefined if there is an empty path. An example of an // empty path is: [lolomo, [], summary] if (key === undefined && iteratorNote && iteratorNote.done) { return; } // loop over every key over the keySet do { fromReference = false; var next; if (key === null) { next = curr; } else { next = curr[key]; optimizedPath[optimizedLength] = key; requestedPath[depth] = key; } // If there is the next position we need to consider references. if (next) { var nType = next.$type; var value = nType && next.value || next; // If next is a reference follow it. If we are in JSONG mode, // report that value into the seed without passing the requested // path. If a requested path is passed to onValueType then it // will add that path to the JSONGraph envelope under `paths` if (nextDepth < path.length && nType && nType === $ref && !isExpired(next)) { if (isJSONG) { onValueType(model, next, path, nextDepth, seed, outerResults, null, optimizedPath, isJSONG, fromReference); } var ref = followReference(model, root, root, next, value, seed, isJSONG); fromReference = true; next = ref[0]; var refPath = ref[1]; var refLength = refPath.length; optimizedPath = []; for (i = 0; i < refLength; ++i) { optimizedPath[i] = refPath[i]; } } } // Recurse to the next level. walkPath(model, root, next, path, nextDepth, seed, outerResults, requestedPath, optimizedPath, isJSONG, fromReference); // If its a keyset, we MUST copy the optimized path per loop. if (isKeySet) { optimizedPath = []; for (i = 0; i < optimizedLength; ++i) { optimizedPath[i] = previousOptimizedPath[i]; } } // If the iteratorNote is not done, get the next key. if (iteratorNote && !iteratorNote.done) { key = iterateKeySet(keySet, iteratorNote); } } while (iteratorNote && !iteratorNote.done); };
"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; Object.defineProperty(exports, "__esModule", { value: true }); /** * Search Component * path: * /search/ */ var core_1 = require("@angular/core"); var RootSearchComponent = (function () { function RootSearchComponent() { } return RootSearchComponent; }()); RootSearchComponent = __decorate([ core_1.Component({ selector: 'container-app', template: "\n<div class=\"container\">\n<menu-app></menu-app>\n <search-app></search-app>\n</div>\n" }) ], RootSearchComponent); exports.RootSearchComponent = RootSearchComponent; //# sourceMappingURL=root.search.component.js.map
exports.name = 'sort'; exports.help = ''; exports.pipeWorker = function (feedIn, feedOut, field) { field || (field = 0 ); feedIn.on('start', function (meta, streamIn) { if (typeof field === 'string') { field = meta.fields.indexOf(field); } var streamOut = feedOut.start(meta); var lines = []; streamIn.on('line', function (line) { lines.push(line); }); streamIn.on('end', function () { lines.sort( function (a, b) { if ( typeof (b[field]) === 'number' && typeof (a[field]) === 'number' ) { return -(b[field] - a[field]); } return -(''+b[field]).localeCompare(''+a[field]); }).forEach( function (line) { streamOut.write(line); }); streamOut.end(); }); }); }
/* * Copyright 2014-15 Intelix Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ (function() { require.config({ packages: [ 'auth' ] }); require(["auth"]); })();
// @link http://schemas.wbeme.com/json-schema/eme/users/node/user/1-0-0.json# import EmeAccountsAccountRefV1Mixin from '@wbeme/schemas/eme/accounts/mixin/account-ref/AccountRefV1Mixin'; import Fb from '@gdbots/pbj/FieldBuilder'; import Format from '@gdbots/pbj/enums/Format'; import GdbotsCommonTaggableV1Mixin from '@gdbots/schemas/gdbots/common/mixin/taggable/TaggableV1Mixin'; import GdbotsNcrIndexedV1Mixin from '@gdbots/schemas/gdbots/ncr/mixin/indexed/IndexedV1Mixin'; import GdbotsNcrNodeV1Mixin from '@gdbots/schemas/gdbots/ncr/mixin/node/NodeV1Mixin'; import GdbotsNcrNodeV1Trait from '@gdbots/schemas/gdbots/ncr/mixin/node/NodeV1Trait'; import Gender from '@gdbots/schemas/gdbots/common/enums/Gender'; import Message from '@gdbots/pbj/Message'; import MessageResolver from '@gdbots/pbj/MessageResolver'; import Schema from '@gdbots/pbj/Schema'; import T from '@gdbots/pbj/types'; import UserId from '@wbeme/schemas/eme/users/UserId'; export default class UserV1 extends Message { /** * @private * * @returns {Schema} */ static defineSchema() { return new Schema('pbj:eme:users:node:user:1-0-0', UserV1, [ Fb.create('_id', T.IdentifierType.create()) .required() .withDefault(() => UserId.generate()) .classProto(UserId) .build(), Fb.create('first_name', T.StringType.create()) .build(), Fb.create('last_name', T.StringType.create()) .build(), Fb.create('email', T.StringType.create()) .format(Format.EMAIL) .build(), Fb.create('email_domain', T.StringType.create()) .format(Format.HOSTNAME) .build(), Fb.create('address', T.MessageType.create()) .anyOfCuries([ 'gdbots:geo::address', ]) .build(), /* * A general format for international telephone numbers. * @link https://en.wikipedia.org/wiki/E.164 */ Fb.create('phone', T.StringType.create()) .asAMap() .pattern('^\\+?[1-9]\\d{1,14}$') .build(), Fb.create('dob', T.DateType.create()) .build(), Fb.create('gender', T.IntEnumType.create()) .withDefault(Gender.UNKNOWN) .classProto(Gender) .build(), /* * Networks is a map that contains handles/usernames on a social network. * E.g. facebook:homer, twitter:stackoverflow, youtube:coltrane78. */ Fb.create('networks', T.StringType.create()) .asAMap() .maxLength(50) .pattern('^[\\w\\.-]+$') .build(), Fb.create('hashtags', T.StringType.create()) .asASet() .format(Format.HASHTAG) .build(), Fb.create('is_blocked', T.BooleanType.create()) .build(), /* * Indicates that the user is a staff member and has access to the dashboard. */ Fb.create('is_staff', T.BooleanType.create()) .build(), /* * A user's roles determine what permissions they'll have when using the system. */ Fb.create('roles', T.StringType.create()) .asASet() .pattern('^[\\w_]+$') .build(), ], [ EmeAccountsAccountRefV1Mixin.create(), GdbotsNcrNodeV1Mixin.create(), GdbotsNcrIndexedV1Mixin.create(), GdbotsCommonTaggableV1Mixin.create(), ], ); } /** * @returns {Object} */ getUriTemplateVars() { return { user_id: `${this.get('_id', '')}` }; } } GdbotsNcrNodeV1Trait(UserV1); MessageResolver.register('eme:users:node:user', UserV1); Object.freeze(UserV1); Object.freeze(UserV1.prototype);
/* global define: false */ /** * Defines a directive who replaces plain text new lines with `<br />` HTML tags. * * Usage: * * Assuming the content of `scopeVarName` would be something like * * ``` * First line of text yada. * Second line of the text and bamm. * ``` * * and * * ``` * <div nl2br="scopeVarName"></div> * ``` * * will produce something like * * ``` * <div nl2br="scopeVarName">First line of text yada.<br/>Second line of the text and bamm.</div> * ``` */ // RequireJS dependencies define([ ], function( ) { 'use strict'; // AngularJS DI return [ function( ) { return { scope: { original: '=nl2br' }, link: function(scope, element, attributes) { element.html((scope.original || '').replace(/\n/g, '<br/>')); } }; }]; });
var React = require('react/addons'); var _ = require('lodash'); var AppConstants = require('../constants/AppConstants'); var MenuItems = AppConstants.MenuItems; var Header = React.createClass({ getInitialState: function() { return { currentMenuItemId: _.find(MenuItems, {default: true}).id }; }, onSelectItem: function() { }, renderMenuItem: function(key) { var item = MenuItems[key]; var className = ''; if(this.state.currentMenuItemId === item.id) { className = 'active'; } return ( <li className={className} key={item.id}> <a href="#" onClick={this.onSelectItem} dataItemId={item.id}>{item.text}</a> </li> ); }, render: function() { var headerStyle = { padding: '10px 5px' }; return ( <header style={headerStyle}> <ul className="nav nav-tabs"> {Object.keys(MenuItems).map(this.renderMenuItem)} </ul> </header> ); } }); module.exports = Header;
/** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var pkgNames = require( '@stdlib/_tools/pkgs/names' ); var isFunction = require( '@stdlib/assert/is-function' ); var copy = require( '@stdlib/utils/copy' ); var validate = require( './validate.js' ); var filter = require( './filter.js' ); var defaults = require( './defaults.json' ); // MAIN // /** * Asynchronously lists stdlib namespaces. * * @param {Options} [options] - function options * @param {string} [options.dir] - directory from which to search for namespaces * @param {string} [options.pattern='**\/package.json'] - glob pattern * @param {StringArray} [options.ignore] - glob pattern(s) to exclude matches * @param {Callback} clbk - callback to invoke after finding namespaces * @throws {TypeError} callback argument must be a function * @throws {TypeError} options argument must be an object * @throws {TypeError} must provide valid options * @throws {Error} `pattern` option must end with `package.json` * * @example * ls( onList ); * * function onList( error, names ) { * if ( error ) { * throw error; * } * console.dir( names ); * } */ function ls() { var options; var clbk; var opts; var err; opts = copy( defaults ); if ( arguments.length < 2 ) { clbk = arguments[ 0 ]; } else { options = arguments[ 0 ]; clbk = arguments[ 1 ]; err = validate( opts, options ); if ( err ) { throw err; } } if ( !isFunction( clbk ) ) { throw new TypeError( 'invalid argument. Callback argument must be a function. Value: `' + clbk + '`.' ); } pkgNames( opts, onPkgs ); /** * Callback invoked after finding packages. * * @private * @param {(Error|null)} error - error object * @param {StringArray} names - list of package names * @returns {void} */ function onPkgs( error, names ) { if ( error ) { return clbk( error ); } clbk( null, filter( names ) ); } } // EXPORTS // module.exports = ls;
/** * Adapted from angular2-webpack-starter */ const helpers = require('./helpers'), webpack = require('webpack'), CleanWebpackPlugin = require('clean-webpack-plugin'); // const stringify = require('json-stringify'); /** * Webpack Plugins */ // const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin; // const CommonsChunkPlugin = webpack.optimize.CommonsChunkPlugin; const ContextReplacementPlugin = require('webpack/lib/ContextReplacementPlugin'); // const CopyWebpackPlugin = require('copy-webpack-plugin'); const DefinePlugin = require('webpack/lib/DefinePlugin'); const ExtractTextPlugin = require('extract-text-webpack-plugin'); const HtmlWebpackPlugin = require('html-webpack-plugin'); // const HtmlElementsPlugin = require('./html-elements-plugin'); const IgnorePlugin = require('webpack/lib/IgnorePlugin'); const LoaderOptionsPlugin = require('webpack/lib/LoaderOptionsPlugin'); // const ngcWebpack = require('ngc-webpack'); const NormalModuleReplacementPlugin = require('webpack/lib/NormalModuleReplacementPlugin'); const OptimizeJsPlugin = require('optimize-js-plugin'); const ProvidePlugin = require('webpack/lib/ProvidePlugin'); const UglifyJsPlugin = require('webpack/lib/optimize/UglifyJsPlugin'); module.exports = { devtool: 'inline-source-map', resolve: { extensions: ['.ts', '.js', '.json'] }, entry: helpers.root('index.ts'), // require those dependencies but don't bundle them externals: [/^@angular\//, /^rxjs\//], module: { rules: [ // { // enforce: 'pre', // test: /\.ts$/, // use: 'tslint-loader', // exclude: [helpers.root('node_modules')] // }, { test: /\.ts$/, use: [ { loader: 'awesome-typescript-loader', options: { declaration: false } }, { loader: 'angular2-template-loader' } ], exclude: [/\.spec\.ts$/] }, // copy those assets to output { test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)(\?v=[0-9]\.[0-9]\.[0-9])?$/, use: ['file-loader?name=fonts/[name].[hash].[ext]?'] }, // Support for *.json files. { test: /\.json$/, use: ['json-loader'] }, { test: /\.css$/, use: ['to-string-loader', 'css-loader'] }, { test: /\.scss$/, use: ["css-to-string-loader", "css-loader", "sass-loader"] }, // todo: change the loader to something that adds a hash to images { test: /\.html$/, use: ['raw-loader'] } ] }, plugins: [ /** * Plugin: ContextReplacementPlugin * Description: Provides context to Angular's use of System.import * * See: https://webpack.github.io/docs/list-of-plugins.html#contextreplacementplugin * See: https://github.com/angular/angular/issues/11580 */ new webpack.ContextReplacementPlugin( // The (\\|\/) piece accounts for path separators in *nix and Windows /angular(\\|\/)core(\\|\/)(esm(\\|\/)src|src)(\\|\/)linker/, helpers.root('./src') ), /** * Webpack plugin to optimize a JavaScript file for faster initial load * by wrapping eagerly-invoked functions. * * See: https://github.com/vigneshshanmugam/optimize-js-plugin */ new OptimizeJsPlugin({ sourceMap: false }), new HtmlWebpackPlugin(), /** * Plugin: ExtractTextPlugin * Description: Extracts imported CSS files into external stylesheet * * See: https://github.com/webpack/extract-text-webpack-plugin */ // new ExtractTextPlugin('[name].[contenthash].css'), new ExtractTextPlugin('[name].css'), new webpack.LoaderOptionsPlugin({ options: { tslintLoader: { emitErrors: false, failOnHint: false }, /** * Sass * Reference: https://github.com/jtangelder/sass-loader * Transforms .scss files to .css */ sassLoader: { //includePaths: [path.resolve(__dirname, "node_modules/foundation-sites/scss")] } } }), // Reference: http://webpack.github.io/docs/list-of-plugins.html#noerrorsplugin // Only emit files when there are no errors new webpack.NoEmitOnErrorsPlugin(), // // Reference: http://webpack.github.io/docs/list-of-plugins.html#dedupeplugin // // Dedupe modules in the output // new webpack.optimize.DedupePlugin(), // Reference: http://webpack.github.io/docs/list-of-plugins.html#uglifyjsplugin // Minify all javascript, switch loaders to minimizing mode // new webpack.optimize.UglifyJsPlugin({sourceMap: true, mangle: { keep_fnames: true }}), // Copy assets from the public folder // Reference: https://github.com/kevlened/copy-webpack-plugin // new CopyWebpackPlugin([{ // from: helpers.root('src/public') // }]), // Reference: https://github.com/johnagan/clean-webpack-plugin // Removes the bundle folder before the build new CleanWebpackPlugin(['bundles'], { root: helpers.root(), verbose: false, dry: false }) ] };
(function (Mettle) { "use strict"; ICEX.controller.Breadcrumb = Mettle.Controller.extend({ autoShowHide: true, inject: { templates: { breadcrumbItem: "tmpl!BreadcrumbItem" }, views: ["breadcrumb"] }, update: function (items) { var that = this; that.views.breadcrumb.remove(); var tmplBreadcrumbItem = this.templates.breadcrumbItem; tmplBreadcrumbItem.load(function() { for (var n = 0; n < items.length; n++) { var item = items[n]; item.pathId = item.id; that.views.breadcrumb.render(tmplBreadcrumbItem.process(item)); } }); }, hideTopic: function () { this.views.breadcrumb.hideTopic(); }, showTopic: function (topicInfo) { this.views.breadcrumb.showTopic(topicInfo); } }); }(Mettle));
/** * Created by cdimitzas on 21/3/2016. */ $(document).ready(function() { // make right selection in mainPanel $("#reports").removeClass("hide").addClass("purple-background"); });
define(function (require, exports, module) { "use strict"; exports.snippetText = require("../requirejs/text!./jsx.snippets"); exports.scope = "jsx"; });
/*! * Ext JS Library 3.3.1 * Copyright(c) 2006-2010 Sencha Inc. * [email protected] * http://www.sencha.com/license */ /** * @class Ext.menu.ColorMenu * @extends Ext.menu.Menu * <p>A menu containing a {@link Ext.ColorPalette} Component.</p> * <p>Notes:</p><div class="mdetail-params"><ul> * <li>Although not listed here, the <b>constructor</b> for this class * accepts all of the configuration options of <b>{@link Ext.ColorPalette}</b>.</li> * <li>If subclassing ColorMenu, any configuration options for the ColorPalette must be * applied to the <tt><b>initialConfig</b></tt> property of the ColorMenu. * Applying {@link Ext.ColorPalette ColorPalette} configuration settings to * <b><tt>this</tt></b> will <b>not</b> affect the ColorPalette's configuration.</li> * </ul></div> * * @xtype colormenu */ Ext.menu.ColorMenu = Ext.extend(Ext.menu.Menu, { /** * @cfg {Boolean} enableScrolling * @hide */ enableScrolling : false, /** * @cfg {Function} handler * Optional. A function that will handle the select event of this menu. * The handler is passed the following parameters:<div class="mdetail-params"><ul> * <li><code>palette</code> : ColorPalette<div class="sub-desc">The {@link #palette Ext.ColorPalette}.</div></li> * <li><code>color</code> : String<div class="sub-desc">The 6-digit color hex code (without the # symbol).</div></li> * </ul></div> */ /** * @cfg {Object} scope * The scope (<tt><b>this</b></tt> reference) in which the <code>{@link #handler}</code> * function will be called. Defaults to this ColorMenu instance. */ /** * @cfg {Boolean} hideOnClick * False to continue showing the menu after a color is selected, defaults to true. */ hideOnClick : true, cls : 'x-color-menu', /** * @cfg {String} paletteId * An id to assign to the underlying color palette. Defaults to <tt>null</tt>. */ paletteId : null, /** * @cfg {Number} maxHeight * @hide */ /** * @cfg {Number} scrollIncrement * @hide */ /** * @property palette * @type ColorPalette * The {@link Ext.ColorPalette} instance for this ColorMenu */ /** * @event click * @hide */ /** * @event itemclick * @hide */ initComponent : function(){ Ext.apply(this, { plain: true, showSeparator: false, items: this.palette = new Ext.ColorPalette(Ext.applyIf({ id: this.paletteId }, this.initialConfig)) }); this.palette.purgeListeners(); Ext.menu.ColorMenu.superclass.initComponent.call(this); /** * @event select * Fires when a color is selected from the {@link #palette Ext.ColorPalette} * @param {Ext.ColorPalette} palette The {@link #palette Ext.ColorPalette} * @param {String} color The 6-digit color hex code (without the # symbol) */ this.relayEvents(this.palette, ['select']); this.on('select', this.menuHide, this); if(this.handler){ this.on('select', this.handler, this.scope || this); } }, menuHide : function(){ if(this.hideOnClick){ this.hide(true); } } }); Ext.reg('colormenu', Ext.menu.ColorMenu);
/* * Ext JS Library 2.0.2 * Copyright(c) 2006-2008, Ext JS, LLC. * [email protected] * * http://extjs.com/license */ /** * @class Ext.layout.CardLayout * @extends Ext.layout.FitLayout * <p>This layout contains multiple panels, each fit to the container, where only a single panel can be * visible at any given time. This layout style is most commonly used for wizards, tab implementations, etc. * This class is intended to be extended or created via the layout:'card' {@link Ext.Container#layout} config, * and should generally not need to be created directly via the new keyword.</p> * <p>The CardLayout's focal method is {@link #setActiveItem}. Since only one panel is displayed at a time, * the only way to move from one panel to the next is by calling setActiveItem, passing the id or index of * the next panel to display. The layout itself does not provide a mechanism for handling this navigation, * so that functionality must be provided by the developer.</p> * <p>In the following example, a simplistic wizard setup is demonstrated. A button bar is added * to the footer of the containing panel to provide navigation buttons. The buttons will be handled by a * common navigation routine -- for this example, the implementation of that routine has been ommitted since * it can be any type of custom logic. Note that other uses of a CardLayout (like a tab control) would require a * completely different implementation. For serious implementations, a better approach would be to extend * CardLayout to provide the custom functionality needed. Example usage:</p> * <pre><code> var navHandler = function(direction){ // This routine could contain business logic required to manage the navigation steps. // It would call setActiveItem as needed, manage navigation button state, handle any // branching logic that might be required, handle alternate actions like cancellation // or finalization, etc. A complete wizard implementation could get pretty // sophisticated depending on the complexity required, and should probably be // done as a subclass of CardLayout in a real-world implementation. }; var card = new Ext.Panel({ title: 'Example Wizard', layout:'card', activeItem: 0, // make sure the active item is set on the container config! bodyStyle: 'padding:15px', defaults: { // applied to each contained panel border:false }, // just an example of one possible navigation scheme, using buttons bbar: [ { id: 'move-prev', text: 'Back', handler: navHandler.createDelegate(this, [-1]), disabled: true }, '->', // greedy spacer so that the buttons are aligned to each side { id: 'move-next', text: 'Next', handler: navHandler.createDelegate(this, [1]) } ], // the panels (or "cards") within the layout items: [{ id: 'card-0', html: '&lt;h1&gt;Welcome to the Wizard!&lt;/h1&gt;&lt;p&gt;Step 1 of 3&lt;/p&gt;' },{ id: 'card-1', html: '&lt;p&gt;Step 2 of 3&lt;/p&gt;' },{ id: 'card-2', html: '&lt;h1&gt;Congratulations!&lt;/h1&gt;&lt;p&gt;Step 3 of 3 - Complete&lt;/p&gt;' }] }); </code></pre> */ Ext.layout.CardLayout = Ext.extend(Ext.layout.FitLayout, { /** * @cfg {Boolean} deferredRender * True to render each contained item at the time it becomes active, false to render all contained items * as soon as the layout is rendered (defaults to false). If there is a significant amount of content or * a lot of heavy controls being rendered into panels that are not displayed by default, setting this to * true might improve performance. */ deferredRender : false, // private renderHidden : true, /** * Sets the active (visible) item in the layout. * @param {String/Number} item The string component id or numeric index of the item to activate */ setActiveItem : function(item){ item = this.container.getComponent(item); if(this.activeItem != item){ if(this.activeItem){ this.activeItem.hide(); } this.activeItem = item; item.show(); this.layout(); } }, // private renderAll : function(ct, target){ if(this.deferredRender){ this.renderItem(this.activeItem, undefined, target); }else{ Ext.layout.CardLayout.superclass.renderAll.call(this, ct, target); } } }); Ext.Container.LAYOUTS['card'] = Ext.layout.CardLayout;
'use strict'; /** * @ngdoc function * @name personalSiteApp.controller:NavCtrl * @description * # NavCtrl * Controller of the personalSiteApp */ angular.module('personalSiteApp') .controller('NavCtrl', function ($scope, $location) { $scope.awesomeThings = [ 'HTML5 Boilerplate', 'AngularJS', 'Karma' ]; //Initialize if we are mobile or dektop //and if our navbar is collapsed $scope.collapseNav = true; $scope.isMobile = function() { //Check to see if the css rule for the collapsible applies var mq = window.matchMedia('(max-width: 767px)'); return mq.matches; } $scope.isActive = function(route) { return route === $location.path(); } });
/* * Kendo UI v2014.3.1119 (http://www.telerik.com/kendo-ui) * Copyright 2014 Telerik AD. All rights reserved. * * Kendo UI commercial licenses may be obtained at * http://www.telerik.com/purchase/license-agreement/kendo-ui-complete * If you do not own a commercial license, this file shall be governed by the trial license terms. */ (function(f, define){ define([], f); })(function(){ (function( window, undefined ) { var kendo = window.kendo || (window.kendo = { cultures: {} }); kendo.cultures["it-IT"] = { name: "it-IT", numberFormat: { pattern: ["-n"], decimals: 2, ",": ".", ".": ",", groupSize: [3], percent: { pattern: ["-n%","n%"], decimals: 2, ",": ".", ".": ",", groupSize: [3], symbol: "%" }, currency: { pattern: ["-$ n","$ n"], decimals: 2, ",": ".", ".": ",", groupSize: [3], symbol: "โ‚ฌ" } }, calendars: { standard: { days: { names: ["domenica","lunedรฌ","martedรฌ","mercoledรฌ","giovedรฌ","venerdรฌ","sabato"], namesAbbr: ["dom","lun","mar","mer","gio","ven","sab"], namesShort: ["do","lu","ma","me","gi","ve","sa"] }, months: { names: ["gennaio","febbraio","marzo","aprile","maggio","giugno","luglio","agosto","settembre","ottobre","novembre","dicembre",""], namesAbbr: ["gen","feb","mar","apr","mag","giu","lug","ago","set","ott","nov","dic",""] }, AM: [""], PM: [""], patterns: { d: "dd/MM/yyyy", D: "dddd d MMMM yyyy", F: "dddd d MMMM yyyy HH:mm:ss", g: "dd/MM/yyyy HH:mm", G: "dd/MM/yyyy HH:mm:ss", m: "dd MMMM", M: "dd MMMM", s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss", t: "HH:mm", T: "HH:mm:ss", u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'", y: "MMMM yyyy", Y: "MMMM yyyy" }, "/": "/", ":": ":", firstDay: 1 } } } })(this); return window.kendo; }, typeof define == 'function' && define.amd ? define : function(_, f){ f(); });
define(['modules/PubSub'],function(PubSub){ 'use strict'; function BaseScoreKeeper(){ this.mediator = PubSub; } return BaseScoreKeeper; });
/*! * ${copyright} */ sap.ui.define([ 'sap/ui/test/_OpaLogger', 'sap/ui/base/Object', 'sap/ui/thirdparty/jquery' ], function (_OpaLogger, Ui5Object, $) { "use strict"; var oLogger = _OpaLogger.getLogger("sap.ui.test.SampleOpaExtension"); var Extension = Ui5Object.extend("sap.ui.test.SampleOpaExtension", { metadata: { publicMethods: [ "onAfterInit", "onBeforeExit", "getAssertions" ] }, onAfterInit: function () { oLogger.info("Default onAfterInit called"); Extension.onAfterInitCalls += 1; var deferred = $.Deferred(); setTimeout(function () { deferred.resolve(); }, 100); return deferred.promise(); }, onBeforeExit: function () { oLogger.info("Default onBeforeExit called"); Extension.onBeforeExitCalls += 1; var deferred = $.Deferred(); setTimeout(function () { deferred.resolve(); }, 100); return deferred.promise(); }, getAssertions: function () { return { myCustomAssertion: function () { var deferred = $.Deferred(); // start custom assertion logic, resolve the promise when ready setTimeout(function () { Extension.assertionCalls += 1; // Assertion passes deferred.resolve({ result: true, message: "Custom assertion passes" }); }, 100); return deferred.promise(); } }; } }); Extension.onAfterInitCalls = 0; Extension.onBeforeExitCalls = 0; Extension.assertionCalls = 0; return Extension; });
/** Node.js based unit tests for the status service should go here; at the moment we don't have any as it doesn't expose anything to test. */ module.exports = (function (Ozone) { describe("ozone-services-status", function () { }); });
/** * * @author Longtian <[email protected]> 2014-7-9 */ module.exports = { /** * @todo test on linux platform * @returns {string} */ getPrivateKeyContent: function() { var readFileSync = require("fs").readFileSync; if (process.platform === 'win32') { return readFileSync(process.env.USERPROFILE + "\\.ssh\\id_rsa"); } else { return readFileSync(process.env.home + "/.ssh/id_rsa"); } } };
/* @flow */ import React from 'react'; import { StyleSheet, View } from 'react-native'; import { IconStar } from '../common/Icons'; const styles = StyleSheet.create({ iconWrapper: { marginTop: 4, flex: 0.1 }, iconStar: { fontSize: 20, color: '#447C22', alignSelf: 'flex-end' } }); export default () => ( <View style={styles.iconWrapper}> <IconStar style={styles.iconStar} /> </View> );
module("RankSymbolLayer-ctl"); var name = "RankSymbol Layer"; test("TestRankSymbol_constructor",function(){ expect(4); var themeLayer = new SuperMap.Layer.RankSymbol(name,"Circle"); ok(themeLayer instanceof SuperMap.Layer.RankSymbol,"layer instanceof SuperMap.Layer.RankSymbol"); equals(themeLayer.name,name,"the name of test"); equals(themeLayer.CLASS_NAME,"SuperMap.Layer.RankSymbol","CLASS_NAME"); equals(themeLayer.symbolType,"Circle","symbolType"); themeLayer.destroy(); }); test("TestRankSymbol_destroy",function(){ expect(3); var themeLayer = new SuperMap.Layer.RankSymbol(name,"Circle"); themeLayer.themeField = "xyz"; themeLayer.symbolSetting ={ codomain: [0,1]}; themeLayer.destroy(); equals(themeLayer.symbolSetting,null,"after destroy"); equals(themeLayer.themeField,null,"after destroy"); equals(themeLayer.symbolType,null,"after destroy"); }); test("TestRankSymbol_setSymbolType",function(){ expect(3); var themeLayer = new SuperMap.Layer.RankSymbol(name,"Circle"); equals(themeLayer.symbolType,"Circle","Test symbolType"); themeLayer.symbolType = "test"; equals(themeLayer.symbolType,"test","Test symbolType"); themeLayer.setSymbolType("Circle"); equals(themeLayer.symbolType,"Circle","Test symbolType"); themeLayer.destroy(); }); test("TestRankSymbol_createThematicFeature",function(){ expect(2); var themeLayer = new SuperMap.Layer.RankSymbol(name,"Circle"); themeLayer.themeField = "xyz"; var point = new SuperMap.Geometry.Point(114,45); var attrs = {};attrs.xyz = 11; var pointFeature = new SuperMap.Feature.Vector(point,attrs); var result = themeLayer.createThematicFeature(pointFeature); //ๆƒ…ๅ†ตไธ€ return thematicFeature equals(result.CLASS_NAME,"SuperMap.Feature.Theme.Circle","test createThematicFeature"); //ๆƒ…ๅ†ตไบŒ return false themeLayer.setSymbolType("Test"); var result = themeLayer.createThematicFeature(pointFeature); ok(!result,"return false"); themeLayer.destroy(); });
/* * Copyright (c) WSO2 Inc. (http://wso2.com) All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Handles notifications and subscriptions for store * @nameSpace NotificationManager */ var notificationManager = {}; (function () { var log = new Log('notificationManager'); //noinspection JSUnresolvedVariable var StoreNotificationService = Packages.org.wso2.carbon.store.notifications.service.StoreNotificationService; var storeNotifier = new StoreNotificationService(); /** * Notify triggered event * @param eventName event that is triggered * @param assetType type of the asset event triggered on * @param assetName name of the asset event triggered on * @param message message to be sent in the notification * @param path path of the resource the event occured * @param user logged in user */ notificationManager.notifyEvent = function (eventName, assetType, assetName, message, path, user) { var isSuccessful; var emailContent = generateEmail(assetType, assetName, message, eventName); try { storeNotifier.notifyEvent(eventName, emailContent, path, user); isSuccessful = true; } catch (e) { log.error('Notifying the event ' + eventName + 'failed for ' + eventName); isSuccessful = false; } return isSuccessful; }; /** * Subscribe for an event * @param tenantId logged in user * @param resourcePath path of the resource subscribing to * @param endpoint method of notification (user, role or email) * @param eventName event subscribing for */ notificationManager.subscribeToEvent = function (tenantId, resourcePath, endpoint, eventName) { var isSuccessful; try { storeNotifier.subscribeToEvent(tenantId, resourcePath, endpoint, eventName); isSuccessful = true; } catch (e) { log.error('Subscribing to asset on ' + resourcePath + ' failed for ' + eventName); isSuccessful = false; } return isSuccessful; }; /** * Remove subscription * @param resourcePath path of the resource subscribed to * @param eventName event subscribed for * @param endpoint method of notification */ notificationManager.unsubscribe = function (resourcePath, eventName, endpoint) { storeNotifier.unsubscribe(resourcePath, eventName, endpoint); }; /** * Get all the event types * @returns event types */ notificationManager.getEventTypes = function () { return storeNotifier.getEventTypes(); }; /** * Get all subscriptions * @returns list of subscriptions */ notificationManager.getAllSubscriptions = function () { try { return storeNotifier.getAllSubscriptions(); } catch (e) { log.error("Retrieving subscription list failed"); return null; } }; /** * Generates an email message containing details of an event * @param assetType type of the asset event triggered on * @param assetName name of the asset event triggered on * @param msg message to send in the email * @param eventName name of the triggered event * @return content of the email */ var generateEmail = function (assetType, assetName, msg, eventName) { var stringAssetName = stringify(assetName); var stringAssetType = stringify(assetType); var stringMsg = stringify(msg); var email_temp; if (eventName == storeConstants.LC_STATE_CHANGE_EVENT) { email_temp = storeConstants.EMAIL_TEMPLATE_LC; } else if (eventName == storeConstants.ASSET_UPDATE_EVENT) { email_temp = storeConstants.EMAIL_TEMPLATE_UPDATE; } else if (eventName == storeConstants.VERSION_CREATED_EVENT) { email_temp = storeConstants.EMAIL_TEMPLATE_VERSION; } else { email_temp = storeConstants.EMAIL_TEMPLATE_DEFAULT; } message = new JaggeryParser().parse(email_temp).toString(); //evaluating the template in Jaggery //TODO improve template evaluation to support custom templates var templateScript = '(function() { var result = ""; var assetName=' + stringAssetName + '; var msg =' + stringMsg + '; var assetType =' + stringAssetType + '; print = function(text) { if(typeof text === "object") {result += stringify(text);} else {result += text;} };' + message + ' return result;}())'; return eval(templateScript); } }());
/** * @license * Copyright 2016 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // NOTE: Only to be invoked from caniuse_idl_urls_import.sh. const request = require('hyperquest'); function loadURL(url) { return new Promise((resolve, reject) => { console.log('Loading', url); request( {uri: url}, (err, res) => { if (err) { console.error('Error loading', url, err); reject(err); return; } let data; res.on('data', chunk => data = data ? data + chunk : chunk); res.on('end', () => { console.log('Loaded', url); resolve(data); }); res.on('error', err => { console.error('Error loading', url, err); reject(err); }); } ); }); } loadURL( 'https://raw.githubusercontent.com/Fyrd/caniuse/master/fulldata-json/' + 'data-2.0.json' ).then(data => { const features = JSON.parse(data).data; const keys = Object.getOwnPropertyNames(features); const urls = keys.map( key => features[key].spec.split('#')[0].split('?')[0] ).filter(url => url); return require('../lib/idl/idl_urls_import.es6.js').importHTTP( urls, require('process').env.WEB_APIS_DIR + '/data/idl/caniuse/linked/all.json' ); });
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import * as serviceWorker from './serviceWorker'; ReactDOM.render( <React.StrictMode> <App /> </React.StrictMode>, document.getElementById('root') ); // If you want your app to work offline and load faster, you can change // unregister() to register() below. Note this comes with some pitfalls. // Learn more about service workers: https://bit.ly/CRA-PWA serviceWorker.unregister();
'use strict'; (function (angular) { angular.module('trng.config', ['dialogs']); })(angular);
import { MessageBox, Loading } from 'element-ui'; import store from '@/store'; import axios from '@/service'; import { INIT, CLEAR_TOKEN, SET_TOKEN } from '@/store/types'; import { HOME_PATH, LOGIN_URL, LOGOUT_URL, LOGOUT_URL_API, AUTH_PATH, AUTH_URL, CLIENT_ID } from '@/config'; import { isObject, parseJWT } from '@/util'; import LoadingBar from '@/components/LoadingBar'; import router from './instance'; import updateBreadcrumb from './breadcrumb'; import updateDocumentTitle from './documentTitle'; /** * ๆฃ€ๆŸฅๅฝ“ๅ‰่ทฏ็”ฑๆ˜ฏๅฆ้œ€่ฆๆŽˆๆƒ่ฎฟ้—ฎ */ const checkRequireAuth = to => to.matched.some(record => record.meta.requireAuth !== false); /** * ๆ˜พ็คบ้š่—ๅ…จๅฑ€ๅŠ ่ฝฝๆ็คบ */ const loading = (() => { let loadingInstance = null; return { show(text) { loadingInstance = Loading.service({ lock: true, text, }); }, close() { loadingInstance.close(); }, }; })(); /** * ๆ˜พ็คบ้”™่ฏฏๆ็คบๅฏน่ฏๆก† */ const showError = (text) => { MessageBox.confirm(text || '็™ปๅฝ•ๅคฑ่ดฅ!', { type: 'error', showClose: false, closeOnClickModal: false, closeOnPressEscape: false, confirmButtonText: '้‡ๆ–ฐ็™ปๅฝ•', cancelButtonText: '้‡่ฏ•', }).then(() => { router.logout(); }).catch(() => { window.location.reload(); }); }; /** * ๅ‡ญcode่Žทๅ–accesstoken */ const fetchAccessToken = async (code) => { try { const { data } = await axios.get(AUTH_URL, { params: { code }, }); const { token } = data.data; const userinfo = parseJWT(token); if (userinfo) { store.commit(SET_TOKEN, { token, userinfo, }); return Promise.resolve(true); } throw new Error(); } catch (e) { return Promise.resolve(false); } }; /** * ้‡ๅฎšๅ‘ๅŽป็™ปๅฝ• */ router.login = (state, next) => { store.commit(CLEAR_TOKEN); const queryData = { client_id: CLIENT_ID, response_type: 'code', state: encodeURIComponent(state), redirect_uri: encodeURIComponent(`${window.location.origin}${window.location.pathname}#${AUTH_PATH}`), }; const query = Object.keys(queryData).map(k => `${k}=${queryData[k]}`).join('&'); const loginUrl = `${LOGIN_URL}${LOGIN_URL.indexOf('?') < 0 ? '?' : '&'}${query}`; if (/^http/.test(loginUrl)) window.location = loginUrl; else if (next) next(loginUrl); else router.push(loginUrl); }; /** * ้€€ๅ‡บ็™ปๅฝ• * ๆธ…้™ค็”จๆˆทๅ‡ญ่ฏๅนถ้‡ๅฎšๅ‘ๅŽป็ปŸไธ€็”จๆˆทๅนณๅฐ้€€ๅ‡บ */ router.logout = () => { const href = window.location.href.replace(window.location.hash, ''); const logoutUri = `${LOGOUT_URL}?${encodeURIComponent(href)}`; if (!store.state.token) { if (/^http/.test(logoutUri)) window.location = logoutUri; else router.push(logoutUri); } store.commit(CLEAR_TOKEN); loading.show('ๆญฃๅœจ้€€ๅ‡บ...'); axios.put(LOGOUT_URL_API).finally(() => { if (/^http/.test(logoutUri)) window.location = logoutUri; else router.push(logoutUri); }); }; /** * ่ทฏ็”ฑไธดๆ—ถๆ•ฐๆฎ */ const { push } = router; const tempData = { breadcrumb: null, documentTitle: null, }; router.push = (location, onComplete, onAbort) => { if (isObject(location)) { Object.keys(location).forEach((key) => { tempData[key] = location[key] || null; }); } push.call(router, location, onComplete, onAbort); }; /** * ่ทฏ็”ฑๅ‰็ฝฎๅฎˆๅซ */ router.beforeEach(async (to, from, next) => { /** * ๆฃ€้ชŒๆ˜ฏๅฆ็™ปๅฝ•ๅ›ž่ฐƒไธญ */ if (to.path === AUTH_PATH) { if (!to.query.code) { next(to.query.state || HOME_PATH); return; } loading.show('็™ปๅฝ•ไธญ'); const done = await fetchAccessToken(to.query.code); if (done) { // router.replace(to.query.state || HOME_PATH); next(to.query.state || HOME_PATH); } else { loading.close(); showError('็™ปๅฝ•ๅคฑ่ดฅ!'); } return; } LoadingBar.start(); if (checkRequireAuth(to)) { if (!store.state.token) { router.login(to.fullPath, next); return; } if (!store.state.inited) { loading.show('ๅŠ ่ฝฝไธญ'); try { await store.dispatch(INIT); loading.close(); } catch (e) { loading.close(); showError(`ๆœๅŠกๅˆๅง‹ๅคฑ่ดฅ๏ผ${e.message}`); return; } } } next(); if (tempData.breadcrumb) { updateBreadcrumb(to, tempData.breadcrumb); tempData.breadcrumb = null; } else { updateBreadcrumb(to); } if (tempData.documentTitle) { updateDocumentTitle(tempData.documentTitle); tempData.documentTitle = null; } else { updateDocumentTitle(to); } }); router.afterEach(() => { LoadingBar.finish(); }); export default router;
// Test that opcounters get incremented properly. // Write command version also available at jstests/core. // Remember the global 'db' var var lastDB = db; var mongo = new Mongo(db.getMongo().host); mongo.writeMode = function() { return "legacy"; }; db = mongo.getDB(db.toString()); var t = db.opcounters; var isMongos = ("isdbgrid" == db.runCommand("ismaster").msg); var opCounters; // // 1. Insert. // // - mongod, single insert: // counted as 1 op if successful, else 0 // - mongod, bulk insert of N with continueOnError=true: // counted as K ops, where K is number of docs successfully inserted // - mongod, bulk insert of N with continueOnError=false: // counted as K ops, where K is number of docs successfully inserted // // - mongos // count ops attempted like insert commands // t.drop(); // Single insert, no error. opCounters = db.serverStatus().opcounters; t.insert({_id: 0}); assert(!db.getLastError()); assert.eq(opCounters.insert + 1, db.serverStatus().opcounters.insert); // Bulk insert, no error. opCounters = db.serverStatus().opcounters; t.insert([{_id: 1}, {_id: 2}]); assert(!db.getLastError()); assert.eq(opCounters.insert + 2, db.serverStatus().opcounters.insert); // Single insert, with error. opCounters = db.serverStatus().opcounters; t.insert({_id: 0}); print(db.getLastError()); assert(db.getLastError()); assert.eq(opCounters.insert + 1, db.serverStatus().opcounters.insert); // Bulk insert, with error, continueOnError=false. opCounters = db.serverStatus().opcounters; t.insert([{_id: 3}, {_id: 3}, {_id: 4}]); assert(db.getLastError()); assert.eq(opCounters.insert + 2, db.serverStatus().opcounters.insert); // Bulk insert, with error, continueOnError=true. var continueOnErrorFlag = 1; opCounters = db.serverStatus().opcounters; t.insert([{_id: 5}, {_id: 5}, {_id: 6}], continueOnErrorFlag); assert(db.getLastError()); assert.eq(opCounters.insert + (isMongos ? 2 : 3), db.serverStatus().opcounters.insert); // // 2. Update. // // - counted as 1 op, regardless of errors // t.drop(); t.insert({_id: 0}); // Update, no error. opCounters = db.serverStatus().opcounters; t.update({_id: 0}, {$set: {a: 1}}); assert(!db.getLastError()); assert.eq(opCounters.update + 1, db.serverStatus().opcounters.update); // Update, with error. opCounters = db.serverStatus().opcounters; t.update({_id: 0}, {$set: {_id: 1}}); assert(db.getLastError()); assert.eq(opCounters.update + 1, db.serverStatus().opcounters.update); // // 3. Delete. // // - counted as 1 op, regardless of errors // t.drop(); t.insert([{_id: 0}, {_id: 1}]); // Delete, no error. opCounters = db.serverStatus().opcounters; t.remove({_id: 0}); assert(!db.getLastError()); assert.eq(opCounters.delete + 1, db.serverStatus().opcounters.delete); // Delete, with error. opCounters = db.serverStatus().opcounters; t.remove({_id: {$invalidOp: 1}}); assert(db.getLastError()); assert.eq(opCounters.delete + 1, db.serverStatus().opcounters.delete); // // 4. Query. // // - mongod: counted as 1 op, regardless of errors // - mongos: counted as 1 op if successful, else 0 // t.drop(); t.insert({_id: 0}); // Query, no error. opCounters = db.serverStatus().opcounters; t.findOne(); assert.eq(opCounters.query + 1, db.serverStatus().opcounters.query); // Query, with error. opCounters = db.serverStatus().opcounters; assert.throws(function() { t.findOne({_id: {$invalidOp: 1}}); }); assert.eq(opCounters.query + (isMongos ? 0 : 1), db.serverStatus().opcounters.query); // // 5. Getmore. // // - counted as 1 op per getmore issued, regardless of errors // t.drop(); t.insert([{_id: 0}, {_id: 1}, {_id: 2}]); // Getmore, no error. opCounters = db.serverStatus().opcounters; t.find().batchSize(2).toArray(); // 3 documents, batchSize=2 => 1 query + 1 getmore assert.eq(opCounters.query + 1, db.serverStatus().opcounters.query); assert.eq(opCounters.getmore + 1, db.serverStatus().opcounters.getmore); // Getmore, with error (TODO implement when SERVER-5813 is resolved). // // 6. Command. // // - unrecognized commands not counted // - recognized commands counted as 1 op, regardless of errors // - some (recognized) commands can suppress command counting (i.e. aren't counted as commands) // t.drop(); t.insert({_id: 0}); // Command, recognized, no error. serverStatus = db.runCommand({serverStatus: 1}); opCounters = serverStatus.opcounters; metricsObj = serverStatus.metrics.commands; assert.eq(opCounters.command + 1, db.serverStatus().opcounters.command); // "serverStatus" counted // Count this and the last run of "serverStatus" assert.eq(metricsObj.serverStatus.total + 2, db.serverStatus().metrics.commands.serverStatus.total, "total ServerStatus command counter did not increment"); assert.eq(metricsObj.serverStatus.failed, db.serverStatus().metrics.commands.serverStatus.failed, "failed ServerStatus command counter incremented!"); // Command, recognized, with error. serverStatus = db.runCommand({serverStatus: 1}); opCounters = serverStatus.opcounters; metricsObj = serverStatus.metrics.commands; var countVal = {"total": 0, "failed": 0}; if (metricsObj.count != null) { countVal = metricsObj.count; } res = t.runCommand("count", {query: {$invalidOp: 1}}); assert.eq(0, res.ok); assert.eq(opCounters.command + 2, db.serverStatus().opcounters.command); // "serverStatus", "count" counted assert.eq(countVal.total + 1, db.serverStatus().metrics.commands.count.total, "total count command counter did not incremented"); assert.eq(countVal.failed + 1, db.serverStatus().metrics.commands.count.failed, "failed count command counter did not increment"); // Command, unrecognized. serverStatus = db.runCommand({serverStatus: 1}); opCounters = serverStatus.opcounters; metricsObj = serverStatus.metrics.commands; res = t.runCommand("invalid"); assert.eq(0, res.ok); assert.eq(opCounters.command + 1, db.serverStatus().opcounters.command); // "serverStatus" counted assert.eq(null, db.serverStatus().metrics.commands.invalid); assert.eq(metricsObj['<UNKNOWN>'] + 1, db.serverStatus().metrics.commands['<UNKNOWN>']);
import '../auto_mock_off'; import { Point,BitBox } from '../point'; describe('Point', () => { it('sets up instance properties correctly', () => { let p = new Point(1, 5); console.log(JSON.stringify(p)); expect(p.x).toBe(1); expect(p.y).toBe(5); let bb = new BitBox(); console.log(bb.address()); //expect(bb.address().length).toBe(32); }); });
import Vue from 'vue'; import VueI18n from 'vue-i18n'; import App from './App.vue'; import i18nSettings from './i18n.js'; import router from './router.js'; Vue.use(VueI18n); const i18n = new VueI18n(i18nSettings); new Vue({ el: '#app', router, i18n, template: '<App/>', components: { App } });
'use strict' var transform = require('./transform') , _ = require('lodash') function create(data) { return _.partial(transform, _, data) } module.exports = create
module.exports = { env: { browser: true, node: true, }, parser: '@typescript-eslint/parser', parserOptions: { project: './tsconfig.json', sourceType: 'module', }, ignorePatterns: ['**/*.js'], plugins: ['eslint-plugin-jsdoc', '@typescript-eslint', 'eslint-plugin-import'], extends: [ 'angular', 'eslint:recommended', 'plugin:@typescript-eslint/eslint-recommended', 'plugin:@typescript-eslint/recommended', 'plugin:import/recommended', 'plugin:import/typescript', 'prettier', ], reportUnusedDisableDirectives: true, rules: { 'angular/no-private-call': 'error', 'angular/controller-as-route': 'error', 'angular/controller-name': 'error', 'angular/module-setter': 'error', 'angular/log': 'error', 'angular/di': 'error', 'angular/on-watch': 'error', 'angular/no-service-method': 'off', 'angular/module-getter': 'off', 'angular/definedundefined': 'off', 'angular/document-service': 'off', 'angular/json-functions': 'off', 'angular/typecheck-array': 'off', 'angular/typecheck-string': 'off', 'angular/typecheck-function': 'off', 'angular/window-service': 'off', 'angular/interval-service': 'off', 'angular/timeout-service': 'off', 'no-bitwise': 'warn', 'no-redeclare': 'warn', 'no-useless-escape': 'error', 'no-prototype-builtins': 'warn', 'no-cond-assign': 'warn', '@typescript-eslint/ban-types': 'error', '@typescript-eslint/no-unused-vars': 'error', '@typescript-eslint/ban-ts-comment': 'warn', '@typescript-eslint/explicit-module-boundary-types': 'off', '@typescript-eslint/no-explicit-any': 'off', eqeqeq: ['warn', 'smart'], 'guard-for-in': 'warn', 'id-blacklist': 'off', 'id-match': 'off', 'jsdoc/check-alignment': 'error', 'jsdoc/check-indentation': 'off', 'jsdoc/newline-after-description': 'error', 'no-caller': 'error', 'no-console': [ 'warn', { allow: [ 'warn', 'dir', 'timeLog', 'assert', 'clear', 'count', 'countReset', 'group', 'groupEnd', 'table', 'dirxml', 'error', 'groupCollapsed', 'Console', 'profile', 'profileEnd', 'timeStamp', 'context', ], }, ], 'no-debugger': 'error', 'no-empty': 'off', 'no-eval': 'error', 'no-fallthrough': 'error', 'no-new-wrappers': 'error', 'no-underscore-dangle': 'off', 'no-unused-labels': 'error', radix: 'error', 'spaced-comment': [ 'warn', 'always', { markers: ['/'], }, ], 'import/order': [ 'error', { groups: ['internal', 'external', 'builtin', 'object', 'type', 'index', 'sibling', 'parent'], 'newlines-between': 'always', }, ], }, };
(function(){ 'use strict'; angular .module('starter') .controller('CompareController', CompareController); CompareController.$inject = ['$stateParams', '$log']; function CompareController($stateParams, $log) { var first = {}; var second = {}; var vm = this; vm.toCompare = []; $log.debug($stateParams); if ($stateParams.left) { //first url exists first.path = $stateParams.left; if ($stateParams.lmime) { // mime type exists first.type = $stateParams.lmime; } vm.toCompare.push(first); if ($stateParams.right) { //second url exists second.path = $stateParams.right; if ($stateParams.rmime) {// second mime type exists second.type = $stateParams.rmime; } vm.toCompare.push(second); } else { // if second url is not defined, call the temporary modified file var tmp = ''; vm.toCompare.push({path: $stateParams.url + tmp}); } } $log.debug(vm.toCompare); } })();
module.exports = { "done": () => { console.log( "context.done fired" ); return "contents of done function"; } }
import {mount} from 'enzyme'; import {BentoInstagram} from '#bento/components/bento-instagram/1.0/component'; import * as Preact from '#preact'; import {createRef} from '#preact'; import {WithAmpContext} from '#preact/context'; import {waitFor} from '#testing/helpers/service'; describes.sandboxed('BentoInstagram preact component v1.0', {}, (env) => { it('Normal render', () => { const wrapper = mount( <BentoInstagram shortcode="B8QaZW4AQY_" style={{ 'width': 500, 'height': 600, }} /> ); const iframe = wrapper.find('iframe'); expect(iframe.prop('src')).to.equal( 'https://www.instagram.com/p/B8QaZW4AQY_/embed/?cr=1&v=12' ); expect(wrapper.find('iframe').prop('style').width).to.equal('100%'); expect(wrapper.find('iframe').prop('style').height).to.equal('100%'); expect(wrapper.find('div')).to.have.lengthOf(2); }); it('Render with caption', () => { const wrapper = mount( <BentoInstagram shortcode="B8QaZW4AQY_" captioned style={{'width': 500, 'height': 705}} /> ); expect(wrapper.find('iframe').prop('src')).to.equal( 'https://www.instagram.com/p/B8QaZW4AQY_/embed/captioned/?cr=1&v=12' ); expect(wrapper.find('iframe').prop('style').width).to.equal('100%'); expect(wrapper.find('iframe').prop('style').height).to.equal('100%'); expect(wrapper.find('div')).to.have.lengthOf(2); }); it('Resize prop is called', () => { const requestResizeSpy = env.sandbox.spy(); const wrapper = mount( <BentoInstagram shortcode="B8QaZW4AQY_" captioned style={{'width': 500, 'height': 705}} requestResize={requestResizeSpy} /> ); const mockEvent = createMockEvent(); mockEvent.source = wrapper .getDOMNode() .querySelector('iframe').contentWindow; window.dispatchEvent(mockEvent); expect(requestResizeSpy).to.have.been.calledOnce; }); it('Height is changed', async () => { const wrapper = mount( <BentoInstagram shortcode="B8QaZW4AQY_" style={{'width': 500, 'height': 600}} /> ); const mockEvent = createMockEvent(); mockEvent.source = wrapper .getDOMNode() .querySelector('iframe').contentWindow; window.dispatchEvent(mockEvent); wrapper.update(); await waitFor( () => wrapper.find('div').at(0).prop('style').height == 1000, 'Height is not changed' ); expect(wrapper.find('div').at(0).prop('style').height).to.equal(1000); }); it('load event is dispatched', async () => { const ref = createRef(); const onReadyState = env.sandbox.spy(); const wrapper = mount( <BentoInstagram ref={ref} shortcode="B8QaZW4AQY_" style={{'width': 500, 'height': 600}} onReadyState={onReadyState} /> ); let api = ref.current; expect(api.readyState).to.equal('loading'); expect(onReadyState).to.not.be.called; await wrapper.find('iframe').invoke('onLoad')(); api = ref.current; expect(api.readyState).to.equal('complete'); expect(onReadyState).to.be.calledOnce.calledWith('complete'); }); it('should reset iframe on pause', () => { const ref = createRef(); const wrapper = mount( <WithAmpContext playable={true}> <BentoInstagram ref={ref} shortcode="B8QaZW4AQY_" style={{'width': 500, 'height': 600}} /> </WithAmpContext> ); expect(wrapper.find('iframe')).to.have.lengthOf(1); const iframe = wrapper.find('iframe').getDOMNode(); let iframeSrc = iframe.src; const iframeSrcSetterSpy = env.sandbox.spy(); Object.defineProperty(iframe, 'src', { get() { return iframeSrc; }, set(value) { iframeSrc = value; iframeSrcSetterSpy(value); }, }); wrapper.setProps({playable: false}); expect(iframeSrcSetterSpy).to.be.calledOnce; }); }); function createMockEvent() { const mockEvent = new CustomEvent('message'); mockEvent.origin = 'https://www.instagram.com'; mockEvent.data = JSON.stringify({ 'type': 'MEASURE', 'details': { 'height': 1000, }, }); return mockEvent; }
/** * Copyright 2016 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; require('../../compiled-check.js')('printer.js'); /* eslint-env mocha */ const Printer = require('../../printer.js'); const assert = require('assert'); const fs = require('fs'); const sampleResults = require('../../../lighthouse-core/test/results/sample.json'); describe('Printer', () => { it('accepts valid output paths', () => { const path = '/path/to/output'; assert.equal(Printer.checkOutputPath(path), path); }); it('rejects invalid output paths', () => { const path = undefined; assert.notEqual(Printer.checkOutputPath(path), path); }); it('creates JSON for results', () => { const mode = Printer.OutputMode.json; const jsonOutput = Printer.createOutput(sampleResults, mode); assert.doesNotThrow(_ => JSON.parse(jsonOutput)); }); it('creates HTML for results', () => { const mode = Printer.OutputMode.html; const htmlOutput = Printer.createOutput(sampleResults, mode); assert.ok(/<!doctype/gim.test(htmlOutput)); assert.ok(/<html lang="en" data-report-context="cli"/gim.test(htmlOutput)); }); it('writes file for results', () => { const mode = 'html'; const path = './.test-file.html'; // Now do a second pass where the file is written out. return Printer.write(sampleResults, mode, path).then(_ => { const fileContents = fs.readFileSync(path, 'utf8'); assert.ok(/<!doctype/gim.test(fileContents)); fs.unlinkSync(path); }); }); it('throws for invalid paths', () => { const mode = 'html'; const path = '!/#@.html'; return Printer.write(sampleResults, mode, path).catch(err => { assert.ok(err.code === 'ENOENT'); }); }); it('writes extended info', () => { const mode = Printer.OutputMode.html; const htmlOutput = Printer.createOutput(sampleResults, mode); const outputCheck = new RegExp('dobetterweb/dbw_tester.css', 'i'); assert.ok(outputCheck.test(htmlOutput)); }); });
"use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var OuterSubscriber_1 = require("../OuterSubscriber"); var subscribeToResult_1 = require("../util/subscribeToResult"); /** * Emits a value from the source Observable only after a particular time span * determined by another Observable has passed without another source emission. * * <span class="informal">It's like {@link debounceTime}, but the time span of * emission silence is determined by a second Observable.</span> * * <img src="./img/debounce.png" width="100%"> * * `debounce` delays values emitted by the source Observable, but drops previous * pending delayed emissions if a new value arrives on the source Observable. * This operator keeps track of the most recent value from the source * Observable, and spawns a duration Observable by calling the * `durationSelector` function. The value is emitted only when the duration * Observable emits a value or completes, and if no other value was emitted on * the source Observable since the duration Observable was spawned. If a new * value appears before the duration Observable emits, the previous value will * be dropped and will not be emitted on the output Observable. * * Like {@link debounceTime}, this is a rate-limiting operator, and also a * delay-like operator since output emissions do not necessarily occur at the * same time as they did on the source Observable. * * @example <caption>Emit the most recent click after a burst of clicks</caption> * var clicks = Rx.Observable.fromEvent(document, 'click'); * var result = clicks.debounce(() => Rx.Observable.interval(1000)); * result.subscribe(x => console.log(x)); * * @see {@link audit} * @see {@link debounceTime} * @see {@link delayWhen} * @see {@link throttle} * * @param {function(value: T): SubscribableOrPromise} durationSelector A function * that receives a value from the source Observable, for computing the timeout * duration for each source value, returned as an Observable or a Promise. * @return {Observable} An Observable that delays the emissions of the source * Observable by the specified duration Observable returned by * `durationSelector`, and may drop some values if they occur too frequently. * @method debounce * @owner Observable */ function debounce(durationSelector) { return function (source) { return source.lift(new DebounceOperator(durationSelector)); }; } exports.debounce = debounce; var DebounceOperator = /** @class */ (function () { function DebounceOperator(durationSelector) { this.durationSelector = durationSelector; } DebounceOperator.prototype.call = function (subscriber, source) { return source.subscribe(new DebounceSubscriber(subscriber, this.durationSelector)); }; return DebounceOperator; }()); /** * We need this JSDoc comment for affecting ESDoc. * @ignore * @extends {Ignored} */ var DebounceSubscriber = /** @class */ (function (_super) { __extends(DebounceSubscriber, _super); function DebounceSubscriber(destination, durationSelector) { var _this = _super.call(this, destination) || this; _this.durationSelector = durationSelector; _this.hasValue = false; _this.durationSubscription = null; return _this; } DebounceSubscriber.prototype._next = function (value) { try { var result = this.durationSelector.call(this, value); if (result) { this._tryNext(value, result); } } catch (err) { this.destination.error(err); } }; DebounceSubscriber.prototype._complete = function () { this.emitValue(); this.destination.complete(); }; DebounceSubscriber.prototype._tryNext = function (value, duration) { var subscription = this.durationSubscription; this.value = value; this.hasValue = true; if (subscription) { subscription.unsubscribe(); this.remove(subscription); } subscription = subscribeToResult_1.subscribeToResult(this, duration); if (subscription && !subscription.closed) { this.add(this.durationSubscription = subscription); } }; DebounceSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { this.emitValue(); }; DebounceSubscriber.prototype.notifyComplete = function () { this.emitValue(); }; DebounceSubscriber.prototype.emitValue = function () { if (this.hasValue) { var value = this.value; var subscription = this.durationSubscription; if (subscription) { this.durationSubscription = null; subscription.unsubscribe(); this.remove(subscription); } // This must be done *before* passing the value // along to the destination because it's possible for // the value to synchronously re-enter this operator // recursively if the duration selector Observable // emits synchronously this.value = null; this.hasValue = false; _super.prototype._next.call(this, value); } }; return DebounceSubscriber; }(OuterSubscriber_1.OuterSubscriber)); //# sourceMappingURL=debounce.js.map
sap.ui.define(['sap/ui/webc/common/thirdparty/base/config/Theme', './v5/display', './v4/display'], function (Theme, display$2, display$1) { 'use strict'; const pathData = Theme.isThemeFamily("sap_horizon") ? display$1 : display$2; var display = { pathData }; return display; });
(function(){ // var vconsoleURL = chrome.extension.getURL('vconsole.min.js'); $(document.body).append("<script src='http://wechatfe.github.io/vconsole/lib/vconsole.min.js?v=3.3.0'></script>"); // $(document.body).append("<script src='" + vconsoleURL + "'></script>"); $(document.body).append("<script>"+"window.vConsole = new window.VConsole();"+"</script>"); console.log('ooo'); function utf16to8(str) { var out, i, len, c; out = ""; len = str.length; for(i = 0; i < len; i++) { c = str.charCodeAt(i); if ((c >= 0x0001) && (c <= 0x007F)) { out += str.charAt(i); } else if (c > 0x07FF) { out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F)); out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F)); out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F)); } else { out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F)); out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F)); } } return out; } function resizePos(){ var height = $(window).height(); var width = $(window).width(); //console.log(height,width); $('#midoks_rand_page_qrcode').css({ 'position':'fixed', 'left':0, 'top':0, 'z-index':100, 'width':width, 'height':height, 'background':'#fff', //'opacity':'0.4', }); $('#midoks_rand_page_qrcode .qrcode').css({ 'position':'fixed', 'top': ( height - 200 ) / 2, 'left' : ( width - 200 ) / 2, 'z-index':101, }); $('#midoks_rand_page_qrcode .close').css({ 'position':'fixed', 'border-radius':15, 'font-size':12, 'padding-top':15, 'width':40, 'height':35, 'text-align':'center', 'top': ( height - 35 ) / 2, 'left' : ( width - 40 ) / 2, 'z-index':102, 'color':'#fff', 'background':'#000', 'cursor':'pointer', }); } function makeQrcode(content){ $('body').append('<div id="midoks_rand_page_qrcode"><div class="qrcode"></div><div class="close">close</div></div>'); resizePos(); $(window).resize(function(){ resizePos(); }); var v = utf16to8(content); $('#midoks_rand_page_qrcode .qrcode').qrcode({width:200,height:200,correctLevel:0,text:v}); $('#midoks_rand_page_qrcode .close').bind('click', function(){ $('#midoks_rand_page_qrcode').remove(); }); } chrome.extension.onRequest.addListener(function(request, sender, sendResponse){ console.log(request); if (typeof request.v != "undefined"){ makeQrcode(request.v); sendResponse({response: "ok"}); } else { sendResponse({}); // snub them. } }); // })();
var assert = require('assert'); var H = require('../test_harness.js'); var cb = H.newClient(); describe('#remove', function() { it('should work with basic inputs', function(done) { var key = H.genKey(); cb.set(key, "a value", H.okCallback(function(result){ cb.get(key, H.okCallback(function(result){ cb.remove(key, H.okCallback(function(result) { cb.get(key, function(err, result) { assert.equal(err.code, H.errors.keyNotFound); done(); }); })); })); })); }); it('should work with cas values', function(done) { var key = H.genKey(); var value = "Value"; cb.set(key, value, H.okCallback(function(result1){ cb.set(key, "new value", H.okCallback(function(result2){ cb.remove(key, { cas: result1.cas }, function(err, result){ assert(err, "Remove fails with bad CAS"); cb.remove(key, {cas: result2.cas}, H.okCallback(function(result){ done(); })); }); })); })); }); it('should fail for non-existent keys', function(done) { var key = H.genKey(); var value = "some value"; cb.set(key, value, H.okCallback(function(result) { cb.remove(key, H.okCallback(function(result){ cb.remove(key, function(err, result) { assert(err, "Can't remove key twice"); done(); }); })); })); }); it('should work with multiple values', function(done) { var kv = H.genMultiKeys(10, "removeMulti"); cb.setMulti(kv, {spooled: true}, H.okCallback(function(results){ cb.getMulti(Object.keys(kv), {spooled: true}, H.okCallback(function(results){ cb.removeMulti(results, {spooled: true}, H.okCallback(function(results){ done(); })); })); })); }); });
/* * Copyright 2016 - 2017 Anton Tananaev ([email protected]) * Copyright 2016 - 2017 Andrey Kunitsyn ([email protected]) * * 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/>. */ Ext.define('Traccar.view.edit.AttributeAliases', { extend: 'Ext.grid.Panel', xtype: 'attributeAliasesView', requires: [ 'Traccar.view.edit.AttributeAliasesController', 'Traccar.view.edit.Toolbar' ], controller: 'attributeAliases', tbar: { xtype: 'editToolbar', items: ['-', { xtype: 'tbtext', html: Strings.sharedDevice }, { xtype: 'combobox', reference: 'deviceField', store: 'Devices', displayField: 'name', valueField: 'id', editable: false, listeners: { change: 'onDeviceChange' } }] }, listeners: { selectionchange: 'onSelectionChange' }, columns: { defaults: { flex: 1, minWidth: Traccar.Style.columnWidthNormal }, items: [{ text: Strings.sharedAttribute, dataIndex: 'attribute' }, { text: Strings.sharedAlias, dataIndex: 'alias' }] } });
"use strict"; const FoldDict = require("./fold_dict").FoldDict; const partners = new Set(); exports.set_partner = function (user_id) { partners.add(user_id); }; exports.is_partner = function (user_id) { return partners.has(user_id); }; class RecentPrivateMessages { // This data structure keeps track of the sets of users you've had // recent conversations with, sorted by time (implemented via // `message_id` sorting, since that's how we time-sort messages). recent_message_ids = new FoldDict(); // key is user_ids_string recent_private_messages = []; insert(user_ids, message_id) { if (user_ids.length === 0) { // The server sends [] for self-PMs. user_ids = [people.my_current_user_id()]; } user_ids.sort((a, b) => a - b); const user_ids_string = user_ids.join(","); let conversation = this.recent_message_ids.get(user_ids_string); if (conversation === undefined) { // This is a new user, so create a new object. conversation = { user_ids_string, max_message_id: message_id, }; this.recent_message_ids.set(user_ids_string, conversation); // Optimistically insert the new message at the front, since that // is usually where it belongs, but we'll re-sort. this.recent_private_messages.unshift(conversation); } else { if (conversation.max_message_id >= message_id) { // don't backdate our conversation. This is the // common code path after initialization when // processing old messages, since we'll already have // the latest message_id for the conversation from // initialization. return; } // update our latest message_id conversation.max_message_id = message_id; } this.recent_private_messages.sort((a, b) => b.max_message_id - a.max_message_id); } get() { // returns array of structs with user_ids_string and // message_id return this.recent_private_messages; } get_strings() { // returns array of structs with user_ids_string and // message_id return this.recent_private_messages.map((conversation) => conversation.user_ids_string); } initialize(params) { for (const conversation of params.recent_private_conversations) { this.insert(conversation.user_ids, conversation.max_message_id); } } } exports.recent = new RecentPrivateMessages(); window.pm_conversations = exports;
// Copyright 2018 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. const settings = require('./settings'); /** * Returns a error message for the given parameters. * @param {String} err error from the exec call. * @param {String} stderr standard error from the exec call. */ const getExecErrorMessage = (err, stderr) => { let errMsg = null; if (err) { errMsg = `exec error: ${err}`; } else if (stderr.length > 0) { errMsg = `stderr: ${stderr.toString()}`; } return errMsg; }; /** * Returns the original string with characters * specified in settings replaced with spaces. * @text {String} text to be replaced. */ const replaceCharactersWithSpaces = (text) => { const re = new RegExp(`[${settings.CHARACTERS_TO_REPLACE_WITH_SPACES}]`, 'g'); const newText = text.replace(re, ' ').trim(); return newText; }; module.exports = { getExecErrorMessage, replaceCharactersWithSpaces, };
/** * @license Apache-2.0 * * Copyright (c) 2020 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); var dnanstdevtk = require( './dnanstdevtk.js' ); var ndarray = require( './ndarray.js' ); // MAIN // setReadOnly( dnanstdevtk, 'ndarray', ndarray ); // EXPORTS // module.exports = dnanstdevtk;
const createNonceStr = function () { return Math.random().toString(36).substr(2, 15); }; const createTimestamp = function () { return parseInt(new Date().getTime() / 1000) + ''; }; const raw = function (args) { let keys = Object.keys(args); keys = keys.sort() let newArgs = {}; keys.forEach(function (key) { newArgs[key.toLowerCase()] = args[key]; }); let string = ''; for (let k in newArgs) { string += '&' + k + '=' + newArgs[k]; } string = string.substr(1); return string; }; /** * @synopsis ็ญพๅ็ฎ—ๆณ• * * @param jsapi_ticket ็”จไบŽ็ญพๅ็š„ jsapi_ticket * @param url ็”จไบŽ็ญพๅ็š„ url ๏ผŒๆณจๆ„ๅฟ…้กปๅŠจๆ€่Žทๅ–๏ผŒไธ่ƒฝ hardcode * * @returns */ const sign = (jsapi_ticket, url) => { const ret = { jsapi_ticket, nonceStr: createNonceStr(), timestamp: createTimestamp(), url, }; let string = raw(ret); shaObj = new jsSHA(string, 'TEXT'); ret.signature = shaObj.getHash('SHA-1', 'HEX'); return ret; };
var classorg_1_1onosproject_1_1pcepio_1_1protocol_1_1PcepCloseMsgTest = [ [ "closeMessageTest1", "classorg_1_1onosproject_1_1pcepio_1_1protocol_1_1PcepCloseMsgTest.html#a30996cd3645f257799088f26d4fd8582", null ] ];
const {JavaEventEmitter} = require('ringo/events'); const {WebSocketListener} = org.eclipse.jetty.websocket.api; const {ByteBuffer} = java.nio; const WebSocket = module.exports = function() { this.session = null; // make WebSocket a java event-emitter (mixin) JavaEventEmitter.call(this, [WebSocketListener], { "onWebSocketConnect": "connect", "onWebSocketClose": "close", "onWebSocketText": "text", "onWebSocketBinary": "binary", "onWebSocketError": "error" }); return this; }; /** @ignore */ WebSocket.prototype.toString = function() { return "[WebSocket]"; }; /** * Closes the WebSocket connection. * @name WebSocket.instance.close * @function */ WebSocket.prototype.close = function() { if (!this.isOpen()) { throw new Error("Not connected"); } this.session.close(); this.session = null; }; /** * Send a string over the WebSocket. * @param {String} message a string * @name WebSocket.instance.send * @deprecated * @see #sendString * @function */ WebSocket.prototype.send = function(message) { return this.sendString(message); }; /** * Send a string over the WebSocket. This method * blocks until the message has been transmitted * @param {String} message a string * @name WebSocket.instance.sendString * @function */ WebSocket.prototype.sendString = function(message) { if (!this.isOpen()) { throw new Error("Not connected"); } this.session.getRemote().sendString(message); }; /** * Send a string over the WebSocket. This method * does not wait until the message as been transmitted. * @param {String} message a string * @name WebSocket.instance.sendStringAsync * @function */ WebSocket.prototype.sendStringAsync = function(message) { if (!this.isOpen()) { throw new Error("Not connected"); } return this.session.getRemote().sendStringByFuture(message); }; /** * Send a byte array over the WebSocket. This method * blocks until the message as been transmitted. * @param {ByteArray} byteArray The byte array to send * @param {Number} offset Optional offset (defaults to zero) * @param {Number} length Optional length (defaults to the * length of the byte array) * @name WebSocket.instance.sendBinary * @function */ WebSocket.prototype.sendBinary = function(byteArray, offset, length) { if (!this.isOpen()) { throw new Error("Not connected"); } const buffer = ByteBuffer.wrap(byteArray, parseInt(offset, 10) || 0, parseInt(length, 10) || byteArray.length); return this.session.getRemote().sendBytes(buffer); }; /** * Send a byte array over the WebSocket. This method * does not wait until the message as been transmitted. * @param {ByteArray} byteArray The byte array to send * @param {Number} offset Optional offset (defaults to zero) * @param {Number} length Optional length (defaults to the * length of the byte array) * @name WebSocket.instance.sendBinaryAsync * @returns {java.util.concurrent.Future} * @function */ WebSocket.prototype.sendBinaryAsync = function(byteArray, offset, length) { if (!this.isOpen()) { throw new Error("Not connected"); } const buffer = ByteBuffer.wrap(byteArray, parseInt(offset, 10) || 0, parseInt(length, 10) || byteArray.length); return this.session.getRemote().sendBytesByFuture(buffer); }; /** * Check whether the WebSocket is open. * @name WebSocket.instance.isOpen * @return {Boolean} true if the connection is open * @function */ WebSocket.prototype.isOpen = function() { return this.session !== null && this.session.isOpen(); };
/* * Copyright 2014 Petr, Frank Breedijk * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ steal( 'jquery/controller', 'jquery/view/ejs', 'jquery/dom/form_params', 'jquery/controller/view', 'seccubus/models', 'seccubus/asset/host/table' ).then( './views/init.ejs', function($){ /** * @class Seccubus.Asset.Edit * @parent Asset * @inherits jQuery.Controller * Generates a dialog to edit a asset * * Story * ----- * As a user I would like to be able to edit scans from the GUI */ $.Controller('Seccubus.Asset.Edit', /** @Static */ { /* * @attribute options * Object that contains the options */ defaults : { /* * @attribute options.onClear * Funciton that is called when the form is cleared, e.g. to * disable a modal display */ onClear : function () { }, /* attribute options.asset * Asset object that needs to be edited */ asset : null, /* attribute options.onHostEdit * Function that is called when the edit link is click in the * hosts screen */ onHostEdit : function(ash) { alert("Seccubus.Asset.Edit: no edit function specified for asset id: " + ash.id ); }, /* attribute options.onHostDelete * Function that is called when the delete link is click in the * hosts screen */ // onHostDelete : function(as){ // alert("Seccubus.Asset.Edit: no delete function specified for asset id: " + as.id ); // }, /* attribute options.onHostCreate * Function that is called when the create button is click in the * hosts screen */ onHostCreate : function(ws,as) { alert("Seccubus.Asset.Edit: no create function specified for asset " + ws + "," + as); }, /* attribute options.workspaces * workspace id we are currently in */ workspace : -1 } }, /** @Prototype */ { init : function(){ this.updateView(); }, updateView : function() { this.element.html( this.view( 'init', this.options.asset ) ); var ws = this.options.workspace, as = this.options.asset.id, options = this.options; $('#editAssetHost').seccubus_asset_host_table({ workspace : ws, asset : as, onEdit : options.onHostEdit }); $('.createHost').click(function(){ options.onHostCreate(ws,as); }); }, submit : function(el, ev){ ev.preventDefault(); var params = el.formParams(); var elements = []; var ok = true; if(params.name == ''){ ok = false; elements.push('#editAssetName'); } if ( ok ) { this.element.find('[type=submit]').val('Updating...') var as = this.options.asset; as.name = params.name; as.hosts = params.hosts; as.recipients = params.recipients; as.recipientsHtml = as.recipients.replace(/([-0-9a-zA-Z.+_]+\@[-0-9a-zA-Z.+_]+\.?[a-zA-Z]{0,4})/g,"<a href='mailto:$1'>$1<\/a>"); as.save(this.callback('saved')); } else { this.nok(elements); } }, nok : function(elements) { this.element.children(".nok").removeClass("nok"); for(i=0;i<elements.length;i++) { $(elements[i]).addClass("nok"); } this.element.css({position : "absolute"}); this.element.animate({left : '+=20'},100); this.element.animate({left : '-=20'},100); this.element.animate({left : '+=20'},100); this.element.animate({left : '-=20'},100); this.element.animate({left : '+=20'},100); this.element.animate({left : '-=20'},100); this.element.css({position : "relative"}); }, ".cancel click" : function() { this.clearAll(); }, saved : function(){ this.clearAll(); }, clearAll : function() { this.element.find('[type=submit]').val('Update'); this.element[0].reset() $(".nok").removeClass("nok"); this.options.onClear(); }, ".nok change" : function(el) { el.removeClass("nok"); }, // ".createNotification click" : function(el, ev) { // ev.preventDefault(); // this.options.onNotificationCreate(this.options.workspace, this.options.scan.id); // }, update : function(options) { this._super(options); this.updateView(); } }); });
import React from 'react'; export default class GenericNotFound extends React.Component { componentWillMount() { this.props.setPageTitle('Oops..'); } render() { return ( <div className="text-center"> <h3>The page you are looking for is not found or has been removed.</h3> </div> ); } }
/** * @license inazumatv.com * @author (at)taikiken / http://inazumatv.com * @date 2015/04/20 - 21:53 * * Copyright (c) 2011-2015 inazumatv.com, inc. * * Distributed under the terms of the MIT license. * http://www.opensource.org/licenses/mit-license.html * * This notice shall be included in all copies or substantial portions of the Software. */ /*jslint node: true */ 'use strict'; // ---------------------------------------------------------------- // setting // ---------------------------------------------------------------- var setting = require( '../setting.js' ); // ---------------------------------------------------------------- // dir & pattern // ---------------------------------------------------------------- var dir = setting.dir; var patterns = setting.patterns; var version = setting.version; // ---------------------------------------------------------------- // gulp & main plugins // ---------------------------------------------------------------- var gulp = setting.gulp; var plugin = setting.plugin; var $ = plugin.$; var del = plugin.del; var runSequence = plugin.runSequence; // ---------------------------------------------------------------- // scripts // ---------------------------------------------------------------- var libName = 'igata.js'; var scripts = []; // ---------------------------------------------------------------- // src // ---------------------------------------------------------------- scripts.push( dir.src + '/igata.js' ); // geom scripts.push( dir.src + '/geom/IVector.js' ); scripts.push( dir.src + '/geom/Vector2.js' ); // ---------------------------------------------------------------- // task // ---------------------------------------------------------------- // concat gulp.task( 'script-concat', function () { return gulp.src( scripts ) .pipe( $.concat( libName ) ) .pipe( $.replaceTask( { patterns: patterns } ) ) .pipe( gulp.dest( dir.lib ) ) .pipe( $.rename( function ( path ) { path.basename = path.basename + '-' + version; } ) ) .pipe( gulp.dest( dir.lib ) ) .pipe( $.size( { title: '*** script-concat ***' } ) ); } ); // minified gulp.task( 'script-min', function () { return gulp.src( [ dir.lib + '/' + libName, dir.lib + '/' + libName.replace( '.js', '-' + version + '.js' ) ] ) .pipe( $.uglify( { preserveComments: 'some' } ) ) .pipe( $.rename( { suffix: '.min' } ) ) .pipe( gulp.dest( dir.lib ) ) .pipe( $.size( { title: '*** script-min ***' } ) ); } ); // docs gulp.task( 'script-docs', function () { return gulp.src( scripts ) .pipe( $.yuidoc() ) .pipe( gulp.dest( dir.docs ) ); } ); // ---------------------------------------------------------------- // run // ---------------------------------------------------------------- // build without docs gulp.task( 'script-dev', function () { runSequence( 'script-concat', 'script-min' ); } ); // build & docs gulp.task( 'script-build', function () { runSequence( 'script-concat', [ 'script-min', 'script-docs' ] ); } );
// spawn npm start from the directory to launch the Webapp // send a request to ensure it's up and running const path = require('path'); const http = require('http'); function setup (mode, callback) { var submission = this.args[0]; var url = require('util').format('http://%s.mybluemix.net', submission); http.get(url, function(res) { if (res.statusCode === 200) { var data = ''; res.on('data', function(chunk) { data += chunk; }).on('end', function() { if (/Last Visit/.test(data)) { callback(); } else { callback(new Error('Could not verify the application')); } }); callback(); } else { callback(new Error('The web app could not be reached')); } }); } function checkcf (exercise) { exercise.addSetup(setup); return exercise; } module.exports = checkcf;
import { registerBidder } from 'src/adapters/bidderFactory'; const BIDDER_CODE = 'optimera'; const SCORES_BASE_URL = 'http://dyv1bugovvq1g.cloudfront.net/'; export const spec = { code: BIDDER_CODE, /** * Determines whether or not the given bid request is valid. * * @param {bidRequest} bid The bid params to validate. * @return boolean True if this is a valid bid, and false otherwise. */ isBidRequestValid: function (bidRequest) { if (typeof bidRequest.params !== 'undefined' && typeof bidRequest.params.clientID !== 'undefined') { return true; } else { return false; } }, /** * Make a server request from the list of BidRequests. * * We call the existing scores data file for ad slot placement scores. * These scores will be added to the dealId to be pushed to DFP. * * @param {validBidRequests[]} - an array of bids * @return ServerRequest Info describing the request to the server. */ buildRequests: function (validBidRequests) { let optimeraHost = window.location.host; let optimeraPathName = window.location.pathname; if (typeof validBidRequests[0].params.clientID !== 'undefined') { let clientID = validBidRequests[0].params.clientID; let scoresURL = SCORES_BASE_URL + clientID + '/' + optimeraHost + optimeraPathName + '.js'; return { method: 'GET', url: scoresURL, payload: validBidRequests, }; } }, /** * Unpack the response from the server into a list of bids. * * Some required bid params are not needed for this so default * values are used. * * @param {*} serverResponse A successful response from the server. * @return {Bid[]} An array of bids which were nested inside the server. */ interpretResponse: function (serverResponse, bidRequest) { let validBids = bidRequest.payload; let bidResponses = []; let dealId = ''; if (typeof serverResponse.body !== 'undefined') { let scores = serverResponse.body; for (let i = 0; i < validBids.length; i++) { if (typeof validBids[i].params.clientID !== 'undefined') { if (validBids[i].adUnitCode in scores) { dealId = scores[validBids[i].adUnitCode]; } let bidResponse = { requestId: validBids[i].bidId, ad: '<div></div>', cpm: 0.01, width: 0, height: 0, dealId: dealId, ttl: 300, creativeId: '1', netRevenue: '0', currency: 'USD' }; bidResponses.push(bidResponse); } } } return bidResponses; } } registerBidder(spec);
/** * Copyright 2015 The Incremental DOM Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS-IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var updateAttribute = require('./attributes').updateAttribute; var nodeData = require('./node_data'), getData = nodeData.getData, initData = nodeData.initData; /** * Creates an Element. * @param {!Document} doc The document with which to create the Element. * @param {string} tag The tag for the Element. * @param {?string} key A key to identify the Element. * @param {?Array<*>} statics An array of attribute name/value pairs of * the static attributes for the Element. * @return {!Element} */ var createElement = function(doc, tag, key, statics) { var el = doc.createElement(tag); initData(el, tag, key); if (statics) { for (var i = 0; i < statics.length; i += 2) { updateAttribute(el, statics[i], statics[i + 1]); } } return el; }; /** * Creates a Text. * @param {!Document} doc The document with which to create the Text. * @param {string} text The intial content of the Text. * @return {!Text} */ var createTextNode = function(doc, text) { var node = doc.createTextNode(text); getData(node).text = text; return node; }; /** * Creates a Node, either a Text or an Element depending on the node name * provided. * @param {!Document} doc The document with which to create the Node. * @param {string} nodeName The tag if creating an element or #text to create * a Text. * @param {?string} key A key to identify the Element. * @param {?Array<*>|string} statics The static data to initialize the Node * with. For an Element, an array of attribute name/value pairs of * the static attributes for the Element. For a Text, a string with the * intial content of the Text. * @return {!Node} */ var createNode = function(doc, nodeName, key, statics) { if (nodeName === '#text') { return createTextNode(doc, statics); } return createElement(doc, nodeName, key, statics); }; /** * Creates a mapping that can be used to look up children using a key. * @param {!Element} el * @return {!Object<string, !Node>} A mapping of keys to the children of the * Element. */ var createKeyMap = function(el) { var map = {}; var children = el.children; var count = children.length; for (var i = 0; i < count; i += 1) { var child = children[i]; var key = getKey(child); if (key) { map[key] = child; } } return map; }; /** * @param {?Node} node A node to get the key for. * @return {?string} The key for the Node, if applicable. */ var getKey = function(node) { return getData(node).key; }; /** * @param {?Node} node A node to get the node name for. * @return {?string} The node name for the Node, if applicable. */ var getNodeName = function(node) { return getData(node).nodeName; }; /** * Retrieves the mapping of key to child node for a given Element, creating it * if necessary. * @param {!Element} el * @return {!Object<string,!Node>} A mapping of keys to child Nodes */ var getKeyMap = function(el) { var data = getData(el); if (!data.keyMap) { data.keyMap = createKeyMap(el); } return data.keyMap; }; /** * Retrieves a child from the parent with the given key. * @param {!Element} parent * @param {?string} key * @return {?Node} The child corresponding to the key. */ var getChild = function(parent, key) { return getKeyMap(parent)[key]; }; /** * Registers a node as being a child. If a key is provided, the parent will * keep track of the child using the key. The child can be retrieved using the * same key using getKeyMap. The provided key should be unique within the * parent Element. * @param {!Element} parent The parent of child. * @param {?string} key A key to identify the child with. * @param {!Node} child The child to register. */ var registerChild = function(parent, key, child) { if (key) { getKeyMap(parent)[key] = child; } }; /** */ module.exports = { createNode: createNode, getKey: getKey, getNodeName: getNodeName, getChild: getChild, registerChild: registerChild };
function CreateMap(e){ } module.exports = CreateMap;
'use strict'; /* wfRegEx.js Standardized list of RegEx's used across the building of WebFundamentals */ var RE_BOOK_PATH = /^book_path: (.*)\n/m; var RE_PROJECT_PATH = /^project_path: (.*)\n/m; var RE_DESCRIPTION = /^description:\s?(.*)\n/m; var RE_REGION = /^{#\s?wf_region:\s?(.*?)\s?#}\s?\n/m; var RE_VERTICAL = /^{#\s?wf_vertical:\s?(.*?)\s?#}\s?\n/m; var RE_FEATURED_DATE = /^{#\s?wf_featured_date:\s?(.*?)\s?#}\s?\n/m; var RE_UPDATED = /^{#\s?wf_updated_on:\s?(.*?)\s?#}\s?\n/m; var RE_PUBLISHED = /^{#\s?wf_published_on:\s?(.*?)\s?#}\s?\n/m; var RE_IMAGE = /^{#\s?wf_featured_image:\s?(.*?)\s?#}\s?\n/m; var RE_IMAGE_SQUARE = /^{#\s?wf_featured_image_square:\s?(.*?)\s?#}\s?\n/m; var RE_BLINK_COMPONENTS = /^{#\s?wf_blink_components:\s?(.*?)\s?#}\s?\n/m; var RE_TAGS = /^{#\s?wf_tags:\s?(.*?)\s?#}\s?\n/m; var RE_SNIPPET = /^{#\s?wf_featured_snippet:\s?(.*?)\s?#}\s?\n/m; var RE_TITLE = /^# (.*) {: \.page-title\s?}/m; var RE_TITLE_CLASS = /{:\s?\.page-title\s?}/gm; var RE_AUTHOR_LIST = /^{%\s?include "web\/_shared\/contributors\/(.*?)\.html"\s?%}\s?\n/gm; var RE_AUTHOR_KEY = /\/contributors\/(.*)\.html"/; var RE_PODCAST = /^{#\s?wf_podcast_audio: (.*?) #}\s?\n/m; var RE_PODCAST_DURATION = /^{#\s?wf_podcast_duration: (.*?)\s?#}\s?\n/m; var RE_PODCAST_SUBTITLE = /^{#\s?wf_podcast_subtitle: (.*?)\s?#}\s?\n/m; var RE_PODCAST_SIZE = /^{#\s?wf_podcast_fileSize: (.*?)\s?#}\s?\n/m; var RE_INCLUDE_MD = /^<<(.*?)>>/gm; var RE_INCLUDE_FILE = /["|'](.*)["|']/; var RE_INCLUDES = /^{%\s?include ["|'](.*)["|']\s?%}/gm; var RE_SINGLE_LINE_COMMENT = /^{%\s?comment\s?%}.*{%\s?endcomment\s?%}$/gm; var RE_MD_INCLUDE = /^{#\s?wf_md_include\s?#}/m; var RE_AUTO_GENERATED = /^{#\s?wf_auto_generated\s?#}/m; var RE_DEVSITE_TRANSLATION = /^{# wf_devsite_translation #}/m; function getMatch(regEx, content, defaultResponse) { var result = content.match(regEx); if (result && result[1]) { return result[1]; } return defaultResponse; } function getMatches(regEx, content) { let results = []; let myArray; while((myArray = regEx.exec(content)) !== null) { results.push(myArray); } return results; } exports.getMatch = getMatch; exports.getMatches = getMatches; exports.RE_BOOK_PATH = RE_BOOK_PATH; exports.RE_PROJECT_PATH = RE_PROJECT_PATH; exports.RE_UPDATED_ON = RE_UPDATED; exports.RE_PUBLISHED_ON = RE_PUBLISHED; exports.RE_DESCRIPTION = RE_DESCRIPTION; exports.RE_BLINK_COMPONENTS = RE_BLINK_COMPONENTS; exports.RE_REGION = RE_REGION; exports.RE_VERTICAL = RE_VERTICAL; exports.RE_FEATURED_DATE = RE_FEATURED_DATE; exports.RE_TITLE = RE_TITLE; exports.RE_TITLE_CLASS = RE_TITLE_CLASS; exports.RE_TAGS = RE_TAGS; exports.RE_IMAGE = RE_IMAGE; exports.RE_IMAGE_SQUARE = RE_IMAGE_SQUARE; exports.RE_SNIPPET = RE_SNIPPET; exports.RE_AUTHOR_LIST = RE_AUTHOR_LIST; exports.RE_AUTHOR_KEY = RE_AUTHOR_KEY; exports.RE_PODCAST = RE_PODCAST; exports.RE_PODCAST_DURATION = RE_PODCAST_DURATION; exports.RE_PODCAST_SUBTITLE = RE_PODCAST_SUBTITLE; exports.RE_PODCAST_SIZE = RE_PODCAST_SIZE; exports.RE_MD_INCLUDE = RE_MD_INCLUDE; exports.RE_INCLUDES = RE_INCLUDES; exports.RE_INCLUDE_MD = RE_INCLUDE_MD; exports.RE_INCLUDE_FILE = RE_INCLUDE_FILE; exports.RE_SINGLE_LINE_COMMENT = RE_SINGLE_LINE_COMMENT; exports.RE_AUTO_GENERATED = RE_AUTO_GENERATED; exports.RE_DEVSITE_TRANSLATION = RE_DEVSITE_TRANSLATION;
/* @flow */ import { connect } from 'react-redux'; import boundActions from '../boundActions'; import { getActiveNarrow, getIsFetching, getIfNoMessages, getUnreadCountInActiveNarrow, } from '../selectors'; import Chat from './Chat'; export default connect( state => ({ isOnline: state.app.isOnline, isFetching: getIsFetching(state), narrow: getActiveNarrow(state), noMessages: getIfNoMessages(state), unreadCount: getUnreadCountInActiveNarrow(state), }), boundActions, )(Chat);
Stevedore.Collections.Documents = Backbone.Collection.extend({ model: Stevedore.Models.Document, });
define( [ 'backbone', 'template!view/page1' ], function( Backbone, template ) { return Backbone.View.extend( { el: 'section#page1', render: function() { // page1.template ํ…œํ”Œ๋ฆฟ์„ ๋ Œ๋”๋งํ•œ ๊ฒฐ๊ณผ๋ฅผ el์˜ ํ•˜๋ถ€์— ์ถ”๊ฐ€ํ•œ๋‹ค. this.$el.html( template() ); return this; }, events: { 'click button.next': 'nextPage' }, nextPage: function() { location.href = '#page2'; } } ); } );
/** * @license * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 */ CLASS({ package: 'foam.util.zip', name: 'LocalFileHeader', extendsModel: 'foam.util.zip.BinaryHeader', imports: [ 'console', 'crc32', 'minimumVersion$ as version$', 'bitFlag$', 'compressionMethod$', 'lastModified$', 'contentCRC32$', 'compressedSize$', 'uncompressedSize$', 'fileNameLength$', 'extraFieldLength$', 'fileName$', 'extraField$', 'fileContents$', ], properties: [ { model_: 'foam.util.zip.BinaryIntProperty', name: 'signature', size: 4, defaultValue: (0x04034b50 | 0), }, { model_: 'foam.util.zip.BinaryIntProperty', name: 'version', offset: 4, }, { model_: 'foam.util.zip.BinaryIntProperty', name: 'bitFlag', offset: 6, }, { model_: 'foam.util.zip.BinaryIntProperty', name: 'compressionMethod', offset: 8, }, { model_: 'foam.util.zip.BinaryIntProperty', name: 'lastModified', size: 4, offset: 10, }, { model_: 'foam.util.zip.BinaryIntProperty', name: 'contentCRC32', size: 4, offset: 14, }, { model_: 'foam.util.zip.BinaryIntProperty', name: 'compressedSize', size: 4, offset: 18, }, { model_: 'foam.util.zip.BinaryIntProperty', name: 'uncompressedSize', size: 4, offset: 22, }, { model_: 'foam.util.zip.BinaryIntProperty', name: 'fileNameLength', offset: 26, }, { model_: 'foam.util.zip.BinaryIntProperty', name: 'extraFieldLength', offset: 28, }, ], methods: [ function size() { return this.binarySize() + this.fileName.length + this.extraField.length; }, function toBuffer() { var binLength = this.binarySize(); var extraFieldOffset = binLength + this.fileName.length; var len = this.size(); var buf = new ArrayBuffer(len); var view = new DataView(buf, 0, len); var i; this.insertHeader(view); for ( i = binLength; i < extraFieldOffset; ++i ) { view.setUint8(i, this.fileName.charCodeAt(i - binLength)); } for ( i = extraFieldOffset; i < len; ++i ) { view.setUint8(i, this.extraField.charCodeAt(i - extraFieldOffset)); } return buf; }, ], });
'use strict'; var _ = require('lodash') , buildConfig = require('./build.config') , config = {} , gulp = require('gulp') , gulpFiles = require('require-dir')('./gulp') , path = require('path') , exec = require('child_process').exec , $, key; $ = require('gulp-load-plugins')({ pattern: [ 'browser-sync', 'del', 'gulp-*', 'karma', 'main-bower-files', 'multi-glob', 'plato', 'run-sequence', 'streamqueue', 'uglify-save-license', 'wiredep', 'yargs' ] }); _.merge(config, buildConfig); config.appComponents = path.join(config.appDir, 'components/**/*'); config.appFiles = path.join(config.appDir, '**/*'); config.appFontFiles = path.join(config.appDir, 'fonts/**/*'); config.appImageFiles = path.join(config.appDir, 'images/**/*'); config.appMarkupFiles = path.join(config.appDir, '**/*.html'); config.appScriptFiles = path.join(config.appDir, '**/*.js'); config.appStyleFiles = path.join(config.appDir, '**/*.css'); config.buildDirectiveTemplateFiles = path.join(config.buildDir, '**/*directive.tpl.html'); config.buildJsFiles = path.join(config.buildJs, '**/*.js'); config.buildTestDirectiveTemplateFiles = path.join(config.buildTestDir, '**/*directive.tpl.html'); config.buildE2eTestsDir = path.join(config.buildTestDir, 'e2e'); config.buildE2eTests = path.join(config.buildE2eTestsDir, '**/*_test.js'); config.buildTestDirectiveTemplatesDir = path.join(config.buildTestDir, 'templates'); config.buildUnitTestsDir = path.join(config.buildTestDir, config.unitTestDir); config.buildUnitTestFiles = path.join(config.buildUnitTestsDir, '**/*_test.js'); config.e2eFiles = path.join('e2e', '**/*.js'); config.unitTestFiles = path.join(config.unitTestDir, '**/*_test.js'); for (key in gulpFiles) { gulpFiles[key](gulp, $, config); } gulp.task('dev', ['build'], function () { gulp.start('browserSync'); gulp.start('watch'); }); gulp.task('default', ['dev']); gulp.task('server', ['build'], function (cb) { exec('node server.js', function (err, stdout, stderr) { console.log(stdout); console.log(stderr); cb(err); }); });
/** * Created by admin on 2017/4/18. */ $(function() { page={ init:function(){ page.aboutUs.init(); }, aboutUs:{ init:function(){ page.aboutUs.nav(); page.aboutUs._link(); page.aboutUs._btn_click(); page.aboutUs._btn_click_p5(); }, nav:function(){ var _link = $(".linkLeft"); var a= 0,b= 1,c=1; $(".linkLeft1").on("click",function(){ if(a==0){ $(".link1").addClass("hide"); $(this).removeClass("bg_yellow") a=1,b= 1,c=1; }else{ $(".link1").removeClass("hide"); $(this).addClass("bg_yellow").siblings().removeClass("bg_yellow"); $(".link2,.link3").addClass("hide"); a=0,b= 1,c=1; } }); $(".linkLeft2").on("click",function(){ if(b==0){ $(".link2").addClass("hide"); $(this).removeClass("bg_yellow") a=1,b= 1,c=1; }else{ $(".link2").removeClass("hide"); $(this).addClass("bg_yellow").siblings().removeClass("bg_yellow"); $(".link1,.link3").addClass("hide"); a=1,b= 0,c=1; } }); $(".linkLeft3").on("click",function(){ if(c==0){ $(".link3").addClass("hide"); $(this).removeClass("bg_yellow") a=1,b= 1,c=1; }else{ $(".link3").removeClass("hide"); $(this).addClass("bg_yellow").siblings().removeClass("bg_yellow"); $(".link1,.link2").addClass("hide"); a=1,b= 1,c=0; } }); }, _link:function(){ var _linkRight = $(".linkRight"); var num; _linkRight.on("click",function(){ _linkRight.removeClass("yellow"); $(this).addClass("yellow"); num = $(this).data("link"); console.log(num) $(".page"+num).removeClass("hide").siblings().addClass("hide") }) }, _btn_click:function(){ $(".page2Left").on("click",function(){ $(".linkTwopage1").removeClass("hide") $(".linkTwopage2").addClass("hide") $(".page2Num").html(1) }) $(".page2right").on("click",function(){ $(".linkTwopage2").removeClass("hide") $(".linkTwopage1").addClass("hide") $(".page2Num").html(2) }) }, _btn_click_p5:function(){ var num=1; $(".page5Left").on("click",function(){ num--; num=num<=1? 1:num; console.log(num) $(".linkFivepage"+num).removeClass("hide").siblings().addClass("hide"); $(".page5Num").html(num) }) $(".page5right").on("click",function(){ num++; num=num>=3? 3:num; console.log(num) $(".linkFivepage"+num).removeClass("hide").siblings().addClass("hide"); $(".page5Num").html(num) }) } } } page.init(); });
///////////////////////////////////////////////////// // Add your custom code here. // This file and any changes you make to it are preserved every time the app is generated. ///////////////////////////////////////////////////// /* global angular */ function factory($q, dsService) { function PersonalfamilyGraphical() { this.scope = null; } PersonalfamilyGraphical.prototype = { /* The resolve method could return arbitrary data, which will be available in the view public controller's constructor as the "stateData" argument and in "onHide" handler as the "customData" argument */ onInit: function($stateParams) { console.log('Init', $stateParams); return {}; }, /* "customData" is the data return by the onInit handler*/ onHide: function(customData) { console.log('hide', customData); } }; return new PersonalfamilyGraphical(); } factory.$inject = ['$q', 'dsService']; export default factory;
// Copyright 2016 SAP SE. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http: //www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific // language governing permissions and limitations under the License. module.exports = function(grunt) { // Project configuration. grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), openui5_preload: { component: { options: { resources: { cwd: '', prefix: 'myDevRequests', src: [ '*.js', '*.json', '*.html', '*/*.js', '*/*.fragment.html', '*/*.fragment.json', '*/*.fragment.xml', '*/*.view.html', '*/*.view.json', '*/*.view.xml', '*/*.properties' ] }, dest: 'preload/', compress: true }, components: true } } }); grunt.loadNpmTasks('grunt-openui5'); }
var _ = require('lib/underscore'); var ppmoreinfo = require('lib/ppmoreinfo') function TestWindow(){ var self = Ti.UI.createWindow({ backgroundColor : 'white', navBarHidden : true, exitOnClose : true, orientationModes: [Ti.UI.LANDSCAPE_LEFT, Ti.UI.LANDSCAPE_RIGHT] }); var temp = 0; var slider = require('lib/slider').createSlider(); var tableData = []; var logoView = Ti.UI.createView({ top: '24dp', height: '70dp', width: '121dp', left : (250/2) - (121/2), backgroundImage: "/images/logo-lrg.png" }); var homeRow = Ti.UI.createTableViewRow({ title : 'Home', }); tableData.push(homeRow); var ppSection = Ti.UI.createTableViewSection({ headerTitle:'Your Propertypond' }); ppSection.add(Ti.UI.createTableViewRow({ title : 'Account', font : { fontSize : 13 } })); ppSection.add(Ti.UI.createTableViewRow({ title : 'My Favorites', font : { fontSize : 13 } })); tableData.push(ppSection); var discoverSection = Ti.UI.createTableViewSection({ headerTitle : 'Discover' }); discoverSection.add(Ti.UI.createTableViewRow({ title : 'Search Rentals', font : { fontSize : 13 } })); tableData.push(discoverSection); var informationSection = Ti.UI.createTableViewSection({ headerTitle : 'Information' }); var count = ppmoreinfo.length; for (var index = 0; index < count; index++) { informationSection.add(Ti.UI.createTableViewRow({ title : ppmoreinfo[index].title, font : { fontSize : 13 } })); // tableData.push({ // title : ppmoreinfo[index].title // }); } slider.addWindow({ createFunction : function(){ var mapWin = Ti.UI.createWindow({ backgroundColor : 'black', title : 'Propertypond' }); if (Ti.Platform.osname == 'android') { }else{ var mountainView = Titanium.Map.createAnnotation({ latitude:37.390749, longitude:-122.081651, title:"Appcelerator Headquarters", subtitle:'Mountain View, CA', pincolor:Titanium.Map.ANNOTATION_RED, animate:true, leftButton: '../images/appcelerator_small.png', myid:1 // Custom property to uniquely identify this annotation. }); var mapview = Titanium.Map.createView({ mapType: Titanium.Map.STANDARD_TYPE, region: {latitude:33.74511, longitude:-84.38993, latitudeDelta:0.01, longitudeDelta:0.01}, animate:true, regionFit:true, userLocation:true, annotations:[mountainView] }); mapWin.add(mapview); // Handle click events on any annotations on this map. mapview.addEventListener('click', function(evt) { Ti.API.info("Annotation " + evt.title + " clicked, id: " + evt.annotation.myid); // Check for all of the possible names that clicksouce // can report for the left button/view. if (evt.clicksource == 'leftButton' || evt.clicksource == 'leftPane' || evt.clicksource == 'leftView') { Ti.API.info("Annotation " + evt.title + ", left button clicked."); } }); } return mapWin; }, rightNavButton : function(){ var filterButton = Titanium.UI.createButton({ title: 'Filter' }); filterButton.addEventListener('click',function(){ alert('For Filter'); }); return filterButton; } }); tableData.push(informationSection); slider.preLoadWindow(0); var table = Ti.UI.createTableView({ rowHeight : '44dp', top : 100 }); discoverSection.addEventListener('click', function(){ slider.addWindow({ createFunction : function(){ var mWin = Ti.UI.createWindow({ backgroundColor : 'white' }); var mView = Ti.UI.createView(); var mLabel = Ti.UI.createLabel({ text : 'HEHEHEHE' }); mView.add(mLabel); mWin.add(mView); return mWin; }, rightNavButton : function(){ var searchButton = Titanium.UI.createButton({ title: 'View Results' }); searchButton.addEventListener('click',function(){ alert('THANK YOU'); }); return searchButton; } }); slider.selectAndClose(1); }); informationSection.addEventListener('click', function(e) { Ti.API.debug('table heard click'); //slider.selectAndClose(e.index); //slider.showNewWindow().open(); console.log(e.index); var InformationDetailWindow = require('ui/handheld/InformationDetailWindow'); var infoWindow = new InformationDetailWindow({ title : ppmoreinfo[e.index - 4].title, content : ppmoreinfo[e.index - 4].content }).open(); }); table.setData(tableData); table.addEventListener('click', function(e){ if (e.index == 0) { slider.selectAndClose(0); } else return; }); logoView.addEventListener('click',function(){ slider.selectAndClose(0); }); self.add(logoView); self.add(table); self.add(slider); var started = false; self.addEventListener('open', function() { /* Wierd - open event on baseWindow gets fired every time slider fires event 'open'. Using started variabled to make sure this only gets run once */ if (!started) { slider.showWindow(0); started = true; } }); function listenForBackButton() { slider.back(); } slider.addEventListener('open', function() { Ti.API.debug('baseWindow heard open'); self.removeEventListener('android:back', listenForBackButton); }); slider.addEventListener('close', function() { Ti.API.debug('baseWindow heard close'); self.addEventListener('android:back', listenForBackButton); }); return self; } module.exports = TestWindow;
// Copyright 2013 Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000, there is a non-exclusive license for use of this work by or on behalf of the U.S. Government. Export of this program may require a license from the United States Government. $(document).ready(function(){ var rv = new ResetValidator(); $('#set-password-form').ajaxForm({ beforeSubmit : function(formData, jqForm, options){; rv.hideAlert(); if (rv.validatePassword($('#pass-tf').val()) == false){ return false; } else{ return true; } }, success : function(responseText, status, xhr, $form){ rv.showSuccess("Your password has been reset."); setTimeout(function(){ window.location.href = '/'; }, 3000); }, error : function(){ rv.showAlert("I'm sorry something went wrong, please try again."); } }); $('#set-password').modal('show'); $('#set-password').on('shown', function(){ $('#pass-tf').focus(); }) });
/* * Copyright (c) 2013 Adobe Systems Incorporated. All rights reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ define([], function (require) { var Backbone = require('backbone'), AppEvent; AppEvent = _.clone(Backbone.Events); return AppEvent; });
"use strict"; var chakram = require("chakram"), mongoose = require("mongoose"), Q = require("q"), patients = require("../../patients/common.js"); var expect = chakram.expect; describe("Medications", function () { describe("Cascade Delete Medication", function () { // setup a test user and patient var patient; before(function () { return patients.testMyPatient({}).then(function (p) { patient = p; }); }); // setup a test doctor and pharmacy var doctorId, pharmacyId; before(function () { return Q.nbind(patient.createDoctor, patient)({ name: "test doctor" }).then(function (d) { doctorId = d._id; }); }); before(function () { return Q.nbind(patient.createPharmacy, patient)({ name: "test pharmacy" }).then(function (p) { pharmacyId = p._id; }); }); // setup test medication for that doctor and pharmacy var medication; before(function () { return Q.nbind(patient.createMedication, patient)({ name: "test medication", doctorId: doctorId, pharmacyId: pharmacyId }).then(function (m) { medication = m; }); }); // setup test dose and journal entry for that medication var entryId, doseId; before(function () { return Q.nbind(patient.createJournalEntry, patient)({ date: {utc: (new Date()).toISOString(), timezone: "America/Los_Angeles"}, text: "example journal entry", creator: "[email protected]", medication_ids: [medication._id] }).then(function (e) { entryId = e._id; }); }); before(function () { return Q.nbind(patient.createDose, patient)({ medication_id: medication._id, date: {utc: (new Date()).toISOString(), timezone: "America/Los_Angeles"}, creator: "[email protected]", taken: true }).then(function (d) { doseId = d._id; }); }); // functions to try and retrieve that pharmacy, doctor, dose and journal entry // and check for their existence var Patient = mongoose.model("Patient"); var resourceExists = function (collectionName, wantedId) { return Q.npost(Patient, "findOne", [{ _id: patient._id }]).then(function (p) { return !!p[collectionName].filter(function (e) { return e._id === wantedId; })[0]; }); }; var entryExists = function () { return resourceExists("entries", entryId); }; var doseExists = function () { return resourceExists("doses", doseId); }; var doctorExists = function () { return resourceExists("doctors", doctorId); }; var pharmacyExists = function () { return resourceExists("pharmacies", pharmacyId); }; describe("initially", function () { it("has a dose", function () { return expect(doseExists()).to.be.true; }); it("has an entry", function () { return expect(entryExists()).to.be.true; }); it("has a doctor", function () { return expect(doctorExists()).to.be.true; }); it("has a pharmacy", function () { return expect(pharmacyExists()).to.be.true; }); }); describe("after deleting the medication", function () { before(function () { return Q.npost(patient, "findMedicationByIdAndDelete", [medication._id]); }); it("has no dose", function () { return expect(doseExists()).to.be.false; }); it("has no entry", function () { return expect(entryExists()).to.be.false; }); it("has a doctor", function () { return expect(doctorExists()).to.be.true; }); it("has a pharmacy", function () { return expect(pharmacyExists()).to.be.true; }); }); }); });
var test = require('tape'); var createSignaller = require('..'); var uuid = require('cuid'); var runTest = module.exports = function(messenger, peers) { var s; var altScopes; test('create', function(t) { t.plan(2); t.ok(s = createSignaller(messenger), 'created'); t.ok(s.id, 'have id'); }); test('change the signaller id', function(t) { t.plan(1); s.id = uuid.v4(); t.pass('signaller id updated'); }); test('convert other peers to signaller scopes', function(t) { t.plan(peers.length); altScopes = peers.map(createSignaller); altScopes.forEach(function(peer) { t.ok(typeof altScopes.request, 'function', 'have a request function'); }) }); test('targeted announce', function(t) { t.plan(1); peers.first().expect(t, '/to|' + altScopes[0].id + '|/announce|{"id":"' + s.id + '"}'); s.to(altScopes[0].id).announce(); }); test('targetted announce captured at the scope level', function(t) { t.plan(2); function announceOne(data) { t.deepEqual({ id: s.id }, data); } function announceTwo(data) { t.fail('should not have captured data'); } altScopes[0].once('announce', announceOne); altScopes[1].once('announce', announceTwo); setTimeout(function() { altScopes[1].removeListener('announce', announceTwo); t.pass('did not capture announce event at second scope'); }, 500); s.to(altScopes[0].id).announce(); }); test('disconnect', function(t) { t.plan(2); peers.expect(t, '/leave|{"id":"' + s.id + '"}'); s.leave(); }); }; if (typeof document == 'undefined' && (! module.parent)) { var peers = require('./helpers/createPeers')(3); runTest(peers.shift(), peers); }
// competitions model var mongoose = require('mongoose'); var Schema = mongoose.Schema; var Competition = new Schema({ id: Number, name: String, own: Boolean, place: String, date: Date, description: String, report: [String, String, Boolean], done: Boolean, comments: [{message: String, username: String}], members: Array }); module.exports = mongoose.model('competition', Competition);
/** * @license Copyright 2016 Google Inc. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ 'use strict'; const EventEmitter = require('events').EventEmitter; const log = require('lighthouse-logger'); const LHError = require('../../lib/errors'); /** * @typedef {LH.StrictEventEmitter<{'protocolevent': LH.Protocol.RawEventMessage}>} CrdpEventMessageEmitter * @typedef {LH.CrdpCommands[keyof LH.CrdpCommands]['paramsType']} CommandParamsTypes * @typedef {LH.CrdpCommands[keyof LH.CrdpCommands]['returnType']} CommandReturnTypes */ class Connection { constructor() { this._lastCommandId = 0; /** @type {Map<number, {resolve: function(Promise<CommandReturnTypes>), method: keyof LH.CrdpCommands, options: {silent?: boolean}}>} */ this._callbacks = new Map(); /** @type {?CrdpEventMessageEmitter} */ this._eventEmitter = new EventEmitter(); } /** * @return {Promise<void>} */ connect() { return Promise.reject(new Error('Not implemented')); } /** * @return {Promise<void>} */ disconnect() { return Promise.reject(new Error('Not implemented')); } /** * @return {Promise<string>} */ wsEndpoint() { return Promise.reject(new Error('Not implemented')); } /* eslint-disable no-unused-vars */ /** * @param {string} message * @protected */ sendRawMessage(message) { throw new Error('Not implemented'); } /* eslint-enable no-unused-vars */ /** * @param {string} message * @return {void} * @protected */ handleRawMessage(message) { const object = /** @type {LH.Protocol.RawMessage} */(JSON.parse(message)); // Responses to commands carry "id" property, while events do not. if (!('id' in object)) { // tsc doesn't currently narrow type in !in branch, so manually cast. const eventMessage = /** @type {LH.Protocol.RawEventMessage} */(object); log.formatProtocol('<= event', {method: eventMessage.method, params: eventMessage.params}, 'verbose'); this.emitProtocolEvent(eventMessage); return; } const callback = this._callbacks.get(object.id); if (callback) { this._callbacks.delete(object.id); // @ts-ignore since can't convince compiler that callback.resolve's return // type and object.result are matching since only linked by object.id. return callback.resolve(Promise.resolve().then(_ => { if (object.error) { const logLevel = callback.options.silent ? 'verbose' : 'error'; log.formatProtocol('method <= browser ERR', {method: callback.method}, logLevel); throw LHError.fromProtocolMessage(callback.method, object.error); } log.formatProtocol('method <= browser OK', {method: callback.method, params: object.result}, 'verbose'); return object.result; })); } else { // In DevTools we receive responses to commands we did not send which we cannot act on, so we // just log these occurrences. const error = object.error && object.error.message; log.formatProtocol(`disowned method <= browser ${error ? 'ERR' : 'OK'}`, {method: 'UNKNOWN', params: error || object.result}, 'verbose'); } } /** * @param {LH.Protocol.RawEventMessage} eventMessage */ emitProtocolEvent(eventMessage) { if (!this._eventEmitter) { throw new Error('Attempted to emit event after connection disposed.'); } this._eventEmitter.emit('protocolevent', eventMessage); } /** * @protected */ dispose() { if (this._eventEmitter) { this._eventEmitter.removeAllListeners(); this._eventEmitter = null; } } } // Declared outside class body because function expressions can be typed via more expressive @type /** * Bind listeners for connection events * @type {CrdpEventMessageEmitter['on']} */ Connection.prototype.on = function on(eventName, cb) { if (eventName !== 'protocolevent') { throw new Error('Only supports "protocolevent" events'); } if (!this._eventEmitter) { throw new Error('Attempted to add event listener after connection disposed.'); } this._eventEmitter.on(eventName, cb); }; /** * Looser-typed internal implementation of `Connection.sendCommand` which is * strictly typed externally on exposed Connection interface. See * `Driver.sendCommand` for explanation. * @type {(this: Connection, method: keyof LH.CrdpCommands, params?: CommandParamsTypes, cmdOpts?: {silent?: boolean}) => Promise<CommandReturnTypes>} */ function _sendCommand(method, params = {}, cmdOpts = {}) { /* eslint-disable no-invalid-this */ log.formatProtocol('method => browser', {method, params}, 'verbose'); const id = ++this._lastCommandId; const message = JSON.stringify({id, method, params}); this.sendRawMessage(message); return new Promise(resolve => { this._callbacks.set(id, {resolve, method, options: cmdOpts}); }); /* eslint-enable no-invalid-this */ } /** * Call protocol methods. * @type {LH.Protocol.SendCommand} */ Connection.prototype.sendCommand = _sendCommand; module.exports = Connection;
button_f2_onclick = function () { efgrid.submitInqu( "ef_grid_result", "ed","EI10","query"); } button_f3_onclick = function () { efgrid.submitForm( "ef_grid_result", "ed","EI10","update",true ); } button_f4_onclick = function () { efgrid.submitForm( "ef_grid_result", "ed","EI10","delete", true ); } button_f6_onclick = function () { efgrid.submitForm( "ef_grid_result", "ed","EI10","insert",true ); }