text
stringlengths
2
6.14k
// Based on https://github.com/alexdavid/scope-eval v0.0.3 // (source: https://unpkg.com/scope-eval@0.0.3/scope_eval.js) // This is basically just a wrapper around new Function() function scopeEval(source, scope) { var keys = []; var values = []; for (var key in scope) { if (Object.prototype.hasOwnProperty.call(scope, key)) { keys.push(key); values.push(scope[key]); } } keys.push(source); return Function.apply(null, keys).apply(null, values); } export default scopeEval;
/** * Session Configuration * (sails.config.session) * * Sails session integration leans heavily on the great work already done by * Express, but also unifies Socket.io with the Connect session store. It uses * Connect's cookie parser to normalize configuration differences between Express * and Socket.io and hooks into Sails' middleware interpreter to allow you to access * and auto-save to `req.session` with Socket.io the same way you would with Express. * * For more information on configuring the session, check out: * http://sailsjs.org/#!/documentation/reference/sails.config/sails.config.session.html */ module.exports.session = { /*************************************************************************** * * * Session secret is automatically generated when your new app is created * * Replace at your own risk in production-- you will invalidate the cookies * * of your users, forcing them to log in again. * * * ***************************************************************************/ secret: '714996e16116b6e48b46eb0766b53d4d', /*************************************************************************** * * * Set the session cookie expire time The maxAge is set by milliseconds, * * the example below is for 24 hours * * * ***************************************************************************/ // cookie: { // maxAge: 24 * 60 * 60 * 1000 // }, /*************************************************************************** * * * Uncomment the following lines to set up a Redis session store that can * * be shared across multiple Sails.js servers. * * * * Requires connect-redis (https://www.npmjs.com/package/connect-redis) * * * ***************************************************************************/ adapter: 'redis', /*************************************************************************** * * * The following values are optional, if no options are set a redis * * instance running on localhost is expected. Read more about options at: * * * * https://github.com/visionmedia/connect-redis * * * ***************************************************************************/ host: process.env.REDIS_HOST || 'localhost', // port: 6379, // ttl: <redis session TTL in seconds>, // db: 0, // pass: <redis auth password>, // prefix: 'sess:', /*************************************************************************** * * * Uncomment the following lines to set up a MongoDB session store that can * * be shared across multiple Sails.js servers. * * * * Requires connect-mongo (https://www.npmjs.com/package/connect-mongo) * * Use version 0.8.2 with Node version <= 0.12 * * Use the latest version with Node >= 4.0 * * * ***************************************************************************/ // adapter: 'mongo', // url: 'mongodb://user:password@localhost:27017/dbname', // user, password and port optional /*************************************************************************** * * * Optional Values: * * * * See https://github.com/kcbanner/connect-mongo for more * * information about connect-mongo options. * * * * See http://bit.ly/mongooptions for more information about options * * available in `mongoOptions` * * * ***************************************************************************/ // collection: 'sessions', // stringify: true, // mongoOptions: { // server: { // ssl: true // } // } };
/** * Copyright 2013-2021 the original author or authors from the JHipster project. * * This file is part of the JHipster project, see https://www.jhipster.tech/ * for more information. * * 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. */ module.exports = { writeFiles, }; function writeFiles() { const suffix = 'k8s'; return { writeDeployments() { for (let i = 0; i < this.appConfigs.length; i++) { const appName = this.appConfigs[i].baseName.toLowerCase(); const appOut = appName.concat('-', suffix); this.app = this.appConfigs[i]; this.template('deployment.yml.ejs', `${appOut}/${appName}-deployment.yml`); this.template('service.yml.ejs', `${appOut}/${appName}-service.yml`); // If we choose microservice with no DB, it is trying to move _no.yml as prodDatabaseType is getting tagged as 'string' type if (this.app.prodDatabaseType !== 'no') { this.template(`db/${this.app.prodDatabaseType}.yml.ejs`, `${appOut}/${appName}-${this.app.prodDatabaseType}.yml`); } if (this.app.searchEngine === 'elasticsearch') { this.template('db/elasticsearch.yml.ejs', `${appOut}/${appName}-elasticsearch.yml`); } if (this.app.applicationType === 'gateway' || this.app.applicationType === 'monolith') { if (this.istio) { this.template('istio/gateway.yml.ejs', `${appOut}/${appName}-gateway.yml`); } else if (this.kubernetesServiceType === 'Ingress') { this.template('ingress.yml.ejs', `${appOut}/${appName}-ingress.yml`); } } if (!this.app.serviceDiscoveryType && this.app.authenticationType === 'jwt') { this.template('secret/jwt-secret.yml.ejs', `${appOut}/jwt-secret.yml`); } if (this.monitoring === 'prometheus') { this.template('monitoring/jhipster-prometheus-sm.yml.ejs', `${appOut}/${appName}-prometheus-sm.yml`); } if (this.istio) { this.template('istio/destination-rule.yml.ejs', `${appOut}/${appName}-destination-rule.yml`); this.template('istio/virtual-service.yml.ejs', `${appOut}/${appName}-virtual-service.yml`); } } }, writeReadme() { this.template('README-KUBERNETES.md.ejs', 'K8S-README.md'); }, writeNamespace() { if (this.kubernetesNamespace !== 'default') { this.template('namespace.yml.ejs', 'namespace.yml'); } }, writeMessagingBroker() { if (!this.useKafka) return; this.template('messagebroker/kafka.yml.ejs', `messagebroker-${suffix}/kafka.yml`); }, writePrometheusGrafanaFiles() { const monitOut = 'monitoring'.concat('-', suffix); if (this.monitoring === 'prometheus') { this.template('monitoring/jhipster-prometheus-crd.yml.ejs', `${monitOut}/jhipster-prometheus-crd.yml`); this.template('monitoring/jhipster-prometheus-cr.yml.ejs', `${monitOut}/jhipster-prometheus-cr.yml`); this.template('monitoring/jhipster-grafana.yml.ejs', `${monitOut}/jhipster-grafana.yml`); this.template('monitoring/jhipster-grafana-dashboard.yml.ejs', `${monitOut}/jhipster-grafana-dashboard.yml`); if (this.istio) { this.template('istio/gateway/jhipster-grafana-gateway.yml.ejs', `${monitOut}/jhipster-grafana-gateway.yml`); } } }, writeRegistryFiles() { const registryOut = 'registry'.concat('-', suffix); if (this.serviceDiscoveryType === 'eureka') { this.template('registry/jhipster-registry.yml.ejs', `${registryOut}/jhipster-registry.yml`); this.template('registry/application-configmap.yml.ejs', `${registryOut}/application-configmap.yml`); } else if (this.serviceDiscoveryType === 'consul') { this.template('registry/consul.yml.ejs', `${registryOut}/consul.yml`); this.template('registry/consul-config-loader.yml.ejs', `${registryOut}/consul-config-loader.yml`); this.template('registry/application-configmap.yml.ejs', `${registryOut}/application-configmap.yml`); } }, writeConfigRunFile() { this.template('kubectl-apply.sh.ejs', 'kubectl-apply.sh'); }, writeObservabilityGatewayFiles() { if (!this.istio) return; const istioOut = 'istio'.concat('-', suffix); this.template('istio/gateway/grafana-gateway.yml.ejs', `${istioOut}/grafana-gateway.yml`); this.template('istio/gateway/zipkin-gateway.yml.ejs', `${istioOut}/zipkin-gateway.yml`); this.template('istio/gateway/kiali-gateway.yml.ejs', `${istioOut}/kiali-gateway.yml`); }, writeKustomize() { const patchOut = 'patch'.concat('-', suffix); this.template('kustomize/kustomization.yml.ejs', 'kustomization.yml'); if (this.istio) { this.template('kustomize/patch/istio-label.yml.ejs', `${patchOut}/istio-label.yml`); this.template('kustomize/patch/istio-namespace.yml.ejs', `${patchOut}/istio-namespace.yml`); } }, writeSkaffold() { this.template('skaffold/skaffold.yml.ejs', 'skaffold.yml'); }, }; }
#!/usr/bin/env node /* global exit */ require('shelljs/global'); require('colors'); var async = require('async'), ESLintCLIEngine = require('eslint').CLIEngine, /** * The list of source code files / directories to be linted. * * @type {Array} */ LINT_SOURCE_DIRS = [ './bin', './lib', './test', './npm/*.js', './index.js' ]; module.exports = function (exit) { // banner line console.info('\nLinting files using eslint...'.yellow.bold); async.waterfall([ /** * Instantiates an ESLint CLI engine and runs it in the scope defined within LINT_SOURCE_DIRS. * * @param {Function} next - The callback function whose invocation marks the end of the lint test run. * @returns {*} */ function (next) { next(null, (new ESLintCLIEngine()).executeOnFiles(LINT_SOURCE_DIRS)); }, /** * Processes a test report from the Lint test runner, and displays meaningful results. * * @param {Object} report - The overall test report for the current lint test. * @param {Object} report.results - The set of test results for the current lint run. * @param {Function} next - The callback whose invocation marks the completion of the post run tasks. * @returns {*} */ function (report, next) { var errorReport = ESLintCLIEngine.getErrorResults(report.results); // log the result to CLI console.info(ESLintCLIEngine.getFormatter()(report.results)); // log the success of the parser if it has no errors (errorReport && !errorReport.length) && console.info('eslint ok!'.green); // ensure that the exit code is non zero in case there was an error next(Number(errorReport && errorReport.length) || 0); } ], exit); }; // ensure we run this script exports if this is a direct stdin.tty run !module.parent && module.exports(exit);
(function () { 'use strict'; angular.module('pnc.common', [ 'pnc.common.directives', 'pnc.common.pnc-client' ]); })();
document.write("this is de_DE sample.js<br>");
/** * Created by maoli on 16/9/3. */ var mongoose = require('mongoose'); var settings = require('../../settings'); var autoIncrement = require('mongoose-auto-increment'); //自增ID 模块 autoIncrement.initialize(mongoose.connection); //初始化 //schema var addFailPatientSchema = new mongoose.Schema({ "id" : String, "StudyID" : String, //研究编号 "SiteID" : String,//中心编号 "ScreenYN" : Number,//筛选结果 "ExcludeStandards" : Array,//入排标准 "SubjID" : String,//受试者流水号 "USubjectID" : String,//受试者编号 "SubjectDOB" : String,//受试者出生日期 "SubjectSex" : String,//受试者性别 "SubjectIn" : String,//受试者姓名缩写 "isOut" : String,//是否完成或退出 'DSSTDAT' : Date, //导入时间 }); addFailPatientSchema.plugin(autoIncrement.plugin, { model: 'Books', field: 'id', startAt: 0, incrementBy: 1 }); //索引 addFailPatientSchema.index({ "Date": 1}); //查找该研究中该手机号是否使用 addFailPatientSchema.statics.chazhaomouyanjiushouji = function (SubjMP,callback) { if (SubjMP.length == 0){ //参数错误 callback({ 'isSucceed' : 200, 'msg' : 'StudyID参数错误' },null) return; }else{ //取出该研究中的所有分仓库 this.model('addFailPatient').find({SubjMP : SubjMP},callback) } } //查找某研究某中心所有失败用户 addFailPatientSchema.statics.chazhaomouyanjiumouzhongxin = function (SiteID,StudyID,callback) { if (SiteID.length == 0){ //参数错误 callback({ 'isSucceed' : 200, 'msg' : 'StudyID参数错误' },null) return; }else{ //取出该研究中的所有分仓库 this.model('addFailPatient').find({SiteID : SiteID,StudyID : StudyID},callback) } } //model var addFailPatient = mongoose.model("addFailPatient",addFailPatientSchema); module.exports = addFailPatient;
//// [instanceSubtypeCheck2.ts] class C1<T> { x: C2<T>; } class C2<T> extends C1<T> { x: string } //// [instanceSubtypeCheck2.js] var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } __.prototype = b.prototype; d.prototype = new __(); }; var C1 = (function () { function C1() { } return C1; })(); var C2 = (function (_super) { __extends(C2, _super); function C2() { _super.apply(this, arguments); } return C2; })(C1);
/** * @description FormSubtract SVG Icon. * @property {string} a11yTitle - Accessibility Title. If not set uses the default title of the status icon. * @property {string} colorIndex - The color identifier to use for the stroke color. * If not specified, this component will default to muiTheme.palette.textColor. * @property {xsmall|small|medium|large|xlarge|huge} size - The icon size. Defaults to small. * @property {boolean} responsive - Allows you to redefine what the coordinates. * @example * <svg width="24" height="24" ><path d="M6,12 L18,12"/></svg> */ // (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import CSSClassnames from '../../../utils/CSSClassnames'; import Intl from '../../../utils/Intl'; import Props from '../../../utils/Props'; const CLASS_ROOT = CSSClassnames.CONTROL_ICON; const COLOR_INDEX = CSSClassnames.COLOR_INDEX; export default class Icon extends Component { render () { const { className, colorIndex } = this.props; let { a11yTitle, size, responsive } = this.props; let { intl } = this.context; const classes = classnames( CLASS_ROOT, `${CLASS_ROOT}-form-subtract`, className, { [`${CLASS_ROOT}--${size}`]: size, [`${CLASS_ROOT}--responsive`]: responsive, [`${COLOR_INDEX}-${colorIndex}`]: colorIndex } ); a11yTitle = a11yTitle || Intl.getMessage(intl, 'form-subtract'); const restProps = Props.omit(this.props, Object.keys(Icon.propTypes)); return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="none" stroke="#000" strokeWidth="2" d="M6,12 L18,12"/></svg>; } }; Icon.contextTypes = { intl: PropTypes.object }; Icon.defaultProps = { responsive: true }; Icon.displayName = 'FormSubtract'; Icon.icon = true; Icon.propTypes = { a11yTitle: PropTypes.string, colorIndex: PropTypes.string, size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']), responsive: PropTypes.bool };
/*eslint-env mocha, node*/ import * as random from '../lib/random.js' var assert = require('assert') describe('Random module', function() { it('seed', () => { random.seed(1) assert(Math.abs(random.random() - 0.177) < 0.01) }) it('sample', () => { let sample = random.sample([1,2], 2) assert.equal(sample.length, 2) assert.equal(sample[0] + sample[1], 3) }) })
// Copyright 2020 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. 'use strict' const i = require('./../index.js') const c = i.constants const u = i.utils const constructors = {} const construct = (data, context) => { const functionToCall = i.evaluate(data.Z7K1, context) if (functionToCall.Z4K2 === undefined) { return i.error(c.error.NO_CONSTRUCTOR, functionToCall.Z1K2) } const keys = i.delistify(functionToCall.Z4K2) const callLength = Object.keys(data).length - 2 if (keys.length !== callLength) { return i.error(c.error.ARITY_MISMATCH, [keys.length, callLength]) } const typename = functionToCall.Z4K1 const constructor = u.load(constructors, __dirname, typename.Z9K1) if (constructor !== null) { // TODO the code in this conditional should go once all constructors // are internalized for (let argument in data) { if (u.zid(argument) === c.OBJECT) continue if (u.zid(argument) === c.FUNCTION_CALL) continue let stringData = i.evaluate(data[argument]) if (stringData.Z1K1 === c.STRING) { const text = stringData.Z6K1 const result = constructor.construct(text) return i.validate(result) } } } const result = { Z1K1: functionToCall.Z1K2 } for (let n = 0; n < keys.length; n++) { const kid = 'K' + (n + 1) const zkid = result.Z1K1 + kid const value = i.evaluate(data[kid]) if (value.Z1K2 === c.NOTHING) continue result[zkid] = value } return i.validate(result) } exports.construct = construct
/* Copyright 2019 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 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 crypto = require('crypto'); const express = require('express'); const fetch = require('node-fetch'); const logger = require('../logger'); const createShortLinkURL = process.CREATE_SHORT_LINK_URL || 'https://us-central1-serverless-io-19.cloudfunctions.net/createShortLink'; const router = express.Router(); /* handle /link. */ router.use('/', async (req, res, next) => { let {url, shortlink} = req.body; if (!url) { const err = new Error('need to include "url" parameter'); err.status = 400; return next(err); } if (url.search(/https?:\/\//) !== 0) { const err = new Error('Cannot shorten invalid URL. Must start with http(s)://'); err.status = 400; return next(err); } if (shortlink && shortlink.search(/^[^!@#$%^&*()+=\[\]{}\\\/:;"'<,>.?]+$/)) { const err = new Error('Invalid shortlink. Cannot use special characters.'); err.status = 400; return next(err); } if (!shortlink) { shortlink = crypto.createHash('sha256') .update(url) .digest('hex') .slice(0,5); } const orgin = `${req.hostname}/${shortlink}`; if (url.includes(orgin)) { const err = new Error('Nice try you clever dan. Recursion is not supported'); err.status = 400; return next(err); } try { logger.info(`creating shortlink: ${shortlink} for url: ${url}`); const response = await fetch(`${createShortLinkURL}?shortlink=${shortlink}&longlink=${url}`); const message = await response.text(); if (response.status !== 200) { const err = new Error(message) err.status = response.status; return next(err); } let result; if (process.env.NODE_ENV === 'production') { result = `https://${req.hostname}/${shortlink}`; } else { const {port} = res.app.locals; result = `http://${req.hostname}:${port}/${shortlink}`; } logger.info(`shortlink: ${result} created for url: ${url}`); res.render('link', { title: 'Success!', url: result }); } catch (e) { next(e) } }); module.exports = router;
(function() { angular.module('appControllers') .controller('U04Controller', ['$scope', '$sce', 'AppService', function($scope, $sce, AppService) { this.update = function() { AppService.getData($scope, 'uj', 'uj-detail', {'resource': $scope.resource}) .then(function(data) { $scope.ucetniJednotka = data["@graph"][0]; $scope.vizuri = $sce.trustAsResourceUrl("http://demo.visualization.linkedpipes.com/api/v1/datacube/custom/210/21c1627f69b4956467936459f98c902a?view=chart&chartType=column&isPolar=false&disableTitle=true&dimensionUri=http://linked.opendata.cz/ontology/application/mfcrapp/rozpocty/refArea&valueUri=" + $scope.ucetniJednotka.okres[0]['@id']); AppService.setTitle("Účetní jednotka " + $scope.ucetniJednotka["prefLabel"]); }); }; AppService.init($scope, ['resource'], this.update); }]); })();
/* * Copyright 2012 Amadeus s.a.s. * 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. */ /** * Default interface for an embed controller */ Aria.interfaceDefinition({ $classpath : "aria.embed.IEmbedController", $interface : { /** * Called when the widget is being displayed * @param {HTMLElement} domContainer Container of this embed based widget * @param {Object} args arguments given in the embed Element widget */ onEmbeddedElementCreate : function (domContainer, arg) {}, /** * Called when the widget is being disposed * @param {HTMLElement} domContainer Container of this embed based widget * @param {Object} args arguments given in the embed Element widget */ onEmbeddedElementDispose : function (domContainer, arg) {} } });
var red = "red", green = "rgb(27,242,0)", orange = "orange"; $(document).ready(function() { var socket = io.connect('http://' + window.location.hostname); socket.on('connect', function() { $(".connection").html('<i class="glyphicon glyphicon-ok" style="color:' + green + ';"></i>'); if (localStorage.me === undefined || localStorage.me === "") { var name = prompt("Geef mij een naam"); localStorage.me = name; socket.emit("me", name); } else { socket.emit("me", localStorage.me); } }); socket.on('connecting', function() { $(".connection").html('<i class="glyphicon glyphicon-minus"></i>'); $(".ssh").html(''); }); socket.on('connect_failed', function() { $(".connection").html('<i class="glyphicon glyphicon-remove" style="color:' + red + ';"></i>'); $(".ssh").html(''); }); socket.on('disconnect', function() { $(".connection").html('<i class="glyphicon glyphicon-remove" style="color:' + red + ';"></i>'); $(".ssh").html(''); }); socket.on('switches', function(data) { var html = "<div class=\"row\">"; $.each(data, function(x, y) { var color = red; if (y.state === 1) { color = green; } html += '<div class="col-md-3"><a class="switch well" id="switch-' + x + '" style="background:' + color + '"><h3><span class="' + y.icon + '"></span> ' + y.name + '</h3></a></div>'; }); $(".switches").html(html + "</div>"); $(".switch").each(function() { $(this).click(function(e) { e.preventDefault(); $(this).css({ "background": orange }); socket.emit("switch", { id: $(this).attr("id").replace("switch-", "") }); }); }); }); socket.on("clients", function(data) { data = JSON.parse(data); console.log(data); var html = ""; $.each(data, function(x, y) { var color = red; if (y === true) { color = green; } if (x != "") html += '<span class="device well" id="device-' + x + '" style="background:' + color + '">' + x + '</span>'; }); $(".clients").html(html); }); socket.on("devices", function(data) { console.log(data); var html = ""; $.each(data, function(x, y) { var color = red; if (y.state === 1) { color = green; } html += '<span class="device well" id="device-' + x + '" style="background:' + color + '"><span class="' + y.icon + '"></span> ' + y.name + '</span>'; }); $(".devices").html(html); }); socket.on("deviceChange", function(data) { console.log(data); var color = red; if (data.state === 1) { color = green; } $("#device-" + data.id).css({ "background": color }); }); socket.on("switched", function(data) { var color = red; if (data. switch.state === 1) { color = green; } $("#switch-" + data.id).css({ "background": color }); }); socket.on("log", function(data) { console.log("LOG", data); var log = ""; var i = 0; $.each(data, function(x, y) { if (i < 50) { log = '<p class="l">' + y.time + ': ' + y.action + '</p>' + log; } i++; }); $(".log").html(log); }); socket.on("logAdd", function(y) { console.log("logAdd", y); $(".log").prepend('<p class="l">' + y.time + ': ' + y.action + '</p>'); }); socket.on("state", function(data) { if (data.ssh) { $(".ssh").html('<i class="glyphicon glyphicon-ok" style="color:' + green + ';"></i>'); } else { $(".ssh").html('<i class="glyphicon glyphicon-remove" style="color:' + red + ';"></i>'); } }); });
resonate .createBodyComponent() .as(function (component) { var adjectives = ["pretty", "large", "big", "small", "tall", "short", "long", "handsome", "plain", "quaint", "clean", "elegant", "easy", "angry", "crazy", "helpful", "mushy", "odd", "unsightly", "adorable", "important", "inexpensive", "cheap", "expensive", "fancy"]; var colors = ["red", "yellow", "blue", "green", "pink", "brown", "purple", "brown", "white", "black", "orange"]; var nouns = ["table", "chair", "house", "bbq", "desk", "car", "pony", "cookie", "sandwich", "burger", "pizza", "mouse", "keyboard"]; var adjectivesCount = adjectives.length; var colorsCount = colors.length; var nounsCount = nouns.length; var random = function (max) { return Math.round(Math.random() * 1000) % max; }; var nextId = 1; var createData = function (count) { var data = new Array(count); for (var i = 0; i < count; i++) { data[i] = { id: nextId++, label: adjectives[random(adjectivesCount)] + ' ' + colors[random(colorsCount)] + ' ' + nouns[random(nounsCount)] }; } return BindingArray.createFrom(data); }; component.data = []; component.selected = -1; component.run = function () { component.data = createData(1000); }; component.runLots = function () { component.data = createData(10000); }; component.add = function () { var appended = createData(1000); for (var i = 0; i < appended.length; i++) { component.data.push(appended[i]); } }; component.update = function () { var data = component.data; for (var i = 0; i < data.length; i += 10) { data[i].label += ' !!!'; } }; component.clear = function () { component.data = []; }; component.swapRows = function () { var data = component.data; if (data.length > 998) { var temp = data[1]; data[1] = data[998]; data[998] = temp; } }; component.removeRow = function (index) { component.data.splice(index, 1); }; component.selectRow = function (index) { component.selected = index; }; }); resonate.initialize();
module.exports = { "tags": [ { "type": "param", "string": "{number} stepdownSecs=60 The number of seconds to step down the primary, during which time the stepdown member is ineligible for becoming primary. If you specify a non-numeric value, the command uses 60 seconds.", "name": "stepdownSecs=60", "description": "The number of seconds to step down the primary, during which time the stepdown member is ineligible for becoming primary. If you specify a non-numeric value, the command uses 60 seconds.", "types": [ "number" ], "typesDescription": "<code>number</code>", "optional": false, "nullable": false, "nonNullable": false, "variable": false }, { "type": "param", "string": "{number} [catchUpSecs] The number of seconds that the mongod will wait for an electable secondary to catch up to the primary.", "name": "[catchUpSecs]", "description": "The number of seconds that the mongod will wait for an electable secondary to catch up to the primary.", "types": [ "number" ], "typesDescription": "<code>number</code>", "optional": true, "nullable": false, "nonNullable": false, "variable": false }, { "type": "param", "string": "{boolean} [options.force=false] A boolean that determines whether the primary steps down if no electable and up-to-date secondary exists within the wait period.", "name": "[options.force=false]", "description": "A boolean that determines whether the primary steps down if no electable and up-to-date secondary exists within the wait period.", "types": [ "boolean" ], "typesDescription": "<code>boolean</code>", "optional": true, "nullable": false, "nonNullable": false, "variable": false }, { "type": "return", "string": "{object} returns the result of the replSetStepDown command", "types": [ "object" ], "typesDescription": "<code>object</code>", "optional": false, "nullable": false, "nonNullable": false, "variable": false, "description": "returns the result of the replSetStepDown command" } ], "description": { "full": "Remove a node from the replicaset", "summary": "Remove a node from the replicaset", "body": "" }, "isPrivate": false, "isConstructor": false, "isClass": false, "isEvent": false, "ignore": false, "line": 114, "codeStart": 122, "code": "stepDown(stepdownSecs = 60, catchUpSecs, options = {}) {\n if (!typeof stepdownSecs == 'number') throw new Error(`stepdownSecs must a number`);\n const command = { replSetStepDown: stepdownSecs };\n if (typeof catchUpSecs == 'number') {\n command['secondaryCatchUpPeriodSecs'] = catchUpSecs;\n }\n\n const admin = this.state.client.db('admin');\n return admin.command(command);\n}", "ctx": { "type": "method", "name": "stepDown", "string": "stepDown()" } }
/*global jQuery, setTimeout, _ */ jQuery.fn.collaboratorSpeechBubbleWidget = function (collaborationModel, timeoutArg) { 'use strict'; var timeout = timeoutArg || 3000; return this.each(function () { var element = jQuery(this), currentCollaborator, showCollaborator = function () { collaborationModel.showCollaborator(currentCollaborator); }, img = element.find('[data-mm-role=collaborator-photo]'), contentTemplate = element.find('[data-mm-role=popover-content-template]').detach(), titleTemplate = element.find('[data-mm-role=popover-title-template]').detach(), popoverContent = function (message, style) { var template = contentTemplate.clone(); template.find('[data-mm-role=popover-content]').text(message); if (style) { template.find('[data-mm-role=popover-content]').addClass(style); } return template.html(); }, popoverTitle = function (nodeTitle) { titleTemplate.find('[data-mm-role=popover-title]').text(nodeTitle); return titleTemplate.html(); }, showSpeechBubble = _.throttle(function (collaborator, message, style) { currentCollaborator = collaborator; img.popover('destroy'); img.attr('src', collaborator.photoUrl); img.css('border-color', collaborator.color); img.popover({ title: popoverTitle(collaborator.name), content: popoverContent(message, style), placement: 'right', trigger: 'manual', animation: true, html: true }); element.fadeIn(200, function () { setTimeout(function () { img.popover('destroy'); element.fadeOut(); }, timeout); }); img.popover('show'); }, timeout + 700, {trailing: false}), onEdit = function (collaborator, node) { var trimmedTitle = node && node.title && node.title.trim(), style = trimmedTitle ? '' : 'muted', nodeTitle = trimmedTitle || 'removed node content'; showSpeechBubble(collaborator, nodeTitle, style); }, onJoin = function (collaborator) { showSpeechBubble(collaborator, 'joined the session', 'muted'); }, onLeave = function (collaborator) { showSpeechBubble(collaborator, 'left the session', 'muted'); }; img.on('click tap', showCollaborator); collaborationModel.addEventListener('collaboratorDidEdit', onEdit); collaborationModel.addEventListener('collaboratorJoined', onJoin); collaborationModel.addEventListener('collaboratorLeft', onLeave); }); };
const path = require('path'); const CopyPlugin = require('copy-webpack-plugin'); // vue.config.js module.exports = { devServer: { port: 3000 }, configureWebpack: { plugins: [ // Copy over media resources from the Blockly package new CopyPlugin([ { from: path.resolve(__dirname, './node_modules/blockly/media'), to: path.resolve(__dirname, 'dist/media') } ]) ] } }
/* Copyright (c) 2004-2009, The Dojo Foundation All Rights Reserved. Available via Academic Free License >= 2.1 OR the modified BSD license. see: http://dojotoolkit.org/license for details */ if(!dojo._hasResource["dojox.encoding.crypto._base"]){dojo._hasResource["dojox.encoding.crypto._base"]=true;dojo.provide("dojox.encoding.crypto._base");(function(){var c=dojox.encoding.crypto;c.cipherModes={ECB:0,CBC:1,PCBC:2,CFB:3,OFB:4,CTR:5};c.outputTypes={Base64:0,Hex:1,String:2,Raw:3};})();}
(function(){ var $users = function($http, $cookieStore, $transformRequestToForm, $upload, appConstants){ var factory = {}; //SIGNUP factory.signup = function(email, password){ return $http({ method: 'POST', url: appConstants.server + appConstants.context + 'rest/auth/register', headers: {'Content-Type': 'application/x-www-form-urlencoded'}, transformRequest: $transformRequestToForm.transformRequest, data: {email: email, password: password} }) } //LOGOUT factory.logout = function(){ return $http({ method: 'POST', url: appConstants.server + appConstants.context + 'rest/auth/logout', headers: {'Content-Type': 'application/x-www-form-urlencoded', service_key: 'webkey:' + $cookieStore.get('email'), auth_token: $cookieStore.get('auth_token')}, }); }; //LOGIN factory.login = function(user){ return $http({ method: 'POST', url: appConstants.server + appConstants.context + 'rest/auth/login', headers: {'Content-Type': 'application/x-www-form-urlencoded', service_key: 'webkey:' + user.email}, transformRequest: $transformRequestToForm.transformRequest, data: {email: user.email, password: user.password} }); }; //LOAD INTEREST factory.loadInterests = function(){ return $http({ method: 'GET', url: appConstants.server + appConstants.context + 'rest/users/'+$cookieStore.get('user_id')+'/interests', headers: {'Content-Type': 'application/x-www-form-urlencoded', service_key: 'webkey:' + $cookieStore.get('email'), auth_token: $cookieStore.get('auth_token')}, transformRequest: $transformRequestToForm.transformRequest, data: {} }); } factory.updateInterests = function(selectedInterests){ return $http({ method: 'POST', url: appConstants.server + appConstants.context + 'rest/users/'+$cookieStore.get('user_id')+"/interests/update", headers: {'Content-Type': 'application/x-www-form-urlencoded', service_key: 'webkey:' + $cookieStore.get('email'), auth_token: $cookieStore.get('auth_token')}, transformRequest: $transformRequestToForm.transformRequest, data: { interests: JSON.stringify(selectedInterests)} }) }; //CREATE PROFILE factory.createProfile = function(){ return $http({ method: 'POST', url: appConstants.server + appConstants.context + 'rest/users/new', headers: {'Content-Type': 'application/x-www-form-urlencoded', service_key: 'webkey:' + $cookieStore.get('email'), auth_token: $cookieStore.get('auth_token')}, transformRequest: $transformRequestToForm.transformRequest, data: {user_id: $cookieStore.get('user_id')} }) }; //GET PROFILE factory.getProfile = function(){ return $http({ method: 'GET', url: appConstants.server + appConstants.context + 'rest/users/' + $cookieStore.get('user_id'), headers: {'Content-Type': 'application/x-www-form-urlencoded', service_key: 'webkey:' + $cookieStore.get('email'), auth_token: $cookieStore.get('auth_token')}, transformRequest: $transformRequestToForm.transformRequest, data: {} }); }; //UPDATE PROFILE factory.updateProfile = function(username, location, bio){ return $http({ method: 'POST', url: appConstants.server + appConstants.context + 'rest/users/' + $cookieStore.get('user_id') + '/update', headers: {'Content-Type': 'application/x-www-form-urlencoded', service_key: 'webkey:' + $cookieStore.get('email'), auth_token: $cookieStore.get('auth_token')}, transformRequest: $transformRequestToForm.transformRequest, data: {username: username, location: location, bio: bio}, }); }; //UPLOAD AVATAR factory.uploadAvatar = function(file) { return $upload.upload({ url: appConstants.server + appConstants.context + 'rest/users/' + $cookieStore.get('user_id') + '/avatar/upload', method: 'POST', headers: {'Content-Type': 'multipart/form-data', service_key: 'webkey:' + $cookieStore.get('email'), auth_token: $cookieStore.get('auth_token')}, file: file, }) }; return factory; }; $users.$inject = ['$http','$cookieStore','$transformRequestToForm', '$upload', 'appConstants']; angular.module("clubhouse").factory("$users",$users); }());
/** * Copyright 2020 The Google Earth Engine Community 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. */ /** * @fileoverview Earth Engine Developer's Guide examples * from 'Joins - Inner toy example' section */ // [START earthengine__joins03__toy_inner] // Create the primary collection. var primaryFeatures = ee.FeatureCollection([ ee.Feature(null, {foo: 0, label: 'a'}), ee.Feature(null, {foo: 1, label: 'b'}), ee.Feature(null, {foo: 1, label: 'c'}), ee.Feature(null, {foo: 2, label: 'd'}), ]); // Create the secondary collection. var secondaryFeatures = ee.FeatureCollection([ ee.Feature(null, {bar: 1, label: 'e'}), ee.Feature(null, {bar: 1, label: 'f'}), ee.Feature(null, {bar: 2, label: 'g'}), ee.Feature(null, {bar: 3, label: 'h'}), ]); // Use an equals filter to specify how the collections match. var toyFilter = ee.Filter.equals({ leftField: 'foo', rightField: 'bar' }); // Define the join. var innerJoin = ee.Join.inner('primary', 'secondary'); // Apply the join. var toyJoin = innerJoin.apply(primaryFeatures, secondaryFeatures, toyFilter); // Print the result. print('Inner join toy example:', toyJoin); // [END earthengine__joins03__toy_inner]
define("Ti/UI/View", ["Ti/_/declare", "Ti/_/dom", "Ti/_/UI/Element", "Ti/_/lang", "Ti/_/string", "Ti/_/Layouts"], function(declare, dom, Element, lang, string, Layouts) { return declare("Ti.UI.View", Element, { _parent: null, constructor: function() { this.children = []; this.layout = "absolute"; this.containerNode = this.domNode; }, add: function(view) { view._parent = this; this.children.push(view); this.containerNode.appendChild(view.domNode); Ti.UI._doFullLayout(); }, remove: function(view) { var i = 0, l = this.children.length; for (; i < l; i++) { if (this.children[i] === view) { this.children.splice(i, 1); break; } } dom.detach(view.domNode); Ti.UI._doFullLayout(); }, destroy: function() { var i = 0, l = this.children.length; for (; i < l; i++) { this.children[i].destroy(); } Element.prototype.destroy.apply(this, arguments); }, _defaultWidth: "100%", _defaultHeight: "100%", properties: { layout: { set: function(value) { var match = value.toLowerCase().match(/^(horizontal|vertical)$/), value = match ? match[0] : "absolute"; if (this._layout) { this._layout.destroy(); this._layout = null; } this._layout = new Layouts[string.capitalize(value)](this); return value; } } } }); });
/* * Copyright 2019 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ const $ = require('jquery'); const CONSTANTS = require('helpers/constants'); const setHeaders = (xhr, version) => { xhr.setRequestHeader("Content-Type", "application/json"); xhr.setRequestHeader("Accept", mrequest.versionHeader(version)); xhr.setRequestHeader("X-GoCD-Confirm", "true"); const csrfToken = $('meta[name=csrf-token]').attr('content'); if (csrfToken) { xhr.setRequestHeader('X-CSRF-Token', csrfToken); } }; const mrequest = { timeout: CONSTANTS.SPA_REQUEST_TIMEOUT, globalAjaxErrorHandler: () => { $(document).ajaxError((_event, jqXHR) => { if (jqXHR.status === 401) { window.location.pathname = CONSTANTS.AUTH_LOGIN_PATH; } }); }, versionHeader(version) { return `application/vnd.go.cd.${version}+json`; }, xhrConfig: { v1: (xhr) => { setHeaders(xhr, 'v1'); }, v2: (xhr) => { setHeaders(xhr, 'v2'); }, v3: (xhr) => { setHeaders(xhr, 'v3'); }, v4: (xhr) => { setHeaders(xhr, 'v4'); }, forVersion: (version) => (xhr) => { setHeaders(xhr, version); } }, unwrapMessageOrEntity: (type, originalEtag) => (data, xhr) => { if (xhr.status === 200) { const entity = type.fromJSON(data); entity.etag(xhr.getResponseHeader('ETag')); return entity; } if (xhr.status === 422 && !!data.data) { const fromJSON = new type.fromJSON(data.data); fromJSON.etag(originalEtag); return fromJSON; } else { return mrequest.unwrapErrorExtractMessage(data, xhr); } }, unwrapMessage: (data) => { if (data && data.message) { return data.message; } }, unwrapErrorExtractMessage: (data, xhr, defaultMessage = "There was an unknown error performing the operation") => { if (mrequest.unwrapMessage(data)) { return mrequest.unwrapMessage(data); } else { if (xhr && xhr.status === 0) { return `There was an unknown error performing the operation. Possible reason (${xhr.statusText})`; } else { return defaultMessage; } } } }; module.exports = mrequest;
import Vue from 'vue' import Vuex from 'vuex' import VueRouter from 'vue-router' import VueFilter from 'vue-filter' import VueResource from 'vue-resource' //登录注册、修密忘记 import join from './components/join.vue' import login from './components/login.vue' import register from './components/register.vue' import password from './components/password.vue' import forget from './components/forget.vue' //入驻 import steps from './components/steps.vue' import joined from './components/joined.vue' //控制面板 import dashboard from './components/dashboard.vue' import ordersRouter from './components/ordersRouter.vue' import user from './components/user.vue' import datas from './components/datas.vue' import charts from './components/charts.vue' //商品 import goods from './components/goods/goods.vue' import good from './components/goods/good.vue' //单购 import orders from './components/orders/orders.vue' import order from './components/orders/order.vue' import ship from './components/orders/ship.vue' //拼团 import tuanPending from './components/tuans/pending.vue' import tuanOrders from './components/tuans/orders.vue' import tuanOrder from './components/tuans/order.vue' import tuanShip from './components/tuans/ship.vue' //订单 import pendings from './components/orders/pendings.vue' import pending from './components/orders/pending.vue' import tuans from './components/orders/tuans.vue' import tuan from './components/orders/tuan.vue' //提现 import cash from './components/cash/cash.vue' import income from './components/cash/income.vue' import withdraws from './components/cash/withdraws.vue' import withdrawing from './components/cash/withdrawing.vue' import withdraw from './components/cash/withdraw.vue' //测试页面 import test from './components/test.vue' //配置 import config from './config' Vue.use(Vuex) Vue.use(VueFilter) Vue.use(VueResource) Vue.use(VueRouter) var App = Vue.extend({}) const router = new VueRouter({ saveScrollPosition: true }) router.map({ '/join': { component: join, gust: true }, '/login': { component: login, gust: true }, '/register': { component: register, gust: true }, '/forget': { component: forget, gust: true }, '/password': { component: password }, '/steps': { component: steps }, '/joined': { component: joined }, '/dashboard': { component: dashboard }, '/ordersRouter': { component: ordersRouter }, '/user': { component: user }, '/datas': { component: datas }, '/datas/charts/:id': { component: charts }, '/goods': { component: goods }, '/goods/:id': { component: good }, '/tuans/orders': { component: tuanOrders }, '/tuans/orders/:id': { component: tuanOrder }, '/tuans/orders/:id/ship': { component: tuanShip }, '/tuans/orders/pendings/:id': { component: tuanPending }, '/orders': { component: orders }, '/orders/:id': { component: order }, '/orders/:id/ship': { component: ship }, '/orders/pendings': { component: pendings }, '/orders/pendings/:id': { component: pending }, '/shop/tuans': { component: tuans }, '/shop/tuans/:id': { component: tuan }, '/cash': { component: cash }, '/cash/income': { component: income }, '/cash/withdraws': { component: withdraws }, '/cash/withdrawing': { component: withdrawing }, //旧路径 '/cash/withdraw/:id':{component:withdraw}, '/cash/withdraws/:id': { component: withdraw }, '/test': { component: test } }) router.redirect({ '/': '/login', '*': '/login' }) Vue.config.debug = false router.beforeEach((transition) => { let token = localStorage.getItem('token') if (!transition.to.gust && (!token || token === null)) { localStorage.setItem('targetUrl',window.location.href) router.go('/login') }else if(transition.to.gust && token != null){ if (localStorage.getItem('nowStep')==null) { router.go('/dashboard') }else if ((localStorage.getItem('nowStep')*1)<3) { router.go('/steps') }else{ router.go('/dashboard') } } //是否开启debug模式 localStorage.setItem('debug',Vue.config.debug) Vue.http.headers.common['Authorization'] = 'Bearer ' + token; transition.next() }); router.start(App, '#app') /* eslint-disable no-new */ // new Vue({ // el: '#app', // components: { join } // }) // 创建一个对象来保存应用启动时的初始状态 const state = { // TODO: 放置初始状态 } // 创建一个对象存储一系列我们接下来要写的 mutation 函数 const mutations = { // TODO: 放置我们的状态变更函数 } // 整合初始状态和变更函数,我们就得到了我们所需的 store // 至此,这个 store 就可以连接到我们的应用中 export default new Vuex.Store({ state, mutations }) Vue.http.options.root = 'http://'+config.server.host // Vue.http.headers.common['Authorization'] = 'Bearer ' + localStorage.getItem('token')
define(function () { var config = null function create (_config) { config = _config createTableTag() } function createTableTag () { var html = document.createElement("table") html.id = config.idTable $(html).addClass("table table-bordered table-striped") $(html).append(createHeader()) $("#"+config.placeAt).html(html); } function createHeader () { var head = document.createElement("thead") var tr = document.createElement("tr") for (var i = 0 ; i< config.columns.length; i++) $(tr).append(createColumnHeader(config.columns[i])) $(head).append(tr); return head } function createColumnHeader (column) { var th = document.createElement("th") $(th).css("width", column.width) $(th).html(column.label) return th; } function fill (data) { clear() var tbody = document.createElement("tbody") for (var i = 0 ; i < data.length ; i++) $(tbody).append(createRow(data, i)) $("#"+config.idTable).append(tbody) } function createRow (data, rowIndex) { var tr = document.createElement("tr") for (var j = 0 ; j < config.columns.length ; j++) { var td = document.createElement("td") var content = createOtherCellContent(j, data[rowIndex]); if (content == null) content = data[rowIndex][config.columns[j].field]; $(td).html(content) $(tr).append(td) } return tr } function createOtherCellContent (columnIndex, row) { var columnConfig = config.columns[columnIndex] var content = null if (isButton (columnIndex, columnConfig, row)) content = createButtonContent(columnIndex, columnConfig, row) else if (isCustomContent(columnConfig.customContent)) content = getCustomContent(columnIndex, columnConfig, row) return content } function createButtonContent (columnIndex, columnConfig, row) { var button = document.createElement("button") button.className = "btn " + columnConfig.className; button.innerHTML = getContentLabel(columnIndex, columnConfig, row) $(button).on("click", function () { columnConfig.onClick(row) }) return button; } function isButton (columnIndex, columnConfig, row) { if (typeof columnConfig.isButton == 'function') return columnConfig.isButton (row, columnIndex) else return columnConfig.isButton } function getContentLabel (columnIndex, columnConfig, row) { if (typeof columnConfig.contentLabel == 'function') return columnConfig.contentLabel (row, columnIndex) else return columnConfig.contentLabel } function isCustomContent (customContent) { return typeof customContent == 'function' || customContent != null } function getCustomContent (columnIndex, columnConfig, row) { if (typeof columnConfig.customContent == 'function') return columnConfig.customContent (row, columnIndex) else return columnConfig.customContent } function clear () { $("#"+config.idTable).find('tbody').remove(); } return { create : create, fill : fill, clear : clear } });
/********************************************************************/ /* */ /* Copyright (C) 2004 Arash Dejkam, All Rights Reserved. */ /* http://www.tracewatch.com */ /* */ /* Please read the licence file distributed with this */ /* file or the one available at tracewatch.com for */ /* the terms under which you can use or modify this file. */ /* */ /********************************************************************/ function ProgressBar() { this.value = 0; this.channelId = Math.floor( Math.random() * 0x7FFFFFFF ); this.ArdeComponent( 'span' ); this.setDisplayMode( 'inline-block' ); this.style( 'width', '200px' ).style( 'height', '15px' ).style( 'border', '1px solid #000' ).style( 'background', '#fff' ); this.indicator = new ArdeComponent( 'span' ).setDisplayMode( 'inline-block' ).appendTo( this ); this.indicator.style( 'height', '15px' ).style( 'width', '0' ).style( 'background', '#080' ); this.indicator.append( new ArdeImg( baseUrl + 'img/dummy.gif', null, 1, 1 ) ); var self = this; this.requester = new ArdeStdRequester(); this.requester.resultReceived = function ( result ) { self.receive( result ); } } ProgressBar.prototype.startPoll = function( recUrl ) { this.recUrl = recUrl; var self = this; this.interval = setInterval( function () { self.poll(); }, 500 ); } ProgressBar.prototype.stopPoll = function () { clearInterval( this.interval ); } ProgressBar.prototype.poll = function () { if( this.requester.isInProgress() ) { return; } this.requester.request( this.recUrl, 'ch='+this.channelId, ProgressResult ); } ProgressBar.prototype.receive = function ( result ) { if( result.num <= this.value ) return; this.value = result.num; this.indicator.style( 'width', ( result.num * 100 )+'%' ); } ArdeClass.extend( ProgressBar, ArdeComponent ); function ProgressResult( num ) { this.num = num; } ProgressResult.fromXml = function( element ) { return new ProgressResult( ArdeXml.floatContent( element ) ); }
if(!dojo._hasResource["tests.string"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code. dojo._hasResource["tests.string"] = true; dojo.provide("tests.string"); dojo.require("dojo.string"); tests.register("tests.string", [ function test_string_pad(t){ t.is("00001", dojo.string.pad("1", 5)); t.is("000001", dojo.string.pad("000001", 5)); t.is("10000", dojo.string.pad("1", 5, null, true)); }, function test_string_substitute(t){ t.is("File 'foo.html' is not found in directory '/temp'.", dojo.string.substitute( "File '${0}' is not found in directory '${1}'.", ["foo.html","/temp"] ) ); t.is("File 'foo.html' is not found in directory '/temp'.", dojo.string.substitute( "File '${name}' is not found in directory '${info.dir}'.", { name: "foo.html", info: { dir: "/temp" } } ) ); // Verify that an error is thrown! t.assertError(Error, dojo.string, "substitute", ["${x}", {y:1}]); }, function test_string_substitute_transform(t){ var getPrefix = function(str){ // try to figure out the type var prefix = (str.charAt(0) == "/") ? "directory": "file"; if(this.____prefix){ prefix = this.____prefix + prefix; } return prefix + " '" + str + "'"; } var obj = { ____prefix: "...", getPrefix: getPrefix }; t.is("file 'foo.html' is not found in directory '/temp'.", dojo.string.substitute( "${0} is not found in ${1}.", ["foo.html","/temp"], getPrefix ) ); t.is("...file 'foo.html' is not found in ...directory '/temp'.", dojo.string.substitute( "${0} is not found in ${1}.", ["foo.html","/temp"], obj.getPrefix, obj ) ); }, function test_string_substitute_formatter(t){ t.is("thinger -- howdy", dojo.string.substitute( "${0:postfix}", ["thinger"], null, { postfix: function(value, key){ return value + " -- howdy"; } } ) ); }, function test_string_trim(t){ t.is("astoria", dojo.string.trim(" \f\n\r\t astoria ")); t.is("astoria", dojo.string.trim("astoria ")); t.is("astoria", dojo.string.trim(" astoria")); t.is("astoria", dojo.string.trim("astoria")); t.is("a", dojo.string.trim(" a ")); }, function test_string_rep(t){ t.is("aaaaa", dojo.string.rep("a", 5)); t.is("abababab", dojo.string.rep("ab", 4)); t.is("", dojo.string.rep("ab", 0)); t.is("", dojo.string.rep("", 3)); } ] ); }
$(document).ready(function () { var actors = new Bloodhound({ datumTokenizer: Bloodhound.tokenizers.whitespace, queryTokenizer: Bloodhound.tokenizers.whitespace, prefetch: '/actors', }); // passing in `null` for the `options` arguments will result in the default // options being used $('#actor').typeahead(null, { name: 'actors', source: actors, }); // Find the Bacon number var ajaxRequest = []; $('form').on('submit', function (e) { e.preventDefault(); var graphDataContainer = $('#graph-data').parent().parent().parent(); var graphVisContainer = $('#the-graph').parent().parent(); var queryContainer = $('#query').parent().parent().parent().parent(); // Loading spinner var loadingSpinner = '<i class="fa fa-spinner fa-spin"></i>'; $('#graph-data, #query, #the-graph, #bacon-number').html(loadingSpinner); var actorName = $('#actor').val(); var url = '/bacon/' + actorName; traversal.addActor(actorName); // Reset All Paths traversal.resetAllPaths(); if ($('#showall').is(':checked')) { url = url + '/showall'; traversal.allPaths(); } $('#query').html(traversal.annotated()); $('[data-toggle="tooltip"]').tooltip(); if (queryContainer.hasClass('hidden')) { queryContainer.removeClass('hidden'); } if (ajaxRequest.length > 0) { ajaxRequest[0].abort(); } ajaxRequest.push($.get(url, function (data) { console.log(data); // $('#query').html(data.query); $('#graph-data').html(JSON.stringify(data.data, null, 4)); if (graphDataContainer.hasClass('hidden')) { graphDataContainer.removeClass('hidden'); graphVisContainer.removeClass('hidden'); } var rawNodes = []; var ignoreNodes = []; var rawEdges = []; var ignoreEdges = []; var baconNumber = 0; var tempBaconNumber = 0; for (i = 0; i < data.data.length; i++) { var path = data.data[i].objects; var tempBaconNumber = 0; for (j = 0; j < path.length; j++) { var obj = path[j]; if (obj.type == 'vertex') { if (ignoreNodes.indexOf(obj.id) < 0) { var nodeObject = { id: obj.id, label: obj.properties.name[0].value, shape: 'circle', }; if (obj.label == 'film') { nodeObject.color = { background:'#41D6C3', border:'#713E7F', color: '#FFFFFF', highlight:{ background:'red', border:'black', }, }; } if (obj.label == 'person' && obj.properties.name[0].value == 'Kevin Bacon') { nodeObject.shape = 'circularImage'; nodeObject.image = 'http://www.nigelfarndale.com/wp-content/uploads/2013/11/kevin-bacon-0808-medium-new.jpg'; } else if (obj.label == 'person' && obj.properties.name[0].value == actorName) { nodeObject.color = { background:'#00B4A0', }; } rawNodes.push(nodeObject); ignoreNodes.push(obj.id); } if (obj.label == 'person') { tempBaconNumber++; } } if (obj.type == 'edge') { if (ignoreEdges.indexOf(obj.id) < 0) { rawEdges.push({ from: obj.outV, to: obj.inV, }); ignoreEdges.push(obj.id); } } } // Check for shortest bacon! if (tempBaconNumber > 0) { if (baconNumber == 0 && tempBaconNumber > 0) { baconNumber = tempBaconNumber; } if (tempBaconNumber < baconNumber) { baconNumber = tempBaconNumber; } } } console.log(rawNodes); // create an array with nodes var nodes = new vis.DataSet(rawNodes); // create an array with edges var edges = new vis.DataSet(rawEdges); // create a network var container = document.getElementById('the-graph'); var data = { nodes: nodes, edges: edges, }; var options = {}; var network = new vis.Network(container, data, options); // Apply the Bacon Number $('#bacon-number').html('<strong>' + (baconNumber - 1) + '</strong>'); })); }); });
/** * Cookie plugin * * Copyright (c) 2006 Klaus Hartl (stilbuero.de) * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * */ /** * Create a cookie with the given name and value and other optional parameters. * * @example $.cookie('the_cookie', 'the_value'); * @desc Set the value of a cookie. * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true }); * @desc Create a cookie with all available options. * @example $.cookie('the_cookie', 'the_value'); * @desc Create a session cookie. * @example $.cookie('the_cookie', null); * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain * used when the cookie was set. * * @param String name The name of the cookie. * @param String value The value of the cookie. * @param Object options An object literal containing key/value pairs to provide optional cookie attributes. * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object. * If a negative value is specified (e.g. a date in the past), the cookie will be deleted. * If set to null or omitted, the cookie will be a session cookie and will not be retained * when the the browser exits. * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie). * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie). * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will * require a secure protocol (like HTTPS). * @type undefined * * @name $.cookie * @cat Plugins/Cookie * @author Klaus Hartl/klaus.hartl@stilbuero.de */ /** * Get the value of a cookie with the given name. * * @example $.cookie('the_cookie'); * @desc Get the value of a cookie. * * @param String name The name of the cookie. * @return The value of the cookie. * @type String * * @name $.cookie * @cat Plugins/Cookie * @author Klaus Hartl/klaus.hartl@stilbuero.de */ jQuery.cookie = function(name, value, options) { if (typeof value != 'undefined') { // name and value given, set cookie options = options || {}; if (value === null) { value = ''; //options = $.extend({}, options); // clone object since it's unexpected behavior if the expired property were changed options.expires = -1; } var expires = ''; if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) { var date; if (typeof options.expires == 'number') { date = new Date(); date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000)); } else { date = options.expires; } expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE } // NOTE Needed to parenthesize options.path and options.domain // in the following expressions, otherwise they evaluate to undefined // in the packed version for some reason... var path = options.path ? '; path=' + (options.path) : ''; var domain = options.domain ? '; domain=' + (options.domain) : ''; var secure = options.secure ? '; secure' : ''; document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join(''); } else { // only name given, get cookie var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } };
Ext.define('gov.va.cprs.CPRSReportModel', { extend: 'Ext.data.Model', fields: [ {name: 'c1', type: 'string'}, {name: 'c2', type: 'string'}, {name: 'c3', type: 'string'}, {name: 'c4', type: 'string'}, {name: 'c5', type: 'string'}, {name: 'c6', type: 'string'}, {name: 'c7', type: 'string'}, {name: 'c8', type: 'string'}, {name: 'c9', type: 'string'}, {name: 'c10', type: 'string'}, {name: 'c11', type: 'string'}, {name: 'c12', type: 'string'}, {name: 'c13', type: 'string'}, {name: 'c14', type: 'string'}, {name: 'c15', type: 'string'}, {name: 'c16', type: 'string'}, {name: 'c17', type: 'string'}, {name: 'c18', type: 'string'}, {name: 'c19', type: 'string'}, {name: 'c20', type: 'string'} ] });
var vso = require('vso-node-api'); var Q = require('q'); var handler = vso.getBasicHandler('ddd', 'ddd'); var serverUrl = 'https://ddd.visualstudio.com/DefaultCollection'; var handlers = [handler]; //var build = new vso.WebApi(serverUrl, handlers); var webapim = require('vso-node-api/WebApi'); var taskagent = new webapim.WebApi(serverUrl, handlers).getTaskAgentApi(); // var defs = build.getDefinitions('GeneralGit', 'foo'); var buildagent = new webapim.WebApi(serverUrl, handlers).getBuildApi(); var buildClient = new webapim.WebApi(serverUrl, handler).getQBuildApi(); var bd = buildClient.getDefinitions('GeneralGit').then( function(foo){ console.log(foo); var thing = { id : foo[0].id, name : foo[0].name, url : foo[0].url, projectId : foo[0].project.id } var buildDefinition = foo[0]; console.log('your project is ' + thing.url); var buildz = buildClient.getDefinition(thing.id, thing.projectId) .then(function(build){ /// TODO: work out what the bug here is.. the call to queueBuild is nfg. var sd = { "definition": { "id": build.id }, "sourceBranch": "master" } buildClient.queueBuild(sd, build.project.name, true) .then(function(err, status, b2){ console.log(b2); }) .fail(function(err){ console.error('failed to queue', err); }) }) .fail(function(err){ console.error('failed on get build', err); }) }).fail( function(err){ console.error('failed', err); }); console.log('done');
//Default Theme var baseFont = "helvetica"; module.exports = { "Global" : { "backgroundColor" : "#000", "dropShadowColor" : "#000", "separatorColor" :"#aaa", "opacity" : 0.9 }, "NavBar" : { "color" : "#fff", "font" : "helvetica", "fontSize" : 22, "fontWeight" : "normal", "buttonWidth" : 32, "buttonHeight" : 32 }, "LocationRow" : { "backgroundColor" : "#000", "selectedBackgroundColor" : "#ddd", "font" : "helvetica", "fontSize" : 12, "color" : "#fff", "distanceFont" : "helvetica", "distanceFontSize" : 10, "distanceColor" : "#000" }, "AddressBar" : { "backgroundColor" : "#000", "font" : "helvetica", "color" : "#fff", "fontSize" : 14 }, "LocationDetail" : { "ButtonFont" : "helvetica", "color" : "#fff", "ButtonFontSize" : 14, "ButtonColor" : "orange", "ButtonBackgroundColor" : "#eee", "ButtonSeparatorColor" : "#999", "ActionButtonIconWidth" : 24, "ActionButtonIconHeight" : 24 }, "icons" : { "collapse" : "/images/icons/collapse.png", "add" : "/images/icons/add.png", "pin" : "/images/icons/pin.png", "share" : "/images/icons/share.png", "map" : "/images/icons/map.png", "back" : "/images/icons/back-button.png", "mail" : "/images/icons/mail.png", "action" : "/images/icons/action.png" } };
module.exports = function (ctr) { ctr.create('.box-1', { background: 'red' }); return ctr; };
var Player = function(videoNode){ // initialize controllers this.videoController = null; this.audioController = null; this.manifestLoader = null; this.videoModel = videoNode; this.manifestModel = null; this.mediasource = this.getMediaSource(); // ici on attache la mediaSource à la balise video this.videoModel.src = window.URL.createObjectURL(this.mediasource); }; Player.prototype.getMediaSource = function() { var MediaSource = window.MediaSource || window.WebKitMediaSource || null; if(MediaSource){ return new MediaSource(); }else{ return null; } }; Player.prototype.load = function(url) { this.manifestLoader = new ManifestLoader(); var deferred = Q.defer(); this.manifestLoader.load(url).then((function(manifest){ this.manifestModel = manifest; this.mediasource.duration = this.manifestModel.mediaPresentationDuration; this.setSource("video",this.manifestModel.videoSet); this.setSource("audio",this.manifestModel.audioSet); deferred.resolve(manifest); }).bind(this)); return deferred.promise; }; Player.prototype.play = function(videoQualityId, audioQualityId) { // si les 2 objet existent, on peut créer les différents sourcebuffer if(this.manifestModel && this.mediasource){ var videoRepresentation = this.manifestModel.getRepresentation("video",videoQualityId); var audioRepresentation = this.manifestModel.getRepresentation("audio",audioQualityId); var videoCodec = this.manifestModel.videoSet.mimeType + ';codecs="'+ videoRepresentation.codecs+'"'; var audioCodec = this.manifestModel.audioSet.mimeType + ';codecs="'+ audioRepresentation.codecs+'"'; //test du support avant l'initialization if(this.videoModel.canPlayType(videoCodec) === "probably"){ if(!this.videoController.buffer){ this.videoController.initialize(this.mediasource.addSourceBuffer(videoCodec),videoRepresentation); }else{ this.videoController.updateRepresentation(videoRepresentation); } }else{ alert("impossible de lire le codec suivant "+ videoCodec); } if(this.videoModel.canPlayType(audioCodec) === "probably"){ if(!this.audioController.buffer){ this.audioController.initialize(this.mediasource.addSourceBuffer(audioCodec),audioRepresentation); }else{ this.audioController.updateRepresentation(audioRepresentation); } }else{ alert("impossible de lire le codec suivant "+ audioCodec); } } }; Player.prototype.setSource= function(type, adaptationSet) { if(type === "video"){ this.videoController = new BufferController(type,adaptationSet,this.manifestModel); } if(type === "audio"){ this.audioController = new BufferController(type,adaptationSet,this.manifestModel); //this.audioController.setBuffer(this.mediasource.addSourceBuffer(codec)); } // here put text };
const utils = require('./utils'); const EARTH_RADIUS = utils.EARTH_RADIUS; const MIN_LAT = utils.MIN_LAT; const MAX_LAT = utils.MAX_LAT; const MIN_LNG = utils.MIN_LNG; const MAX_LNG = utils.MAX_LNG; const toDegrees = require('./to-degrees'); const toRad = require('./to-rad'); module.exports = (position, distance) => { var minLat, maxLat, minLng, maxLng; var deltaLng; var radDist = distance / EARTH_RADIUS; var radLat = toRad(position.lat), radLng = toRad(position.lng); minLat = radLat - radDist; maxLat = radLat + radDist; if (minLat > MIN_LAT && maxLat < MAX_LAT) { deltaLng = Math.asin(Math.sin(radDist) / Math.cos(radLat)); minLng = radLng - deltaLng; if (minLng < MIN_LNG) minLng += 2 * Math.PI; maxLng = radLng + deltaLng; if (maxLng > MAX_LNG) maxLng -= 2 * Math.PI; } else { minLat = Math.max(minLat, MIN_LAT); maxLat = Math.min(maxLat, MAX_LAT); minLng = MIN_LNG; maxLng = MAX_LNG; } return [ { lat: toDegrees(minLat), lng: toDegrees(minLng) }, // Southwest { lat: toDegrees(maxLat), lng: toDegrees(maxLng) } // Northeast ]; };
var Rx = require('rx'); var MRHelper = (function () { function MRHelper() { this.window = window; } MRHelper.prototype.getModule = function (loadedName) { return this.window[loadedName]; }; MRHelper.prototype.getSubject = function (moduleName, subjectName) { return this.getModule(moduleName)[subjectName]; }; MRHelper.prototype.getObservable = function (moduleName, subjectName) { return this.getModule(moduleName)[subjectName]; }; MRHelper.prototype.loadModule = function (moduleName, loadedName) { var _this = this; System.import(moduleName).then(function (mod) { _this.window[loadedName] = mod.default; streamInterface.push(true, loadedName); }); }; MRHelper.prototype.portal = function (loadedName, subjectName) { if (this.getSubject(loadedName, subjectName) == undefined) { var portal = new Rx.Subject(); this.getModule(loadedName)[subjectName] = portal; } }; MRHelper.prototype.activatePortal = function (loadedName, subjectName, serializedInput) { var data = JSON.parse(serializedInput); this.getSubject(loadedName, subjectName).onNext(data); }; MRHelper.prototype.reversePortal = function (loadedName, subjectName) { this.getObservable(loadedName, subjectName).subscribe(function (data) { reversePortalInterface.onNext(data, subjectName); }); }; MRHelper.prototype.portalsGenerated = function (loadedName) { this.getModule(loadedName).portalsGenerated(); }; MRHelper.prototype.portalsLinked = function (loadedName) { this.getModule(loadedName).portalsLinked(); }; MRHelper.prototype.unloadModule = function (loadedName) { this.getModule(loadedName).destroy(); this.window[loadedName] = null; }; return MRHelper; })(); exports.MRHelper = MRHelper;
var path = require('path'); var fs = require('fs'); // 打印目录下 指定扩展名的文件列表 // API DOC URL //https://nodejs.org/api/fs.html#fs_fs_readdir_path_callback AND //https://nodejs.org/api/path.html var dir = 'D:/NodeApp/nodelearn/lesson'; var ext='.txt'; var filelist; function getlist(callback){ fs.readdir(dir, function(err,list){ if(err) throw err; console.log('dirs',list) filelist=list callback() }) } function getextlist(){ for(var i=0;i<filelist.length;i++) { if(path.extname(filelist[i]) ===ext ) console.log('txt is ',filelist[i]) } } getlist(getextlist);
var request = require('request'); var jwt = require('jsonwebtoken'); var crud = require('../libs/crud'); var auth = require('../libs/auth'); var subs = require('../libs/subscriptions'); var config = require('../libs/config'); var express = require('express'); var router = express.Router(); var apiKeyExtract = new RegExp(/[a-z,0-9]{32}/m); module.exports = function (cmd_args) { var admin_dash_public_key = cmd_args.auth_server_public_key.replace(/'/g, "").replace(/"/g, '').replace(/\\n/g, "\n"); return function (req, res, next) { jwt.verify(req.signedCookies.session, admin_dash_public_key, function (err, decoded) { if ( err ) { res.render('/admin/login') } else { subs.getPEATSubscriptions(req.signedCookies.session, function (err, body) { //console.log(JSON.parse(body)['result']); if ( err ) { console.log(err) } if ( body !== undefined || body !== null || body['result'].length !== 0) { body = JSON.parse(body); res.render('subscriptions', { user : decoded.user_id, 's' : body['result'], 'session': req.signedCookies.session }); } else { res.render('subscriptions', { user : decoded.user_id, 's' : [], 'session': req.signedCookies.session }); } }); } }); }; };
var fs = require("fs"); var path = require("path"); var encryption = require("../scripts/app-encryption"); module.exports = function($logger, $projectData, $usbLiveSyncService, hookArgs) { // Encrypt only in release if (!$projectData.$options.release) { return; } // Generate key var key = encryption.generateKey(); console.log('Encrypting with key: ' + key); var platformData = $injector.resolve("platformsData").getPlatformData(hookArgs.platform); // Save the key in file var keyFile = path.join(platformData.projectRoot, 'k'); fs.writeFileSync(keyFile, key); if (hookArgs.platform == 'ios') { /* * Inject the plugin specific linker flags in plugin-release.xcconfig file. This is needed because relying on the CLI mechanism for * merging .xcconfig files results in reordering of the linker flags. */ var pluginReleaseFile = path.join(platformData.projectRoot, 'plugins-release.xcconfig'); var placeholder = /___app_encryption_plugin_OTHER_LDFLAGS_placeholder___/g; var linkerFlags = '$(inherited) -ObjC -sectcreate __DATA __bin_data $(PROJECT_DIR)/k'; fs.readFile(pluginReleaseFile, 'utf8', function (err, fileContent) { var newFileContent = fileContent.replace(placeholder, linkerFlags); fs.writeFile(pluginReleaseFile, newFileContent, 'utf8'); }); } // Encrypt files return encryption.encryptPreparedAppFolder(platformData.appDestinationDirectoryPath, key); }
import React, {Component} from "react"; import { Row, Col, Modal, ModalHeader, ModalBody, ModalFooter, Button, } from "helpers/reactstrap"; import * as Components from "../../viewscreens"; import {capitalCase} from "change-case"; import ConfigComponent from "./ConfigComponent"; const components = Object.keys(Components).filter( c => c.indexOf("Config") === -1, ); class HotkeysConfig extends Component { constructor(props) { super(props); const storedAllowed = localStorage.getItem("allowed_viewscreenHotkeys"); const allowed = storedAllowed ? JSON.parse(storedAllowed) : { 1: {component: "auto", data: "{}"}, 2: {component: "ShipLogo", data: "{}"}, 3: {component: "RedAlert", data: "{}"}, 4: {component: "CollisionAlert", data: "{}"}, 5: {component: "Communications", data: "{}"}, 6: {component: "DamageMonitoring", data: "{}"}, 7: {component: "Overheating", data: "{}"}, 8: {component: "ViewscreenOffline", data: "{}"}, 9: {component: "RadiationMonitoring", data: "{}"}, 0: {component: "Blackout", data: "{}"}, }; this.state = { allowed, setConfig: null, }; } updateAllowed = value => { const i = this.state.setConfig; this.setState( state => ({ allowed: { ...state.allowed, [i]: { component: state.allowed[i].component || state.allowed[i], data: value, }, }, }), () => { localStorage.setItem( "allowed_viewscreenHotkeys", JSON.stringify(this.state.allowed), ); }, ); }; render() { const {modal, toggle} = this.props; const {setConfig, allowed} = this.state; return ( <Modal isOpen={modal} toggle={toggle} size="lg"> <ModalHeader toggle={toggle}> <div>Viewscreen Hotkey Config</div> <small> Configure which viewscreen hotkeys are available in this browser. Hotkeys are accessed with 'Option' + 'Shift' + a number key </small> </ModalHeader> <ModalBody> <Row> <Col sm={6}> <div className="flex-column" style={{display: "flex"}}> {Array(10) .fill(0) .map((_, i) => ( <div key={`hotkey-${i}`}> {i}:{" "} <select value={ this.state.allowed[i].component || this.state.allowed[i] } onChange={e => { const value = e.target.value; this.setState( state => ({ allowed: { ...state.allowed, [i]: { data: state.allowed[i].data, component: value, }, }, }), () => { localStorage.setItem( "allowed_viewscreenHotkeys", JSON.stringify(this.state.allowed), ); }, ); }} > <option value={"auto"}>Auto Viewscreens</option> {components .concat() .sort() .map(c => ( <option value={c} key={c}> {capitalCase(c)} </option> ))} </select> <Button color="info" size="sm" disabled={setConfig === i} onClick={() => this.setState({setConfig: i})} > Config </Button> </div> ))} </div> </Col> <Col sm={6} style={{maxHeight: "50vh", overflowY: "auto"}}> <h4>Config</h4> {setConfig && ( <ConfigComponent simulator={this.props.simulator} flightId={this.props.flightId} data={allowed[setConfig].data || "{}"} updateData={this.updateAllowed} simple component={allowed[setConfig].component || allowed[setConfig]} /> )} </Col> </Row> </ModalBody> <ModalFooter> <Button color="primary" onClick={toggle}> Close </Button> </ModalFooter> </Modal> ); } } export default HotkeysConfig;
var stormpath = require('express-stormpath'); var bodyParser = require('body-parser'); var morgan = require('morgan'); var path = require('path'); var express = require('express'); var webpack = require('webpack'); var config = require('./webpack.config'); var ora = require('ora'); var port = process.env.PORT || 3000; var app = express() var compiler = webpack(config); var spinner = ora({ interval: 100 }); function failAndExit(err) { spinner.fail(); console.error(err.stack); process.exit(1); } app.use(morgan('combined')); app.use(require('webpack-dev-middleware')(compiler, { noInfo: true, publicPath: config.output.publicPath })); app.use('/css', express.static(__dirname + '/src/css')); app.use(stormpath.init(app, { // Disable logging until startup, so that we can catch errors // and display them nicely. debug: 'none', web: { produces: ['application/json'], me: { expand: { customData: true } }, register: { form: { fields: { color: { enabled: true, label: 'Color', placeholder: 'E.g. blue', type: 'text' } } } } } })); app.post('/me', bodyParser.json(), stormpath.loginRequired, function (req, res) { function writeError(message) { res.status(400); res.json({ message: message, status: 400 }); res.end(); } function saveAccount() { req.user.givenName = req.body.givenName; req.user.surname = req.body.surname; req.user.email = req.body.email; if ('color' in req.body.customData) { req.user.customData.color = req.body.customData.color; } req.user.save(function (err) { if (err) { return writeError(err.userMessage || err.message); } res.end(); }); } if (req.body.password) { var application = req.app.get('stormpathApplication'); application.authenticateAccount({ username: req.user.username, password: req.body.existingPassword }, function (err) { if (err) { return writeError('The existing password that you entered was incorrect.'); } req.user.password = req.body.password; saveAccount(); }); } else { saveAccount(); } }); app.get('*', function (req, res) { res.sendFile(path.join(__dirname, 'src/html/index.html')); }); spinner.text = 'Starting Dev Server on port ' + port, spinner.start(); app.on('error', failAndExit); app.on('stormpath.error', failAndExit); app.listen(port, function () { spinner.succeed(); spinner.text = 'Initializing Stormpath'; spinner.start(); app.on('stormpath.ready', function () { spinner.succeed(); console.log('\nListening at http://localhost:' + port); // Now bring back error logging. app.get('stormpathLogger').transports.console.level = 'error'; }); }); // app.listen(port, function() { // console.log('Server running at localhost:' + port) // })
(function () { "use strict"; var app = angular .module("benefitsResourceMock", ["ngMockE2E"]); app.run(function ($httpBackend) { var benefits = [{ updateError: false, updateSuccess: false, users: [ { _id: "10", firstName: "c", lastName: "k", benefitStartDate: "2039-12-02" }, { _id: "11", firstName: "a", lastName: "b", benefitStartDate: "2029-12-21" }, { _id: "12", firstName: "p", lastName: "k", benefitStartDate: "2019-02-02" } ] }]; var benefitsUrl = "/api/benefits"; $httpBackend.whenGET(benefitsUrl).respond(benefits); // Pass through any requests for application files $httpBackend.whenGET(/pages/).passThrough(); }) }());
var instagram = require('./../index.js').createClient('a8d764b1a7fe4089959910ee6bdcedce', '253a2b9abade4f25adb3825249d98b85'); exports.testMediaFetchById = function (test) { test.expect(2); instagram.media.id(100, function (media, error) { test.ok(media['type']); test.equal(error, null, "Returned an error"); test.done(); }); }; exports.testMediaFetchPopular = function (test) { test.expect(2) instagram.media.popular(function (media, error) { test.ok((media.length > 0)); test.equal(error, null, "Returned an error"); test.done(); }); }; exports.testMediaSearch = function (test) { var params = [{lat: 37.7937111, lng: -122.3926227}, {lat: 37.7937111, lng: -122.3926227, distance: 2000}]; test.expect(params.length*2); var do_it = function (i, callback) { instagram.media.search(params[i], function (media, error) { test.ok((media.length > 0)); test.equal(error, null, "Return error for "+params); if (i < params.length-1) { do_it(i+1, do_it); }else{ test.done(); } }); } do_it(0); };
define({ root: ({ _widgetLabel: "Basemap Gallery" }), "ar": 1, "cs": 1, "da": 1, "de": 1, "es": 1, "et": 1, "fi": 1, "fr": 1, "he": 1, "it": 1, "ja": 1, "ko": 1, "lt": 1, "lv": 1, "nb": 1, "nl": 1, "pl": 1, "pt-br": 1, "pt-pt": 1, "ro": 1, "ru": 1, "sv": 1, "th": 1, "tr": 1, "vi": 1, "zh-cn": 1 });
var coordinates = require('./coordinates'); var _ = require('lodash'); // var debug = require('debug')('mgenerate:polygon'); /** * $polygon operator, returns a GeoJSON formatted Polygon with `corners` corners * * @example Creates random GeoJSON polygon of format with 4 corners: * * { * "type": "Polygon", * "coordinates": [ [ [<long>, <lat>], [<long>, <lat>], ... ] ] * } * * {"polygon": {"$polygon": {"corners": 4}}} * * @param {Function} evaluator evaluator function, passed in for every operator * @param {Object} options options to configure the array operator * @return {Array} array of `number` elements */ module.exports = function(evaluator, options) { // default options options = _.defaults(options, { corners: 3 }); // evaluate corners option first var corners = evaluator(options.corners, true); // remove corners from options and produce `corners` coordinate pairs options = _.omit(options, 'corners'); var coords = _.map(_.range(corners), function() { return coordinates(evaluator, options); }); // close polygon coords.push(coords[0]); var result = { type: 'Polygon', coordinates: [coords] }; return result; };
import classNames from "classnames/dedupe"; import React from "react"; import Config from "../config/Config"; function getDefaultMessage() { const slackLink = ( <a href={Config.slackChannel} target="_blank"> Slack channel </a> ); const supportLink = ( <a href={`mailto:${Config.supportEmail}`}> {Config.supportEmail} </a> ); return ( <p className="text-align-center flush-bottom"> </p> ); // 汉化版本删除 // return ( // <p className="text-align-center flush-bottom"> // You can also join us on our // {" "} // {slackLink} // {" "} // or send us an email at // {" "} // {supportLink} // . // </p> // ); } class RequestErrorMsg extends React.Component { render() { let { columnClasses, header, message } = this.props; columnClasses = classNames( "column-small-8 column-small-offset-2", "column-medium-6 column-medium-offset-3", columnClasses ); return ( <div className="row"> <div className={columnClasses}> <h3 className="text-align-center flush-top"> {header} </h3> {message} </div> </div> ); } } RequestErrorMsg.defaultProps = { columnClasses: {}, header: "无法连接到服务器", message: getDefaultMessage() }; RequestErrorMsg.propTypes = { columnClasses: React.PropTypes.oneOfType([ React.PropTypes.array, React.PropTypes.object, React.PropTypes.string ]), header: React.PropTypes.node, message: React.PropTypes.node }; module.exports = RequestErrorMsg;
/** * @license * Copyright 2017 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'; /** * @fileoverview Ensures elements with an ARIA role contain any required children. * e.g. A parent node with role="list" should contain children with role="listitem". * See base class in axe-audit.js for audit() implementation. */ const AxeAudit = require('./axe-audit'); class AriaRequiredChildren extends AxeAudit { /** * @return {!AuditMeta} */ static get meta() { return { category: 'Accessibility', name: 'aria-required-children', description: '`[role]`s that require child `[role]`s contain them.', helpText: 'Some ARIA parent roles require specific roles on their children to perform ' + 'their accessibility function.', requiredArtifacts: ['Accessibility'] }; } } module.exports = AriaRequiredChildren;
import React, { Component, PropTypes } from 'react'; import ItemTypes from './ItemTypes'; import { DragSource } from 'react-dnd'; const boxSource = { beginDrag(props) { return { name: props.name }; }, endDrag(props, monitor, component) { const item = monitor.getItem(); const dropResult = monitor.getDropResult(); if (dropResult) { component.setState({ droped: true }); } } }; class Box extends Component { static propTypes = { connectDragSource: PropTypes.func.isRequired, isDragging: PropTypes.bool.isRequired, name: PropTypes.string.isRequired }; constructor() { super(); this.state= { droped: false }; } render() { const { isDragging, connectDragSource } = this.props; const { name } = this.props const opacity = isDragging ? 0.4 : 1; let classes = this.state.droped ? 'box reset-svg-color ' + name : 'box ' + name; return ( connectDragSource( <div className="col-xs-3 flex-container"> <a href="#" className={classes} style={{ opacity }}></a> </div> ) ); } } export default DragSource(ItemTypes.BOX, boxSource, (connect, monitor) => ({ connectDragSource: connect.dragSource(), isDragging: monitor.isDragging() }))(Box);
// Load Jasmine - This will still create all of the normal Jasmine browser globals unless `boot.js` is re-written to use the // AMD or UMD specs. `boot.js` will do a bunch of configuration and attach it's initializers to `window.onload()`. Because // we are using RequireJS `window.onload()` has already been triggered so we have to manually call it again. This will // initialize the HTML Reporter and execute the environment. require(['jasmine-boot', 'jasmine-console'], function () { jasmine.getEnv().addReporter(new getJasmineRequireObj().ConsoleReporter()({ print : function(msg) { console.log(msg); } })); // Load the specs require(specs, function() { // Initialize the HTML Reporter and execute the environment (setup by `boot.js`) window.onload(); }); });
define([], /** * @lends Utils */ function(){ /** * Validation class * This is the interface class for user enties validation * @class Validation * @constructor * @return Session Object */ Validation = {}; /** * Checks if the given text is not empty * @param {String} text - to be checked * @public * @name Validation#_isEmpty * @function **/ Validation._isEmpty = function(text){ if(!text || text.length == 0) return true; return false; }; /** * Checks if the given text is a valid username * The username must be between 5 and 15 characters, dot and underscore are allowed, the first letter should be number or character. * @param {String} username - to be checked * @public * @name Validation#_isEmpty * @function **/ Validation._isUsername = function(username){ var usernameRegex = /[a-zA-Z0-9][a-zA-Z0-9_.@]/; return (usernameRegex.test(username)); }; /** * Checks if the given text is a human name or surname. * Acceptable names include compound names with a hyphen or a space in them. * @param {String} name - string name to be checked * @public * @name Validation#_isName * @function **/ Validation._isName = function(name){ var nameRegex = /^[a-zA-Z]+((\s|\-)[a-zA-Z]+)?$/; return (nameRegex.test(name)); }; /** * Checks if the given text is a valid email address * @param {String} email - email to be validated * @public * @name Validation#_isEmail * @function **/ Validation._isEmail = function(email){ if(Validation._isEmpty(email)) return false; var regEmailExp = /^\w+([\.-]?\w)*@\w+([\.-]?\w)*(\.\w{2,4})+$/; return regEmailExp.test(email); }; /** * Checks if the given password is strong enough. * Password must be between 4 and 8 digits long and include at least one numeric digit. * @param {String} pwd - password string to be validated * @public * @name Validation#_isPassword * @function **/ Validation._isPassword = function(pwd){ var strongPwd = /^(?=.*\d).{4,8}$/; return (strongPwd.test(pwd)); }; /** * Checks if the given affiliation has a valid syntax. * The affiliation should be between 2 and 20 digits, underscore, hyphen, apostrophe and dots are allowed. First letter can be only character. * @param {String} affiliation - affiliation value to be validated * @public * @name Validation#_isAffiliation * @function **/ Validation._isAffiliation = function(affiliation){ var affReg = /^[a-zA-Z]+([a-zA-Z0-9\s_'-.]{2,20})$/; return (affReg.test(affiliation)); }; /** * Checks if the given public key description name has a valid syntax. * The public key description should be from 3 to 15 digits long. The first letter has to be a character. Only alphanumeric characters are allowed. * @param {String} keyDescription - public key description value to be validated * @public * @name Validation#_isKeyName * @function **/ Validation._isKeyName = function(key){ var keyNameReg = /^[a-zA-Z]+([a-zA-Z0-9\s]{3,15})$/; return (keyNameReg.test(key)); }; /** * Checks if the given public key value has a valid syntax. * Client side validation is just checking for valid length. The public key length should be between 100 and 500 digits. * @param {String} keyValue - public key value value to be validated * @public * @name Validation#_isKeyValue * @function **/ Validation._isKeyValue = function(keyValue){ // TODO Add appropriate public key validation var isValid = false; var keyLength = keyValue.length; if( 100 < keyLength && keyLength < 500 ) isValid = true; return isValid; } /** * Checks if the given password phrase is strong enough. * Password must be at least 4 characters, no more than 8 characters, and must include at least one lower case letter, and one numeric digit. * @param {String} phrase - password phrase to be validated * @public * @name Validation#_isPassphrase * @function **/ Validation._isPassphrase = function(phrase){ var strongPwd = /^(?=.*\d)(?=.*[a-z]).{4,8}$/; return (strongPwd.test(phrase)); }; /** * Checks if the given public file extension is a valid one. * @param {String} extension - public key file extension to be validated * @public * @name Validation#_isValidPublicKeyFileExtension * @function **/ Validation._isValidPublicKeyFileExtension = function(ext){ if(ext === 'pub') return true; return false; }; /** * Checks if the given public file size has a valid length. * @param {String} file_size - public key file size to be validated * @public * @name Validation#_isValidPublicKeyFileSize * @function **/ Validation._isValidPublicKeyFileSize = function(size){ var minSize = 100; var maxSize = 400; if( !(minSize < size&&size < maxSize)) return false; return true; }; return Validation; });
export default function isObject(obj) { return typeof obj === 'object'; }
var through2 = require('through2'); module.exports = function (fnProcess){ function process(file,enc,callback) { if(file.isNull()){ this.push(file); return callback(); } if(file.isStream()) { return this.emit('error', new gutil.PluginError('gulp-anycontent', 'Streaming not supported')); } if(file.isBuffer()){ var contents = file.contents.toString('utf8'); if(fnProcess && typeof fnProcess == 'function'){ contents = fnProcess(contents, file.path) || contents; } var outfile = file.clone(); outfile.contents = new Buffer(contents); } this.push(outfile); return callback(); } return through2.obj(process); }
/** * Create with IntelliJ IDEA * Project name : blur-admin-1.2.0 * Package name : * Author : Wukunmeng * User : wukm * Date : 17-7-20 * Time : 上午11:16 * --------------------------------- * */ (function () { 'use strict'; angular.module("BlurAdmin.pages.trade.history",[]).config(routeConfig); /** @ngInject */ function routeConfig($stateProvider) { $stateProvider .state('trade.history', { url: '/history', templateUrl: 'app/pages/trade/history/history_list.html', controller: "HistoryCtrl", title: '历史订单', sidebarMeta: { icon: 'ion-ios-pulse', order: 50, }, }); } })();
define( ({ map: { error: "Nie można utworzyć mapy", views: "widoków mapy." }, report: { flag: "Oflaguj jako niewłaściwe", error: "Błąd", success: "Oflagowano", loading: "Loading&hellip;" }, mapNotes:{ notesUnavailable: "Opis niedostępny", bookmarks: "Zakładki", zoomTo: "Powiększ do tej lokalizacji, aby uzyskać więcej informacji.", untitledNote: "Bez tytułu" }, social: { flickr: "Flickr", mediaLayers: "Warstwy multimediów", mediaLayersDescription: "Pokaż na mapie zasoby udostępnione przez ogół użytkowników.", flickrSettings: "Ustawienia dla serwisu Flickr", twitter: "Twitter", twitterSettings: "Ustawienia dla serwisu Twitter", twitterUser: "Konto w serwisie Twitter", twitterSignIn: "Zaloguj się do serwisu Twitter", webcams: "Webcams.travel", instagram: "Instagram", instagramSettings: "Ustawienia serwisu Instagram", igTime: "Przesłane w ciągu ostatnich dni", youtube: "YouTube", youtubeSettings: "Ustawienia serwisu YouTube", ytSettingsInfo: "Zapoznaj się z materiałami wideo utworzonymi przez użytkowników, które zawierają zasoby sieciowe oraz profesjonalne.", ytTime: "Przesłane w ciągu ostatnich", today: "Dzień", this_week: "Tydzień", this_month: "Miesiąc", all_time: "Wszystkie okresy", moreInfo: "Więcej informacji", searchTerms: "Słowa kluczowe", search: "Wyszukaj", flSettingsInfo: "Zwrócone wyniki, które pasują do tytułu, opisu lub znaczników zdjęcia.", twSettingsInfo: "Zobacz, co się teraz dzieje", igSettingsInfo: "Instagram to szybki, estetyczny i ciekawy sposób na dzielenie się nowymi wydarzeniami z życia z przyjaciółmi i rodziną.", advancedOperators: "Wskazówka: w celu stworzenia procesów wyszukiwania zaawansowanego, skorzystaj z <a target=\"_blank\" href=\"https://support.twitter.com/articles/71577-using-advanced-search\">operatorów</a>.", tweetsFilteredBy: "Filtrowanie wpisów w serwisie Twitter według:", photosFilteredBy: "Filtrowanie zdjęć według:", videosFilteredBy: "Filtrowanie filmów wideo:", twitterAccountStatus: "Zezwól na wyświetlanie Twojego statusu w warstwie Twitter." }, general: { map: "Mapa", mapInfo: "Informacje o mapie", legend: "Legenda", featured: "Polecane lokalizacje", layers: "Warstwy", share: "Udostępnij", about: "Informacje o", find: "Kod pocztowy, miasto itd.", moreInfo: "Więcej informacji", dateModified: "Ostatnia modyfikacja", noSearchResult: "Nie znaleziono wyników", switchAccount: "Przełącz konto", signIn: "Zaloguj się", settings: "Ustawienia" } }) );
/* * ../../../..//extensions/a11y/mathmaps/es/units/volume.js * * Copyright (c) 2009-2018 The MathJax Consortium * * 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. */ [ { locale: "es" }, { key: "bbl", names: ["bbl.", "bbl"], mappings: { default: { default: "barrile" } }, category: "volume" }, { key: "cu", names: ["cu", "cu."], mappings: { default: { default: "cúbico" } }, category: "volume" }, { key: "fl. oz.", names: ["fl. oz."], mappings: { default: { default: "onzas líquidas" } }, category: "volume" }, { key: "gal", names: ["gal", "gal."], mappings: { default: { default: "galone" } }, category: "volume" }, { key: "pt", names: ["pt", "pt."], mappings: { default: { default: "pinta" } }, category: "volume" }, { key: "qt", names: ["qt", "qt."], mappings: { default: { default: "quart" } }, category: "volume" }, { key: "tbsp", names: ["tbsp", "tbsp."], mappings: { default: { default: "cuchara" } }, category: "volume" }, { key: "tsp", names: ["tsp", "tsp."], mappings: { default: { default: "cucharilla" } }, category: "volume" }, { key: "cc", names: ["cc"], mappings: { default: { default: "centímetros cúbicos" } }, category: "volume" }, { key: "kl", names: ["kl"], mappings: { default: { default: "kilolitro" } }, category: "volume" }, { key: "l", names: ["l"], mappings: { default: { default: "litro" } }, category: "volume" }, { key: "ml", names: ["ml"], mappings: { default: { default: "mililitro" } }, category: "volume" } ];
/* * Copyright 2017 dialog LLC <info@dlg.im> * @flow */ import type { Country } from '../../CountryCodeSelector/utils/countries'; import countries from '../../CountryCodeSelector/utils/countries'; function normalize(code: string): string { return code.replace(/\s/g, ''); } function getCountryByPhone(phone: string, languages: string[]): ?Country { const variants = countries.filter((country) => { return phone.startsWith(normalize(country.code)); }); if (!variants.length) { return null; } variants.sort((a, b) => { const lengthDiff = normalize(b.code).length - normalize(a.code).length; if (lengthDiff === 0) { return languages.indexOf(b.alpha) - languages.indexOf(a.alpha); } return lengthDiff; }); return variants[0]; } export default getCountryByPhone;
// // RGB Colors - #ff0014, #eee // colorLib.Color = function (rgb, a) { // // The end goal here, is to parse the arguments // into an integer triplet, such as `128, 255, 0` // // This facilitates operations and conversions. // if (Array.isArray(rgb)) { this.rgb = rgb; } else if (rgb.length === 6) { this.rgb = rgb.match(/.{2}/g).map(function (c) { return parseInt(c, 16); }); } else { this.rgb = rgb.split('').map(function (c) { return parseInt(c + c, 16); }); } this.alpha = typeof(a) === 'number' ? a : 1; }; colorLib.Color.prototype = { type: "Color", eval: function () { return this; }, luma: function () { return (0.2126 * this.rgb[0] / 255) + (0.7152 * this.rgb[1] / 255) + (0.0722 * this.rgb[2] / 255); }, // // If we have some transparency, the only way to represent it // is via `rgba`. Otherwise, we use the hex representation, // which has better compatibility with older browsers. // Values are capped between `0` and `255`, rounded and zero-padded. // toCSS: function (env, doNotCompress) { var compress = env && env.compress && !doNotCompress; if (this.alpha < 1.0) { return "rgba(" + this.rgb.map(function (c) { return Math.round(c); }).concat(this.alpha).join(',' + (compress ? '' : ' ')) + ")"; } else { var color = this.rgb.map(function (i) { i = Math.round(i); i = (i > 255 ? 255 : (i < 0 ? 0 : i)).toString(16); return i.length === 1 ? '0' + i : i; }).join(''); if (compress) { color = color.split(''); // Convert color to short format if (color[0] === color[1] && color[2] === color[3] && color[4] === color[5]) { color = color[0] + color[2] + color[4]; } else { color = color.join(''); } } return '#' + color; } }, // // Operations have to be done per-channel, if not, // channels will spill onto each other. Once we have // our result, in the form of an integer triplet, // we create a new Color node to hold the result. // operate: function (env, op, other) { var result = []; if (! (other instanceof colorLib.Color)) { other = other.toColor(); } for (var c = 0; c < 3; c++) { result[c] = colorLib.operate(env, op, this.rgb[c], other.rgb[c]); } return new(colorLib.Color)(result, this.alpha + other.alpha); }, toHSL: function () { var r = this.rgb[0] / 255, g = this.rgb[1] / 255, b = this.rgb[2] / 255, a = this.alpha; var max = Math.max(r, g, b), min = Math.min(r, g, b); var h, s, l = (max + min) / 2, d = max - min; if (max === min) { h = s = 0; } else { s = l > 0.5 ? d / (2 - max - min) : d / (max + min); switch (max) { case r: h = (g - b) / d + (g < b ? 6 : 0); break; case g: h = (b - r) / d + 2; break; case b: h = (r - g) / d + 4; break; } h /= 6; } return { h: h * 360, s: s, l: l, a: a }; }, //Adapted from http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript toHSV: function () { var r = this.rgb[0] / 255, g = this.rgb[1] / 255, b = this.rgb[2] / 255, a = this.alpha; var max = Math.max(r, g, b), min = Math.min(r, g, b); var h, s, v = max; var d = max - min; if (max === 0) { s = 0; } else { s = d / max; } if (max === min) { h = 0; } else { switch(max){ case r: h = (g - b) / d + (g < b ? 6 : 0); break; case g: h = (b - r) / d + 2; break; case b: h = (r - g) / d + 4; break; } h /= 6; } return { h: h * 360, s: s, v: v, a: a }; }, toARGB: function () { var argb = [Math.round(this.alpha * 255)].concat(this.rgb); return '#' + argb.map(function (i) { i = Math.round(i); i = (i > 255 ? 255 : (i < 0 ? 0 : i)).toString(16); return i.length === 1 ? '0' + i : i; }).join(''); }, compare: function (x) { if (!x.rgb) { return -1; } return (x.rgb[0] === this.rgb[0] && x.rgb[1] === this.rgb[1] && x.rgb[2] === this.rgb[2] && x.alpha === this.alpha) ? 0 : -1; } };
$(function () { $('#login_submit').click(function () { if (!validLogin()) { return; } var postdata = "username="+$.trim($("#username").val())+"&pwd="+ $.trim($("#password").val()); ajax( { method:'POST', url:'adminLoginAction_login.action', params: postdata, callback:function(data) { if (data == 1) { //管理员 window.location.href = "admin/admin.jsp"; } else if (data == -1) { showInfo("账号不存在"); } else if (data == -2) { showInfo("密码错误"); } else { showInfo("登录失败,请重试"); } } } ); }); var alert = $('.alert'); var formWidth = $('.bootstrap-admin-login-form').innerWidth(); var alertPadding = parseInt($('.alert').css('padding')); if (isNaN(alertPadding)) { alertPadding = parseInt($(alert).css('padding-left')); } $('.alert').width(formWidth - 2 * alertPadding); }); function validLogin() { var flag = true; var username = $.trim($("#username").val()); if (username == "") { $('#username').parent().addClass("has-error"); $('#username').next().text("请输入账号"); $("#username").next().show(); flag = false; } else if (username.length<2 || username.length > 15) { $("#username").parent().addClass("has-error"); $("#username").next().text("账号长度必须在2~15之间"); $("#username").next().show(); flag = false; } else { $('#username').parent().removeClass("has-error"); $('#username').next().text(""); $("#username").next().hide(); } var password = $.trim($("#password").val()); if (password == "") { $('#password').parent().addClass("has-error"); $('#password').next().text("请输入密码"); $("#password").next().show(); flag = false; } else if (password.length<3 || password.length > 15) { $("#password").parent().addClass("has-error"); $("#password").next().text("密码长度必须在3~15之间"); $("#password").next().show(); flag = false; } else { $('#password').parent().removeClass("has-error"); $('#password').next().text(""); $("#password").next().hide(); } return flag; } function showInfo(msg) { $("#div_info").text(msg); $("#modal_info").modal('show'); }
Ti.include('/runtimeTester.js'); module.exports = function($) { //jasmine.currentEnv_ = null; addMatchers(); describe('proxy controller', function() { if (OS_IOS) { validateUiComponent($, 'pullView', { api: 'Ti.UI.View', style: { height: "60dp", backgroundColor: "#aaa", id: "pullView" } }); validateUiComponent($, 'pullText', { api: 'Ti.UI.Label', style: { text: "Something about refreshing would be here", id: "pullText", height: Ti.UI.SIZE, width: Ti.UI.SIZE, bottom: 10 } }); } validateUiComponent($, 'headerView', { api: 'Ti.UI.View', style: { height: "60dp", backgroundColor: "#0f0", id: "headerView" } }); validateUiComponent($, 'headerText', { api: 'Ti.UI.Label', style: { text: "I'm an ugly headerView", id: "headerText" } }); validateUiComponent($, 'footerView', { api: 'Ti.UI.View', style: { height: "60dp", backgroundColor: "#0f0", id: "footerView" } }); validateUiComponent($, 'footerText', { api: 'Ti.UI.Label', style: { text: "I'm an equally ugly footerView", id: "footerText" } }); }); };
var Recruit = require('../../models/recruit'); exports.index = function(req, res, next){ var footer = req.footer; var side = req.side; Recruit .find({}) .sort('meta.updateAt') .exec(function(err, recruit){ res.render('front/recruit', { title: '产品展示', type: 'recruit', footer: footer, side: side, recruit: recruit }) }) }
var items = {} var types = {} var parents = {} var standings = {} var replayables = [] var replayableItems = {} var replayableTypes = {} function updateStandings(ss){ for(var s in ss){ standings[clean(s)] = ss[s]; } } var voteCount = 0 function preProcessVotes(post){ post.votes.forEach(function(v){ v.id = v.time v.creationDate = v.time parents[v.id] = post.id replayableItems[v.id] = v replayableTypes[v.id] = "vote" }) } function preProcessComment(c,a){ preProcessVotes(c) parents[c.id] = a.id replayableItems[c.id] = c replayableTypes[c.id] = "comment" c.comments.map(function(_c){preProcessComment(_c,c)}) } var receivePolicy = 0 function receiveQuestions(qs){ _.defer(function(){ switch(receivePolicy){ case 0: $(document).off("previewOnQuestion") doReceiveQuestionsShort(qs) break; case 1: doReceiveQuestionsShort(qs) break; } renderBlendedTimeline(); }); } function doReceiveQuestionsShort(qs){ qs.forEach(doReceiveQuestion) var seedType = "topic" trunk.pushAll(seedType,_.keys(categories[seedType]),seedType) indexStack(); } function receiveQuestion(q){ _.defer(function(){doReceiveQuestion(q)}); } function recordAuthor(a){ categoriesOfWork["author"](a,{id:a}) items[a] = { integer:standings[a] || 0, standing:standing(standings[a]), id:a } } function doReceiveQuestion(q){ $(document).trigger("previewOnQuestion",[q]) items[q.id] = q; var recordVotes = function(post){ post.votes.map(function(v){ v.id = sprintf("%s%s",v.author,v.time) items[v.id] = v parents[v.id] = post.id categoriesOfWork["vote"](v.id,v) recordAuthor(v.author) }) } var recordComments = function(c,parent){ items[c.id] = c parents[c.id] = parent.id categoriesOfWork["comment"](c.id,c) recordAuthor(c.discussion.author) recordVotes(c) c.comments.map(function(c1){ recordComments(c1,c) }); } if(!(q.teachingEvent in items)){ items[q.teachingEvent] = { id:q.teachingEvent, final:q, questions:[] } } else{ items[q.teachingEvent].questions.push(q) } categoriesOfWork["topic"](q.teachingEvent,items[q.teachingEvent]) categoriesOfWork["question"](q.id,q) recordAuthor(q.discussion.author) recordVotes(q) q.answers.map(function(a){ items[a.id] = a parents[a.id] = q.id categoriesOfWork["answer"](a.id,a) recordAuthor(a.discussion.author) a.comments.map(function(c){recordComments(c,a)}) recordVotes(a) }) $(document).trigger("onQuestion",[q]) }
/*! * Start Bootstrap - Grayscale Bootstrap Theme (http://startbootstrap.com) * Code licensed under the Apache License v2.0. * For details, see http://www.apache.org/licenses/LICENSE-2.0. * HEAVILY MODIFIED - By Chamu Rajasekera */ // jQuery to collapse the navbar on scroll $(window).scroll(function() { if ($(".navbar").offset().top > 50) { $(".navbar-fixed-top").addClass("top-nav-collapse"); } else { $(".navbar-fixed-top").removeClass("top-nav-collapse"); } }); // jQuery for page scrolling feature - requires jQuery Easing plugin $(function() { $('a.page-scroll').bind('click', function(event) { var $anchor = $(this); $('html, body').stop().animate({ scrollTop: $($anchor.attr('href')).offset().top }, 1500, 'easeInOutExpo'); event.preventDefault(); }); }); function goToSlide(number) { $("#portfolio-carousel").carousel(number); } $(document).ready(function() { var url = window.location.href; var start = url.lastIndexOf("target")+7 var end = url.lastIndexOf("#") var slide = url.substring(start,end); if (slide > -1) { goToSlide(parseInt(slide)) } $('#gal1').galereya({ wave: false }); }); // Closes the Responsive Menu on Menu Item Click $('.navbar-collapse ul li a').click(function() { $('.navbar-toggle:visible').click(); }); var toggled = false; function expand() { if (!toggled) { $("#collage").height(200); console.log("expanded"); } else { $("#collage").height(0); console.log("collapsed"); } toggled = !toggled; } // $(document).ready(function() { // $('.title').before('<i class="fa fa-chevron-right"></i>'); // $('.title').after('<i class="fa fa-chevron-left"></i>'); // }); // Google Maps Scripts // When the window has finished loading create our google map below
/** * Site stats utilities. * * 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 classnames from 'classnames'; /** * WordPress dependencies */ import { __, _x, sprintf } from '@wordpress/i18n'; /** * Internal dependencies */ import { getLocale, numFmt, getChartDifferenceArrow, stringToDate, calculateDifferenceBetweenChartValues, } from '../../../util'; import { adsenseDateToInstance } from './date'; /** * Gets data for a Google Chart from an AdSense report. * * @since 1.23.0 * @since 1.36.0 Updated for API v2 report format. * * @param {Object} current A report object for the current period. * @param {Object} previous A report object for the previous period. * @param {string} label Metric label. * @param {number} selectedColumn Selected column index. * @param {Object} metadata Data metadata. * @return {Array.<Array.<number|string>>} Data array. */ export function getSiteStatsDataForGoogleChart( current, previous, label, selectedColumn, metadata ) { const dataMap = [ [ { type: 'date', label: __( 'Day', 'google-site-kit' ) }, { type: 'string', role: 'tooltip', p: { html: true } }, { type: 'number', label }, { type: 'number', label: __( 'Previous period', 'google-site-kit' ), }, ], ]; const nextDate = ( date ) => { const next = new Date( date ); next.setDate( date.getDate() + 1 ); return next; }; const findRowByDate = ( searchDate ) => ( row ) => searchDate.getTime() === stringToDate( row.cells[ 0 ].value ).getTime(); let currentDate = adsenseDateToInstance( current.startDate ); let previousDate = adsenseDateToInstance( previous.startDate ); const endDate = adsenseDateToInstance( current.endDate ); const locale = getLocale(); const localeDateOptions = { weekday: 'short', month: 'short', day: 'numeric', }; while ( currentDate <= endDate ) { const currentMonth = parseFloat( ( current?.rows || [] ).find( findRowByDate( currentDate ) ) ?.cells?.[ selectedColumn ]?.value || 0 ); const prevMonth = parseFloat( ( previous?.rows || [] ).find( findRowByDate( previousDate ) ) ?.cells?.[ selectedColumn ]?.value || 0 ); const difference = calculateDifferenceBetweenChartValues( currentMonth, prevMonth ); const svgArrow = getChartDifferenceArrow( difference ); const dateRange = sprintf( /* translators: 1: date for user stats, 2: previous date for user stats comparison */ _x( '%1$s vs %2$s', 'Date range for chart tooltip', 'google-site-kit' ), currentDate.toLocaleDateString( locale, localeDateOptions ), previousDate.toLocaleDateString( locale, localeDateOptions ) ); let tooltipData = numFmt( currentMonth, metadata?.currencyCode ); if ( metadata?.type === 'METRIC_RATIO' ) { tooltipData = numFmt( currentMonth, '%' ); } const statInfo = sprintf( /* translators: 1: selected stat label, 2: numeric value of selected stat, 3: up or down arrow , 4: different change in percentage, %%: percent symbol */ _x( '%1$s: <strong>%2$s</strong> <em>%3$s %4$s%%</em>', 'Stat information for chart tooltip', 'google-site-kit' ), label, tooltipData, svgArrow, Math.abs( difference ) .toFixed( 2 ) .replace( /(.00|0)$/, '' ) // .replace( ... ) removes trailing zeros ); dataMap.push( [ currentDate, `<div class="${ classnames( 'googlesitekit-visualization-tooltip', { 'googlesitekit-visualization-tooltip--up': difference > 0, 'googlesitekit-visualization-tooltip--down': difference < 0, } ) }"> <p>${ dateRange }</p> <p>${ statInfo }</p> </div>`, currentMonth, prevMonth, ] ); currentDate = nextDate( currentDate ); previousDate = nextDate( previousDate ); } return dataMap; }
// Copyright 2015 UniMOOC. 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'; angular.module('GCB-CMS').controller('IndexCtrl',['$scope', '$translate', '$timeout', function ($scope, $translate, $timeout) { $scope.config = { sidebarCollapsed: false, debugMode: false }; $scope.InitIndex = function(){ // Inicializar Menu $('#side-menu').metisMenu(); // Petición para pedir nombre }; //************* Traducciones // $translate('ENGLISH').then(function(translation){ // }); //************* Funciones //**** Select Picker $scope.MakeInitSelectPicker = function(){ var lang = $translate.use(); var word = (lang === 'es' ? $translate.instant('SPANISH') : $translate.instant('ENGLISH')); var image = 'images/' + lang + '.png'; var obj = $('.selectpicker .filter-option.pull-left'); obj.find('span[translate]').html(word); obj.find('img').attr('src',image); } $scope.UpdateSelectPicker = function(){ var lang = $('[selectpicker]').selectpicker('val'); if($translate.use() !== lang) $scope.$apply(function() { $translate.use(lang); }); var word = ''; if(lang === 'es') $translate('SPANISH').then(function (translation) { word = translation; }); else $translate('ENGLISH').then(function (translation) { word = translation; }); var image = 'images/' + lang + '.png'; var obj = $('.selectpicker .filter-option.pull-left'); $timeout(function(){ obj.find('span[translate]').html(word); obj.find('img').attr('src',image); }, 100); $timeout(function(){ obj.find('span[translate]').html(word); obj.find('img').attr('src',image); }, 550); // Por si falla el primero }; $scope.InitSelectPicker = function(){ $timeout(function(){ $scope.MakeInitSelectPicker(); }, 100); $timeout(function(){ $scope.MakeInitSelectPicker(); }, 550); // Por si falla el primero $timeout(function(){ $scope.MakeInitSelectPicker(); }, 1850); }; //************* jQuery $(function() { $timeout($scope.InitSelectPicker, 40); //Loads the correct sidebar on window load, collapses the sidebar on window resize. // Sets the min-height of #page-wrapper to window size $(window).on('load resize', function() { var topOffset = 50; var width = (this.window.innerWidth > 0) ? this.window.innerWidth : this.screen.width; if (width < 768) { $('div.navbar-collapse').addClass('collapse') topOffset = 100; // 2-row-menu } else { $('div.navbar-collapse').removeClass('collapse') } var height = (this.window.innerHeight > 0) ? this.window.innerHeight : this.screen.height; height = height - topOffset; if (height < 1) height = 1; if (height > topOffset) { $("#page-wrapper").css("min-height", (height) + "px"); } }); //******* Bootstrap Select, con esto se arregla el error de la traducción $('body').on('click', '.selectpicker a', $scope.UpdateSelectPicker); }); }]);
var a03437 = [ [ "base", "a03437.html#a70e40ea8a648d89f902ce9d912303fc0", null ], [ "MemberSignature", "a03437.html#a099d8ba06c8d2308099dbb100333e387", null ], [ "_ConstTessMemberResultCallback_4_2", "a03437.html#a3eafab2d508e54e50a53ef091b86a3d6", null ], [ "Run", "a03437.html#a5a6dc489db05720779034162b527114b", null ] ];
console.log('티아카데미'); console.log("1"); console.log("2"); console.log("3"); console.log("4"); console.log("5"); console.log("브랜치 구분을 잘하자");
define([ 'shared/util/TemplateUtil', 'shared/models/BaseSchema' ], function (TemplateUtil, BaseSchema) { var UserSchema = BaseSchema.Model.extend({ urlRoot: '/api/v1/user/schemas' }); var tmpl = TemplateUtil.tpl('/api/v1/user/types/{{objTypeId}}/schemas'); var UserSchemas = BaseSchema.Collection.extend({ model: UserSchema, initialize: function (models, options) { this.objTypeId = options && options.objTypeId; }, url: function () { return tmpl(this); } }); return { Model: UserSchema, Collection: UserSchemas }; });
// Copyright 2022 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. // // ** This file is automatically generated by gapic-generator-typescript. ** // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** 'use strict'; function main(parent) { // [START retail_v2alpha_generated_CatalogService_ListCatalogs_async] /** * TODO(developer): Uncomment these variables before running the sample. */ /** * Required. The account resource name with an associated location. * If the caller does not have permission to list * Catalog google.cloud.retail.v2alpha.Catalog s under this location, * regardless of whether or not this location exists, a PERMISSION_DENIED * error is returned. */ // const parent = 'abc123' /** * Maximum number of Catalog google.cloud.retail.v2alpha.Catalog s to * return. If unspecified, defaults to 50. The maximum allowed value is 1000. * Values above 1000 will be coerced to 1000. * If this field is negative, an INVALID_ARGUMENT is returned. */ // const pageSize = 1234 /** * A page token * ListCatalogsResponse.next_page_token google.cloud.retail.v2alpha.ListCatalogsResponse.next_page_token, * received from a previous * CatalogService.ListCatalogs google.cloud.retail.v2alpha.CatalogService.ListCatalogs * call. Provide this to retrieve the subsequent page. * When paginating, all other parameters provided to * CatalogService.ListCatalogs google.cloud.retail.v2alpha.CatalogService.ListCatalogs * must match the call that provided the page token. Otherwise, an * INVALID_ARGUMENT error is returned. */ // const pageToken = 'abc123' // Imports the Retail library const {CatalogServiceClient} = require('@google-cloud/retail').v2alpha; // Instantiates a client const retailClient = new CatalogServiceClient(); async function callListCatalogs() { // Construct request const request = { parent, }; // Run request const iterable = await retailClient.listCatalogsAsync(request); for await (const response of iterable) { console.log(response); } } callListCatalogs(); // [END retail_v2alpha_generated_CatalogService_ListCatalogs_async] } process.on('unhandledRejection', err => { console.error(err.message); process.exitCode = 1; }); main(...process.argv.slice(2));
/** * Copyright © 2017 EaDesign by Eco Active S.R.L. All rights reserved. * See LICENSE for license details. */ define( [ 'jquery', "underscore", 'ko', 'uiComponent', 'mage/calendar' ], function ($, _, ko, Component) { 'use strict'; return Component.extend({ defaults: { template: 'Eadesigndev_Checkoutaddressfields/checkout/delivery-date' }, initialize: function () { this._super(); ko.bindingHandlers.datepicker = { init: function (element, valueAccessor, allBindingsAccessor) { var $el = $(element); var options = {minDate: 1}; $el.datepicker(options); var writable = valueAccessor(); if (!ko.isObservable(writable)) { var propWriters = allBindingsAccessor()._ko_property_writers; if (propWriters && propWriters.datepicker) { writable = propWriters.datepicker; } else { return; } } writable($(element).datepicker("getDate")); }, update: function (element, valueAccessor) { var widget = $(element).data("DateTimePicker"); if (widget) { var date = ko.utils.unwrapObservable(valueAccessor()); widget.date(date); } } }; return this; } }); } );
Ext.define('portlet.columns.Pie', { extend: 'portlet.HighchartColumn', xtype: 'pieColumn', dataBind: 'last', chartConfig: { chart: { plotBackgroundColor: null, plotBorderWidth: null, plotShadow: false, spacingBottom: 8, type: 'pie' }, title: { text: '' }, plotOptions: { pie: { allowPointSelect: true, cursor: 'pointer', showInLegend: true, dataLabels: { enabled: false } } }, tooltip: { headerFormat: '', pointFormat: ' <span style="color:{point.color}">\u25CF</span> {point.name}: <b>{point.y}</b><br/>' }, exporting: { buttons: { contextButton: { enabled: false } } } } });
var jsface = require('jsface'), unirest = require('unirest'), Queue = require('../utilities/Queue'), Helpers = require('../utilities/Helpers'), Globals = require('../utilities/Globals'), EventEmitter = require('../utilities/EventEmitter'), VariableProcessor = require('../utilities/VariableProcessor.js'), _und = require('underscore'); /** * @class RequestRunner * @classdesc RequestRunner is a singleton object which fires the XHR and takes the * appropriate action on the response. * @mixes EventEmitter , Queue */ var RequestRunner = jsface.Class([Queue, EventEmitter], { $singleton: true, $statics: { METHODS_WHICH_ALLOW_BODY: ['POST','PUT','PATCH','DELETE','LINK','UNLINK','LOCK','PROPFIND'] }, /** * Adds the Request to the RequestRunner's queue. * @memberOf RequestRunner * @param {RequestModel} request Takes a RequestModel Object. */ addRequest: function(request) { this.addToQueue(request); }, /** * Starts the RequestRunner going to each request in the queue. * @memberOf RequestRunner */ start: function() { this._bindedOnRequestExecuted = this._onRequestExecuted.bind(this); this.addEventListener('requestExecuted', this._bindedOnRequestExecuted); this._execute(); }, // Gets a request from the queue and executes it. _execute: function() { var request = this.getFromQueue(); if (request) { this._sendRequestAndGenerateReponse(request); } else { this._destroy(); } }, _sendRequestAndGenerateReponse: function(request) { this._processUrlUsingEnvVariables(request); var RequestOptions = this._getRequestOptions(request); request.startTime = new Date().getTime(); var unireq = unirest.request(RequestOptions, function(error, response, body) { if(response) { // save some stats, only if response exists this._appendStatsToReponse(request, response); } else { // initialize response for reporting and testcases response = { stats: { timeTaken: 0}, statusCode: 0, headers: [] }; } // emit event to signal request has been executed this.emit('requestExecuted', error, response, body, request); }.bind(this)); this._setFormDataIfParamsInRequest(unireq, request); }, // clean up the requestrunner _destroy: function() { this.removeEventListener('requestExecuted', this._bindedOnRequestExecuted); this.emit('requestRunnerOver'); }, _onRequestExecuted: function(error, response, body, request) { // Call the next request to execute this._execute(); }, // Generates and returns the request Options to be used by unirest. _getRequestOptions: function(request) { var RequestOptions = {}; RequestOptions.url = request.transformed.url; RequestOptions.method = request.method; RequestOptions.headers = Helpers.generateHeaderObj(request.transformed.headers); RequestOptions.followAllRedirects = true; RequestOptions.jar = true; this._setBodyData(RequestOptions, request); return RequestOptions; }, // Takes request as the input, parses it for different types and // sets it as the request body for the unirest request. _setBodyData: function(RequestOptions, request) { if (RequestRunner.METHODS_WHICH_ALLOW_BODY.indexOf(request.method) > -1) { if (request.dataMode === "raw") { RequestOptions.body = request.transformed.data; } else if (request.dataMode === "urlencoded") { var reqData = request.transformed.data; RequestOptions.form = _und.object(_und.pluck(reqData, "key"), _und.pluck(reqData, "value")); } } }, // Request Mumbo jumbo for `multipart/form-data`. _setFormDataIfParamsInRequest: function(unireq, request) { if (RequestRunner.METHODS_WHICH_ALLOW_BODY.indexOf(request.method) > -1 && request.dataMode === "params" && request.data.length > 0) { var form = unireq.form(); _und.each(request.data, function(dataObj) { // TODO: @viig99 add other types like File Stream, Blob, Buffer. if (dataObj.type === 'text') { form.append(dataObj.key, dataObj.value); } }); } }, // placeholder function to append stats to response _appendStatsToReponse: function(req, res) { res.stats = {}; res.stats.timeTaken = new Date().getTime() - req.startTime; }, _processUrlUsingEnvVariables: function(request) { VariableProcessor.processRequestVariables(request, { envJson: Globals.envJson }); } }); module.exports = RequestRunner;
/*! Copyright 2016 Brazil 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. */ const fs = require('fs'); const awaiter = require('./awaiter.js'); const mirakurunRequest = require('./mirakurunRequest.js'); function updateArchive(options) { return new Promise((resolve, reject) => { Promise.all([ mirakurunRequest(options.mirakurunPath, '/api/channels'), mirakurunRequest(options.mirakurunPath, '/api/programs'), ]).then((values) => { awaiter(function* exec(sleep) { const writeData = { channels: values[0], programs: values[1], }; console.log( '%s: %d channels and %d programs recieved.', new Date().toISOString(), writeData.channels.length, writeData.programs.length ); yield sleep(100); let archiveData; try { archiveData = JSON.parse(fs.readFileSync(options.archiveFile)) || archiveData; } catch (e) { if (e.code !== 'ENOENT') { console.error('%s: %s', new Date().toISOString(), e.message); } archiveData = {}; } yield sleep(100); if (archiveData.programs) { let start = 0; try { const recorded = JSON.parse(fs.readFileSync(options.recordedFile)); yield sleep(100); start = Math.min.apply(null, recorded.map(a => a.start)); yield sleep(100); } catch (e) { console.error('%s: %s', new Date().toISOString(), e.message); start = 0; } for (let i = 0; i < archiveData.programs.length; i += 1) { const program = archiveData.programs[i]; if (program.startAt >= start) { const exists = writeData.programs.some(a => a.id === program.id); if (!exists) { writeData.programs.push(program); } } yield sleep(10); } } console.log( '%s: Archive %d channels and %d programs.', new Date().toISOString(), writeData.channels.length, writeData.programs.length ); try { fs.writeFileSync(options.archiveFile, JSON.stringify(writeData)); resolve(); } catch (e) { console.error('%s: %s', new Date().toISOString(), e.message); reject(e); } }); }, e => reject(e)); }); } module.exports = updateArchive;
//// [TwoInternalModulesThatMergeEachWithExportedAndNonExportedClassesOfTheSameName.ts] module A { export class Point { x: number; y: number; } } module A { class Point { fromCarthesian(p: A.Point) { return { x: p.x, y: p.y }; } } } // ensure merges as expected var p: { x: number; y: number; }; var p: A.Point; module X.Y.Z { export class Line { length: number; } } module X { export module Y { export module Z { class Line { name: string; } } } } // ensure merges as expected var l: { length: number; } var l: X.Y.Z.Line; //// [TwoInternalModulesThatMergeEachWithExportedAndNonExportedClassesOfTheSameName.js] var A; (function (A) { var Point = (function () { function Point() { } return Point; })(); A.Point = Point; })(A || (A = {})); var A; (function (A) { var Point = (function () { function Point() { } Point.prototype.fromCarthesian = function (p) { return { x: p.x, y: p.y }; }; return Point; })(); })(A || (A = {})); // ensure merges as expected var p; var p; var X; (function (X) { var Y; (function (Y) { var Z; (function (Z) { var Line = (function () { function Line() { } return Line; })(); Z.Line = Line; })(Z = Y.Z || (Y.Z = {})); })(Y = X.Y || (X.Y = {})); })(X || (X = {})); var X; (function (X) { var Y; (function (Y) { var Z; (function (Z) { var Line = (function () { function Line() { } return Line; })(); })(Z = Y.Z || (Y.Z = {})); })(Y = X.Y || (X.Y = {})); })(X || (X = {})); // ensure merges as expected var l; var l;
import { getFacetType } from '@ncigdc/components/FacetWrapper'; describe('getFacetType', () => { describe('returns "range"', () => { it('for long types', () => { expect(getFacetType({ type: 'long' })).toBe('range'); }); it('for float types', () => { expect(getFacetType({ type: 'float' })).toBe('range'); }); it('for double types', () => { expect(getFacetType({ type: 'double' })).toBe('range'); }); }); });
"use strict"; function metadata(state = {}, action) { switch (action.type) { case "SET_METADATA": { let temp = Object.assign({}, state, action.metadata); return temp; } default: return state; } } export default metadata;
/**! * * Copyright (c) 2015-2016 Cisco Systems, Inc. See LICENSE file. */ import {oneFlight} from '@ciscospark/common'; import {SparkPlugin} from '@ciscospark/spark-core'; import {omit} from 'lodash'; import util from 'util'; import FeaturesModel from './features-model'; import {persist, waitForValue} from '@ciscospark/spark-core'; const Device = SparkPlugin.extend({ children: { features: FeaturesModel }, idAttribute: `url`, namespace: `Device`, props: { modificationTime: `string`, services: { // Even though @jodykstr will tell you the docs claim you don't need to // initialize `object` properties, the docs lie. default() { return {}; }, type: `object` }, url: `string`, userId: `string`, webSocketUrl: `string` }, derived: { registered: { deps: [`url`], fn() { return Boolean(this.url); } } }, @waitForValue(`@`) getServiceUrl(service) { return this._getServiceUrl(this.services, service) .then((isServiceUrl) => isServiceUrl || this.getPreDiscoveryServiceUrl(service)); }, getPreDiscoveryServiceUrl(service) { // The Promise.resolve here is temporary. A future PR will make the // corresponding _ method async to allow for lazy device registration return Promise.resolve(this._getServiceUrl(this.config.preDiscoveryServices, service)); }, @persist initialize(...args) { Reflect.apply(SparkPlugin.prototype.initialize, this, args); // Propagate change(:[attribute]) events from collections [`developer`, `entitlement`, `user`].forEach((collectionName) => { this.features.on(`change:${collectionName}`, (model, value, options) => { this.trigger(`change`, this, options); this.trigger(`change:features`, this, this.features, options); }); }); }, /** * Don't log the features object * @param {number} depth * @returns {Object} */ inspect(depth) { return util.inspect(omit(this.serialize(), `features`), {depth}); }, isPreDiscoveryService(service) { // The Promise.resolve here is temporary. A future PR will make the // corresponding _ method async to allow for lazy device registration return Promise.resolve(this._isService(this.config.preDiscoveryServices, service)); }, isPreDiscoveryServiceUrl(uri) { // The Promise.resolve here is temporary. A future PR will make the // corresponding _ method async to allow for lazy device registration return Promise.resolve(this._isServiceUrl(this.config.preDiscoveryServices, uri)); }, @waitForValue(`@`) isService(service) { return this._isService(this.services, service) .then((_isService) => _isService || this.isPreDiscoveryService(service)); }, @waitForValue(`@`) isServiceUrl(uri) { // The Promise.resolve here is temporary. A future PR will make the // corresponding _ method async to allow for lazy device registration return Promise.resolve(this._isServiceUrl(this.services, uri)); }, @waitForValue(`@`) isSpecificService(service, key) { if (key === service) { return Promise.resolve(true); } return this.getServiceUrl(service) .then((serviceUrl) => key.includes(serviceUrl)); }, _getServiceUrl(target, service) { /* istanbul ignore if */ if (!target) { return Promise.reject(new Error(`\`target\` is a required parameter`)); } if (!service) { return Promise.reject(new Error(`\`service\` is a required parameter`)); } return Promise.resolve(target[`${service}ServiceUrl`]); }, _isService(target, service) { return this._getServiceUrl(target, service) .then((url) => Boolean(url)); }, _isServiceUrl(target, uri) { if (!uri) { return Promise.reject(new Error(`\`uri\` is a required parameter`)); } for (const key in target) { if (target[key] && uri.indexOf(target[key]) === 0) { return Promise.resolve(true); } } return Promise.resolve(false); }, @oneFlight @waitForValue(`@`) refresh() { this.logger.info(`device: refreshing`); if (!this.registered) { this.logger.info(`device: device not registered, refreshing`); return this.register(); } this.logger.info(`device: refreshing`); return this.request({ method: `PUT`, uri: this.url, body: omit(this.serialize(), `features`, `mediaClusters`) }) .then((res) => this._processRegistrationSuccess(res)) .catch((reason) => { if (reason.statusCode === 404) { // If we get a 404, it means the device is no longer valid and we need // to register a new one. this.logger.info(`device: refresh failed with 404, attempting to register new device`); this.clear(); return this.register(); } return Promise.reject(reason); }); }, @oneFlight @waitForValue(`@`) register() { /* eslint no-invalid-this: [0] */ this.logger.info(`device: registering`); if (this.registered) { this.logger.info(`device: device already registered, refreshing`); return this.refresh(); } return this.request({ method: `POST`, api: `wdm`, resource: `devices`, body: this.config.defaults }) .then((res) => this._processRegistrationSuccess(res)); }, _processRegistrationSuccess(res) { this.logger.info(`device: received registration payload`); this.set(res.body); } }); export default Device;
/* * Copyright (c) 2014 Samsung Electronics Co., 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. */ var __memTestDone = false; (function () { function baz() { return function () {}; } var x = baz(); var t = setTimeout(x,1000); x = null; clearTimeout(t); __memTestDone = true; })();
window.addEventListener('load', function() { 'use strict'; const ECHO_PORT = 7; var myAddress = null; var mySocket = null; var echoServers = {}; var infoDiv, serversDiv, messagesDiv; var loremIpsum = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'.replace(/[,.]/g, '').split(' '); init(); function init() { console.log('echoipsum'); infoDiv = document.getElementById('info'); serversDiv = document.getElementById('servers'); messagesDiv = document.getElementById('messages'); // TODO ensure NETWORK is available! showNetworkInfo(); setupServiceDiscovery(); registerEchoService(); setupPingInterval(); } function showNetworkInfo() { var wifiManager = navigator.mozWifiManager; if(!wifiManager) { info.innerHTML = 'Not available'; return; } var connInfo = wifiManager.connectionInformation; var fields = []; fields.push(['mac', wifiManager.macAddress]); if(status === 'associated' || status === 'connected') { var network = wifiManager.connection.network; fields.push(['Network name', network.ssid]); fields.push(['Security', network.security]); } if(connInfo) { fields.push(['ip', connInfo.ipAddress]); myAddress = connInfo.ipAddress; } var txt = fields.map(function(pair) { return `<strong>${pair[0]}: </strong> ${pair[1]}`; }).join('<br />'); infoDiv.innerHTML = txt; } function setupServiceDiscovery() { DNSSD.addEventListener('discovered', onServiceDiscovered); DNSSD.startDiscovery(); } function onServiceDiscovered(ev) { var address = ev.address; var echoServices = ev.services.filter(service => { return service.match('echo'); }); // TODO: weird thing, services registered with dns-sd // seem to be registered/detected twice, so we'll deduplicate. var tmpServices = []; echoServices.forEach(service => { if(tmpServices.indexOf(service) === -1) { tmpServices.push(service); } }); echoServices = tmpServices; if(echoServices.length > 0) { if(address !== myAddress) { if(echoServers[address] === undefined) { echoServers[address] = { lastPinged: null, sentWord: null, returnedWord: null }; } } } else { delete(echoServers[address]); } updateServersList(); } function registerEchoService() { mySocket = new UDPSocket({ localPort: ECHO_PORT }); var decoder = new TextDecoder('utf-8'); mySocket.onmessage = (message) => { var decodedMessage = decoder.decode(message.data); messagesDiv.innerHTML = `<div class="message">${decodedMessage}</div> from ${message.remoteAddress}`; }; DNSSD.registerService('_echo._udp.local', ECHO_PORT, {}); } function updateServersList() { var names = Object.keys(echoServers); var items = names.map(function(serverName) { return `<li><strong>${serverName}</strong>`; }); serversDiv.innerHTML = `<ul>${items}</ul>`; } function setupPingInterval() { setInterval(pingServers, 1000); pingServers(); } function pingServers() { var keys = Object.keys(echoServers); keys.forEach(address => { var details = echoServers[address]; // Only ping them if we haven't yet if(details.sentWord === null) { pingServer(address); } }); } function pingServer(address) { var wordIndex = Math.round(Math.random() * loremIpsum.length) % loremIpsum.length; var word = loremIpsum[wordIndex]; var socket = new UDPSocket({ remoteAddress: address, remotePort: ECHO_PORT }); socket.opened.then(() => { socket.send(word); // close the socket or else... BOOOOOOM // See: https://bugzilla.mozilla.org/show_bug.cgi?id=1152283 socket.close(); }); } });
function Notifier() { const that = this; this.token = ""; Notifier.prototype.requestPermissions = function () { function newMessage(permission) { return permission == "granted"; } Notification.requestPermission(newMessage); }; Notifier.prototype.connect = function () { var websocket = ebsocket = new WebSocket("ws://" + location.host + "/teamnotifier/1.0/state/" + that.token); websocket.onopen = function () { that.connectionSuccessHandler(); }; websocket.onclose = function () { that.connectionCloseHandler(); }; websocket.onmessage = function (evt) { var event = JSON.parse(evt.data); that.eventHandler(event); }; websocket.onerror = function (error) { that.errorHandler(error); }; }; } Notifier.prototype.connectionSuccessHandler = function () { throw new Error("not bound"); }; Notifier.prototype.connectionCloseHandler = function () { throw new Error("not bound"); }; Notifier.prototype.errorHandler = function (error) { throw new Error("not bound"); }; Notifier.prototype.eventHandler = function () { throw new Error("not bound"); };
/** * Created by P0015475 on 2015/9/15. */ myApp.config(function ($httpProvider) { /** * 解决post问题 * */ $httpProvider.defaults.headers.put['Content-Type'] = 'application/x-www-form-urlencoded'; $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; $httpProvider.defaults.transformRequest = [function (data) { var param = function (obj) { var query = ''; var name, value, fullSubName, subName, subValue, innerObj, i; for (name in obj) { value = obj[name]; if (value instanceof Array) { for (i = 0; i < value.length; ++i) { subValue = value[i]; fullSubName = name + '[' + i + ']'; innerObj = {}; innerObj[fullSubName] = subValue; query += param(innerObj) + '&'; } } else if (value instanceof Object) { for (subName in value) { subValue = value[subName]; fullSubName = name + '[' + subName + ']'; innerObj = {}; innerObj[fullSubName] = subValue; query += param(innerObj) + '&'; } } else if (value !== undefined && value !== null) { query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&'; } } return query.length ? query.substr(0, query.length - 1) : query; }; return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data; }]; /** * 解决post问题/ * */ });
/*! Deck JS - deck.hash Copyright (c) 2011 Caleb Troughton Dual licensed under the MIT license and GPL license. https://github.com/imakewebthings/deck.js/blob/master/MIT-license.txt https://github.com/imakewebthings/deck.js/blob/master/GPL-license.txt */ /* This module adds deep linking to individual slides, enables internal links to slides within decks, and updates the address bar with the hash as the user moves through the deck. A permalink anchor is also updated. Standard themes hide this link in browsers that support the History API, and show it for those that do not. Slides that do not have an id are assigned one according to the hashPrefix option. In addition to the on-slide container state class kept by core, this module adds an on-slide state class that uses the id of each slide. */ (function ($, deck, window, undefined) { var $d = $(document), $window = $(window), /* Collection of internal fragment links in the deck */ $internals, /* Internal only function. Given a string, extracts the id from the hash, matches it to the appropriate slide, and navigates there. */ goByHash = function(str) { var id = str.substr(str.indexOf("#") + 1), slides = $[deck]('getSlides'); $.each(slides, function(i, $el) { if ($el.attr('id') === id) { $[deck]('go', i); return false; } }); // If we don't set these to 0 the container scrolls due to hashchange $[deck]('getContainer').scrollLeft(0).scrollTop(0); }; /* Extends defaults/options. options.selectors.hashLink The element matching this selector has its href attribute updated to the hash of the current slide as the user navigates through the deck. options.hashPrefix Every slide that does not have an id is assigned one at initialization. Assigned ids take the form of hashPrefix + slideIndex, e.g., slide-0, slide-12, etc. options.preventFragmentScroll When deep linking to a hash of a nested slide, this scrolls the deck container to the top, undoing the natural browser behavior of scrolling to the document fragment on load. */ $.extend(true, $[deck].defaults, { selectors: { hashLink: '.deck-permalink' }, hashPrefix: 'slide-', preventFragmentScroll: true }); $d.bind('deck.init', function() { var opts = $[deck]('getOptions'); $internals = $(), slides = $[deck]('getSlides'); $.each(slides, function(i, $el) { var hash; /* Hand out ids to the unfortunate slides born without them */ if (!$el.attr('id') || $el.data('deckAssignedId') === $el.attr('id')) { $el.attr('id', opts.hashPrefix + i); $el.data('deckAssignedId', opts.hashPrefix + i); } hash ='#' + $el.attr('id'); /* Deep link to slides on init */ if (hash === window.location.hash) { $[deck]('go', i); } /* Add internal links to this slide */ $internals = $internals.add('a[href="' + hash + '"]'); }); if (!Modernizr.hashchange) { /* Set up internal links using click for the poor browsers without a hashchange event. */ $internals.unbind('click.deckhash').bind('click.deckhash', function(e) { goByHash($(this).attr('href')); }); } /* Set up first id container state class */ if (slides.length) { $[deck]('getContainer').addClass(opts.classes.onPrefix + $[deck]('getSlide').attr('id')); }; }) /* Update permalink, address bar, and state class on a slide change */ .bind('deck.change', function(e, from, to) { var hash = '#' + $[deck]('getSlide', to).attr('id'), hashPath = window.location.href.replace(/#.*/, '') + hash, opts = $[deck]('getOptions'), osp = opts.classes.onPrefix, $c = $[deck]('getContainer'); $c.removeClass(osp + $[deck]('getSlide', from).attr('id')); $c.addClass(osp + $[deck]('getSlide', to).attr('id')); $(opts.selectors.hashLink).attr('href', hashPath); //by Ali - synch with tree jQuery Address var h_node_id=getPropertiesFromHash(hash.split('#')[1])['nodeId']; highlightNode(h_node_id); //enable iframes $.each($('#'+h_node_id+'-view iframe'),function(index,value){ if($(value)[0]._src) $(value).attr('src',$(value)[0]._src); }); //------------------------ if (Modernizr.history) { // by Ali window.history.replaceState({}, "", window.location.pathname+hash); } }); /* Deals with internal links in modern browsers */ $window.bind('hashchange.deckhash', function(e) { if (e.originalEvent && e.originalEvent.newURL) { goByHash(e.originalEvent.newURL); } else { goByHash(window.location.hash); } }) /* Prevent scrolling on deep links */ .bind('load', function() { if ($[deck]('getOptions').preventFragmentScroll) { $[deck]('getContainer').scrollLeft(0).scrollTop(0); } }); })(jQuery, 'deck', this);
var rpsls = angular.module('rpslsApp', ["chart.js"]) .controller('mainController', function($scope) { //Main controller for the app, this holds the player name, the choices for the game, and the labels for the pie chart $scope.playerName = "Player"; //Player's name, if they choose not to enter anything, the default will be player. // The list of choices for the player to choose from. This can be expanded upon, if you want a more complicated version of the game, but the 5 // choices of Rock, Paper, Scissors, Lizard and Spock are here right now. $scope.choices = [ {name: "Rock", beats: ["Scissors", "Lizard"], image: "img/rock.jpg"}, {name: "Paper", beats: ["Rock", "Spock"], image: "img/paper.jpg"}, {name: "Scissors", beats: ["Paper", "Lizard"], image: "img/scissors.jpg"}, {name: "Lizard", beats: ["Paper", "Spock"], image: "img/lizard.jpg"}, {name: "Spock", beats: ["Rock", "Scissors"], image: "img/spock2.jpg"} ]; // Labels for the pie chart that shows the wins, losses and ties. $scope.labels = ["Wins", "Losses", "Ties"]; }) .controller('rpslsController', ['$scope', '$interval', function($scope, $interval) { //Controller for the game and stat portions. $scope.stats = {"wins": 0, "losses": 0, "ties": 0}; // Object to store the stats in. $scope.data = []; // Empty data array for the pie chart $scope.playerChoice = []; //Empty array for the player's choice $scope.computerChoice = []; //Empty array for the computer's choice $scope.min = 0; //The minimum value for the random number generator that chooses for the computer //Max value for the RNG, this is set to the length of the choices array, so that as options are added to the choices, this doesn't have to be adjusted $scope.max = $scope.choices.length - 1; $scope.played = 0; // Total number of games played $scope.won = 0; // Total number of games won $scope.lost = 0; // Total number of games lost $scope.tied = 0; // Total number of games tied // Function that resets the stats back to 0 $scope.resetStats = function() { $scope.played = 0; $scope.won = 0; $scope.lost = 0; $scope.tied = 0; $scope.stats["wins"] = 0; $scope.stats["losses"] = 0; $scope.stats["ties"] = 0; $scope.data = []; }; // Function to get a random number, for when the computer chooses. It takes the minimum and maximum values, to get a random number, // in this instance, from 0-4 inclusive. $scope.getRandomNumber = function(min, max) { var random = Math.floor(Math.random() * (max - min + 1)) + min; return random; }; // Function to get the computer choice. It uses the random number generator to generate a number from 0-4 inclusive, and uses that to choose an array index // from the choices array. $scope.getComputerChoice = function(){ var random = $scope.getRandomNumber($scope.min, $scope.max); return $scope.choices[random]; }; // Set default images for the player and computer to question marks, used for when the page first loads. $scope.playerChoice.image = "img/question-mark.png"; $scope.computerChoice.image = "img/question-mark.png"; // The text to display for the game results. $scope.resultText = ""; // Main game function. This will choose for the computer, and compare the results with the player's choice to determine who won. // As the games are played, the total played, won, lost, and tied variables are incremented, and the stats object is updated, as is the data for the pie chart // so the chart can be displayed in real time. $scope.letsPlay = function(playerChoice) { // Assume at the start that player lost var playerWon = false; // Select the computer's option var computerChoice = $scope.getComputerChoice(); //Set the computer and player choices to scope variables, to display data in the view $scope.playerChoice = playerChoice; $scope.computerChoice = computerChoice; // Check the player's choice against the computer's. If the names are the same, then they tied if (playerChoice.name === computerChoice.name) { $scope.resultText = $scope.playerName + " and computer tied!"; $scope.tied += 1; } else { // Otherwise, we need to check the strings in the Beats array in the choice object to see if the option the computer chose is beaten by the player's // choice. I chose to use a for loop here because the angular.forEach() loop doesn't allow breaking out of the loop, and for this operation, the // standard for loop was a faster choice. for (var i=0; i < playerChoice.beats.length; i++) { if (playerChoice.beats[i] === computerChoice.name) { playerWon = true; break; } } // If the player won, then increment the won variable, and add the result text if (playerWon) { $scope.won += 1; $scope.resultText = $scope.playerName + " Won!"; } else { // Otherwise, the player lost, increment the lost variable, and add the result text. $scope.lost += 1; $scope.resultText = $scope.playerName + " lost."; } } $scope.played += 1; $scope.stats["wins"] = $scope.won; $scope.stats["losses"] = $scope.lost; $scope.stats["ties"] = $scope.tied; $scope.data = [$scope.stats["wins"], $scope.stats["losses"], $scope.stats["ties"]]; }; }]); // Directive to highlight the text in the playername text box. I pulled this directive from stack overflow to use in this app. rpsls.directive('selectOnClick', ['$window', function ($window) { return { restrict: 'A', link: function (scope, element, attrs) { element.on('click', function () { if (!$window.getSelection().toString()) { // Required for mobile Safari this.setSelectionRange(0, this.value.length) } }); } }; }]);
(function(angular) { 'use strict'; // module angular .module('app.dashboard', []); })(angular);
/*global cordova, module*/ module.exports = MediaStreamRenderer; MediaStreamRenderer.prototype.captureStillAsURI = function(successCB,errorCB) { var self = this; exec(successCB,errorCB,"iosrtcPlugin","captureStillAsURI",[self.id]); } function captureStillAsUID(elementid, successCB, errorCB) { if (typeof mediaStreamRenderers === 'undefined') { if (typeof errorCB == 'function') { errorCB("mediaStreamRenderers is not defined. Are you loading the iosrtc framework?"); } else { throw new Error("mediaStreamRenderers is not defined. Are you loading the iosrtc framework?"); } } if (typeof mediaStreamRenderers[elementid] == 'undefined') { if (typeof errorCB == 'function') { errorCB("elementid "+elementid+" is not defined in mediaStreamRenderers"); } else { throw new Error("elementid "+elementid+" is not defined in mediaStreamRenderers"); } } // var keys = Object.keys(mediaStreamRenderers); var id = mediaStreamRenderers[elementid].id; cordova.exec(successCB, errorCB, "iosrtcPlugin", "captureStillAsURI", [id]); }
/* * Copyright (C) 2017-2019 Dremio Corporation * * 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. */ import { Schema } from 'normalizr'; const historyItem = new Schema('historyItem', { idAttribute: 'datasetVersion' }); export default historyItem;
var _ = require('lodash'); module.exports = function(Model, server, config, log) { return function(msg) { log.debug("Remove %s request", Model.name, msg.id); return Model.remove(msg.id, {params: _.omit(msg, "credentials"), credentials: msg.credentials }); } };
ngDescribe({ name: 'Service: Storage tests', modules: 'atstop', inject: ['StorageService'], tests: function(deps) { it('should add to and get from localstorage', function() { deps.StorageService.set('1234ABCD'); expect(deps.StorageService.get() === ['1234ABCD']); }); } });
/* * Copyright (c) 2015. Zuercher Hochschule fuer Angewandte Wissenschaften * 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. */ (function() { /* Module Setup */ angular.module('dashboard.utils') .service('responseParser', ResponseParser); /* Controllers, Factories, Services, Directives */ function ResponseParser() { this.getStaticRatingListFromResponse = function(responseData) { var rates = responseData.rate || {}; var staticRatingList = {}; for(var meterName in rates) { var rate = rates[meterName]; staticRatingList[meterName] = { 'name': meterName, 'rate': rate }; } return staticRatingList; }; this.getAdminListFromResponse = function(responseData) { var userStrings = responseData.uniqueMember || []; var userList = []; for(var i = 0; i < userStrings.length; i++) { var re = /uid=(.*?),/g; var matched = re.exec(userStrings[i]); if(matched && matched[1]) { userList.push(matched[1]); } } return userList; }; this.getUserListFromResponse = function(responseData) { return responseData.result || []; }; this.getAdminStatusFromResponse = function(responseData) { var groups = responseData.isMemberOf || ""; if(groups instanceof Array) { groups = groups.join(); } return /cn=CyclopsAdmin/g.test(groups); }; } })();
import React from 'react'; import { connect } from 'react-redux'; import { VIEW_1K } from '../EditableWordCloudDataCard'; /** * Wrap any component that wants to display an EditableWordCloud. This manages the sampleSize parameter. * Your child should accept a `sampleSize` property, and call the supplied `onViewSampleSizeClick` when the sampled * size is changed. If your component is a `withFilteredAsyncData` one, it should make sure to include `sampleSize` * in it's `propsToRefetchOn`. */ const withSampleSize = (ChildComponent) => { class SampleSize extends React.Component { state = { sampleSize: VIEW_1K, }; render() { const { sampleSize } = this.state; // must instantiate here and pass as props to child component - this.state.sampleSize doesn't work return ( <div className="sample-size"> <ChildComponent {...this.props} sampleSize={sampleSize} onViewSampleSizeClick={newSampleSize => this.setState({ sampleSize: newSampleSize })} /> </div> ); } } SampleSize.propTypes = { }; return connect()(SampleSize); }; export default withSampleSize;
var a02707 = [ [ "QLSQ", "a02707.html#a397f12ae540c919ecd64f4fc17427501", null ], [ "add", "a02707.html#adbbaa8f4d49392cc26b46fabc476cc88", null ], [ "clear", "a02707.html#a9f6ee88370df57093e248a2918ab20b2", null ], [ "count", "a02707.html#a704d9647f648df9cb7fd1004ec7cc8e7", null ], [ "fit", "a02707.html#a847b2fa0f918e971a56e8db0ce8ed18f", null ], [ "get_a", "a02707.html#a748cebc68a35dcb80970e2cfc1cace2d", null ], [ "get_b", "a02707.html#ab8de83e0968609f28aa83854431e2593", null ], [ "get_c", "a02707.html#aeeedb9b168cef907167e4530dd4bf68a", null ], [ "remove", "a02707.html#a504bacca02e1204111ae32d152e95a70", null ] ];
import React from 'react'; import { connect } from 'react-redux'; import { trackAnalyticsEvent } from '../../utils/tracking-utils'; import { doControl } from '../../actions/app-actions'; class NodeDetailsControlButton extends React.Component { constructor(props, context) { super(props, context); this.handleClick = this.handleClick.bind(this); } render() { let className = `node-control-button fa ${this.props.control.icon}`; if (this.props.pending) { className += ' node-control-button-pending'; } return ( <span className={className} title={this.props.control.human} onClick={this.handleClick} /> ); } handleClick(ev) { ev.preventDefault(); const { id, human } = this.props.control; trackAnalyticsEvent('scope.node.control.click', { id, title: human }); this.props.dispatch(doControl(this.props.nodeId, this.props.control)); } } // Using this instead of PureComponent because of props.dispatch export default connect()(NodeDetailsControlButton);
var canvas; var ctx; var drawing = false; var lastX = 0; var lastY = 0; var resizing = false; var originalHeight = 400; var originalWidth = 400; Template.drawPreview.rendered = function(){ var canvas = $('#canvas')[0]; var ctx = canvas.getContext('2d'); ctx.lineWidth = document.getElementById("stroke").value; ctx.lineJoin = "round"; ctx.lineCap = "round"; } Template.drawEditor.events = { 'change #bgColor': function(){ backgroundColor= document.getElementById("bgColor").value; if(backgroundColor == "transparent"){ canvas = $('#canvas')[0]; ctx = canvas.getContext('2d'); ctx.clearRect(0, 0, canvas.width, canvas.height); return; } canvas = $('#canvas')[0]; ctx = canvas.getContext('2d'); ctx.fillStyle = backgroundColor; console.log('color is now ' + ctx.fillStyle); ctx.rect(0, 0, canvas.width, canvas.height); ctx.fill(); }, 'change #stroke': function(){ var canvas = $('#canvas')[0]; var ctx = canvas.getContext('2d'); stroke = document.getElementById("stroke").value; if (stroke < 1) stroke = 1; if (stroke > 20) stroke = 20; ctx.lineWidth = stroke; console.log(ctx.lineWidth); } } Template.drawPreview.events = { 'mousedown #canvas': function(e){ drawing = true; lastX = e.pageX - e.target.offsetLeft; lastY = e.pageY - e.target.offsetTop; }, 'mouseup #canvas': function(e){ drawing = false; }, 'mousemove #canvas': function(e){ if(!drawing) return; var canvas = $('#canvas')[0]; var ctx = canvas.getContext('2d'); var x = e.pageX - e.target.offsetLeft; console.log(x); var y = e.pageY - e.target.offsetTop; var currentWidth = $('#canvas').width(); var currentHeight = $('#canvas').height(); var relX = (x/currentWidth)*originalWidth; var relLastX = (lastX/currentWidth)*originalWidth; var relY = (y/currentHeight)*originalHeight; var relLastY = (lastY/currentHeight)*originalHeight; ctx.beginPath(); ctx.moveTo(relLastX, relLastY); ctx.lineTo(relX, relY); ctx.strokeStyle = document.getElementById("inkColor").value; ctx.stroke(); lastX = x; lastY = y; }, 'touchstart #canvas': function(e){ var touchEvent = e.originalEvent.changedTouches[0]; lastX = touchEvent.pageX - e.target.offsetLeft; lastY = touchEvent.pageY - e.target.offsetTop; }, 'touchmove #canvas': function(e){ var touchEvent = e.originalEvent.changedTouches[0]; e.preventDefault(); var canvas = $('#canvas')[0]; var ctx = canvas.getContext('2d'); var x = touchEvent.pageX - e.target.offsetLeft; var y = touchEvent.pageY - e.target.offsetTop; var currentWidth = $('#canvas').width(); var currentHeight = $('#canvas').height(); var relX = (x/currentWidth)*originalWidth; var relLastX = (lastX/currentWidth)*originalWidth; var relY = (y/currentHeight)*originalHeight; var relLastY = (lastY/currentHeight)*originalHeight; ctx.beginPath(); ctx.moveTo(relLastX, relLastY); ctx.lineTo(relX, relY); ctx.strokeStyle = document.getElementById("inkColor").value; ctx.stroke(); lastX = x; lastY = y; }, 'click .clear': function(){ canvas = $('#canvas')[0]; ctx = canvas.getContext('2d'); ctx.clearRect(0, 0, canvas.width, canvas.height); }, 'click .resize': function(){ if(!resizing){ $('#canvas').resizable({ maxHeight: 1000, maxWidth: 1000, minHeight: 50, minWidth: 50 }); $(".resize").html("Stop Resizing"); resizing = true; } else{ resizing = false; $('#canvas').resizable('destroy'); $(".resize").html("Resize Canvas"); } } }
var fs = require('fs'); module.exports = walk; function walk(dir, files_, base) { var base = base || dir; files_ = files_ || []; var files = fs.readdirSync(dir); for (var i in files){ var name = dir + '/' + files[i]; if (fs.statSync(name).isDirectory()){ walk(name, files_, base); } else { files_.push({name: name, base: base}); } } return files_; }
goog.module('grrUi.client.checkClientAccessDirective'); goog.module.declareLegacyNamespace(); const apiService = goog.requireType('grrUi.core.apiService'); const routingService = goog.requireType('grrUi.routing.routingService'); /** * Controller for CheckClientAccessDirective. * @unrestricted */ const CheckClientAccessController = class { /** * @param {!angular.Scope} $scope * @param {!angular.$timeout} $timeout * @param {!apiService.ApiService} grrApiService * @param {!routingService.RoutingService} grrRoutingService * @ngInject */ constructor($scope, $timeout, grrApiService, grrRoutingService) { /** @private {!angular.Scope} */ this.scope_ = $scope; /** @private {!angular.$timeout} */ this.timeout_ = $timeout; /** @private {!apiService.ApiService} */ this.grrApiService_ = grrApiService; /** @private {!routingService.RoutingService} */ this.grrRoutingService_ = grrRoutingService; this.scope_.$watch('clientId', this.onClientIdChange_.bind(this)); } /** * Handles changes to the client id. * * @param {string} clientId The new value for the client id state param. * @private */ onClientIdChange_(clientId) { if (angular.isDefined(clientId)) { this.scope_['outHasAccess'] = undefined; this.grrApiService_.head('clients/' + clientId + '/flows') .then( this.onClientAccessPermitted_.bind(this), this.onClientAccessRejected_.bind(this)); } } /** * @private */ onClientAccessPermitted_() { this.scope_['outHasAccess'] = true; } /** * @private */ onClientAccessRejected_() { this.scope_['outHasAccess'] = false; if (!this.scope_['noRedirect']) { this.timeout_(function() { var clientId = this.scope_['clientId']; if (angular.isDefined(clientId)) { this.grrRoutingService_.go('client', {clientId: clientId}); } }.bind(this), 1000); } } }; /** * Directive that displays data objects. * * @return {!angular.Directive} Directive definition object. */ exports.CheckClientAccessDirective = function() { return { scope: { noRedirect: '=', clientId: '=', outHasAccess: '=?' // hasAccess is an "out" binding, and not a simple // parameter. Other directives may bind to hasAccess // to check whether access to the client is allowed. }, transclude: true, restrict: 'E', templateUrl: '/static/angular-components/client/check-client-access.html', controller: CheckClientAccessController, controllerAs: 'controller' }; }; /** * Name of the directive in Angular. */ exports.CheckClientAccessDirective.directive_name = 'grrCheckClientAccess';
var fs = require('fs'); function print(filename, data) { fs.writeFile(filename, data, function(err) { if (err) { console.log(err); return; } console.log("Print to " + filename + " succeeds."); }) } exports.print = print;
/* * 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'; var mat4 = Marzipano.dependencies.glMatrix.mat4; var quat = Marzipano.dependencies.glMatrix.quat; var degToRad = Marzipano.util.degToRad; var viewerElement = document.querySelector("#pano"); var enterVrElement = document.querySelector("#enter-vr"); var noVrElement = document.querySelector("#no-vr"); // Install the WebVR polyfill, which makes the demo functional on "fake" WebVR // displays such as Google Cardboard. var polyfill = new WebVRPolyfill(); // Create stage and register renderers. var stage = new Marzipano.WebGlStage(); Marzipano.registerDefaultRenderers(stage); // Insert stage into the DOM. viewerElement.appendChild(stage.domElement()); // Update the stage size whenever the window is resized. function updateSize() { stage.setSize({ width: viewerElement.clientWidth, height: viewerElement.clientHeight }); } updateSize(); window.addEventListener('resize', updateSize); // Create geometry. var geometry = new Marzipano.CubeGeometry([ { tileSize: 256, size: 256, fallbackOnly: true }, { tileSize: 512, size: 512 }, { tileSize: 512, size: 1024 }, { tileSize: 512, size: 2048 }, { tileSize: 512, size: 4096 } ]); // Create view. var limiter = Marzipano.RectilinearView.limit.traditional(4096, 110*Math.PI/180); var viewLeft = new WebVrView(); var viewRight = new WebVrView(); // Create layers. var layerLeft = createLayer(stage, viewLeft, geometry, 'left', { relativeWidth: 0.5, relativeX: 0 }); var layerRight = createLayer(stage, viewRight, geometry, 'right', { relativeWidth: 0.5, relativeX: 0.5 }); // Add layers into stage. stage.addLayer(layerLeft); stage.addLayer(layerRight); // Check for an available VR device and initialize accordingly. var vrDisplay = null; navigator.getVRDisplays().then(function(vrDisplays) { if (vrDisplays.length > 0) { vrDisplay = vrDisplays[0]; vrDisplay.requestAnimationFrame(render); } enterVrElement.style.display = vrDisplay ? 'block' : 'none'; noVrElement.style.display = vrDisplay ? 'none' : 'block'; }); // Enter WebVR mode when the button is clicked. enterVrElement.addEventListener('click', function() { vrDisplay.requestPresent([{source: stage.domElement()}]); }); var proj = mat4.create(); var pose = mat4.create(); function render() { var frameData = new VRFrameData; vrDisplay.getFrameData(frameData); // Update the view. // The panorama demo at https://github.com/toji/webvr.info/tree/master/samples // recommends computing the view matrix from `frameData.pose.orientation` // instead of using `frameData.{left,right}ViewMatrix. if (frameData.pose.orientation) { mat4.fromQuat(pose, frameData.pose.orientation); mat4.invert(pose, pose); mat4.copy(proj, frameData.leftProjectionMatrix); mat4.multiply(proj, proj, pose); viewLeft.setProjection(proj); mat4.copy(proj, frameData.rightProjectionMatrix); mat4.multiply(proj, proj, pose); viewRight.setProjection(proj); } // Render and submit to WebVR display. stage.render(); vrDisplay.submitFrame(); // Render again on the next frame. vrDisplay.requestAnimationFrame(render); } function createLayer(stage, view, geometry, eye, rect) { var urlPrefix = "//www.marzipano.net/media/music-room"; var source = new Marzipano.ImageUrlSource.fromString( urlPrefix + "/" + eye + "/{z}/{f}/{y}/{x}.jpg", { cubeMapPreviewUrl: urlPrefix + "/" + eye + "/preview.jpg" }); var textureStore = new Marzipano.TextureStore(source, stage); var layer = new Marzipano.Layer(source, geometry, view, textureStore, { effects: { rect: rect }}); layer.pinFirstLevel(); return layer; }
const cacheResponseDirective = require('express-cache-response-directive'); module.exports = { name: 'cache control', configure(app) { app.use(cacheResponseDirective()); }, };
// To create multiple component libraries, just add another library file define({ libraryName: "Example Component Library", libraryDescription: "Description of example component library", // Associate library categories with a reference, // so we can use it for our ordered array below libraryCategoriesByRef: { exampleCategory: { categoryName: "Example Category", categoryDescription: "Description of example category", categoryComponents: [ // in the order of appearance "forms/Button" ] } }, // List of category references, in the order they appear libraryCategories: [ "exampleCategory" ] });
tinyMCE.addI18n('ia.mmimage_dlg',{ tab_general:"\u57FA\u672C", tab_appearance:"\u5916\u89C2", tab_advanced:"\u9AD8\u7EA7", general:"\u57FA\u672C", title:"\u67E5\u627E", preview:"\u9884\u89C8", constrain_proportions:"\u4FDD\u6301\u6BD4\u4F8B", langdir:"\u8BED\u8A00\u4E66\u5199\u65B9\u5411", langcode:"\u8BED\u8A00\u7F16\u7801", long_desc:"\u63CF\u8FF0", style:"\u6837\u5F0F", classes:"\u6837\u5F0F\u7C7B", ltr:"\u4ECE\u5DE6\u5230\u53F3", rtl:"\u4ECE\u53F3\u5230\u5DE6", id:"Id", map:"\u56FE\u7247\u70ED\u70B9", swap_image:"\u5207\u6362\u56FE\u7247", alt_image:"\u4EA4\u66FF\u56FE\u7247", mouseover:"\u9F20\u6807\u5212\u8FC7", mouseout:"\u9F20\u6807\u79FB\u51FA", misc:"\u5176\u5B83", example_img:"\u9884\u89C8\u56FE\u7247", missing_alt:" \u662F\u5426\u4E0D\u4E3A\u56FE\u7247\u52A0\u5165\u8BF4\u660E\u6587\u5B57\uFF0C\u5982\u679C\u4E0D\u52A0\u5165\u8BF4\u660E\u6587\u5B57\uFF0C\u5C06\u5BFC\u81F4\u4E0D\u652F\u6301\u56FE\u7247\u7684\u6D4F\u89C8\u5668\u5FFD\u7565\u672C\u5185\u5BB9", dialog_title:"\u63D2\u5165/\u7F16\u8F91 \u56FE\u7247", src:"\u56FE\u7247\u5730\u5740", alt:"\u56FE\u7247\u8BF4\u660E", list:"\u56FE\u7247\u6E05\u5355", border:"\u8FB9\u6846", dimensions:"\u5C3A\u5BF8", vspace:"\u5782\u76F4\u95F4\u8DDD", hspace:"\u6C34\u5E73\u95F4\u8DDD", align:"\u5BF9\u9F50\u65B9\u5F0F", align_baseline:"\u57FA\u7EBF", align_top:"\u9876\u90E8", align_middle:"\u4E2D\u90E8", align_bottom:"\u5E95\u90E8", align_texttop:"\u6587\u5B57\u4E0A\u65B9", align_textbottom:"\u6587\u5B57\u4E0B\u65B9", align_left:"\u5C45\u5DE6", align_right:"\u5C45\u53F3", image_list:"\u56FE\u7247\u6E05\u5355" });