text
stringlengths
2
6.14k
'use strict'; var inheritance = require('./../../helpers/inheritance'), Field = require('./field'); var FilterField = function(){}; inheritance.inherits(Field,FilterField); FilterField.prototype.isOpen = function(){ return this.world.helper.elementGetter(this._root,this._data.elements.body).isDisplayed(); }; FilterField.prototype.accordionSelf = function(status){ var _this=this; switch(status){ case 'open': return _this.isOpen() .then(function(is){ if(!is){ return _this._root.scrollIntoView() .then(function(){ return _this._root.element(by.css('span.filter__sub-title')).click(); }) .then(function(){ return _this.world.helper.elementGetter(_this._root,_this._data.elements.body).waitToBeCompletelyVisibleAndStable(); }); } }); case 'close': return _this.isOpen() .then(function(is){ if(is){ return _this._root.scrollIntoView() .then(function(){ return _this._root.element(by.css('span.filter__sub-title')).click(); }) .then(function(){ return _this.world.helper.elementGetter(_this._root,_this._data.elements.body).waitToBeHidden(); }); } }); default: throw new Error('Wrong status of slider: '+status); } }; module.exports = FilterField;
define([ 'jquery', 'underscore', 'backbone', 'text!template/login.html', 'models/campus' ], function ($, _, Backbone, LoginTemplate, CampusModel) { var LoginView = Backbone.View.extend({ tagName: 'section', className: 'container', template: _.template(LoginTemplate), events: { 'submit #frm-login': 'frmLoginOnSubmit', 'click #chk-password': 'chkPasswordOnCheck' }, render: function () { this.el.innerHTML = this.template(); return this; }, frmLoginOnSubmit: function (e) { e.preventDefault(); var self = this; var hostName = self.$('#txt-hostname').val().trim(); var username = self.$('#txt-username').val().trim(); var password = self.$('#txt-password').val().trim(); if (!hostName) { return; } if (!username) { return; } if (!password) { return; } self.$('#btn-submit').prop('disabled', true); var checkingLogin = $.post(hostName + '/main/webservices/rest.php', { action: 'loginNewMessages', username: username, password: password }); $.when(checkingLogin).done(function (response) { if (!response.status) { self.$('#btn-submit').prop('disabled', false); return; } var campusModel = new CampusModel({ url: hostName, username: username, apiKey: response.apiKey }); var savingCampus = campusModel.save(); $.when(savingCampus).done(function () { window.location.reload(); }); $.when(savingCampus).fail(function () { self.$('#btn-submit').prop('disabled', false); }); }); $.when(checkingLogin).fail(function () { self.$('#btn-submit').prop('disabled', false); }); }, chkPasswordOnCheck: function (e) { var inputType = e.target.checked ? 'text' : 'password'; this.$('#txt-password').attr('type', inputType); } }); return LoginView; });
const AWS = require('aws-sdk'); const s3 = new AWS.S3(); const conf = require('./config'); const { tmpdir } = require('os'); const fs = require('fs'); const path = require('path'); const mozlog = require('./log'); const log = mozlog('send.storage'); const redis = require('redis'); const redis_client = redis.createClient({ host: conf.redis_host, connect_timeout: 10000 }); redis_client.on('error', err => { log.error('Redis:', err); }); let tempDir = null; if (conf.s3_bucket) { module.exports = { filename: filename, exists: exists, ttl: ttl, length: awsLength, get: awsGet, set: awsSet, setField: setField, delete: awsDelete, forceDelete: awsForceDelete, ping: awsPing, flushall: flushall, quit: quit, metadata }; } else { tempDir = fs.mkdtempSync(`${tmpdir()}${path.sep}send-`); log.info('tempDir', tempDir); module.exports = { filename: filename, exists: exists, ttl: ttl, length: localLength, get: localGet, set: localSet, setField: setField, delete: localDelete, forceDelete: localForceDelete, ping: localPing, flushall: flushall, quit: quit, metadata }; } function flushall() { redis_client.flushdb(); } function quit() { redis_client.quit(); } function metadata(id) { return new Promise((resolve, reject) => { redis_client.hgetall(id, (err, reply) => { if (err || !reply) { return reject(err); } resolve(reply); }); }); } function ttl(id) { return new Promise((resolve, reject) => { redis_client.ttl(id, (err, reply) => { if (err || !reply) { return reject(err); } resolve(reply * 1000); }); }); } function filename(id) { return new Promise((resolve, reject) => { redis_client.hget(id, 'filename', (err, reply) => { if (err || !reply) { return reject(); } resolve(reply); }); }); } function exists(id) { return new Promise((resolve, reject) => { redis_client.exists(id, (rediserr, reply) => { if (reply === 1 && !rediserr) { resolve(); } else { reject(rediserr); } }); }); } function setField(id, key, value) { redis_client.hset(id, key, value); } function localLength(id) { return new Promise((resolve, reject) => { try { resolve(fs.statSync(path.join(tempDir, id)).size); } catch (err) { reject(); } }); } function localGet(id) { return fs.createReadStream(path.join(tempDir, id)); } function localSet(newId, file, filename, meta) { return new Promise((resolve, reject) => { const filepath = path.join(tempDir, newId); const fstream = fs.createWriteStream(filepath); file.pipe(fstream); file.on('limit', () => { file.unpipe(fstream); fstream.destroy(new Error('limit')); }); fstream.on('finish', () => { redis_client.hmset(newId, meta); redis_client.expire(newId, conf.expire_seconds); log.info('localSet:', 'Upload Finished of ' + newId); resolve(meta.delete); }); fstream.on('error', err => { log.error('localSet:', 'Failed upload of ' + newId); fs.unlinkSync(filepath); reject(err); }); }); } function localDelete(id, delete_token) { return new Promise((resolve, reject) => { redis_client.hget(id, 'delete', (err, reply) => { if (!reply || delete_token !== reply) { reject(); } else { redis_client.del(id); log.info('Deleted:', id); resolve(fs.unlinkSync(path.join(tempDir, id))); } }); }); } function localForceDelete(id) { return new Promise((resolve, reject) => { redis_client.del(id); resolve(fs.unlinkSync(path.join(tempDir, id))); }); } function localPing() { return new Promise((resolve, reject) => { redis_client.ping(err => { return err ? reject() : resolve(); }); }); } function awsLength(id) { const params = { Bucket: conf.s3_bucket, Key: id }; return new Promise((resolve, reject) => { s3.headObject(params, function(err, data) { if (!err) { resolve(data.ContentLength); } else { reject(); } }); }); } function awsGet(id) { const params = { Bucket: conf.s3_bucket, Key: id }; try { return s3.getObject(params).createReadStream(); } catch (err) { return null; } } function awsSet(newId, file, filename, meta) { const params = { Bucket: conf.s3_bucket, Key: newId, Body: file }; let hitLimit = false; const upload = s3.upload(params); file.on('limit', () => { hitLimit = true; upload.abort(); }); return upload.promise().then( () => { redis_client.hmset(newId, meta); redis_client.expire(newId, conf.expire_seconds); }, err => { if (hitLimit) { throw new Error('limit'); } else { throw err; } } ); } function awsDelete(id, delete_token) { return new Promise((resolve, reject) => { redis_client.hget(id, 'delete', (err, reply) => { if (!reply || delete_token !== reply) { reject(); } else { const params = { Bucket: conf.s3_bucket, Key: id }; s3.deleteObject(params, function(err, _data) { redis_client.del(id); err ? reject(err) : resolve(err); }); } }); }); } function awsForceDelete(id) { return new Promise((resolve, reject) => { const params = { Bucket: conf.s3_bucket, Key: id }; s3.deleteObject(params, function(err, _data) { redis_client.del(id); err ? reject(err) : resolve(); }); }); } function awsPing() { return localPing().then(() => s3.headBucket({ Bucket: conf.s3_bucket }).promise() ); }
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; var fs = require("fs"); var path = require("path"); var utils = require("../utils"); var chai = require("chai"); var expect = chai.expect; var exec = utils.exec; var simpleAddonPath = path.join(__dirname, "..", "fixtures", "simple-addon"); describe("jpm xpi", function () { beforeEach(utils.setup); afterEach(utils.tearDown); it("creates a xpi of the simple-addon", function (done) { var proc = exec("xpi", { addonDir: simpleAddonPath }); proc.on("close", function () { var xpiPath = path.join(simpleAddonPath, "@simple-addon-1.0.0.xpi"); utils.unzipTo(xpiPath, utils.tmpOutputDir).then(function () { utils.compareDirs(simpleAddonPath, utils.tmpOutputDir); fs.unlink(xpiPath); done(); }); }); }); });
import React, { Fragment } from 'react'; import { compose, graphql } from 'react-apollo'; import { set } from 'react-redux-values'; import ReduxForm from 'declarative-redux-form'; import { Row, Col } from 'joyent-react-styled-flexboxgrid'; import { Margin } from 'styled-components-spacing'; import { change } from 'redux-form'; import { connect } from 'react-redux'; import intercept from 'apr-intercept'; import get from 'lodash.get'; import { NameIcon, H3, Button, H4, P } from 'joyent-ui-toolkit'; import Title from '@components/create-image/title'; import Details from '@components/create-image/details'; import Description from '@components/description'; import GetRandomName from '@graphql/get-random-name.gql'; import createClient from '@state/apollo-client'; import { instanceName as validateName } from '@state/validators'; import { Forms } from '@root/constants'; const NameContainer = ({ expanded, proceeded, name, version, description, placeholderName, randomizing, handleAsyncValidate, shouldAsyncValidate, handleNext, handleRandomize, handleEdit, step }) => ( <Fragment> <Title id={step} onClick={!expanded && !name && handleEdit} collapsed={!expanded && !proceeded} icon={<NameIcon />} > Image name and details </Title> {expanded ? ( <Description> Here you can name your custom image, version it, and give it a description so that you can identify it elsewhere in the Triton ecosystem. </Description> ) : null} <ReduxForm form={Forms.FORM_DETAILS} destroyOnUnmount={false} forceUnregisterOnUnmount={true} asyncValidate={handleAsyncValidate} shouldAsyncValidate={shouldAsyncValidate} onSubmit={handleNext} > {props => expanded ? ( <Details {...props} placeholderName={placeholderName} randomizing={randomizing} onRandomize={handleRandomize} /> ) : name ? ( <Margin top="3"> <H3 bold noMargin> {name} </H3> {version ? ( <Margin top="2"> <H4 bold noMargin> {version} </H4> </Margin> ) : null} {description ? ( <Row> <Col xs="12" sm="8"> <Margin top="1"> <P>{description}</P> </Margin> </Col> </Row> ) : null} </Margin> ) : null } </ReduxForm> {expanded ? ( <Margin top="4" bottom="7"> <Button type="button" disabled={!name} onClick={handleNext}> Next </Button> </Margin> ) : proceeded ? ( <Margin top="4" bottom="7"> <Button type="button" onClick={handleEdit} secondary> Edit </Button> </Margin> ) : null} </Fragment> ); export default compose( graphql(GetRandomName, { options: () => ({ fetchPolicy: 'network-only', ssr: false }), props: ({ data }) => ({ placeholderName: data.rndName || '' }) }), connect( ({ form, values }, ownProps) => { const name = get(form, `${Forms.FORM_DETAILS}.values.name`, ''); const version = get(form, `${Forms.FORM_DETAILS}.values.version`, ''); const description = get( form, `${Forms.FORM_DETAILS}.values.description`, '' ); const proceeded = get(values, `${Forms.FORM_DETAILS}-proceeded`, false); const randomizing = get(values, 'create-image-name-randomizing', false); return { ...ownProps, proceeded, randomizing, name, version, description }; }, (dispatch, { history, match }) => ({ handleNext: () => { dispatch(set({ name: `${Forms.FORM_DETAILS}-proceeded`, value: true })); return history.push(`/images/~create/${match.params.instance}/tag`); }, handleEdit: () => { dispatch(set({ name: `${Forms.FORM_DETAILS}-proceeded`, value: true })); return history.push(`/images/~create/${match.params.instance}/name`); }, shouldAsyncValidate: ({ trigger }) => { return trigger === 'change'; }, handleAsyncValidate: validateName, handleRandomize: async () => { dispatch(set({ name: 'create-image-name-randomizing', value: true })); const [err, res] = await intercept( createClient().query({ fetchPolicy: 'network-only', query: GetRandomName }) ); dispatch(set({ name: 'create-image-name-randomizing', value: false })); if (err) { // eslint-disable-next-line no-console console.error(err); return; } const { data } = res; const { rndName } = data; return dispatch(change(Forms.FORM_DETAILS, 'name', rndName)); } }) ) )(NameContainer);
/* Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang("placeholder","pt",{title:"Propriedades dos marcadores",toolbar:"Símbolo",name:"Nome do marcador",invalidName:"O marcador não pode estar em branco e não pode conter qualquer dos seguintes carateres: [, ], <, >",pathName:"símbolo"});
exports.main = function(env){ var capsule = env.capsule; var mtests = capsule.tests.modules; var thsocket = capsule.tests.modules.transport.http.socket_srv; // mtests.http_responder.test(capsule); // thsocket.test({ 'url' : 'http://localhost:8810/sockethh.js'}, capsule); var thttp = capsule.tests.modules.transport.http.server; thttp.test({ 'url' : 'http://localhost:8810/krevetk/o'}, capsule); }
/* Copyright (c) 2006-2012 by OpenLayers Contributors (see authors.txt for * full list of contributors). Published under the 2-clause BSD license. * See license.txt in the OpenLayers distribution or repository for the * full text of the license. */ /** * @requires OpenLayers/Format/SLD/v1.js * @requires OpenLayers/Format/Filter/v1_0_0.js */ /** * Class: OpenLayers.Format.SLD.v1_0_0 * Write SLD version 1.0.0. * * Inherits from: * - <OpenLayers.Format.SLD.v1> */ OpenLayers.Format.SLD.v1_0_0 = OpenLayers.Class( OpenLayers.Format.SLD.v1, { /** * Constant: VERSION * {String} 1.0.0 */ VERSION: "1.0.0", /** * Property: schemaLocation * {String} http://www.opengis.net/sld * http://schemas.opengis.net/sld/1.0.0/StyledLayerDescriptor.xsd */ schemaLocation: "http://www.opengis.net/sld http://schemas.opengis.net/sld/1.0.0/StyledLayerDescriptor.xsd", /** * Constructor: OpenLayers.Format.SLD.v1_0_0 * Instances of this class are not created directly. Use the * <OpenLayers.Format.SLD> constructor instead. * * Parameters: * options - {Object} An optional object whose properties will be set on * this instance. */ CLASS_NAME: "OpenLayers.Format.SLD.v1_0_0" });
'use strict'; angular.module('GO.Modules.GroupOffice.Contacts').factory('GO.Modules.GroupOffice.Contacts.Model.ContactGroup', [ 'GO.Core.Factories.Data.Model', function (Model) { var ContactGroup = GO.extend(Model, function () { //rename function because this record has a delete attribute on the server this.deleteRecord = this.delete; this.$parent.constructor.call(this, arguments); }); ContactGroup.prototype.getStoreRoute = function () { return 'contacts/'+this.contactId+'/permissions'; }; ContactGroup.prototype.$keys = ['groupId']; return ContactGroup; }]);
import React from 'react' import {intlEnzyme} from 'tocco-test-util' import MenuChildrenWrapper from './MenuChildrenWrapper' import {StyledMenuChildrenWrapper} from './StyledComponents' describe('admin', () => { describe('components', () => { describe('Navigation', () => { describe('menuType', () => { describe('MenuChildrenWrapper', () => { test('should render children when expanded', () => { const isOpen = true const canCollapse = true const children = <div id="child">Hallo</div> const props = { isOpen, canCollapse, menuTreePath: 'address', preferencesPrefix: '' } const wrapper = intlEnzyme.mountWithIntl(<MenuChildrenWrapper {...props}>{children}</MenuChildrenWrapper>) expect(wrapper.find(StyledMenuChildrenWrapper).prop('isOpen')).to.be.true }) test('should not render children when collapsed', () => { const isOpen = false const canCollapse = true const children = <div id="child">Hallo</div> const props = { isOpen, canCollapse, menuTreePath: 'address', preferencesPrefix: '' } const wrapper = intlEnzyme.mountWithIntl(<MenuChildrenWrapper {...props}>{children}</MenuChildrenWrapper>) expect(wrapper.find(StyledMenuChildrenWrapper).prop('isOpen')).to.be.false }) test('should render children when not collapsible', () => { const isOpen = false const canCollapse = false const children = <div id="child">Hallo</div> const props = { isOpen, canCollapse, menuTreePath: 'address', preferencesPrefix: '' } const wrapper = intlEnzyme.mountWithIntl(<MenuChildrenWrapper {...props}>{children}</MenuChildrenWrapper>) expect(wrapper.find(StyledMenuChildrenWrapper).prop('isOpen')).to.be.true }) }) }) }) }) })
'use strict'; var phonetic = require('phonetic'); var socketio = require('socket.io'); var _ = require('underscore'); var load = function(http) { var io = socketio(http); var ioNamespace = '/'; var getEmptyRoomId = function() { var roomId = null; do { roomId = phonetic.generate().toLowerCase() } while (io.nsps[ioNamespace].adapter.rooms[roomId]); return roomId; }; var sendRoomInfo = function(socket, info) { if (!info.roomId) { return; } var clients = io.nsps[ioNamespace].adapter.rooms[info.roomId]; io.sockets.in(info.roomId).emit('room.info', { id: info.roomId, count: clients ? Object.keys(clients).length : 0 }); }; var onJoin = function(socket, info, data) { if (info.roomId) { return; } info.roomId = data && data.roomId ? data.roomId : null; if (!info.roomId || !io.nsps[ioNamespace].adapter.rooms[data.roomId]) { info.roomId = getEmptyRoomId(socket); console.log('[Socket] Assigning room id ' + info.roomId + ' to ip ' + socket.handshake.address); } else { console.log('[Socket] Assigning room id ' + info.roomId + ' to ip ' + socket.handshake.address + ' (from client)'); } socket.join(info.roomId); socket.emit('join', { roomId: info.roomId }); sendRoomInfo(socket, info); }; var onEvent = function(socket, info, event, data) { if (!info.roomId) { return; } socket.broadcast.to(info.roomId).emit(event, data); }; var onChunk = function(socket, info, data) { socket.emit('file.ack', { guid: data.guid }); onEvent(socket, info, 'file.chunk', data); }; var onConnection = function(socket) { console.log('[Socket] New connection from ip ' + socket.handshake.address); var info = { roomId: null }; socket.on('disconnect', function() { console.log('[Socket] Connection from ip ' + socket.handshake.address + ' disconnected'); sendRoomInfo(socket, info); }); socket.on('join', _.partial(onJoin, socket, info)); socket.on('file.start', _.partial(onEvent, socket, info, 'file.start')); socket.on('file.chunk', _.partial(onChunk, socket, info)); } io.on('connection', onConnection); }; module.exports = { load: load };
var searchData= [ ['backtrace',['backtrace',['../class_logger.html#a5deb9b10c43285287a9113f280ee8fab',1,'Logger']]], ['baseexception',['BaseException',['../class_base_exception.html',1,'']]], ['baseexception_2ephp',['BaseException.php',['../_base_exception_8php.html',1,'']]], ['basic_2ephp',['Basic.php',['../_menu_2_basic_8php.html',1,'']]], ['basic_2ephp',['Basic.php',['../_paginator_2_basic_8php.html',1,'']]], ['basic_2ephp',['Basic.php',['../_auth_2_basic_8php.html',1,'']]], ['basic_2ephp',['Basic.php',['../_t_mail_2_basic_8php.html',1,'']]], ['basic_2ephp',['Basic.php',['../_form_2_basic_8php.html',1,'']]], ['basic_2ephp',['Basic.php',['../_grid_2_basic_8php.html',1,'']]], ['basicauth',['BasicAuth',['../class_basic_auth.html',1,'']]], ['basicauth_2ephp',['BasicAuth.php',['../_basic_auth_8php.html',1,'']]], ['beforedelete',['beforeDelete',['../class_s_q_l___relation.html#a44c9d7a3b22619b53d4f49f1070d5235',1,'SQL_Relation']]], ['beforefield',['beforeField',['../class_form___field.html#aa4bbfb40048e1c3fe939621179652be1',1,'Form_Field']]], ['beforeinsert',['beforeInsert',['../class_s_q_l___relation.html#ada6a7f2abf3ba1c19e4ba3711da1a61e',1,'SQL_Relation']]], ['beforeload',['beforeLoad',['../class_s_q_l___relation.html#a665492752f54f9cbc3fd2cae51ca4373',1,'SQL_Relation']]], ['beforemodify',['beforeModify',['../class_s_q_l___relation.html#a3ad587772d12f99af11a3db64d879210',1,'SQL_Relation']]], ['beforesave',['beforeSave',['../class_s_q_l___relation.html#ab9e4fb36c177d9633b81fc184f7bd933',1,'SQL_Relation']]], ['begintransaction',['beginTransaction',['../class_d_b.html#af3380f3b13931d581fa973a382946b32',1,'DB\beginTransaction()'],['../class_d_blite__mysql.html#a06fdc3063ff49b8de811683aae3483e6',1,'DBlite_mysql\beginTransaction()']]], ['belowfield',['belowField',['../class_form___field.html#a27cd7c6e75ed8c09aae8af32905a888d',1,'Form_Field']]], ['box_2ephp',['Box.php',['../_box_8php.html',1,'']]], ['breakhook',['breakHook',['../class_abstract_object.html#a446b3f8327b3272c838ae46f40a9da06',1,'AbstractObject']]], ['bt',['bt',['../class_d_b__dsql.html#aa374d1bfaabf3f546fe8862d09f4a096',1,'DB_dsql']]], ['button',['Button',['../class_button.html',1,'']]], ['button_2ephp',['Button.php',['../_button_8php.html',1,'']]], ['button_2ephp',['Button.php',['../_form_2_button_8php.html',1,'']]], ['button_2ephp',['Button.php',['../_view_2_button_8php.html',1,'']]], ['buttonset',['ButtonSet',['../class_button_set.html',1,'']]], ['buttonset_2ephp',['ButtonSet.php',['../_button_set_8php.html',1,'']]], ['buttonset_2ephp',['ButtonSet.php',['../_view_2_button_set_8php.html',1,'']]] ];
import React from 'react'; import PropTypes from 'prop-types'; import ManaUsageGraph from './ManaUsageGraph'; class HealingDoneGraph extends React.PureComponent { static propTypes = { start: PropTypes.number.isRequired, end: PropTypes.number.isRequired, offset: PropTypes.number.isRequired, healingBySecond: PropTypes.object.isRequired, manaUpdates: PropTypes.array.isRequired, }; groupHealingBySeconds(healingBySecond, interval) { return Object.keys(healingBySecond) .reduce((obj, second) => { const healing = healingBySecond[second]; const index = Math.floor(second / interval); if (obj[index]) { obj[index] = obj[index].add(healing.regular, healing.absorbed, healing.overheal); } else { obj[index] = healing; } return obj; }, {}); } render() { const { start, end, offset, healingBySecond, manaUpdates } = this.props; // TODO: move this to vega-lite window transform // e.g. { window: [{op: 'mean', field: 'hps', as: 'hps'}], frame: [-2, 2] } const interval = 5; const healingPerFrame = this.groupHealingBySeconds(healingBySecond, interval); let max = 0; Object.keys(healingPerFrame) .map(k => healingPerFrame[k]) .forEach((healingDone) => { const current = healingDone.effective; if (current > max) { max = current; } }); max /= interval; const manaUsagePerFrame = { 0: 0, }; const manaLevelPerFrame = { 0: 1, }; manaUpdates.forEach((item) => { const frame = Math.floor((item.timestamp - start) / 1000 / interval); manaUsagePerFrame[frame] = (manaUsagePerFrame[frame] || 0) + item.used / item.max; manaLevelPerFrame[frame] = item.current / item.max; // use the lowest value of the frame; likely to be more accurate }); const fightDurationSec = Math.ceil((end - start) / 1000); const labels = []; for (let i = 0; i <= fightDurationSec / interval; i += 1) { labels.push(Math.ceil(offset/1000) + i * interval); healingPerFrame[i] = healingPerFrame[i] !== undefined ? healingPerFrame[i].effective : 0; manaUsagePerFrame[i] = manaUsagePerFrame[i] !== undefined ? manaUsagePerFrame[i] : 0; manaLevelPerFrame[i] = manaLevelPerFrame[i] !== undefined ? manaLevelPerFrame[i] : null; } let lastKnown = null; const mana = Object.values(manaLevelPerFrame).map((value, i) => { if (value !== null) { lastKnown = value; } return { x: labels[i], y: lastKnown * max, }; }); const healing = Object.values(healingPerFrame).map((value, i) => ({ x: labels[i], y: value / interval })); const manaUsed = Object.values(manaUsagePerFrame).map((value, i) => ({ x: labels[i], y: value * max })); return ( <div className="graph-container" style={{ marginBottom: 20 }}> <ManaUsageGraph mana={mana} healing={healing} manaUsed={manaUsed} /> </div> ); } } export default HealingDoneGraph;
"use strict"; require("./setup"); var exchange = require("../src/exchange"), assert = require("assert"), config = require("config"), async = require("async"); describe("Exchange", function () { describe("rounding", function () { it("should round as expected", function() { assert.equal( exchange.round("USD", 33.38 + 10.74), 44.12); }); }); describe("Load and keep fresh the exchange rates", function () { it("should be using test path", function () { // check it is faked out for tests var stubbedPath = "config/initial_exchange_rates.json"; assert.equal( exchange.pathToLatestJSON(), stubbedPath); // check it is normally correct exchange.pathToLatestJSON.restore(); assert.notEqual( exchange.pathToLatestJSON(), stubbedPath); }); it("fx object should convert correctly", function () { assert.equal(exchange.convert(100, "GBP", "USD"), 153.85 ); // 2 dp assert.equal(exchange.convert(100, "GBP", "JPY"), 15083 ); // 0 dp assert.equal(exchange.convert(100, "GBP", "LYD"), 195.385 ); // 3 dp assert.equal(exchange.convert(100, "GBP", "XAG"), 6.15 ); // null dp }); it("should reload exchange rates periodically", function (done) { var fx = exchange.fx; var clock = this.sandbox.clock; // change one of the exchange rates to test for the reload var originalGBP = fx.rates.GBP; fx.rates.GBP = 123.456; // start the delayAndReload exchange.initiateDelayAndReload(); // work out how long to wait var delay = exchange.calculateDelayUntilNextReload(); // go almost to the roll over and check no change clock.tick( delay-10 ); assert.equal(fx.rates.GBP, 123.456); async.series([ function (cb) { // go past rollover and check for change exchange.hub.once("reloaded", function () { assert.equal(fx.rates.GBP, originalGBP); cb(); }); clock.tick( 20 ); }, function (cb) { // reset it again and go ahead another interval and check for change fx.rates.GBP = 123.456; exchange.hub.once("reloaded", function () { assert.equal(fx.rates.GBP, originalGBP); cb(); }); clock.tick( config.exchangeReloadIntervalSeconds * 1000 ); } ], done); }); it.skip("should handle bad exchange rates JSON"); }); });
window.WebServiceClientTest = new Class( { Implements : [Events, JsTestClass, Options], Binds : ['onDocumentReady', 'onDocumentError'], options : { testMethods : [ { method : 'initialize_', isAsynchron : false }] }, constants : { }, initialize : function( options ) { this.setOptions( options ); this.webServiceClient; }, beforeEachTest : function(){ this.webServiceClient = new WebServiceClient({ }); }, afterEachTest : function (){ this.webServiceClient = null; }, initialize_ : function() { assertThat( this.webServiceClient, JsHamcrest.Matchers.instanceOf( WebServiceClient )); } });
import { module, test } from 'qunit'; import { setupTest } from 'ember-qunit'; module('Unit | Model | partner partnerclient plan', function(hooks) { setupTest(hooks); // Replace this with your real tests. test('it exists', function(assert) { let store = this.owner.lookup('service:store'); let model = store.createRecord('partner/partnerclient-plan', {}); assert.ok(model); }); });
'use strict'; /** * @ngdoc directive * @name GO.Core.CustomFields.goCustomFieldsEdit * * @description * Prints custom fields form fieldsets. * * * @param {string} ngModel The customFields model property of the model the customFields belong to * @param {string} serverModel The custom fields server model. * * @example * <go-custom-fields-edit ng-model="contact.customFields" server-model="GO\Modules\GroupOffice\Contacts\Model\ContactCustomFields"></go-custom-fields-edit> */ angular.module('GO.Core').directive('goCustomFieldsEdit', [ '$templateCache', '$compile', 'GO.Core.Directives.CustomFields', function ($templateCache, $compile, CustomFields) { var buildTemplate = function (customFieldSetStore) { var tpl = ''; for (var i = 0, l = customFieldSetStore.items.length; i < l; i++) { var fieldSet = customFieldSetStore.items[i]; tpl += '<fieldset><h3>{{::"' + fieldSet.name + '" | goT}}</h3>'; for (var n = 0, cl = fieldSet.fields.length; n < cl; n++) { var field = fieldSet.fields[n]; tpl += buildFunctions[field.type](field); } tpl += '</fieldset>'; } return tpl; }; var buildFunctions = { formName: null, text: function (field) { return '<md-input-container class="md-block">\ <md-icon>star</md-icon>\ <label>{{::"' + field.name + '" | goT}}</label>\ <input name="' + field.databaseName + '" type="text" maxlength="' + field.data.maxLength + '" ng-model="goModel[\'' + field.databaseName + '\']" ng-required="' + (field.required ? 'true' : 'false') + '" />\ <md-hint>{{::"'+field.hintText+'" | goT}}</md-hint>\ <div ng-messages="formController.' + field.databaseName + '.$error" role="alert">\ <div ng-message="required">\ {{::"This field is required" | goT}}\ </div>\ </div>\ </md-input-container>'; }, textarea: function (field) { return '<md-input-container class="md-block">\ <md-icon>star</md-icon>\ <label>{{::"' + field.name + '" | goT}}</label>\ <textarea id="' + field.databaseName + '" name="' + field.databaseName + '" maxlength="' + field.data.maxLength + '" ng-model="goModel[\'' + field.databaseName + '\']" ng-required="' + (field.required ? 'true' : 'false') + '"></textarea>\ <md-hint>{{::"'+field.hintText+'" | goT}}</md-hint>\ <div ng-messages="formController.' + field.databaseName + '.$error" role="alert">\ <div ng-message="required">\ {{::"This field is required" | goT}}\ </div>\ </div>\ </md-input-container>'; }, select: function (field) { var tpl = '<md-input-container class="md-block">\ <md-icon>star</md-icon>\ <label>{{::"' + field.name + '" | goT}}</label>\ <md-select name="' + field.databaseName + '" ng-model="goModel[\'' + field.databaseName + '\']" ng-required="' + (field.required ? 'true' : 'false') + '">'; for (var i = 0, l = field.data.options.length; i < l; i++) { tpl += '<md-option value="' + field.data.options[i] + '">{{::"' + field.data.options[i] + '" | goT}}</md-option>'; } tpl += '</md-select>\ <md-hint>{{::"'+field.hintText+'" | goT}}</md-hint>\ <div class="md-errors-spacer"></div>\ <div ng-messages="formController.' + field.databaseName + '.$error" role="alert">\ <div ng-message="required">\ {{::"This field is required" | goT}}\ </div>\ </div>'; tpl += '</md-input-container>'; return tpl; }, checkbox: function (field) { return '<md-input-container class="md-block">\ <md-checkbox id="cf_{{field.id}}" ng-model="goModel[\'' + field.databaseName + '\']" ng-required="' + (field.required ? 'true' : 'false') + '"> {{::"' + field.name + '" | goT}}</md-checkbox>\ <md-hint>{{::"'+field.hintText+'" | goT}}</md-hint>\ </md-input-container>'; }, date: function (field) { return '<go-date-picker id="cf_{{field.id}}" name="dateOfBirth" hint="{{::\''+field.hintText+'\' | goT }}" label="' + field.name + '" ng-model="goModel[\'' + field.databaseName + '\']" ng-required="' + (field.required ? 'true' : 'false') + '"></go-date-picker>'; }, number: function (field) { return '<md-input-container class="md-block">\ <md-icon>star</md-icon>\ <label>{{::"' + field.name + '" | goT}}</label>\ <input go-number id="cf_{{field.id}}" name="' + field.databaseName + '" type="text" ng-model="goModel[\'' + field.databaseName + '\']" ng-required="' + (field.required ? 'true' : 'false') + '" />\ <md-hint>{{::"'+field.hintText+'" | goT}}</md-hint>\ <div ng-messages="formController.' + field.databaseName + '.$error" role="alert">\ <div ng-message="required">\ {{::"This field is required" | goT}}\ </div>\ </div>\ </md-input-container>'; } }; return { restrict: 'E', scope: { goModel: '=ngModel', serverModel: '@', formController: '=' }, link: function (scope, element, attrs) { var customFieldSetStore = CustomFields.getFieldSetStore(attrs.serverModel); //TODO load is called twice now customFieldSetStore.promise.then(function () { var tpl = buildTemplate(customFieldSetStore); element.html(tpl); $compile(element.contents())(scope); }); } }; }]);
'use strict' var config = {} config.facebook = { 'appID': '261938654297222', 'appSecret': 'cd8d0bf4ce75ae5e24be29970b79876f', 'callbackUrl': '/login/facebook/callback/' } config.server = { 'port': process.env.PORT || 3000, 'env': process.env.NODE_ENV || 'dev', 'dbUrl': process.env.MONGODB_URI || 'mongodb://localhost:27017/minihero', 'sessionSecret': 'Minihero FTW!' } config.defaultLocation = { // The default location shown to signed out users on /missions is Amsterdam! latitude: 52.370216, longitude: 4.895168 } config.apiKeys = { google: 'AIzaSyA4vKjKRLNIZ829rfFvz9m_-OFhiORB5Q8' } module.exports = config
/* * _ _ _ * | | | | | | * | | __ _| |__ ___ ___ __ _| |_ Labcoat (R) * | |/ _` | '_ \ / __/ _ \ / _` | __| Powerful development environment for Quirrel. * | | (_| | |_) | (_| (_) | (_| | |_ Copyright (C) 2010 - 2013 SlamData, Inc. * |_|\__,_|_.__/ \___\___/ \__,_|\__| All Rights Reserved. * * * This program is free software: you can redistribute it and/or modify it under the terms of the * GNU Affero General Public License as published by the Free Software Foundation, either version * 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See * the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this * program. If not, see <http://www.gnu.org/licenses/>. * */ define(function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var CSharpHighlightRules = require("./csharp_highlight_rules").CSharpHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { this.$tokenizer = new Tokenizer(new CSharpHighlightRules().getRules()); this.$outdent = new MatchingBraceOutdent(); this.$behaviour = new CstyleBehaviour(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.lineCommentStart = "//"; this.blockComment = {start: "/*", end: "*/"}; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokenizedLine = this.$tokenizer.getLineTokens(line, state); var tokens = tokenizedLine.tokens; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } if (state == "start") { var match = line.match(/^.*[\{\(\[]\s*$/); if (match) { indent += tab; } } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; this.createWorker = function(session) { return null; }; }).call(Mode.prototype); exports.Mode = Mode; });
/** * Based conceptually on the _.extend() function in underscore.js ( see http://documentcloud.github.com/underscore/#extend for more details ) * Copyright (C) 2012 Kurt Milam - http://xioup.com | Source: https://gist.github.com/1868955 * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/. **/ var _ = require('underscore'); deepExtend = function(obj) { var parentRE = /#{\s*?_\s*?}/, slice = Array.prototype.slice, hasOwnProperty = Object.prototype.hasOwnProperty; _.each(slice.call(arguments, 1), function(source) { for (var prop in source) { if (hasOwnProperty.call(source, prop)) { if (_.isUndefined(obj[prop]) || _.isFunction(obj[prop]) || _.isNull(source[prop])) { obj[prop] = source[prop]; } else if (_.isString(source[prop]) && parentRE.test(source[prop])) { if (_.isString(obj[prop])) { obj[prop] = source[prop].replace(parentRE, obj[prop]); } } else if (_.isArray(obj[prop]) || _.isArray(source[prop])){ if (!_.isArray(obj[prop]) || !_.isArray(source[prop])){ throw 'Error: Trying to combine an array with a non-array (' + prop + ')'; } else { obj[prop] = _.reject(_.deepExtend(obj[prop], source[prop]), function (item) { return _.isNull(item);}); } } else if (_.isObject(obj[prop]) || _.isObject(source[prop])){ if (!_.isObject(obj[prop]) || !_.isObject(source[prop])){ throw 'Error: Trying to combine an object with a non-object (' + prop + ')'; } else { obj[prop] = _.deepExtend(obj[prop], source[prop]); } } else { obj[prop] = source[prop]; } } } }); return obj; }; exports.deepExtend = deepExtend;
import CodeClipboard from './CodeClipboard'; export default CodeClipboard;
const { Array } = require.main.require('./Tag/Classes'); class GetTag extends Array { constructor(client) { super(client, { name: 'get', args: [ { name: 'array' }, { name: 'index' } ], minArgs: 2, maxArgs: 2 }); } async execute(ctx, args) { const res = await super.execute(ctx, args, true); args = args.parsedArgs; let arr = await this.loadArray(ctx, args.array); let index = this.parseInt(args.index, 'index'); return res.setContent(arr[index]); } get implicit() { return false; } } module.exports = GetTag;
/** * @ngdoc service * @name ftepApp.SubscriptionService * @description * # SubscriptionService * Service for subscriptions. */ 'use strict'; define(['../ftepmodules', 'traversonHal'], function (ftepmodules, TraversonJsonHalAdapter) { ftepmodules.service('SubscriptionService', [ 'ftepProperties', '$q', 'traverson', function (ftepProperties, $q, traverson) { var self = this; traverson.registerMediaType(TraversonJsonHalAdapter.mediaType, TraversonJsonHalAdapter); var rootUri = ftepProperties.URLv2; var halAPI = traverson.from(rootUri).jsonHal().useAngularHttp(); var deleteAPI = traverson.from(rootUri).useAngularHttp(); this.getUserSubscriptions = function(user) { var deferred = $q.defer(); halAPI.from(rootUri + '/subscriptions/search/findByOwner?owner=' + user._links.self.href) .newRequest() .getResource() .result .then( function(document) { deferred.resolve(document); }, function(error) { MessageService.addError('Failed to get subscriptions for user ' + user.name, error); deferred.reject(); }); return deferred.promise; }; this.updateSubscription = function(subscription) { var patchedSubscription = { packageName: subscription.packageName, storageQuota: subscription.storageQuota, processingQuota: subscription.processingQuota, subscriptionStart: subscription.subscriptionStart, subscriptionEnd: subscription.subscriptionEnd, commentText: subscription.commentText }; var deferred = $q.defer(); halAPI.from(rootUri + '/subscriptions/' + subscription.id) .newRequest() .patch(patchedSubscription) .result .then( function(document) { deferred.resolve(document); }, function(error) { MessageService.addError('Failed to update subscription ' + subscription.id, error); deferred.reject(); }); return deferred.promise; }; this.createSubscription = function(subscription, subscriptionOwner, subscriptionCreator) { var newSubscription = { owner: subscriptionOwner._links.self.href, packageName: subscription.packageName, storageQuota: subscription.storageQuota, processingQuota: subscription.processingQuota, subscriptionStart: subscription.subscriptionStart, subscriptionEnd: subscription.subscriptionEnd, commentText: subscription.commentText, creator: subscriptionCreator._links.self.href }; var deferred = $q.defer(); halAPI.from(rootUri + '/subscriptions') .newRequest() .post(newSubscription) .result .then( function(document) { deferred.resolve(document); }, function(error) { MessageService.addError('Failed to update subscription ' + subscription.id, error); deferred.reject(); }); return deferred.promise; }; this.deleteSubscription = function(subscription) { var deferred = $q.defer(); deleteAPI.from(rootUri + '/subscriptions/' + subscription.id) .newRequest() .delete() .result .then( function(document) { if (200 <= document.status && document.status < 300) { deferred.resolve(document); } else { MessageService.addError('Failed to delete subscription ' + subscription.id, error); deferred.reject(); } }, function(error) { MessageService.addError('Failed to delete subscription ' + subscription.id, error); deferred.reject(); }); return deferred.promise; }; this.cancelSubscription = function(subscription) { var deferred = $q.defer(); halAPI.from(rootUri + '/subscriptions/' + subscription.id + "/cancel") .newRequest() .post() .result .then( function(document) { deferred.resolve(document); }, function(error) { MessageService.addError('Failed to cancel subscription ' + subscription.id, error); deferred.reject(); }); return deferred.promise; }; return this; }]); });
var request = require("request"); var yaml = require("js-yaml"); var jsonfile = require("jsonfile"); request("https://raw.githubusercontent.com/unitedstates/congress-legislators/master/legislators-current.yaml", function(error, response, body) { if (!error && response.statusCode == 200) { var legislators = yaml.safeLoad(body); legislators = legislators.map(function(legislator) { var term = legislator.terms[legislator.terms.length-1]; return { firstName: legislator.name.first, lastName: legislator.name.last, bioguideId: legislator.id.bioguide, chamber: term.type == "rep" ? "house" : "senate", title: term.type == "rep" ? "Rep" : "Sen", state: term.state, district: typeof term.district == "undefined" ? null : term.district.toString() }; }); jsonfile.writeFileSync("congress.json", legislators, { spaces: 2 }); } else if (error) { console.error("Failed to fetch legislators-current.yaml", error); } else { console.error("Failed to fetch legislators-current.yaml", "("+response.statusCode+" "+response.statusMessage+")"); } });
/** * Nooku Framework - http://www.nooku.org * * @copyright Copyright (C) 2011 - 2017 Johan Janssens and Timble CVBA. (http://www.timble.net) * @license GNU AGPLv3 <https://www.gnu.org/licenses/agpl.html> * @link https://github.com/timble/openpolice-platform */ if(!Ckeditor) var Ckeditor = {}; Ckeditor.Files = new Class({ Extends: Files.App, Implements: [Events, Options], options: { types: ['file', 'image'], editor: null, preview: 'files-preview', grid: { cookie: false, layout: 'compact', batch_delete: false }, history: { enabled: false } }, initialize: function(options) { this.parent(options); this.editor = this.options.editor; this.preview = document.id(this.options.preview); }, setPaginator: function() { }, setPathway: function() { }, setState: function() { // TODO: Implement pagination into the view this.fireEvent('beforeSetState'); var opts = this.options.state; this.state = new Files.State(opts); this.fireEvent('afterSetState'); }, setGrid: function() { var opts = this.options.grid; var that = this; $extend(opts, { 'onClickImage': function(e) { that.setPreview(document.id(e.target), 'image'); }, 'onClickFile': function(e) { that.setPreview(document.id(e.target), 'file'); } }); this.grid = new Files.Grid(this.options.grid.element, opts); }, setPreview: function(target, type) { var node = target.getParent('.files-node-shadow') || target.getParent('.files-node'); var row = node.retrieve('row'); var copy = $extend({}, row); var path = row.baseurl+"/"+row.filepath; var url = path.replace(Files.sitebase+'/', '').replace(/files\/[^\/]+\//, ''); // Update active row node.getParent().getChildren().removeClass('active'); node.addClass('active'); // Load preview template copy.template = 'details_'+type; this.preview.empty(); copy.render('compact').inject(this.preview); // Inject preview image if (type == 'image') { this.preview.getElement('img').set('src', copy.image); } // When no text is selected use the file name if (type == 'file') { if(document.id('image-text').get('value') == ""){ document.id('image-text').set('value', row.name); } } document.id('image-url').set('value', url); document.id('image-type').set('value',row.metadata.mimetype); } });
var articles = null; function restore_all_articles_view() { $("#allbtn").button('toggle'); $('#articleslist').empty(); $('#articleslist').append(articles); $('#filterwarning').hide(); } function switch_category(category) { if (typeof category != "undefined") { $("#articleslist").empty(); var filtered = articles.filter('.'.concat(category)); $("#articleslist").append(filtered); } else { restore_all_articles_view(); } timeandtips("#articleslist"); } $(document).ready(function() { timeandtips(); articles = $('#articleslist article'); $('#searchfield').removeAttr("disabled"); }); $("#searchfield").keyup(function(event) { var text = $('#searchfield').val(); if (text.length >= 3) { $("#allbtn").button('toggle'); var found = articles.filter('article:containsi("'.concat(text, '")')); $('#filterwarning').show(); $('#articleslist').empty(); $('#articleslist').append(found); } else if (text.length == 0) { restore_all_articles_view(); } });
OC.L10N.register( "templateeditor", { "Could not load template" : "امکان بارگذاری قالب وجود ندارد", "Saved" : "ذخیره شد", "Reset" : "تنظیم مجدد", "An error occurred" : "یک خطا رخ داده است", "Sharing email - public link shares (HTML)" : "ایمیل اشتراک گذاری-لینک عمومی اشتراک گذاری(HTML)", "Sharing email - public link shares (plain text fallback)" : "ایمیل اشتراک گذاری-لینک عمومی اشتراک گذاری(plain text fallback)", "Sharing email (HTML)" : "اشتراک‎گذاری ایمیل (HTML)", "Sharing email (plain text fallback)" : "ایمیل اشتراک گذاری (plain text fallback)", "Lost password mail" : "ایمیل فراموش کردن رمز عبور", "New user email (HTML)" : "ایمیل کاربری جدید (HTML)", "New user email (plain text fallback)" : "ایمیل کاربر جدید (plain text fallback)", "Activity notification mail" : "ایمیل هشدار فعالیت", "Mail Templates" : "قالب‌های ایمیل", "Theme" : "تم", "Template" : "قالب", "Please choose a template" : "لطفا یک قالب انتخاب کنید", "Save" : "ذخیره" }, "nplurals=1; plural=0;");
/* Copyright (c) 2003-2020, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang( 'specialchar', 'cs', { options: 'Nastavení speciálních znaků', title: 'Výběr speciálního znaku', toolbar: 'Vložit speciální znaky' } );
(function() { 'use strict'; angular.module('columbyApp') .controller('SearchCtrl', function($log,$rootScope, $scope, SearchSrv) { /* ---------- SETUP ----------------------------------------------------------------------------- */ $scope.contentLoading = true; $scope.search = {}; $rootScope.title = 'columby.com | search'; $scope.pagination = { itemsPerPage: 20, datasets:{ currentPage: 1 }, accounts:{ currentPage: 1 }, tags:{ currentPage: 1 } }; /* ---------- SCOPE FUNCTIONS ------------------------------------------------------------------- */ $scope.doSearch = function(){ $scope.search.hits = null; if ($scope.search.searchTerm.length>2){ $scope.search.message = 'Searching for: ' + $scope.search.searchTerm; SearchSrv.query({ text: $scope.search.searchTerm, limit: $scope.pagination.itemsPerPage }).then(function (response) { $scope.search.hits = response; $scope.search.message = null; $scope.pagination.datasets.numPages = response.datasets.count / $scope.pagination.itemsPerPage; $scope.pagination.accounts.numPages = response.accounts.count / $scope.pagination.itemsPerPage; $scope.pagination.tags.numPages = response.tags.count / $scope.pagination.itemsPerPage; }, function(err){ $scope.search.message = 'Error: ' + err.data.message; }); } else { $scope.search.message = 'Type at least 3 characters.'; } }; /* ---------- INIT ---------------------------------------------------------------------------- */ if ($rootScope.searchTerm){ $scope.search.searchTerm = $rootScope.searchTerm; $log.debug($scope.search.searchTerm); delete $rootScope.searchTerm; $log.debug($scope.search.searchTerm); $scope.doSearch(); } }); })();
/** * ISARI Import Scripts File Definitions * ====================================== * * Defining the various files to import as well as their line consumers. */ module.exports = { organizations: require('./organizations.js'), people: require('./people.js'), activities: require('./activities.js'), postProcessing: require('./post-processing.js') };
import _ from 'underscore' import Base from '../graphs/base' import DayBinner from '../graphs/DayBinner' import WeekBinner from '../graphs/WeekBinner' import MonthBinner from '../graphs/MonthBinner' import ScaleByBins from '../graphs/ScaleByBins' import helpers from '../helpers' import I18n from 'i18n!page_views' // # // Parent class for all graphs that have a date-aligned x-axis. Note: Left // padding for this graph style is space from the frame to the start date's // tick mark, not the leading graph element's edge. Similarly, right padding // is space from the frame to the end date's tick, not the trailing graph // element's edge. This is necessary to keep the date graphs aligned. const defaultOptions = { // # // The date for the left end of the graph. Required. startDate: null, // # // The date for the right end of the graph. Required. endDate: null, // # // The size of the date tick marks, in pixels. tickSize: 5, // # // If any date is outside the bounds of the graph, we have a clipped date clippedDate: false } export default class DateAlignedGraph extends Base { // # // Takes an element and options, same as for Base. Recognizes the options // described above in addition to the options for Base. constructor(div, options) { super(...arguments) // mixin ScaleByBins functionality _.extend(this, ScaleByBins) // check for required options if (options.startDate == null) throw new Error('startDate is required') if (options.endDate == null) throw new Error('endDate is required') // copy in recognized options with defaults for (const key in defaultOptions) { const defaultValue = defaultOptions[key] this[key] = options[key] != null ? options[key] : defaultValue } this.initScale() } // # // Set up X-axis scale initScale() { const interior = this.width - this.leftPadding - this.rightPadding // mixin for the appropriate bin size // use a minimum of 10 pixels for bar width plus spacing before consolidating this.binner = new DayBinner(this.startDate, this.endDate) if (this.binner.count() * 10 > interior) this.binner = new WeekBinner(this.startDate, this.endDate) if (this.binner.count() * 10 > interior) this.binner = new MonthBinner(this.startDate, this.endDate) // scale the x-axis for the number of bins return this.scaleByBins(this.binner.count()) } // # // Reset the graph chrome. Adds an x-axis with daily ticks and weekly (on // Mondays) labels. reset() { super.reset(...arguments) if (this.startDate) this.initScale() return this.drawDateAxis() } // # // Convert a date to a bin index. dateBin(date) { return this.binner.bin(date) } // # // Convert a date to its bin's x-coordinate. binnedDateX(date) { return this.binX(this.dateBin(date)) } // # // Given a datetime, return the floor and ceil as calculated by the binner dateExtent(datetime) { const floor = this.binner.reduce(datetime) return [floor, this.binner.nextTick(floor)] } // # // Given a datetime and a datetime range, return a number from 0.0 to 1.0 dateFraction(datetime, floorDate, ceilDate) { const deltaSeconds = datetime.getTime() - floorDate.getTime() const totalSeconds = ceilDate.getTime() - floorDate.getTime() return deltaSeconds / totalSeconds } // # // Convert a date to an intra-bin x-coordinate. dateX(datetime) { const minX = this.leftMargin const maxX = this.leftMargin + this.width const [floorDate, ceilDate] = this.dateExtent(datetime) const floorX = this.binnedDateX(floorDate) const ceilX = this.binnedDateX(ceilDate) const fraction = this.dateFraction(datetime, floorDate, ceilDate) if (datetime.getTime() < this.startDate.getTime()) { // out of range, left this.clippedDate = true return minX } else if (datetime.getTime() > this.endDate.getTime()) { // out of range, right this.clippedDate = true return maxX } else { // in range return floorX + fraction * (ceilX - floorX) } } // # // Draw a guide along the x-axis. Each day gets a pair of ticks; one from // the top of the frame, the other from the bottom. The ticks are replaced // by a full vertical grid line on Mondays, accompanied by a label. drawDateAxis() { // skip if we haven't set start/end dates yet (@reset will be called by // Base's constructor before we set startDate or endDate) if (this.startDate == null || this.endDate == null) return return this.binner.eachTick((tick, chrome) => { const x = this.binnedDateX(tick) if (chrome && chrome.label) return this.dateLabel(x, this.topMargin + this.height, chrome.label) }) } // # // Draw label text at (x, y). dateLabel(x, y, text) { const label = this.paper.text(x, y, text) return label.attr({fill: this.frameColor}) } // # // Get date text for a bin binDateText(bin) { const lastDay = this.binner.nextTick(bin.date).addDays(-1) const daysBetween = helpers.daysBetween(bin.date, lastDay) if (daysBetween < 1) { // single-day bucket: label the date return I18n.l('date.formats.medium', bin.date) } else if (daysBetween < 7) { // one-week bucket: label the start and end days; include the year only with the end day unless they're different return I18n.t('%{start_date} - %{end_date}', { start_date: I18n.l( bin.date.getFullYear() === lastDay.getFullYear() ? 'date.formats.short' : 'date.formats.medium', bin.date ), end_date: I18n.l('date.formats.medium', lastDay) }) } else { // one-month bucket; label the month and year return I18n.l('date.formats.medium_month', bin.date) } } }
SavedSearchSelect.$inject = ['session', 'savedSearch']; export function SavedSearchSelect(session, savedSearch) { return { link: function(scope) { savedSearch.getUserSavedSearches(session.identity).then(function(res) { scope.searches = res; }); } }; }
import React from 'react'; import { Card } from 'bm-kit'; import './_pillar.schedule.source.scss'; const friday = [ { start: '6:00 PM', name: '📋 Check in begins' }, { start: '8:00 PM', name: '🎤 Opening Ceremonies' }, { start: '9:00 PM', name: '🤝 Team assembly' }, { start: '9:30 PM', name: '🌮 Dinner' }, { start: '10:00 PM', name: '💻 Hacking Begins' }, { start: '10:00 PM', name: '🤖 Fundamentals of AI with Intel' }, { start: '12:00 AM', name: '🥋 Ninja' } ]; let saturday = [ { start: '3:00 AM', name: '🍿 Late Night Snack' }, { start: '8:00 AM', name: '🥓 Breakfast' }, { start: '9:00 AM', name: '🏗 Workshop' }, { start: '12:30 PM', name: '🍝 Lunch' }, { start: '1:00 PM', name: '👪 Facebook Tech Talk' }, { start: '2:00 PM', name: '🐶 Doggos/Woofers' }, { start: '2:30 PM', name: '✈️ Rockwell Collins Talk' }, { start: '3:00 PM', name: '🍿 Snack' }, { start: '3:00 PM', name: '🚣🏽 Activity' }, { start: '4:00 PM', name: '📈 Startups with T.A. MaCann' }, { start: '6:00 PM', name: '🍕 Dinner' }, { start: '9:00 PM', name: '🥤 Cup stacking with MLH' }, { start: '10:00 PM', name: '🍩 Donuts and Kona Ice' }, { start: '10:00 PM', name: '🏗️ Jenga' } ]; let sunday = [ { start: '1:00 AM', name: '🍿 Late Night Snack' }, { start: '8:00 AM', name: '🍳 Breakfast' }, { start: '9:30 AM', name: '🛑 Hacking Ends' }, { start: '10:00 AM', name: '📔 Expo Begins' }, { start: '11:30 AM', name: '🍞 Lunch' }, { start: '1:00 PM', name: '🎭 Closing Ceremonies' }, { start: '2:30 PM', name: '🚌 Buses Depart' } ]; const ScheduleDay = ({ dayData, title }) => ( <Card className="p-schedule__day"> <h3 className="text-center">{title}</h3> {dayData.map(item => ( <div className="p-schedule__item" key={item.name + item.start}> <div className="p-schedule__item_about"> <span className="p-schedule__item_time">{item.start}</span> <span className="p-schedule__item_title">{item.name}</span> </div> <div className="p-schedule__item_info">{item.info}</div> </div> ))} </Card> ); const Schedule = ({ small }) => ( <div className="p-schedule"> {small ? <h3 style={{ marginTop: 0 }}>Schedule</h3> : <h1>Schedule</h1>} <div className="p-schedule__days"> <ScheduleDay dayData={friday} title="Friday (10/19)" /> <ScheduleDay dayData={saturday} title="Saturday (10/20)" /> <ScheduleDay dayData={sunday} title="Sunday (10/21)" /> </div> </div> ); export default Schedule;
function timenow(){ var timenow1 = Date.getHours(); return timenow1; }
'use strict'; angular.module('cheeperApp') .controller('AuthCtrl', function ($scope, $http) { $scope.signin = function() { $http .post('http://127.0.0.1:8000/auth-token/', $scope.credentials) .success(function(data, status, headers, config) { $scope.token = data.token; }) .error(function(data, status, headers, config) { console.log(data); }); }; });
// in all regexp "\" must be replaced by "\\" var datas= { "default": { // the name of this definition group. It's posisble to have different rules inside the same definition file "REGEXP": { "before_word": "[^a-zA-Z0-9_]|^" // \\s|\\.| ,"possible_words_letters": "[a-zA-Z0-9_]+" ,"letter_after_word_must_match": "[^a-zA-Z0-9_]|$" ,"prefix_separator": "\\.|->" } ,"CASE_SENSITIVE": true ,"MAX_TEXT_LENGTH": 100 // the length of the text being analyzed before the cursor position ,"KEYWORDS": [ // [ // 0 : the keyword the user is typing // 1 : the string inserted in code ("{_@_}" being the new position of the cursor) // 2 : the needed prefix // 3 : the text the appear in the suggestion box (if empty, the string to insert will be displayed ['Array', 'Array()', '', 'alert( String message )'] ,['alert', 'alert({_@_})', '', 'alert(message)'] ,['ascrollTo', 'scrollTo({_@_})', '', 'scrollTo(x,y)'] ,['alert', 'alert({_@_},bouh);', '', 'alert(message, message2)'] ,['aclose', 'close({_@_})', '', 'alert(message)'] ,['aconfirm', 'confirm({_@_})', '', 'alert(message)'] ,['aonfocus', 'onfocus', '', ''] ,['aonerror', 'onerror', '', 'blabla'] ,['aonerror', 'onerror', '', ''] ,['window', '', '', ''] ,['location', 'location', 'window', ''] ,['document', 'document', 'window', ''] ,['href', 'href', 'location', ''] ] } }; // the second identifier must be the same as the one of the syntax coloring definition file EditArea_autocompletion._load_auto_complete_file( datas, "php" );
#!/usr/bin/env kjscmd5 function Calculator(ui) { // Setup entry functions var display = ui.findChild('display'); this.display = display; this.one = function() { display.intValue = display.intValue*10+1; } this.two = function() { display.intValue = display.intValue*10+2; } this.three = function() { display.intValue = display.intValue*10+3; } this.four = function() { display.intValue = display.intValue*10+4; } this.five = function() { display.intValue = display.intValue*10+5; } this.six = function() { display.intValue = display.intValue*10+6; } this.seven = function() { display.intValue = display.intValue*10+7; } this.eight = function() { display.intValue = display.intValue*10+8; } this.nine = function() { display.intValue = display.intValue*10+9; } this.zero = function() { display.intValue = display.intValue*10+0; } ui.connect( ui.findChild('one'), 'clicked()', this, 'one()' ); ui.connect( ui.findChild('two'), 'clicked()', this, 'two()' ); ui.connect( ui.findChild('three'), 'clicked()', this, 'three()' ); ui.connect( ui.findChild('four'), 'clicked()', this, 'four()' ); ui.connect( ui.findChild('five'), 'clicked()', this, 'five()' ); ui.connect( ui.findChild('six'), 'clicked()', this, 'six()' ); ui.connect( ui.findChild('seven'), 'clicked()', this, 'seven()' ); ui.connect( ui.findChild('eight'), 'clicked()', this, 'eight()' ); ui.connect( ui.findChild('nine'), 'clicked()', this, 'nine()' ); ui.connect( ui.findChild('zero'), 'clicked()', this, 'zero()' ); this.val = 0; this.display.intValue = 0; this.lastop = function() {} this.plus = function() { this.val = display.intValue+this.val; display.intValue = 0; this.lastop=this.plus } this.minus = function() { this.val = display.intValue-this.val; display.intValue = 0; this.lastop=this.minus; } ui.connect( ui.findChild('plus'), 'clicked()', this, 'plus()' ); ui.connect( ui.findChild('minus'), 'clicked()', this, 'minus()' ); this.equals = function() { this.lastop(); display.intValue = this.val; } this.clear = function() { this.lastop=function(){}; display.intValue = 0; this.val = 0; } ui.connect( ui.findChild('equals'), 'clicked()', this, 'equals()' ); ui.connect( ui.findChild('clear'), 'clicked()', this, 'clear()' ); } var loader = new QUiLoader(); var ui = loader.load('calc.ui', this); var calc = new Calculator(ui); ui.show(); exec();
var namespaces = [ [ "shyft", "namespaceshyft.html", "namespaceshyft" ] ];
/* * Copyright (C) 2021 Inera AB (http://www.inera.se) * * This file is part of sklintyg (https://github.com/sklintyg). * * sklintyg is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * sklintyg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ angular.module('StatisticsApp.treeMultiSelector.controller', []) .controller('treeMultiSelectorCtrl', ['$scope', '$uibModal', function($scope, $uibModal) { 'use strict'; $scope.openDialogClicked = function() { if (angular.isFunction($scope.onOpen)) { $scope.onOpen(); } var modalInstance = $uibModal.open({ animation: false, templateUrl: '/app/shared/treemultiselector/modal/modal.html', controller: 'TreeMultiSelectorModalCtrl', windowTopClass: 'tree-multi-selector', size: 'lg', backdrop: 'true', resolve: { directiveScope: $scope } }); modalInstance.result.then(function() { $scope.doneClicked(); }, function() { }); }; }]);
// node/this-3.js var object = { id: "xyz", printId: function() { console.log('The id is '+ this.id + ' ' + this.toString()); } }; // setTimeout(object.printId, 100); var callback = object.printId; callback();
<import resource="classpath:alfresco/site-webscripts/org/alfresco/callutils.js"> if (!json.isNull("wikipage")) { var wikipage = String(json.get("wikipage")); model.pagecontent = getPageText(wikipage); model.title = wikipage.replace(/_/g, " "); } else { model.pagecontent = "<h3>" + msg.get("message.nopage") + "</h3>"; model.title = ""; } function getPageText(wikipage) { var c = sitedata.getComponent(url.templateArgs.componentId); c.properties["wikipage"] = wikipage; c.save(); var siteId = String(json.get("siteId")); var uri = "/slingshot/wiki/page/" + siteId + "/" + encodeURIComponent(wikipage) + "?format=mediawiki"; var connector = remote.connect("alfresco"); var result = connector.get(uri); if (result.status == status.STATUS_OK) { /** * Always strip unsafe tags here. * The config to option this is currently webscript-local elsewhere, so this is the safest option * until the config can be moved to share-config scope in a future version. */ return stringUtils.stripUnsafeHTML(result.response); } else { return ""; } }
var KevoreeEntity = require('./KevoreeEntity'); /** * AbstractChannel entity * * @type {AbstractChannel} extends KevoreeEntity */ module.exports = KevoreeEntity.extend({ toString: 'AbstractChannel', construct: function () { this.remoteNodes = {}; this.inputs = {}; }, internalSend: function (portPath, msg) { var remoteNodeNames = this.remoteNodes[portPath]; for (var remoteNodeName in remoteNodeNames) { this.onSend(remoteNodeName, msg); } }, /** * * @param remoteNodeName * @param msg */ onSend: function (remoteNodeName, msg) { }, remoteCallback: function (msg) { for (var name in this.inputs) { this.inputs[name].getCallback().call(this, msg); } }, addInternalRemoteNodes: function (portPath, remoteNodes) { this.remoteNodes[portPath] = remoteNodes; }, addInternalInputPort: function (port) { this.inputs[port.getName()] = port; } });
'use strict'; const chai = require('chai'); const assert = chai.assert; const sinon = require('sinon'); const responseError = require('../../../server/utils/errors/responseError'); describe('responseError', () => { let spyCall; const res = {}; let error = 'An error message'; beforeEach(() => { res.status = sinon.stub().returns(res); res.json = sinon.stub(); responseError(error, res); }); it('Calls response method with default(500) error code', () => { spyCall = res.status.getCall(0); assert.isTrue(res.status.calledOnce); assert.isTrue(spyCall.calledWithExactly(500)); }); it('Returns error wrapped in json response', () => { spyCall = res.json.getCall(0); assert.isTrue(res.json.calledOnce); assert.isObject(spyCall.args[0]); assert.property(spyCall.args[0], 'response', 'status'); }); it('Calls response method with custom error code', () => { error = { description: 'Bad request', status_code: 400, }; responseError(error, res); spyCall = res.status.getCall(0); assert.isTrue(res.status.called); assert.isTrue(res.status.calledWithExactly(400)); }); });
<import resource="classpath:alfresco/site-webscripts/org/alfresco/components/workflow/workflow.lib.js"> var workflowDefinitions = getWorkflowDefinitions(), filters = []; if (workflowDefinitions) { for (var i = 0, il = workflowDefinitions.length; i < il; i++) { filters.push( { id: "workflowType", data: workflowDefinitions[i].name, label: workflowDefinitions[i].title }); } } model.filters = filters;
/******************************************************************** Export *********************************************************************/ /** @private */ vs.util.extend (exports, { Animation: Animation, Trajectory: Trajectory, Vector1D: Vector1D, Vector2D: Vector2D, Circular2D: Circular2D, Pace: Pace, Chronometer: Chronometer, generateCubicBezierFunction: generateCubicBezierFunction, createTransition: createTransition, freeTransition: freeTransition, animateTransitionBis: animateTransitionBis, attachTransition: attachTransition, removeTransition: removeTransition });
'use strict'; var app = angular.module('App', ['App.controller']);
var Theme = (function() { var Theme = function() { }; return Theme; })(); module.exports = Theme;
exports = module.exports = addShims; function addShims() { Function.prototype.extend = function(parent) { var child = this; var args = Array.prototype.slice.call(arguments, 0); child.prototype = parent; child.prototype = new (Function.prototype.bind.apply(parent, args))(); child.prototype.constructor = child; var parentProxy = child.prototype.parent = {}; for (var i in parent) { switch(typeof parent[i]) { case 'function': parentProxy[i] = parent[i].bind(child); break; default: parentProxy[i] = parent[i]; } } return this; }; }
#!/usr/bin/env node var http = require('http'); var moment = require('moment'); var server = undefined; var threshold = undefined; var units = undefined; if (!isValid(process.argv)) { console.error('invalid arguments, expected hostname threshold and units'); process.exit(-1); } var request = http.request('http://' + server + '/api/temperatures', function(response) { var statusCode = response.statusCode; var result = []; var json = undefined; if (statusCode === 200) { response.on('data', function(chunk) { result.push(chunk.toString()); }); response.on('end', function() { json = JSON.parse(result.join('')); analyze(json); }); } }); request.end(); function analyze(data) { var length = data.length; var i, sensorData, sensorId, sensorLog, dates; var analysis; for (i = 0; i < length; i++) { sensorData = data[i]; sensorId = sensorData['_id']; sensorLog = sensorData['value']; dates = sensorLog.map(function(log) { return moment(log.date); }); dates.sort(function(a, b) { return (a < b ? -1 : (a > b ? 1 : 0)); }); analysis = dates.reduce(function(analysis, to) { var from = analysis.previous; var diff; if (analysis.previous) { diff = to.diff(from, units); if (diff > threshold) { analysis.result.push({ diff: diff + ' ' + units, from: from.format('YYMMDDHHmm'), to: to.format('YYMMDDHHmm') }); } } return { previous: to, result: analysis.result }; }, { result: [] }); console.log(sensorId, analysis.result); } } function isValid(args) { if (args.length === 5) { server = args[2]; threshold = parseInt(args[3], 10); units = args[4]; return true; } else { return false; } }
/******************************************************************************* Add to .git/hooks/pre-commit (and chmod +x) to enable auto-linting/uglifying: #!/bin/sh grunt build if [ $? -ne 0 ]; then exit 1 fi git add deflector.min.js exit 0 *******************************************************************************/ module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), connect: { all: { options: { base: '.', port: 9999 }} }, jshint: { all: ['deflector.js', 'deflector.test.js', 'Gruntfile.js'] }, qunit: { all: ['index.html'] }, 'saucelabs-qunit': { all: { options: { testname: '<%= pkg.name %> tests', tags: ['master'], urls: ['http://127.0.0.1:9999/'], build: process.env.TRAVIS_JOB_ID, browsers: [ { browserName: "internet explorer", version: "11" }, { browserName: "android", version: "4.4" }, { browserName: "iphone", version: "7.1" } ], tunnelTimeout: 5, concurrency: 3 } } }, uglify: { all: { files: { 'deflector.min.js': 'deflector.js' }} }, watch: { all: { files: ['deflector.js', 'deflector.test.js'], tasks: ['build'] } } }); for (var key in grunt.file.readJSON('package.json').devDependencies) { if (key !== 'grunt' && key.indexOf('grunt') === 0) { grunt.loadNpmTasks(key); } } grunt.registerTask('build', ['jshint', 'uglify', 'qunit']); grunt.registerTask('test', ['build', 'connect', 'saucelabs-qunit']); grunt.registerTask('default', ['build', 'connect', 'watch']); };
avatar = function(x){ this.x = x; this.y = 0; this.prevY = 0; this.velocity_x = 0; this.velocity_y = 0; this.img = loadImage("stickman.png"); this.crouch = loadImage("crouch.png"); this.width = 16; this.standingHeight=64; this.crouchHeight=44; this.height = this.standingHeight; this.collisionCheck = []; }; avatar.prototype.addCollisionCheck = function(item){ this.collisionCheck.push(item); //console.log("add "+item); } avatar.prototype.removeCollisionCheck = function(item){ this.collisionCheck.splice( this.collisionCheck.indexOf(item), 1); //console.log("remove mushroom"); } avatar.prototype.platformCheck = function(){ this.talajon=false; if(this.y<=0){ this.y=0; this.velocity_y=0; this.talajon=true; } for(var i in elements.es){ if(elements.es[i] instanceof platform){ var p=elements.es[i]; if(p.x<this.x +this.width && p.x+p.width > this.x){ if(this.prevY>=p.y && this.y<=p.y){ this.y=p.y; this.velocity_y=0; this.talajon=true; } } } } } avatar.prototype.death = function(){ new Audio(explosionSound.src).play(); life--; lifeText.text = "Life: "+life; if(life <= 0) gameOver(); this.x = 0; this.y = 0; } avatar.prototype.spikeCheck = function(){ for(var i in elements.es){ if(elements.es[i] instanceof spike){ var p=elements.es[i]; if(p.x<this.x +this.width && p.x+p.width > this.x){ /*console.log("player.y = "+this.y); console.log("spike.y = "+p.y); console.log("spike.height = "+p.height); console.log("player.height = "+this.height);*/ if(p.y<this.y+this.height && p.y+p.height-3 > this.y){ this.death(); } } } } } avatar.prototype.mushroomCheck = function(){ for(var i in elements.es){ if(elements.es[i] instanceof mushroom){ var p=elements.es[i]; if(p.x<=this.x +this.width && p.x+p.width >= this.x){ /*console.log("player.y = "+this.y); console.log("spike.y = "+p.y); console.log("spike.height = "+p.height); console.log("player.height = "+this.height);*/ if(p.y<=this.y+this.height && p.y+p.height >= this.y){ if(this.prevY>p.y+p.height) { p.death(); }else { this.death(); } } } } } } avatar.prototype.logic = function(){ var speedX = 5; if(keys[KEY_RIGHT]){ this.x += speedX; }if(keys[KEY_LEFT]){ this.x -= speedX; } this.prevY = this.y; this.y += this.velocity_y; if(keys[KEY_UP] && this.talajon){ this.velocity_y = 14; this.y += 0.001; } this.platformCheck(); //this.spikeCheck(); //this.mushroomCheck(); //collision Test for(var i in this.collisionCheck){ var p = this.collisionCheck[i]; if(p.x<this.x +this.width && p.x+p.width > this.x){ if(p.y<this.y+this.height && p.y+p.height > this.y){ p.collide(this); } } } if(!this.talajon){ this.velocity_y-=1; } if(keys[KEY_DOWN]){ this.currentImg=this.crouch; this.height=this.crouchHeight; }else{ this.currentImg=this.img; this.height=this.standingHeight; } }; avatar.prototype.draw=function(context, t){ context.drawImage(this.currentImg, t.tX(this.x), t.tY(this.y)-this.standingHeight); };
var leaderboard2 = function(data) { return data.data.sort(function(a,b){return b.points-a.points;}); }; function liCreate(name,points) { var li = $('<li>'+name+'</li>'); li.append('<span>'+points+'</span>'); } $(document).ready(function() { // var sorted = leaderboard2(data); // for (var i=0; i<sorted.length; i++) { // $('body').append('<div><p>'+sorted[i].name+' '+sorted[i].points+'</p></div>') // } // //problem here is with repeated DOM manipulation var studentArray = []; $.getJSON('http://192.168.1.35:8000/data.json').success(function(data){ //using '$.getJSON' as opposed to $.ajax specifies //also, include both success and error handler to account for asynchrony. //i.e., if/when SUCCESS, execute some code block; if ERROR, execute another. console.log(data); var sorted = leaderboard2(data); for (var i=0; i<sorted.length; i++) { var student = ('<div><p>'+sorted[i].name+' '+sorted[i].points+'</p></div>'); studentArray.push(student); } //^^ FIXED!!! Append entire array ^^ console.log(studentArray); $('body').append(studentArray); }) .error(function(error){ console.log(error); }); });
sap.ui.define(['sap/ui/webc/common/thirdparty/base/asset-registries/Icons'], function (Icons) { 'use strict'; const name = "status-completed"; const pathData = "M256 0q53 0 99.5 20T437 75t55 81.5 20 99.5-20 99.5-55 81.5-81.5 55-99.5 20-99.5-20T75 437t-55-81.5T0 256t20-99.5T75 75t81.5-55T256 0zM128 256q-14 0-23 9t-9 23q0 12 9 23l64 64q11 9 23 9 13 0 23-9l192-192q9-11 9-23 0-13-9.5-22.5T384 128q-12 0-23 9L192 307l-41-42q-10-9-23-9z"; const ltr = false; const collection = "SAP-icons-v5"; const packageName = "@ui5/webcomponents-icons"; Icons.registerIcon(name, { pathData, ltr, collection, packageName }); var pathDataV4 = { pathData }; return pathDataV4; });
var baseClone = require('./_baseClone'); /** * This method is like `_.clone` except that it accepts `customizer` which * is invoked to produce the cloned value. If `customizer` returns `undefined`, * cloning is handled by the method instead. The `customizer` is invoked with * up to four arguments; (value [, index|key, object, stack]). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to clone. * @param {Function} [customizer] The function to customize cloning. * @returns {*} Returns the cloned value. * @see _.cloneDeepWith * @example * * function customizer(value) { * if (_.isElement(value)) { * return value.cloneNode(false); * } * } * * var el = _.cloneWith(document.body, customizer); * * console.log(el === document.body); * // => false * console.log(el.nodeName); * // => 'BODY' * console.log(el.childNodes.length); * // => 0 */ function cloneWith(value, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; return baseClone(value, false, true, customizer); } module.exports = cloneWith;
/* jshint sub: true */ /* global exports: true */ 'use strict'; // ////////////////////////////////////////////////////////////////////////////// // / @brief node-request-style HTTP requests // / // / @file // / // / DISCLAIMER // / // / Copyright 2015 triAGENS GmbH, Cologne, Germany // / // / 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. // / // / Copyright holder is triAGENS GmbH, Cologne, Germany // / // / @author Alan Plum // / @author Copyright 2015, triAGENS GmbH, Cologne, Germany // ////////////////////////////////////////////////////////////////////////////// const internal = require('internal'); const Buffer = require('buffer').Buffer; const extend = require('lodash').extend; const httperr = require('http-errors'); const is = require('@arangodb/is'); const querystring = require('querystring'); const qs = require('qs'); const url = require('url'); class Response { throw (msg) { if (this.status >= 400) { throw Object.assign( httperr(this.status, msg || this.message), {details: this} ); } } constructor (res, encoding, json) { this.status = this.statusCode = res.code; this.message = res.message; this.headers = res.headers ? res.headers : {}; this.body = this.rawBody = res.body; if (this.body && encoding !== null) { this.body = this.body.toString(encoding || 'utf-8'); if (json) { try { this.json = JSON.parse(this.body); } catch (e) { this.json = undefined; } } } } } function querystringify (query, useQuerystring) { if (!query) { return ''; } if (typeof query === 'string') { return query.charAt(0) === '?' ? query.slice(1) : query; } return (useQuerystring ? querystring : qs).stringify(query) .replace(/[!'()*]/g, function (c) { // Stricter RFC 3986 compliance return '%' + c.charCodeAt(0).toString(16); }); } function request (req) { if (typeof req === 'string') { req = {url: req, method: 'GET'}; } let path = req.url || req.uri; if (!path) { throw new Error('Request URL must not be empty.'); } let pathObj = typeof path === 'string' ? url.parse(path) : path; if (pathObj.auth) { let auth = pathObj.auth.split(':'); req = extend({ auth: { username: decodeURIComponent(auth[0]), password: decodeURIComponent(auth[1]) } }, req); delete pathObj.auth; } let query = typeof req.qs === 'string' ? req.qs : querystringify(req.qs, req.useQuerystring); if (query) { pathObj.search = query; } path = url.format(pathObj); let contentType; let body = req.body; if (req.json) { body = JSON.stringify(body); contentType = 'application/json'; } else if (typeof body === 'string') { contentType = 'text/plain; charset=utf-8'; } else if (typeof body === 'object' && body instanceof Buffer) { contentType = 'application/octet-stream'; } else if (!body) { if (req.form) { contentType = 'application/x-www-form-urlencoded'; body = typeof req.form === 'string' ? req.form : querystringify(req.form, req.useQuerystring); } else if (req.formData) { // contentType = 'multipart/form-data' // body = formData(req.formData) throw new Error('Multipart form encoding is currently not supported.'); } else if (req.multipart) { // contentType = 'multipart/related' // body = multipart(req.multipart) throw new Error('Multipart encoding is currently not supported.'); } } const headers = {}; if (contentType) { headers['content-type'] = contentType; } if (req.headers) { Object.keys(req.headers).forEach(function (name) { headers[name.toLowerCase()] = req.headers[name]; }); } if (req.auth) { headers['authorization'] = ( // eslint-disable-line dot-notation req.auth.bearer ? 'Bearer ' + req.auth.bearer : 'Basic ' + new Buffer( req.auth.username + ':' + req.auth.password ).toString('base64') ); } let options = { method: (req.method || 'get').toUpperCase(), headers: headers, returnBodyAsBuffer: true, returnBodyOnError: req.returnBodyOnError !== false }; if (is.existy(req.timeout)) { options.timeout = req.timeout; } if (is.existy(req.followRedirect)) { options.followRedirects = req.followRedirect; // [sic] node-request compatibility } if (is.existy(req.maxRedirects)) { options.maxRedirects = req.maxRedirects; } else { options.maxRedirects = 10; } if (req.sslProtocol) { options.sslProtocol = req.sslProtocol; } let result = internal.download(path, body, options); return new Response(result, req.encoding, req.json); } exports = request; exports.request = request; exports.Response = Response; ['delete', 'get', 'head', 'patch', 'post', 'put'] .forEach(function (method) { exports[method.toLowerCase()] = function (url, options) { if (typeof url === 'object') { options = url; url = undefined; } else if (typeof url === 'string') { options = extend({}, options, {url: url}); } return request(extend({method: method.toUpperCase()}, options)); }; }); module.exports = exports;
/** * Created by plter on 6/13/16. */ (function () { var files = ["hello.js", "app.js"]; files.forEach(function (file) { var scriptTag = document.createElement("script"); scriptTag.async = false; scriptTag.src = file; document.body.appendChild(scriptTag); }); }());
var interfaceorg_1_1onosproject_1_1grpc_1_1Port_1_1PortStatisticsOrBuilder = [ [ "getPacketsReceived", "interfaceorg_1_1onosproject_1_1grpc_1_1Port_1_1PortStatisticsOrBuilder.html#a190993a33fa895f9d07145f3a04f5d22", null ], [ "getPacketsSent", "interfaceorg_1_1onosproject_1_1grpc_1_1Port_1_1PortStatisticsOrBuilder.html#ae9a71f2c48c5430a348eba326eb6d112", null ], [ "getPort", "interfaceorg_1_1onosproject_1_1grpc_1_1Port_1_1PortStatisticsOrBuilder.html#af9c20290d571c3f0b6bf99f28ffc4005", null ] ];
define([ "settings", "views/tags" ], function(panelSettings, TagsView) { var PanelFileView = codebox.require("views/panels/file"); var PanelOutlineView = PanelFileView.extend({ className: "cb-panel-outline", FileView: TagsView }); return PanelOutlineView; });
define(["Log","FS"],function (Log,FS) {//MODJSL return function showErrorPos(elem, err) { var mesg, src, pos; if (!err) { close(); return; } var row,col; if (err.isTError) { mesg=err.mesg; src=err.src; pos=err.pos; row=err.row+1; col=err.col+1; } else { src={name:function (){return "不明";},text:function () { return null; }}; pos=0; mesg=err; } function close(){ elem.empty(); } if(typeof pos=="object") {row=pos.row; col=pos.col;} close(); var mesgd=$("<div>").text(mesg+" 場所:"+src.name()+(typeof row=="number"?":"+row+":"+col:"")); //mesgd.append($("<button>").text("閉じる").click(close)); elem.append(mesgd); elem.append($("<div>").attr("class","quickFix")); console.log("src=",src); var str=src.text(); if (str && typeof pos=="object") { var npos=0; var lines=str.split(/\n/); for (var i=0 ; i<lines.length && i+1<pos.row ; i++) { npos+=lines[i].length; } npos+=pos.col; pos=npos; } var srcd=$("<pre>"); srcd.append($("<span>").text(str.substring(0,pos))); srcd.append($("<img>").attr("src",FS.expandPath("${sampleImg}/ecl.png")));//MODJSL srcd.append($("<span>").text(str.substring(pos))); elem.append(srcd); //elem.attr("title",mesg+" 場所:"+src.name()); elem.attr("title","エラー"); var diag=elem.dialog({width:600,height:400}); Log.d("error", mesg+"\nat "+src+":"+err.pos+"\n"+str.substring(0,err.pos)+"##HERE##"+str.substring(err.pos)); return diag; }; });
/* * JBoss, Home of Professional Open Source. * Copyright 2014-2020 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * 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 () { 'use strict'; var module = angular.module('pnc.common.restclient', [ 'ngResource', 'pnc.common.util', ]); // TODO: Remove this unnecessary layer of indirection. module.factory('REST_BASE_URL', [ 'restConfig', function(restConfig) { return restConfig.getPncUrl(); } ]); module.factory('REST_BASE_REST_URL', [ 'restConfig', function(restConfig) { return restConfig.getPncRestUrl(); } ]); })();
HB.RadioButtonComponent = Ember.Component.extend({ tagName: 'input', type: 'radio', attributeBindings: ['type', 'htmlChecked:checked', 'value', 'name'], htmlChecked: function(){ return this.get('value') === this.get('checked'); }.property('value', 'checked'), change: function(){ this.set('checked', this.get('value')); } });
define([ './user-settings' ], function (userSettings) { var context; var exposed = { init: function(thisContext){ context = thisContext; context.sandbox.on('settings.close', userSettings.close); context.sandbox.on('settings.open', userSettings.open); context.sandbox.on('menu.opening', userSettings.handleMenuOpening); context.sandbox.on('data.clear.all', userSettings.clear); }, publishMessage: function(params) { context.sandbox.emit('message.publish', params); }, publishOpening: function(params){ context.sandbox.emit('menu.opening', params); }, zoomToLocation: function(params){ context.sandbox.emit('map.zoom.toLocation',params); }, changeBasemap: function(params) { context.sandbox.emit('map.basemap.change', params); }, closeUserSettings: function() { context.sandbox.emit('settings.close'); }, openUserSettings: function() { context.sandbox.emit('settings.open'); } }; return exposed; });
/* * 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. */ /** * Generates paragraph text style for a text element. * * @param {Object} props Props. * @param {function(number):any} dataToStyleX Converts a x-unit to CSS. * @param {function(number):any} dataToStyleY Converts a y-unit to CSS. * @param {function(number):any} dataToFontSizeY Converts a font-size metric to * y-unit CSS. * @param {Object<*>} element Text element properties. * @param {function(number):any} dataToPaddingY Falls back to dataToStyleX if not provided. * @return {Object} The map of text style properties and values. */ export function generateParagraphTextStyle( props, dataToStyleX, dataToStyleY, dataToFontSizeY = dataToStyleY, element, dataToPaddingY = dataToStyleY ) { const { font, fontSize, lineHeight, padding, textAlign } = props; const { marginOffset } = calcFontMetrics(element); const verticalPadding = padding?.vertical || 0; const horizontalPadding = padding?.horizontal || 0; const hasPadding = verticalPadding || horizontalPadding; const paddingStyle = hasPadding ? `${dataToStyleY(verticalPadding)} ${dataToStyleX(horizontalPadding)}` : 0; return { dataToEditorY: dataToStyleY, whiteSpace: 'pre-wrap', overflowWrap: 'break-word', wordBreak: 'break-word', margin: `${dataToPaddingY(-marginOffset / 2)} 0`, fontFamily: generateFontFamily(font), fontSize: dataToFontSizeY(fontSize), font, lineHeight, textAlign, padding: paddingStyle, }; } export const generateFontFamily = ({ family, fallbacks } = {}) => { const genericFamilyKeywords = [ 'cursive', 'fantasy', 'monospace', 'serif', 'sans-serif', ]; // Wrap into " since some fonts won't work without it. let fontFamilyDisplay = family ? `"${family}"` : ''; if (fallbacks && fallbacks.length) { fontFamilyDisplay += family ? `,` : ``; fontFamilyDisplay += fallbacks .map((fallback) => genericFamilyKeywords.includes(fallback) ? fallback : `"${fallback}"` ) .join(`,`); } return fontFamilyDisplay; }; export const getHighlightLineheight = function ( lineHeight, verticalPadding = 0, unit = 'px' ) { if (verticalPadding === 0) { return `${lineHeight}em`; } return `calc(${lineHeight}em ${verticalPadding > 0 ? '+' : '-'} ${ 2 * Math.abs(verticalPadding) }${unit})`; }; export function calcFontMetrics(element) { if (!element.font.metrics) { return { contentAreaPx: 0, lineBoxPx: 0, marginOffset: 0, }; } const { fontSize, lineHeight, font: { metrics: { upm, asc, des }, }, } = element; // We cant to cut some of the "virtual-area" // More info: https://iamvdo.me/en/blog/css-font-metrics-line-height-and-vertical-align const contentAreaPx = ((asc - des) / upm) * fontSize; const lineBoxPx = lineHeight * fontSize; const marginOffset = lineBoxPx - contentAreaPx; return { marginOffset, contentAreaPx, lineBoxPx, }; }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * 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. * */ NamingPeopleContentManager = function() { this.SaveSchema = function(parentCallback) { var schemaId = jq('#namingPeopleSchema').val(); if (schemaId == 'custom') { NamingPeopleContentController.SaveCustomNamingSettings(jq('#usrcaption').val().substring(0, 30), jq('#usrscaption').val().substring(0, 30), jq('#grpcaption').val().substring(0, 30), jq('#grpscaption').val().substring(0, 30), jq('#usrstatuscaption').val().substring(0, 30), jq('#regdatecaption').val().substring(0, 30), jq('#grpheadcaption').val().substring(0, 30), jq('#guestcaption').val().substring(0, 30), jq('#guestscaption').val().substring(0, 30), function(result) { if (parentCallback != null) parentCallback(result.value); }); } else NamingPeopleContentController.SaveNamingSettings(schemaId, function(result) { if (parentCallback != null) parentCallback(result.value); }); } this.SaveSchemaCallback = function(res) { } this.LoadSchemaNames = function(parentCallback) { var schemaId = jq('#namingPeopleSchema').val(); NamingPeopleContentController.GetPeopleNames(schemaId, function(res) { var names = res.value; jq('#usrcaption').val(names.UserCaption); jq('#usrscaption').val(names.UsersCaption); jq('#grpcaption').val(names.GroupCaption); jq('#grpscaption').val(names.GroupsCaption); jq('#usrstatuscaption').val(names.UserPostCaption); jq('#regdatecaption').val(names.RegDateCaption); jq('#grpheadcaption').val(names.GroupHeadCaption); jq('#guestcaption').val(names.GuestCaption); jq('#guestscaption').val(names.GuestsCaption); if (parentCallback != null) parentCallback(res.value); }); } } NamingPeopleContentViewer = new function() { this.ChangeValue = function(event) { jq('#namingPeopleSchema').val('custom'); } }; jq(document).ready(function() { jq('.namingPeopleBox input[type="text"]').each(function(i, el) { jq(el).keypress(function(event) { NamingPeopleContentViewer.ChangeValue(); }); }); var manager = new NamingPeopleContentManager(); jq('#namingPeopleSchema').change(function () { manager.LoadSchemaNames(null); }); manager.LoadSchemaNames(null); });
import React from 'react'; import RadioButton from '../RadioButton'; import { mount } from 'enzyme'; const render = (props) => mount( <RadioButton {...props} className="extra-class" name="test-name" value="test-value" /> ); describe('RadioButton', () => { describe('renders as expected', () => { const wrapper = render({ checked: true, }); const input = wrapper.find('input'); const label = wrapper.find('label'); const div = wrapper.find('div'); describe('input', () => { it('is of type radio', () => { expect(input.props().type).toEqual('radio'); }); it('has the expected class', () => { expect(input.hasClass('bx--radio-button')).toEqual(true); }); it('has a unique id set by default', () => { expect(input.props().id).toBeDefined(); }); it('should have checked set when checked is passed', () => { wrapper.setProps({ checked: true }); expect(input.props().checked).toEqual(true); }); it('should set the name prop as expected', () => { expect(input.props().name).toEqual('test-name'); }); }); describe('label', () => { it('should set htmlFor', () => { expect(label.props().htmlFor) .toEqual(input.props().id); }); it('should set the correct class', () => { expect(label.props().className).toEqual('bx--radio-button__label'); }); it('should render a span with the correct class', () => { const span = label.find('span'); expect(span.hasClass('bx--radio-button__appearance')).toEqual(true); }); it('should render label text', () => { wrapper.setProps({ labelText: 'test label text' }); expect(label.text()).toMatch(/test label text/); }); }); describe('wrapper', () => { it('should have the correct class', () => { expect(div.hasClass('radioButtonWrapper')).toEqual(true); }); it('should have extra classes applied', () => { expect(div.hasClass('extra-class')).toEqual(true); }); }); }); it('should set defaultChecked as expected', () => { const wrapper = render({ defaultChecked: true, }); const input = wrapper.find('input'); expect(input.props().defaultChecked).toEqual(true); wrapper.setProps({ defaultChecked: false }); expect(input.props().defaultChecked).toEqual(false); }); it('should set id if one is passed in', () => { const wrapper = render({ id: 'unique-id', }); const input = wrapper.find('input'); expect(input.props().id).toEqual('unique-id'); }); describe('events', () => { it('should invoke onChange with expected arguments', () => { const onChange = jest.fn(); const wrapper = render({ onChange }); const input = wrapper.find('input'); const inputElement = input.get(0); inputElement.checked = true; wrapper.find('input').simulate('change'); const call = onChange.mock.calls[0]; expect(call[0]).toEqual('test-value'); expect(call[1]).toEqual('test-name'); expect(call[2].target).toBe(inputElement); }); }); });
module.exports = function(fancyRequire) { fancyRequire('merchant_row'); };
/* * Copyright (c) 2013 EMBL - European Bioinformatics Institute * 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 lodeNamespacePrefixes = { rdf: 'http://www.w3.org/1999/02/22-rdf-syntax-ns#', rdfs: 'http://www.w3.org/2000/01/rdf-schema#', owl: 'http://www.w3.org/2002/07/owl#', dc: 'http://purl.org/dc/elements/1.1/', dcterms: 'http://purl.org/dc/terms/', obo: 'http://purl.obolibrary.org/obo/', efo: 'http://www.ebi.ac.uk/efo/', 'biosd-terms': 'http://rdf.ebi.ac.uk/terms/biosd/', pav: 'http://purl.org/pav/2.0/', prov: 'http://www.w3.org/ns/prov#', foaf: 'http://xmlns.com/foaf/0.1/', sio: 'http://semanticscience.org/resource/', atlas: 'http://rdf.ebi.ac.uk/terms/atlas/', oac: 'http://www.openannotation.org/ns/' };
/** * @author: Alberto Cerqueira * @email: alberto.cerqueira1990@gmail.com */ jQuery.controller = function() { var controllerClass = function() { this.init = (function(){ $("#gravar").click(function(){ _self.gravar(); return false; }); }); this.gravar = (function() { $("#manterEntidade").ajaxSubmit({ url : systemURL, dataType : "json", success : (function(jsonReturn){ var consequence = jsonReturn.consequence; if (consequence == "ERRO") { alert(jsonReturn.message); } else if (consequence == "SUCESSO") { alert(jsonReturn.message + ": " + jsonReturn.dado.toString()); } else if(consequence == "MUITOS_ERROS"){ var mensagem = ['']; jQuery.each(jsonReturn.dado, function(i, dado) { mensagem.push(dado.localizedMessage + "\n"); }); alert(mensagem.join('')); } //location.reload(); }), error : (function(XMLHttpRequest, textStatus, errorThrown){ alert(errorConexao); }) }); }); var _self = this; }; return new controllerClass(); };
var Alloy = require("alloy"), _ = Alloy._, Backbone = Alloy.Backbone; Alloy.Globals.steps = 0; Alloy.Globals.capacity = 0; Alloy.Globals.basketImage = ""; Alloy.Globals.fruitCount = 0; Alloy.createController("index");
/* ~ Copyright (c) 2014 George Norman. ~ Licensed under the Apache License, Version 2.0 (the "License"); ~ http://www.apache.org/licenses/LICENSE-2.0 ~ ~ -------------------------------------------------------------- ~ Renders <css-lab-about> tags - sharable among all projects. ~ -------------------------------------------------------------- */ /** * The &lt;css-lab-about&gt; tag renders a common introduction, displayed across all of the * CSS Lab projects and pages. There can be only one Introduction section per page. *<p> * Example: * <pre style="background:#eee; padding:6px;"> * &lt;css-lab-about style="margin-top:12px;"/&gt; * </pre> * * @module cssLabAboutTag */ var cssLabAboutTag = (function(tzDomHelper, tzCustomTagHelper) { "use strict"; // http://stackoverflow.com/questions/805107/creating-multiline-strings-in-javascript var template = ['This page contains example code used for the <a href="http://www.thruzero.com/jcat3/apps/resources/resources.jsf?rid=css.overview">CSS Summary</a>', 'at <a href="http://www.thruzero.com/">ThruZero</a>. ', 'The example code (e.g., CSS and HTML) is defined with inline-templates and then rendered live, so it will always match the rendered example. ' ].join('\n'); return { getTagName: function() { return "css-lab-about"; }, /** * Render the first &lt;css-lab-about&gt; tag on the page - only one tag per page is supported. */ renderAll: function() { tzCustomTagHelper.renderFirst(this); }, /** * Render the &lt;css-lab-about&gt; tag identified by the given tagId. * * @param tagId ID of the tag to render. */ renderTagById: function(tagId) { tzCustomTagHelper.renderTagById(this, tagId); }, /** * Render the given aboutTagNode. * * @param aboutTagNode the node to retrieve the attributes from and then render the result to. */ renderTag: function(aboutTagNode) { this.render(aboutTagNode); }, /** * Render the 'About Application' HTML, into the given containerNode. * * @param containerNode where to render the result. */ render: function(containerNode) { containerNode.style.display = 'block'; //var template = tzCustomTagHelper.getTemplate(this.getTagName() + "Template"); // @-@:p1(geo) Experimental tzCustomTagHelper.renderTagFromTemplate(containerNode, template, {}); } } }(tzDomHelperModule, tzCustomTagHelperModule));
/* eslint-disable local/html-template */ const documentModes = require('./document-modes'); const {AmpState, ampStateKey} = require('./amphtml-helpers'); const {html, joinFragments} = require('./html'); const jsModes = [ { value: 'default', description: `Unminified AMP JavaScript is served from the local server. For local development you will usually want to serve unminified JS to test your changes.`, }, { value: 'minified', description: html` Minified AMP JavaScript is served from the local server. This is only available after running <code>amp dist --fortesting</code> `, }, { value: 'cdn', description: 'Minified AMP JavaScript is served from the AMP Project CDN.', }, ]; const stateId = 'settings'; const htmlEnvelopePrefixStateKey = 'htmlEnvelopePrefix'; const jsModeStateKey = 'jsMode'; const panelStateKey = 'panel'; const htmlEnvelopePrefixKey = ampStateKey(stateId, htmlEnvelopePrefixStateKey); const panelKey = ampStateKey(stateId, panelStateKey); const PanelSelectorButton = ({expression, type, value}) => html` <button class="settings-panel-button" [class]="'settings-panel-button' + (${panelKey} != '${type}' ? '' : ' open')" data-type="${type}" tabindex="0" on="tap: AMP.setState({ ${stateId}: { ${panelStateKey}: (${panelKey} != '${type}' ? '${type}' : null), } })" > <span>${type}</span> <strong [text]="${expression}">${value}</strong> </button> `; const PanelSelector = ({children, compact = false, key, name = null}) => html` <amp-selector layout="container" name="${name || key}" class="${compact ? 'compact ' : ''}" on="select: AMP.setState({ ${stateId}: { ${panelStateKey}: null, ${key}: event.targetOption, } })" > ${joinFragments(children)} </amp-selector> `; const PanelSelectorBlock = ({children, id, selected, value}) => html` <div class="selector-block" ${selected ? ' selected' : ''} id="${id}" option="${value}" > <div class="check-icon icon"></div> ${children} </div> `; const HtmlEnvelopeSelector = ({htmlEnvelopePrefix}) => PanelSelector({ compact: true, key: htmlEnvelopePrefixStateKey, children: Object.entries(documentModes).map(([prefix, name]) => PanelSelectorBlock({ id: `select-html-mode-${name}`, value: prefix, selected: htmlEnvelopePrefix === prefix, children: html`<strong>${name}</strong>`, }) ), }); const JsModeSelector = ({jsMode}) => PanelSelector({ key: jsModeStateKey, name: 'mode', children: jsModes.map(({description, value}) => PanelSelectorBlock({ id: `serve-mode-${value}`, value, selected: jsMode === value, children: html` <strong>${value}</strong> <p>${description}</p> `, }) ), }); const SettingsPanelButtons = ({htmlEnvelopePrefix, jsMode}) => html` <div style="flex: 1"> <div class="settings-panel-button-container"> ${PanelSelectorButton({ type: 'HTML', expression: `${stateId}.documentModes[${htmlEnvelopePrefixKey}]`, value: documentModes[htmlEnvelopePrefix], })} ${PanelSelectorButton({ type: 'JS', expression: `${stateId}.${jsModeStateKey}`, value: jsMode, })} </div> ${SettingsPanel({htmlEnvelopePrefix, jsMode})} </div> `; const SettingsSubpanel = ({children, type}) => html` <div hidden [hidden]="${panelKey} != '${type}'">${children}</div> `; const SettingsPanel = ({htmlEnvelopePrefix, jsMode}) => html` <div class="settings-panel" hidden [hidden]="${panelKey} == null"> ${AmpState(stateId, { documentModes, [panelStateKey]: null, [htmlEnvelopePrefixStateKey]: htmlEnvelopePrefix, [jsModeStateKey]: jsMode, })} ${SettingsSubpanel({ type: 'HTML', children: html` <h4>Select an envelope to serve HTML documents.</h4> ${HtmlEnvelopeSelector({htmlEnvelopePrefix})} `, })} ${SettingsSubpanel({ type: 'JS', children: html` <h4>Select the JavaScript binaries to use in served documents.</h4> <form action="/serve_mode_change" action-xhr="/serve_mode_change" target="_blank" id="serve-mode-form" > ${JsModeSelector({jsMode})} </form> `, })} </div> `; module.exports = { SettingsPanel, SettingsPanelButtons, htmlEnvelopePrefixKey, };
/** * * Web Starter Kit * Copyright 2014 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'; // Include Gulp & Tools We'll Use var gulp = require('gulp'); var $ = require('gulp-load-plugins')(); var del = require('del'); var runSequence = require('run-sequence'); var browserSync = require('browser-sync'); var reload = browserSync.reload; // Clean Output Directory gulp.task('clean', del.bind(null, ['./index.js', './assertRank.js', './specs.js'])); gulp.task('es6', ['clean'], function () { return gulp.src(['./src/**/*.js']) // .pipe($.sourcemaps.init({loadMaps: true})) .pipe($['6to5']()).on('error', console.error.bind(console)) // .pipe($.sourcemaps.write()) .pipe(gulp.dest('.')) .pipe($.size({title: 'es6'})) }) gulp.task('browserify', ['es6'], function () { return gulp.src(['./specs.js']) .pipe($.browserify({debug: false})) .pipe(gulp.dest('.')) .pipe($.size({title: 'browserify'})) }) // Watch Files For Changes & Reload gulp.task('serve', ['browserify'], function () { browserSync({ notify: false, browser: 'skip', ghostMode: false, // Customize the BrowserSync console logging prefix logPrefix: 'WSK', port: 3010, // Run as an https by uncommenting 'https: true' // Note: this uses an unsigned certificate which on first access // will present a certificate warning in the browser. // https: true, server: ['.', 'src'] }); gulp.watch(['gulpfile.js'], process.exit) gulp.watch(['./src/**/*.{js,html}'], ['browserify', reload]); }); gulp.task('default', ['es6']) // Load custom tasks from the `tasks` directory // try { require('require-dir')('tasks'); } catch (err) { console.error(err); }
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-65704319-1', 'auto'); ga('send', 'pageview');
//Declare app level module which depends on filters, and services var SFApplicationAuth = angular.module('SFApplicationAuth.Auth',[]); SFApplicationAuth.config( [ '$stateProvider', '$urlRouterProvider', function ( $stateProvider, $urlRouterProvider ) { console.log("inciando bootstrap auth"); $stateProvider.state('auth', { url: '/auth', abstract: true, templateUrl: 'modules/auth/partials/template.html', data: { isPublic: true } }); $stateProvider.state('auth.login', { url: '/login', templateUrl: 'modules/auth/partials/login.html', controller: 'AuthController' }); $stateProvider.state('auth.logout', { url: '/logout', controller: 'LogoutController' }); $stateProvider.state('auth.reset-password', { url: '/reset-password', templateUrl: 'application/auth/partials/reset-password.html', controller: 'AuthController' }); }]); SFApplicationAuth.run(['$rootScope', '$state', '$location', '$log', 'authFactory', function($rootScope, $state, $location, $log, authFactory) { $log.log('Running Auth...'); $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) { $log.log('$stateChangeStart'); if( toState && ( "data" in toState ) === true && ( "isPublic" in toState.data ) === true && toState.data.isPublic == true ) { $log.log( 'Public page...' ); } else if( toState && ( "data" in toState ) === true && ( ( "isPublic" in toState.data ) === false || ( "isPublic" in toState.data ) === true && toState.data.isPublic == false ) ) { $log.log( 'Private page...' ); /** * Check if has some webSession active and do the logout. */ if( ! authFactory.checkIsLogged() ) { $log.error( 'You don\'t have permission to access this area.' ); /** * Prevent Default action. */ event.preventDefault(); $log.log( 'Fazendo loggof' ); /** * Redirect to login */ $state.go( 'auth.logout' ); } } }); $rootScope.$on('$stateChangeSuccess', function(next, current) { $log.log('$stateChangeSuccess'); }); $rootScope.$on('$stateChangeError', function( event, toState, toParams, fromState, fromParams, rejection) { $log.log('$stateChangeError'); }); $rootScope.$on('$stateUpdate', function(next, current) { $log.log('$stateUpdate'); }); $rootScope.$on('$stateNotFound', function(event, unfoundState, fromState, fromParams){ $log.log('$stateNotFound'); $log.log(unfoundState.to); // "lazy.state" $log.log(unfoundState.toParams); // {a:1, b:2} $log.log(unfoundState.options); // {inherit:false} + default options }); $rootScope.$on('$viewContentLoading', function(event, viewConfig){ $log.log('$viewContentLoading'); }); $rootScope.$on('$viewContentLoaded', function(event, viewConfig){ $log.log('$viewContentLoaded'); }); }]);
const spinny = 'div.spinny'; exports.command = function navigateTo (url, expectSpinny = true) { this.url('data:,'); // https://github.com/nightwatchjs/nightwatch/issues/1724 this.url(url); if (expectSpinny) { this.waitForElementVisible(spinny); this.waitForElementNotVisible(spinny); } return this; };
import React from 'react'; import renderer from 'react-test-renderer'; import VideoQuestion from './VideoQuestion'; jest.mock('expo', () => ({ Video: 'Video' })); it('renders without crashing', () => { const tree = renderer.create( <VideoQuestion video={require('../../assets/videos/placeholder.mp4')} question="Wer ist eine Ananas?" answers={[ 'Ich bin eine Ananas', 'Du bist eine Ananas', 'Wir sind eine Ananas' ]} /> ); expect(tree).toMatchSnapshot(); });
"use strict"; const apisObject = { "type": "object", "required": false, "patternProperties": { "^[_a-z\/][_a-zA-Z0-9\/:]*$": { //pattern to match an api route "type": "object", "required": true, "properties": { "access": {"type": "boolean", "required": false}, } } } }; const aclRoute = { "type": "array", "required": false, "items": { "type": "object", "required": false, "properties": { "access": {"type": "string", "required": false}, "apis": apisObject } } }; const scope = { "type": "object", "patternProperties": { "^[^\W\.]+$": { "type": "object", "required": false, "patternProperties": { ".+": { "type": "object", "required": false, "properties": { "access": {"type": "boolean", "required": false}, "apisPermission": { "type": "string", "enum": ["restricted"], "required": false }, "get": aclRoute, "post": aclRoute, "put": aclRoute, "delete": aclRoute, "head": aclRoute, "options": aclRoute, "other": aclRoute, "additionalProperties": false }, "additionalProperties": false } }, "additionalProperties": false }, }, "additionalProperties": false }; module.exports = scope;
// // https://github.com/Dogfalo/materialize/issues/634#issuecomment-113213629 // and // https://github.com/noodny/materializecss-amd/blob/master/config.js // // require([ 'global', 'initial', 'animation', 'buttons', 'cards', 'carousel', 'character_counter', 'chips', 'collapsible', 'dropdown', 'forms', 'hammerjs', 'jquery.easing', 'jquery.hammer', 'jquery.timeago', 'leanModal', 'materialbox', 'parallax', 'picker', 'picker.date', 'prism', 'pushpin', 'scrollFire', 'scrollspy', 'sideNav', 'slider', 'tabs', 'toasts', 'tooltip', 'transitions', 'velocity' ], function(Materialize) { return Materialize; } );
/* * 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. */ /** * External dependencies */ import styled from 'styled-components'; import PropTypes from 'prop-types'; import { Popup } from '@googleforcreators/design-system'; import { __ } from '@googleforcreators/i18n'; /** * Internal dependencies */ import { useCanvas, useConfig } from '../../../app'; import useElementsWithLinks from '../../../utils/useElementsWithLinks'; import { OUTLINK_THEME } from '../../../constants'; import DefaultIcon from './icons/defaultIcon.svg'; import ArrowIcon from './icons/arrowBar.svg'; const Wrapper = styled.div` position: absolute; display: flex; align-items: center; justify-content: flex-end; flex-direction: column; bottom: 0; height: 20%; width: 100%; color: ${({ theme }) => theme.colors.standard.white}; z-index: 3; `; const Guideline = styled.div` mix-blend-mode: difference; position: absolute; height: 1px; bottom: 20%; width: 100%; background-image: ${({ theme }) => `linear-gradient(to right, ${theme.colors.standard.black} 50%, ${theme.colors.standard.white} 0%)`}; background-position: top; background-size: 16px 0.5px; background-repeat: repeat-x; z-index: 3; `; // The CSS here is based on how it's displayed in the front-end, including static // font-size, line-height, etc. independent of the viewport size -- it's not responsive. const ArrowBar = styled(ArrowIcon)` display: block; cursor: pointer; margin-bottom: 10px; filter: drop-shadow(0px 2px 6px rgba(0, 0, 0, 0.3)); width: 20px; height: 8px; `; const OutlinkChip = styled.div` height: 36px; display: flex; position: relative; padding: 10px 6px; margin: 0 0 20px; max-width: calc(100% - 64px); border-radius: 30px; place-items: center; box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.15); background: ${({ bgColor }) => bgColor}; `; const TextWrapper = styled.span` font-family: Roboto, sans-serif; font-size: 16px; line-height: 18px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; position: relative; padding-inline-start: 6px; padding-inline-end: 8px; height: 16px; letter-spacing: 0.3px; font-weight: 700; max-width: 210px; color: ${({ fgColor }) => fgColor}; `; const Tooltip = styled.div` background-color: ${({ theme }) => theme.colors.standard.black}; color: ${({ theme }) => theme.colors.standard.white}; width: 200px; padding: 8px; font-size: 14px; border-radius: 4px; text-align: center; `; const LinkImage = styled.div` height: 24px; width: 24px; vertical-align: middle; background-size: cover; background-repeat: no-repeat; background-position: 50%; border-radius: 50%; background-image: url('${({ icon }) => icon}') !important; `; const spacing = { x: 8 }; const LIGHT_COLOR = '#FFFFFF'; const DARK_COLOR = '#000000'; function PageAttachment({ pageAttachment = {} }) { const { displayLinkGuidelines, pageAttachmentContainer, setPageAttachmentContainer, } = useCanvas((state) => ({ displayLinkGuidelines: state.state.displayLinkGuidelines, pageAttachmentContainer: state.state.pageAttachmentContainer, setPageAttachmentContainer: state.actions.setPageAttachmentContainer, })); const { hasInvalidLinkSelected } = useElementsWithLinks(); const { ctaText = __('Learn more', 'web-stories'), url, icon, theme, } = pageAttachment; const { isRTL, styleConstants: { topOffset } = {} } = useConfig(); const bgColor = theme === OUTLINK_THEME.DARK ? DARK_COLOR : LIGHT_COLOR; const fgColor = theme === OUTLINK_THEME.DARK ? LIGHT_COLOR : DARK_COLOR; return ( <> {(displayLinkGuidelines || hasInvalidLinkSelected) && <Guideline />} <Wrapper role="presentation" ref={setPageAttachmentContainer}> {url?.length > 0 && ( <> <ArrowBar fill={bgColor} /> <OutlinkChip bgColor={bgColor}> {icon ? ( <LinkImage icon={icon} /> ) : ( <DefaultIcon fill={fgColor} width={24} height={24} /> )} <TextWrapper fgColor={fgColor}>{ctaText}</TextWrapper> </OutlinkChip> {pageAttachmentContainer && hasInvalidLinkSelected && ( <Popup isRTL={isRTL} anchor={{ current: pageAttachmentContainer }} isOpen placement={'left'} spacing={spacing} topOffset={topOffset} > <Tooltip> {__( 'Links can not reside below the dashed line when a page attachment is present. Your viewers will not be able to click on the link.', 'web-stories' )} </Tooltip> </Popup> )} </> )} </Wrapper> </> ); } PageAttachment.propTypes = { pageAttachment: PropTypes.shape({ url: PropTypes.string, ctaText: PropTypes.string, }), }; export default PageAttachment;
module.exports = function (config) { 'use strict'; config.set({ basePath: '../', files: [ // Angular libraries. 'app/assets/lib/angular/angular.js', 'app/assets/lib/angular-ui-router/release/angular-ui-router.js', 'app/assets/lib/angular-bootstrap/ui-bootstrap.min.js', 'app/assets/lib/angular-mocks/angular-mocks.js', 'app/assets/lib/angular-bootstrap/ui-bootstrap-tpls.min.js', 'app/assets/lib/angular-busy/dist/angular-busy.min.js', 'app/assets/lib/angular-resource/angular-resource.min.js', 'app/assets/lib/angular-confirm-modal/angular-confirm.js', // JS files. 'app/app.js', 'app/components/**/*.js', 'app/shared/*.js', 'app/shared/**/*.js', 'app/assets/js/*.js', // Test Specs. 'tests/unit/*.js' ], autoWatch: true, frameworks: ['jasmine'], browsers: ['Firefox', 'PhantomJS', 'Chrome'], plugins: [ 'karma-chrome-launcher', 'karma-firefox-launcher', 'karma-phantomjs-launcher', 'karma-jasmine' ], junitReporter: { outputFile: 'test_out/unit.xml', suite: 'unit' } }); };
import { inject as service } from '@ember/service'; import Route from '@ember/routing/route'; import { get } from '@ember/object'; export default Route.extend({ access: service(), catalog: service(), scope: service(), beforeModel() { this._super(...arguments); return get(this, 'catalog').fetchUnScopedCatalogs().then((hash) => { this.set('catalogs', hash); }); }, model(params) { return get(this, 'catalog').fetchTemplates(params) .then((res) => { res.catalogs = get(this, 'catalogs'); return res; }); }, resetController(controller, isExiting/* , transition*/) { if (isExiting) { controller.setProperties({ category: '', catalogId: '', projectCatalogId: '', clusterCatalogId: '', }) } }, deactivate() { // Clear the cache when leaving the route so that it will be reloaded when you come back. this.set('cache', null); }, actions: { refresh() { // Clear the cache so it has to ask the server again this.set('cache', null); this.refresh(); }, }, queryParams: { category: { refreshModel: true }, catalogId: { refreshModel: true }, clusterCatalogId: { refreshModel: true }, projectCatalogId: { refreshModel: true }, }, });
import Ember from 'ember'; const DELAY = 100; export default Ember.Component.extend({ classNameBindings : ['inlineBlock:inline-block','clip:clip'], tooltipService : Ember.inject.service('tooltip'), inlineBlock : true, clip : false, model : null, size : 'default', ariaRole : ['tooltip'], textChangedEvent : null, showTimer : null, textChanged: Ember.observer('textChangedEvent', function() { this.show(this.get('textChangedEvent')); }), mouseEnter(evt) { if ( !this.get('tooltipService.requireClick') ) { let tgt = Ember.$(evt.currentTarget); if (this.get('tooltipService.tooltipOpts')) { this.set('tooltipService.tooltipOpts', null); } // Wait for a little bit of time so that the mouse can pass through // another tooltip-element on the way to the dropdown trigger of a // tooltip-action-menu without changing the tooltip. this.set('showTimer', Ember.run.later(() => { this.show(tgt); }, DELAY)); } }, show(node) { if ( this._state === 'destroying' ) { return; } let svc = this.get('tooltipService'); this.set('showTimer', null); svc.cancelTimer(); let out = { type : this.get('type'), baseClass : this.get('baseClass'), eventPosition : node.offset(), originalNode : node, model : this.get('model'), template : this.get('tooltipTemplate'), }; if ( this.get('isCopyTo') ) { out.isCopyTo = true; } svc.set('tooltipOpts', out); }, mouseLeave: function() { if (!this.get('tooltipService.openedViaContextClick')) { if ( this.get('showTimer') ) { Ember.run.cancel(this.get('showTimer')); } else { this.get('tooltipService').leave(); } } }, modelObserver: Ember.observer('model', 'textChangedEvent', function() { let opts = this.get('tooltipService.tooltipOpts'); if (opts) { this.set('tooltipService.tooltipOpts.model', this.get('model')); } }) });
function f1(a) { try { throw "x"; } catch (arguments) { console.log(arguments); } } f1(3);
// JavaScript Document var flag1=true; var flag2=true; $(function () { /*********************/ $.ajax({ type : 'POST', dataType : 'json', url : 'baseNeiName.do', async : true, cache : false, error : function(request) { bootbox.alert({ message : "请求异常", size : 'small' }); }, success : function(data) { var i = 0; for ( var item in data) { $("#baselistid").after( "<option value="+data[i].id+">" + data[i].name + "</option>"); i++; } } }); /**************************/ /*########*/ $(document).on("click", "#Submit", function() { var projectname=$("#projectname").val(); var name=$("#name").val(); var address=$("#address").val(); var budget=$("#budget").val(); budget=budget.trim(); var baselist=$("#baselist").val(); var reason=$("#reason").val(); var strmoney=/^[0-9]*$/.test(budget); var money=budget.substring(1,0); if(projectname==""){ bootbox.alert({ message : "请填写项目名称", size : 'small' }); return 0; } else if(name==""){ bootbox.alert({ message : "请填写报修人", size : 'small' }); return 0; } else if(address==""){ bootbox.alert({ message : "请填写具体位置", size : 'small' }); return 0; } else if(budget==""){ bootbox.alert({ message : "请填写预算金额", size : 'small' }); return 0; } else if(strmoney==false){ bootbox.alert({ message : "预算金额只能为数字", size : 'small' }); return 0; } else if(budget.length>1&&money==0){ bootbox.alert({ message : "请填写正确的预算金额格式,第一个数字不能为零", size : 'small' }); return 0; } else if(baselist=="请选择"){ bootbox.alert({ message : "请选择基地", size : 'small' }); return 0; } else if(reason==""){ bootbox.alert({ message : "请填写原因", size : 'small' }); return 0; } if (!flag1) { bootbox.alert({ message: "上传资料仅限于rar,zip压缩包格式", size: 'small' }); $("#applyfile").val(''); return; } if (!flag2) { bootbox.alert({ message: "上传资料大小不能大于10M", size: 'small' }); $("#applyfile").val(''); return; } /*************/ $("#applyform").submit(); /*************/ }) $('#applyfile').change(function() { var filepath = $(this).val(); var file_size = this.files[0].size; var size = file_size / 1024; var extStart = filepath.lastIndexOf("."); var ext = filepath.substring(extStart, filepath.length).toUpperCase(); if (ext != ".RAR" && ext != ".ZIP") { bootbox.alert({ message: "上传资料仅限于rar,zip压缩包格式", size: 'small' }); $("#applyfile").val(''); flag1=false; return; } if (size > 1024 * 10) { bootbox.alert({ message: "上传资料大小不能大于10M", size: 'small' }); $("#applyfile").val(''); flag2=false; return; } flag1=true; flag2=true; }); /*########*/ });
/* * Copyright 2019 The Project Oak Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; const showGreenIconForExtensionPages = { conditions: [ new chrome.declarativeContent.PageStateMatcher({ pageUrl: { hostEquals: chrome.runtime.id, schemes: ['chrome-extension'], pathEquals: '/index.html', }, }), ], actions: [new chrome.declarativeContent.SetIcon({ path: 'icon-green.png' })], }; chrome.runtime.onInstalled.addListener(function () { chrome.declarativeContent.onPageChanged.removeRules(undefined, function () { chrome.declarativeContent.onPageChanged.addRules([ showGreenIconForExtensionPages, ]); }); }); async function loadPageInASecureSandbox({ id: tabId }) { const src = ( await new Promise((resolve) => chrome.tabs.executeScript(tabId, { file: 'getInnerHtml.js' }, resolve) ) )?.[0]; // It's possible that the chrome extension cannot read the source code, either // because it is served via a non-permitted scheme (eg `chrome-extension://`), // or bc the user/adminstrator has denied this extension access to the page. if (!src) { chrome.notifications.create(undefined, { type: 'basic', title: 'Could not sandbox this page', message: 'The extension does not have permission to modify this page.', iconUrl: 'icon-red.png', isClickable: false, eventTime: Date.now(), }); return; } const searchParams = new URLSearchParams({ src }); const url = `index.html?${searchParams.toString()}`; chrome.tabs.update({ url }); } chrome.browserAction.onClicked.addListener(loadPageInASecureSandbox);
// svgmap.js 0.2.0 // // Copyright (c) 2014 jalal @ gnomedia // // 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 SvgMap = function (opts) { /*global Snap:false, console:false */ 'use strict'; console.log("SvgMap initializing"); var defaults = { svgid: '', mapurl: '', mapid: '', coordsurl: '', hoverFill: '#fff', strokeColor: '#000', resultid: 'results' }; var svgid = opts.svgid || defaults.svgid, mapurl = opts.mapurl || defaults.mapurl, mapid = opts.mapid || defaults.mapid, coordsurl = opts.coordsurl || defaults.coordsurl, strokeColor = opts.strokeColor || defaults.strokeColor, hoverFill = opts.hoverFill || defaults.hoverFill, resultid = opts.resultid || defaults.resultid; var i, w, h, areas, pre; var s = new Snap(svgid); var group = s.group(); Snap.load(mapurl, function (f) { i = f.select('image'); h = i.attr('height'); w = i.attr('width'); group.append(f); s.attr({ viewBox: [0, 0, w, h] }); var newmap = document.getElementById('newmap'); if (newmap) { newmap.style.height = h + 'px'; newmap.style.maxWidth = w + 'px'; } }); var shadow = new Snap(svgid); areas = document.getElementsByTagName('area'); var area; for (var j = areas.length - 1; j >= 0; j--) { area = areas[j]; // console.log("Coord: " + area.coords); var coords = area.coords.split(','); var path = 'M '; if (coords.length) { for (var k = 0; k < coords.length; k += 2) { if (!k) {pre = ''; } else {pre = ' L '; } path += pre + coords[k] + ',' + coords[k + 1]; } } var p = new Snap(); var el = p.path(path); el.attr({ id: area.title, fill: 'none', stroke: strokeColor, link: area.href, d: path, title: area.title}); el.hover(function () { this.attr('fill', hoverFill); }, function () { this.attr('fill', 'transparent'); }); el.click(function () { // console.log('click: ' + this.attr('id')); hideAll(); show('Clicked: ' + this.attr('id')); }); el.touchstart(function () { console.log('touch: ' + this.attr('id')); this.attr('fill', hoverFill); hideAll(); show('Touched: ' + this.attr('id')); }); el.touchend(function () { this.attr('fill', 'transparent'); }); shadow.append(el); } function hideAll() { var el = document.getElementById(resultid); if (el) {el.style.display = "none"; } // $(resultid).hide(); } function show(txt) { var el = document.getElementById(resultid); if (el) { el.style.display = ""; if (el.firstChild) { el.removeChild(el.firstChild); } var t = document.createTextNode(txt); el.appendChild(t); } } };
(function () { 'use strict'; app.service('reportService', reportService); function reportService($http, $window, $interval, timeAgo, restCall, queryService, dashboardFactory, ngAuthSettings, reportServiceUrl) { var populateReport = function (report, url) { function successCallback(response) { if (response.data.data.length === 0) { report.status = 'EMPTY' } else { report.status = 'SUCCESS'; report.data = response.data.data; report.getTotal(); console.log(report); } } function errorCallback(error) { console.log(error); this.status = 'FAILED'; } restCall('GET', url, null, successCallback, errorCallback) } var getReport = function () { return { data: {}, searchParam : { startdate: null, enddate: null, type: "ENTERPRISE", generateexcel: false, userid: null, username: null }, total : { totalVendor: 0, totalDelivery: 0, totalPending: 0, totalInProgress: 0, totalCompleted: 0, totalCancelled: 0, totalProductPrice: 0, totalDeliveryCharge: 0 }, getTotal: function () { var itSelf = this; itSelf.total.totalVendor = 0; itSelf.total.totalDelivery = 0; itSelf.total.totalPending = 0; itSelf.total.totalInProgress = 0; itSelf.total.totalCompleted = 0; itSelf.total.totalCancelled = 0; itSelf.total.totalProductPrice = 0; itSelf.total.totalDeliveryCharge = 0; angular.forEach(this.data, function (value, key) { itSelf.total.totalVendor += 1; itSelf.total.totalDelivery += value.TotalDelivery; itSelf.total.totalPending += value.TotalPending; itSelf.total.totalInProgress += value.TotalInProgress; itSelf.total.totalCompleted += value.TotalCompleted; itSelf.total.totalCancelled += value.TotalCancelled; itSelf.total.totalProductPrice += value.TotalProductPrice; itSelf.total.totalDeliveryCharge += value.TotalDeliveryCharge; }); console.log(this.total) }, getUrl: function () { // FIXME: need to be refactored if (this.searchParam.type === "BIKE_MESSENGER") { return reportServiceUrl + "api/report?startdate="+this.searchParam.startdate+"&enddate="+this.searchParam.enddate+"&usertype="+this.searchParam.type; } return reportServiceUrl + "api/report?startdate="+this.searchParam.startdate+"&enddate="+this.searchParam.enddate+"&usertype="+this.searchParam.type; }, getReport: function () { var reportUrl = this.getUrl(); this.status = 'IN_PROGRESS'; populateReport(this, reportUrl); }, goToReportJobs : function (user) { console.log(user) console.log(this.data) if (this.searchParam.type === "BIKE_MESSENGER") { $window.open("#/report/jobs?" + "startdate=" + this.searchParam.startdate + "&enddate="+ this.searchParam.enddate + "&usertype=BIKE_MESSENGER" + "&userid=" + this.data[user].UserId, '_blank'); } else { $window.open("#/report/jobs?" + "startdate=" + this.searchParam.startdate + "&enddate="+ this.searchParam.enddate + "&usertype=" + this.searchParam.type + "&username=" + user, '_blank'); } }, exportExcel : function () { var excelReportUrl = reportServiceUrl + "api/report?startdate="+this.searchParam.startdate+"&enddate="+this.searchParam.enddate+"&usertype="+this.searchParam.type + "&generateexcel=true"; $window.open(excelReportUrl, '_blank'); }, status : 'NONE' } } return { getReport: getReport } } })();
var array = trace ( new Array()); var m = trace ( 0 ); var n = trace ( 3 ); var o = trace ( 5 ); var p = trace ( 7 ); array[0] = m; array[1] = n; array[2] = o; array[3] = p; var result = new Array(); // FOR-IN Schleife for ( i in array ) { result.push(i); x = i; z = 7; } var a = result; var b = result[0]; var c = 7; var d = x;
'use strict' /*eslint-env node */ exports.config = { specs: [ 'test/e2e/**/*.js' ], baseUrl: 'http://localhost:9000', chromeOnly: true }
/** * @license AngularJS v1.3.0-build.2690+sha.be7c02c * (c) 2010-2014 Google, Inc. http://angularjs.org * License: MIT */ (function(window, angular, undefined) {'use strict'; /** * @ngdoc module * @name ngCookies * @description * * # ngCookies * * The `ngCookies` module provides a convenient wrapper for reading and writing browser cookies. * * * <div doc-module-components="ngCookies"></div> * * See {@link ngCookies.$cookies `$cookies`} and * {@link ngCookies.$cookieStore `$cookieStore`} for usage. */ angular.module('ngCookies', ['ng']). /** * @ngdoc service * @name $cookies * * @description * Provides read/write access to browser's cookies. * * Only a simple Object is exposed and by adding or removing properties to/from this object, new * cookies are created/deleted at the end of current $eval. * The object's properties can only be strings. * * Requires the {@link ngCookies `ngCookies`} module to be installed. * * @example * * ```js * function ExampleController($cookies) { * // Retrieving a cookie * var favoriteCookie = $cookies.myFavorite; * // Setting a cookie * $cookies.myFavorite = 'oatmeal'; * } * ``` */ factory('$cookies', ['$rootScope', '$browser', function ($rootScope, $browser) { var cookies = {}, lastCookies = {}, lastBrowserCookies, runEval = false, copy = angular.copy, isUndefined = angular.isUndefined; //creates a poller fn that copies all cookies from the $browser to service & inits the service $browser.addPollFn(function() { var currentCookies = $browser.cookies(); if (lastBrowserCookies != currentCookies) { //relies on browser.cookies() impl lastBrowserCookies = currentCookies; copy(currentCookies, lastCookies); copy(currentCookies, cookies); if (runEval) $rootScope.$apply(); } })(); runEval = true; //at the end of each eval, push cookies //TODO: this should happen before the "delayed" watches fire, because if some cookies are not // strings or browser refuses to store some cookies, we update the model in the push fn. $rootScope.$watch(push); return cookies; /** * Pushes all the cookies from the service to the browser and verifies if all cookies were * stored. */ function push() { var name, value, browserCookies, updated; //delete any cookies deleted in $cookies for (name in lastCookies) { if (isUndefined(cookies[name])) { $browser.cookies(name, undefined); } } //update all cookies updated in $cookies for(name in cookies) { value = cookies[name]; if (!angular.isString(value)) { value = '' + value; cookies[name] = value; } if (value !== lastCookies[name]) { $browser.cookies(name, value); updated = true; } } //verify what was actually stored if (updated){ updated = false; browserCookies = $browser.cookies(); for (name in cookies) { if (cookies[name] !== browserCookies[name]) { //delete or reset all cookies that the browser dropped from $cookies if (isUndefined(browserCookies[name])) { delete cookies[name]; } else { cookies[name] = browserCookies[name]; } updated = true; } } } } }]). /** * @ngdoc service * @name $cookieStore * @requires $cookies * * @description * Provides a key-value (string-object) storage, that is backed by session cookies. * Objects put or retrieved from this storage are automatically serialized or * deserialized by angular's toJson/fromJson. * * Requires the {@link ngCookies `ngCookies`} module to be installed. * * @example * * ```js * function ExampleController($cookieStore) { * // Put cookie * $cookieStore.put('myFavorite','oatmeal'); * // Get cookie * var favoriteCookie = $cookieStore.get('myFavorite'); * // Removing a cookie * $cookieStore.remove('myFavorite'); * } * ``` */ factory('$cookieStore', ['$cookies', function($cookies) { return { /** * @ngdoc method * @name $cookieStore#get * * @description * Returns the value of given cookie key * * @param {string} key Id to use for lookup. * @returns {Object} Deserialized cookie value. */ get: function(key) { var value = $cookies[key]; return value ? angular.fromJson(value) : value; }, /** * @ngdoc method * @name $cookieStore#put * * @description * Sets a value for given cookie key * * @param {string} key Id for the `value`. * @param {Object} value Value to be stored. */ put: function(key, value) { $cookies[key] = angular.toJson(value); }, /** * @ngdoc method * @name $cookieStore#remove * * @description * Remove given cookie * * @param {string} key Id of the key-value pair to delete. */ remove: function(key) { delete $cookies[key]; } }; }]); })(window, window.angular);
/* * Copyright 2016 The Closure Compiler 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 Tests for user-defined Symbols. */ goog.require('goog.testing.jsunit'); const s1 = Symbol('example'); const s2 = Symbol('example'); /** @unrestricted */ const SymbolProps = class { [s1]() { return 's1'; } [s2]() { return 's2'; } } function testSymbols() { const sp = new SymbolProps(); assertEquals('s1', sp[s1]()); assertEquals('s2', sp[s2]()); } function testArrayIterator() { // Note: this test cannot pass in IE8 since we can't polyfill // Array.prototype methods and maintain correct for-in behavior. if (typeof Object.defineProperties !== 'function') return; const iter = [2, 4, 6][Symbol.iterator](); assertObjectEquals({value: 2, done: false}, iter.next()); assertObjectEquals({value: 4, done: false}, iter.next()); assertObjectEquals({value: 6, done: false}, iter.next()); assertTrue(iter.next().done); }
// Reset $('.touch .client-wrap').click(function(event){ var target = $( event.target ); if ( target.hasClass( "client-close" ) ) { $('.client-wrap div.client').addClass('reset'); } else{ $('.client-wrap div.client').removeClass('reset'); } }); // David Walsh simple lazy loading [].forEach.call(document.querySelectorAll('img[data-src]'), function(img) { img.setAttribute('src', img.getAttribute('data-src')); img.onload = function() { img.removeAttribute('data-src'); }; });
(function() { 'use strict'; angular .module('sentryApp') .controller('TimeFrameController', TimeFrameController); TimeFrameController.$inject = ['$scope', '$state', 'TimeFrame', 'ParseLinks', 'AlertService', 'paginationConstants', 'pagingParams']; function TimeFrameController ($scope, $state, TimeFrame, ParseLinks, AlertService, paginationConstants, pagingParams) { var vm = this; vm.loadPage = loadPage; vm.predicate = pagingParams.predicate; vm.reverse = pagingParams.ascending; vm.transition = transition; vm.itemsPerPage = paginationConstants.itemsPerPage; loadAll(); function loadAll () { TimeFrame.query({ page: pagingParams.page - 1, size: vm.itemsPerPage, sort: sort() }, onSuccess, onError); function sort() { var result = [vm.predicate + ',' + (vm.reverse ? 'asc' : 'desc')]; if (vm.predicate !== 'id') { result.push('id'); } return result; } function onSuccess(data, headers) { vm.links = ParseLinks.parse(headers('link')); vm.totalItems = headers('X-Total-Count'); vm.queryCount = vm.totalItems; vm.timeFrames = data; vm.page = pagingParams.page; } function onError(error) { AlertService.error(error.data.message); } } function loadPage(page) { vm.page = page; vm.transition(); } function transition() { $state.transitionTo($state.$current, { page: vm.page, sort: vm.predicate + ',' + (vm.reverse ? 'asc' : 'desc'), search: vm.currentSearch }); } } })();
/*price range*/ $('#sl2').slider(); var RGBChange = function() { $('#RGB').css('background', 'rgb('+r.getValue()+','+g.getValue()+','+b.getValue()+')') }; /*scroll to top*/ $(document).ready(function(){ $(function () { $.scrollUp({ scrollName: 'scrollUp', // Element ID scrollDistance: 300, // Distance from top/bottom before showing element (px) scrollFrom: 'top', // 'top' or 'bottom' scrollSpeed: 300, // Speed back to top (ms) easingType: 'linear', // Scroll to top easing (see http://easings.net/) animation: 'fade', // Fade, slide, none animationSpeed: 200, // Animation in speed (ms) scrollTrigger: false, // Set a custom triggering element. Can be an HTML string or jQuery object //scrollTarget: false, // Set a custom target element for scrolling to the top scrollText: '<i class="fa fa-angle-up"></i>', // Text for element, can contain HTML scrollTitle: false, // Set a custom <a> title if required. scrollImg: false, // Set true to use image activeOverlay: false, // Set CSS color to display scrollUp active point, e.g '#00FFFF' zIndex: 2147483647 // Z-Index for the overlay }); }); }); // Returns a random integer between min and max // Using Math.round() will give you a non-uniform distribution! function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } // Replace url parameter - WishlistItems function replaceUrlParam(url, paramName, paramValue) { var pattern = new RegExp('(' + paramName + '=).*?(&|$)') var newUrl = url if (url.search(pattern) >= 0) { newUrl = url.replace(pattern, '$1' + paramValue + '$2'); } else { newUrl = newUrl + (newUrl.indexOf('?') > 0 ? '&' : '?') + paramName + '=' + paramValue } return newUrl } // Scroll back to selected wishlist item if (window.location.hash != '') { var target = window.location.hash; //var $target = $(target); $('html, body').stop().animate({ //'scrollTop': $target.offset().top }, 900, 'swing', function () { window.location.hash = target; }); }
import { extend } from 'flarum/extend'; import PermissionGrid from 'flarum/components/PermissionGrid'; export default function() { extend(PermissionGrid.prototype, 'moderateItems', items => { items.add('tag', { icon: 'fas fa-tag', label: app.translator.trans('flarum-tags.admin.permissions.tag_discussions_label'), permission: 'discussion.tag' }, 95); }); }
const loopback = require('loopback'); const boot = require('loopback-boot'); const request = require('request-promise'); const config = require('./config.json'); const log = require('log4js').getLogger('server'); const jwt = require('jwt-simple'); var app = module.exports = loopback(); var apiUrl = config.restApiRoot + '/*'; function parseJwt (token) { var base64Url = token.split('.')[1]; var base64 = base64Url.replace('-', '+').replace('_', '/'); var json = new Buffer(base64, 'base64').toString('binary'); return JSON.parse(json); }; app.use(loopback.context()); app.use(['/api/todos'], function(req, res, next) { var accessToken = req.query.access_token || req.headers['Authorization']; if(accessToken) { app.accessTokenProvider.getUserInfo(accessToken) .then(userInfo => { log.debug('userInfo:', userInfo); loopback.getCurrentContext().set('userInfo', userInfo); next(); }).catch(error => { log.error(error); next(error); }); } else { log.debug('missing accessToken'); next({ name: 'MISSING_ACCESS_TOKEN', status: 401, message: 'tenant access token is required to access this endpoint' }); } }); app.start = () => { // start the web server return app.listen(() => { app.emit('started'); var baseUrl = app.get('url').replace(/\/$/, ''); log.info('Web server listening at: %s', baseUrl); if (app.get('loopback-component-explorer')) { var explorerPath = app.get('loopback-component-explorer').mountPath; log.info('Browse your REST API at %s%s', baseUrl, explorerPath); } }); }; // Bootstrap the application, configure models, datasources and middleware. // Sub-apps like REST API are mounted via boot scripts. boot(app, __dirname, function(err) { if (err) throw err; // start the server if `$ node server.js` if (require.main === module) app.start(); });
'use strict'; angular.module('donetexampleApp') .service('ParseLinks', function () { this.parse = function (header) { if (header.length == 0) { throw new Error("input must not be of zero length"); } // Split parts by comma var parts = header.split(','); var links = {}; // Parse each part into a named link angular.forEach(parts, function (p) { var section = p.split(';'); if (section.length != 2) { throw new Error("section could not be split on ';'"); } var url = section[0].replace(/<(.*)>/, '$1').trim(); var queryString = {}; url.replace( new RegExp("([^?=&]+)(=([^&]*))?", "g"), function($0, $1, $2, $3) { queryString[$1] = $3; } ); var page = queryString['page']; if( angular.isString(page) ) { page = parseInt(page); } var name = section[1].replace(/rel="(.*)"/, '$1').trim(); links[name] = page; }); return links; } });
var searchData= [ ['interactiontype',['InteractionType',['../class_student_record.html#a00e060bc8aa9829e5db087e2cba21009',1,'StudentRecord']]] ];
import Vue from 'vue' import { hasFetch, normalizeError, addLifecycleHook } from '../utils' const isSsrHydration = (vm) => vm.$vnode && vm.$vnode.elm && vm.$vnode.elm.dataset && vm.$vnode.elm.dataset.fetchKey const nuxtState = window.<%= globals.context %> export default { beforeCreate () { if (!hasFetch(this)) { return } this._fetchDelay = typeof this.$options.fetchDelay === 'number' ? this.$options.fetchDelay : 200 Vue.util.defineReactive(this, '$fetchState', { pending: false, error: null, timestamp: Date.now() }) this.$fetch = $fetch.bind(this) addLifecycleHook(this, 'created', created) addLifecycleHook(this, 'beforeMount', beforeMount) } } function beforeMount() { if (!this._hydrated) { return this.$fetch() } } function created() { if (!isSsrHydration(this)) { return } // Hydrate component this._hydrated = true this._fetchKey = +this.$vnode.elm.dataset.fetchKey const data = nuxtState.fetch[this._fetchKey] // If fetch error if (data && data._error) { this.$fetchState.error = data._error return } // Merge data for (const key in data) { Vue.set(this.$data, key, data[key]) } } async function $fetch() { this.$nuxt.nbFetching++ this.$fetchState.pending = true this.$fetchState.error = null this._hydrated = false let error = null const startTime = Date.now() try { await this.$options.fetch.call(this) } catch (err) { error = normalizeError(err) } const delayLeft = this._fetchDelay - (Date.now() - startTime) if (delayLeft > 0) { await new Promise(resolve => setTimeout(resolve, delayLeft)) } this.$fetchState.error = error this.$fetchState.pending = false this.$fetchState.timestamp = Date.now() this.$nextTick(() => this.$nuxt.nbFetching--) }
/*! * Copyright 2012 Sakai Foundation (SF) Licensed under the * Educational Community 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.osedu.org/licenses/ECL-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. */ require(['jquery', 'oae.core'], function($, oae) { // Get the group id from the URL. The expected URL is /group/<groupId> var groupId = document.location.pathname.split('/')[2]; if (!groupId) { oae.api.util.redirect().login(); } // Variable used to cache the requested user's profile var groupProfile = null; // Variable used to cache the group's base URL var baseUrl = '/group/' + groupId; /** * Get the group's basic profile and set up the screen. If the groups * can't be found or is private to the current user, the appropriate * error page will be shown */ var getGroupProfile = function() { oae.api.group.getGroup(groupId, function(err, profile) { if (err && err.code === 404) { oae.api.util.redirect().notfound(); } else if (err && err.code === 401) { oae.api.util.redirect().accessdenied(); } groupProfile = profile; setUpClip(); setUpNavigation(); // Set the browser title oae.api.util.setBrowserTitle(groupProfile.displayName); }); }; $(document).on('oae.context.get', function() { $(document).trigger('oae.context.send', groupProfile); }); $(document).trigger('oae.context.send', groupProfile); /** * Render the group's clip, containing the profile picture, display name as well as the * group's admin options */ var setUpClip = function() { oae.api.util.template().render($('#group-clip-template'), {'group': groupProfile}, $('#group-clip-container')); // Only show the create and upload clips to managers if (groupProfile.isManager) { $('#group-actions').show(); } }; /** * Set up the left hand navigation with the me space page structure */ var setUpNavigation = function() { // Structure that will be used to construct the left hand navigation var lhNavigation = [ { 'id': 'activity', 'title': oae.api.i18n.translate('__MSG__RECENT_ACTIVITY__'), 'icon': 'icon-dashboard', 'layout': [ { 'width': 'span8', 'widgets': [ { 'id': 'activity', 'settings': { 'principalId': groupProfile.id, 'canManage': groupProfile.isManager } } ] } ] }, { 'id': 'library', 'title': oae.api.i18n.translate('__MSG__LIBRARY__'), 'icon': 'icon-briefcase', 'layout': [ { 'width': 'span12', 'widgets': [ { 'id': 'library', 'settings': { 'principalId': groupProfile.id, 'canManage': groupProfile.isManager } } ] } ] }, { 'id': 'members', 'title': oae.api.i18n.translate('__MSG__MEMBERS__'), 'icon': 'icon-user', 'layout': [ { 'width': 'span12', 'widgets': [ { 'id': 'participants', 'settings': { 'principalId': groupProfile.id, 'canManage': groupProfile.isManager } } ] } ] } ]; $(window).trigger('oae.trigger.lhnavigation', [lhNavigation, baseUrl]); $(window).on('oae.ready.lhnavigation', function() { $(window).trigger('oae.trigger.lhnavigation', [lhNavigation, baseUrl]); }); }; getGroupProfile(); });