code
stringlengths
2
1.05M
/*! simpler-sidebar v1.4.9 (https://github.com/dcdeiv/simpler-sidebar) ** Copyright (c) 2015 - 2016 Davide Di Criscito ** Dual licensed under MIT and GPL-2.0 */ ( function( $ ) { $.fn.simplerSidebar = function( options ) { var cfg = $.extend( true, $.fn.simplerSidebar.settings, options ); return this.each( function() { var align, sbw, ssbInit, ssbStyle, maskInit, maskStyle, attr = cfg.attr, $sidebar = $( this ), $opener = $( cfg.opener ), $links = cfg.sidebar.closingLinks, duration = cfg.animation.duration, sbMaxW = cfg.sidebar.width, gap = cfg.sidebar.gap, winMaxW = sbMaxW + gap, w = $( window ).width(), animationStart = {}, animationReset = {}, hiddenFlow = function() { $( "body, html" ).css( "overflow", "hidden" ); }, autoFlow = function() { $( "body, html" ).css( "overflow", "auto" ); }, activate = { duration: duration, easing: cfg.animation.easing, complete: hiddenFlow }, deactivate = { duration: duration, easing: cfg.animation.easing, complete: autoFlow }, animateOpen = function() { $sidebar .animate( animationStart, activate ) .attr( "data-" + attr, "active" ); $mask.fadeIn( duration ); }, animateClose = function() { $sidebar .animate( animationReset, deactivate ) .attr( "data-" + attr, "disabled" ); $mask.fadeOut( duration ); }, closeSidebar = function() { var isWhat = $sidebar.attr( "data-" + attr ), csbw = $sidebar.width(); animationReset[ align ] = -csbw; if ( isWhat === "active" ) { animateClose(); } }, $mask = $( "<div>" ).attr( "data-" + attr, "mask" ); //Checking sidebar align if ( [ undefined, "right" ].indexOf( cfg.sidebar.align ) !== -1 ) { align = "right"; } else if ( cfg.sidebar.align === "left" ) { align = "left"; } else { console.log( "ERR sidebar.align: you typed \"" + cfg.sidebar.align + "\". You should choose between \"right\" or \"left\"." ); } //Sidebar style if ( w < winMaxW ) { sbw = w - gap; } else { sbw = sbMaxW; } ssbInit = { position: "fixed", top: cfg.top, bottom: 0, width: sbw }; ssbInit[ align ] = -sbw; animationStart[ align ] = 0; ssbStyle = $.extend( true, ssbInit, cfg.sidebar.css ); $sidebar.css( ssbStyle ) .attr( "data-" + attr, "disabled" ); //Mask style maskInit = { position: "fixed", top: cfg.top, right: 0, bottom: 0, left: 0, zIndex: cfg.sidebar.css.zIndex - 1, display: "none" }; maskStyle = $.extend( true, maskInit, cfg.mask.css ); //Appending Mask if mask.display is true if ( [ true, "true", false, "false" ].indexOf( cfg.mask.display) !== -1 ) { if ( [ true, "true" ].indexOf( cfg.mask.display ) !== -1 ) { $mask.appendTo( "body" ).css( maskStyle ); } } else { console.log( "ERR mask.display: you typed \"" + cfg.mask.display + "\". You should choose between true or false." ); } //Opening and closing the Sidebar when $opener is clicked $opener.click( function() { var isWhat = $sidebar.attr( "data-" + attr ), csbw = $sidebar.width(); animationReset[ align ] = -csbw; if ( isWhat === "disabled" ) { animateOpen(); } else if ( isWhat === "active" ) { animateClose(); } }); //Closing Sidebar when the mask is clicked $mask.click( closeSidebar ); //Closing Sidebar when a link inside of it is clicked $sidebar.on( "click", $links, closeSidebar ); //Adjusting width; $( window ).resize( function() { var rsbw, update, isWhat = $sidebar.attr( "data-" + attr ), nw = $( window ).width(); if ( nw < winMaxW ) { rsbw = nw - gap; } else { rsbw = sbMaxW; } update = { width: rsbw }; if ( isWhat === "disabled" ) { update[ align ] = -rsbw; $sidebar.css( update ); } else if ( isWhat === "active" ) { $sidebar.css( update ); } }); }); }; $.fn.simplerSidebar.settings = { attr: "simplersidebar", top: 0, animation: { duration: 500, easing: "swing" }, sidebar: { width: 300, gap: 64, closingLinks: "a", css: { zIndex: 3000 } }, mask: { display: true, css: { backgroundColor: "black", opacity: 0.5, filter: "Alpha(opacity=50)" } } }; } )( jQuery );
// Fill in topbar details. $('header .right').append(Handlebars.templates.userTopbar(user)); // Fill in sidebar details. user.created_at = moment(user.created_at).format('MMM DD, YYYY'); var userStars = {user: user, stars: stars}; $('aside').prepend(Handlebars.templates.userSidebar(userStars)); // Populate the organizations list on the sidebar. var orgList = $('aside #organizations'); orgs.forEach(function (org) { orgList.append(Handlebars.templates.org(org)); }); // Populate the repos list in the main page. var repoList = $('section.main .repo-list'); repos = _.sortBy( repos, 'updated_at' ).reverse(); repos.forEach(function (repo) { repo.updated_at = moment(repo.updated_at).fromNow(); repoList.append(Handlebars.templates.repo(repo)); });
import { faker } from 'ember-cli-mirage'; import lodash from 'npm:lodash'; export const CONTAINER_MEMORY = 8023089152; export function getPorts(isContainer=false) { let ports = []; for (let j = 1; j <= faker.random.number({ max: 3 }); j++) { let obj = { name: faker.hacker.noun(), protocol: 'TCP', }; obj[isContainer ? 'hostPort': 'port'] = faker.random.number(); obj[isContainer ? 'containerPort': 'targetPort'] = faker.random.number(); ports.push(obj); } return ports; } export function getLabels() { let labels = {}; for (let j = 1; j <= faker.random.number({ max: 3 }); j++) { labels[faker.hacker.verb()] = faker.hacker.noun(); } return labels; } export function getSpec(isContainer=false) { let containers = []; for (let j = 1; j <= faker.random.number({ min: 1, max: 5 }); j++) { const name = faker.hacker.verb(); containers.push({ name, image: `${name}:v${j / 2}`, ports: getPorts(isContainer), terminationMessagePath: '/dev/termination-log', imagePullPolicy: faker.random.arrayElement(['Always', 'Never', 'IfNotPresent']) }); } return { containers, restartPolicy: faker.random.arrayElement(['Always', 'OnFailure', 'Never']), terminationGracePeriodSeconds: faker.random.number(), dnsPolicy: faker.random.arrayElement(['ClusterFirst', 'Default']), nodeName: faker.internet.ip(), hostNetwork: faker.random.boolean() }; } export function getId(kind, index) { return `${kind.toLowerCase()}-${index}`; } export function getMetadata(kind='Node', index=0, namespace=null) { let name = getId(kind, index), creationTimestamp = faker.date.recent(), labels = getLabels(); if (!namespace && kind !== 'Node') { namespace = faker.random.arrayElement(['default', 'kube-system', 'app-namespace']); } return { name, namespace, creationTimestamp, labels }; } export function getCAdvisorContainerSpec() { return { creation_time: faker.date.recent(), has_cpu: true, has_memory: true, has_filesystem: true, memory: { limit: CONTAINER_MEMORY } }; } export function getStat(total, timestamp, cpus=4) { let per_cpu_usage = [], maxPerCpu = Math.round(total / cpus); for (let i = 1; i < cpus; i++) { per_cpu_usage.push(faker.random.number({ max: maxPerCpu })); } let cpu = { usage: { total, per_cpu_usage } }, memory = { usage: faker.random.number({ max: CONTAINER_MEMORY }) }, filesystems = [], devices = [ '/dev/sda1', 'docker-8:1-7083173-pool', '/dev/mapper/docker-8:1-7083173-8f138ecc6e8dc81a08b9fee2f256415e96de06a8eb4ab247bde008932fc53c3a' ]; lodash.each(devices, (device) => { let min = 1024, max = 1024 * 20, capacity = faker.random.number({ min, max }), usage = faker.random.number({ min, max: capacity }); filesystems.push({ device, capacity, usage }); }); return { timestamp, cpu, memory, filesystem: filesystems }; }
module.exports = function () { return { templateUrl : './shared/partials/footer/directives/footer.html', controller: require('./footerCtrl'), restrict: 'E', scope: {} }; };
import React from 'react'; import PropTypes from 'prop-types'; import ColumnChart from './columnChart'; import Tooltip from './../tooltip/tooltip'; import {dateFormats} from './../../utils/displayFormats'; import './columnWidget.css'; const ColumnWidget = ({ chartTitle, chartDescription, chartUpdatedDate, series, xAxis, yAxis, viewport, displayHighContrast, }) => { return ( <article role="article" className="D_widget"> <header> {chartDescription && <div className="D_CW_infoContainer"><Tooltip text={chartDescription} viewport={viewport} /></div>} <h1 className="highcharts-title">{chartTitle}</h1> <span className="highcharts-subtitle">Last updated at <time dateTime={dateFormats.dateTime(chartUpdatedDate)}>{dateFormats.dayMonthYear(chartUpdatedDate)}</time></span> </header> <section> <ColumnChart series={series} xAxis={xAxis} yAxis={yAxis} chartDescription={chartDescription} displayHighContrast={displayHighContrast} /> </section> </article> ) }; if (__DEV__) { ColumnWidget.propTypes = { chartTitle: PropTypes.string, chartDescription: PropTypes.string, chartUpdatedDate: PropTypes.string, series: PropTypes.arrayOf(PropTypes.shape({ name: PropTypes.string.isRequired, units: PropTypes.string, color: PropTypes.string, data: PropTypes.array.isRequired, })).isRequired, xAxis: PropTypes.arrayOf(PropTypes.shape({ categories: PropTypes.array, })), yAxis: PropTypes.arrayOf(PropTypes.shape({ title: PropTypes.object, })), viewport: PropTypes.oneOf(['sm', 'md', 'lg', 'xl']), displayHighContrast: PropTypes.bool, }; } export default ColumnWidget;
import React from 'react'; import { render } from 'react-dom'; import { Provider } from 'react-redux'; import App from './containers/App'; import configureStore from './store/configureStore'; import 'todomvc-app-css/index.css'; const store = configureStore(); render( <Provider store={store}> <App /> </Provider>, document.getElementById('layout') );
// // window.onload = function() { // var data = {username:'52200', password:'123', remember:52200}; // fetch('/api/users/getUser?id=1').then(function(res) { // console.log("请求的数据是", res); // if (res.ok) { // alert('Submitted!'); // } else { // alert('Error!'); // } // }).then(function(body) { // console.log("请求body的数据是", body); // // body // }); // };
Meteor.methods({ addAllUserToRoom(rid, activeUsersOnly = false) { check (rid, String); check (activeUsersOnly, Boolean); if (RocketChat.authz.hasRole(this.userId, 'admin') === true) { const userCount = RocketChat.models.Users.find().count(); if (userCount > RocketChat.settings.get('API_User_Limit')) { throw new Meteor.Error('error-user-limit-exceeded', 'User Limit Exceeded', { method: 'addAllToRoom', }); } const room = RocketChat.models.Rooms.findOneById(rid); if (room == null) { throw new Meteor.Error('error-invalid-room', 'Invalid room', { method: 'addAllToRoom', }); } const userFilter = {}; if (activeUsersOnly === true) { userFilter.active = true; } const users = RocketChat.models.Users.find(userFilter).fetch(); const now = new Date(); users.forEach(function(user) { const subscription = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(rid, user._id); if (subscription != null) { return; } RocketChat.callbacks.run('beforeJoinRoom', user, room); RocketChat.models.Subscriptions.createWithRoomAndUser(room, user, { ts: now, open: true, alert: true, unread: 1, userMentions: 1, groupMentions: 0, }); RocketChat.models.Messages.createUserJoinWithRoomIdAndUser(rid, user, { ts: now, }); Meteor.defer(function() {}); return RocketChat.callbacks.run('afterJoinRoom', user, room); }); return true; } else { throw (new Meteor.Error(403, 'Access to Method Forbidden', { method: 'addAllToRoom', })); } }, });
const HttpStatus = require('http-status-codes'); const build = status => { return (ctx, message) => { ctx.status = status ctx.body = message || {message: HttpStatus.getStatusText(status)} return ctx } } module.exports = { accepted: build(HttpStatus.ACCEPTED), // 202 badGateway: build(HttpStatus.BAD_GATEWAY), // 502 badRequest: build(HttpStatus.BAD_REQUEST), // 400 conflict: build(HttpStatus.CONFLICT), // 409 continue: build(HttpStatus.CONTINUE), // 100 created: build(HttpStatus.CREATED), // 201 expectationFailed: build(HttpStatus.EXPECTATION_FAILED), // 417 failedDependency: build(HttpStatus.FAILED_DEPENDENCY), // 424 forbidden: build(HttpStatus.FORBIDDEN), // 403 gatewayTimeout: build(HttpStatus.GATEWAY_TIMEOUT), // 504 gone: build(HttpStatus.GONE), // 410 httpVersionNotSupported: build(HttpStatus.HTTP_VERSION_NOT_SUPPORTED), // 505 imATeapot: build(HttpStatus.IM_A_TEAPOT), // 418 insufficientSpaceOnResource: build(HttpStatus.INSUFFICIENT_SPACE_ON_RESOURCE), // 419 insufficientStorage: build(HttpStatus.INSUFFICIENT_STORAGE), // 507 internalServerError: build(HttpStatus.INTERNAL_SERVER_ERROR), // 500 lengthRequired: build(HttpStatus.LENGTH_REQUIRED), // 411 locked: build(HttpStatus.LOCKED), // 423 methodFailure: build(HttpStatus.METHOD_FAILURE), // 420 methodNotAllowed: build(HttpStatus.METHOD_NOT_ALLOWED), // 405 movedPermanently: build(HttpStatus.MOVED_PERMANENTLY), // 301 movedTemporarily: build(HttpStatus.MOVED_TEMPORARILY), // 302 multiStatus: build(HttpStatus.MULTI_STATUS), // 207 multipleChoices: build(HttpStatus.MULTIPLE_CHOICES), // 300 networkAuthenticationRequired: build(HttpStatus.NETWORK_AUTHENTICATION_REQUIRED), // 511 noContent: build(HttpStatus.NO_CONTENT), // 204 nonAuthoritativeInformation: build(HttpStatus.NON_AUTHORITATIVE_INFORMATION), // 203 notAcceptable: build(HttpStatus.NOT_ACCEPTABLE), // 406 notFound: build(HttpStatus.NOT_FOUND), // 404 notImplemented: build(HttpStatus.NOT_IMPLEMENTED), // 501 notModified: build(HttpStatus.NOT_MODIFIED), // 304 ok: build(HttpStatus.OK), // 200 partialContent: build(HttpStatus.PARTIAL_CONTENT), // 206 paymentRequired: build(HttpStatus.PAYMENT_REQUIRED), // 402 permanentRedirect: build(HttpStatus.PERMANENT_REDIRECT), // 308 preconditionFailed: build(HttpStatus.PRECONDITION_FAILED), // 412 preconditionRequired: build(HttpStatus.PRECONDITION_REQUIRED), // 428 processing: build(HttpStatus.PROCESSING), // 102 proxyAuthenticationRequired: build(HttpStatus.PROXY_AUTHENTICATION_REQUIRED), // 407 requestHeaderFieldsTooLarge: build(HttpStatus.REQUEST_HEADER_FIELDS_TOO_LARGE), // 431 requestTimeout: build(HttpStatus.REQUEST_TIMEOUT), // 408 requestTooLong: build(HttpStatus.REQUEST_TOO_LONG), // 413 requestUriTooLong: build(HttpStatus.REQUEST_URI_TOO_LONG), // 414 requestedRangeNotSatisfiable: build(HttpStatus.REQUESTED_RANGE_NOT_SATISFIABLE), // 416 resetContent: build(HttpStatus.RESET_CONTENT), // 205 seeOther: build(HttpStatus.SEE_OTHER), // 303 serviceUnavailable: build(HttpStatus.SERVICE_UNAVAILABLE), // 503 switchingProtocols: build(HttpStatus.SWITCHING_PROTOCOLS), // 101 temporaryRedirect: build(HttpStatus.TEMPORARY_REDIRECT), // 307 tooManyRequests: build(HttpStatus.TOO_MANY_REQUESTS), // 429 unauthorized: build(HttpStatus.UNAUTHORIZED), // 401 unprocessableEntity: build(HttpStatus.UNPROCESSABLE_ENTITY), // 422 unsupportedMediaType: build(HttpStatus.UNSUPPORTED_MEDIA_TYPE), // 415 useProxy: build(HttpStatus.USE_PROXY) // 305 }
module.exports = function verify(check) { if (typeof check !== 'object') { throw new Error('check is not an object'); } var errors = []; Object.keys(check).forEach(_verify, check); if (errors.length > 0) { throw new Error('Health checks failed: '+ errors.join(', ')); } return true; function _verify(key, i) { if (this[key] === false || this[key] instanceof Error) { errors.push(key); } else if (this[key] && typeof this[key] === 'object' && !Array.isArray(this[key])) { Object.keys(this[key]).forEach(_verify, this[key]); } } };
/* globals describe, beforeEach, it, expect, inject, vehicles, VehicleMock */ describe("Vehicles Factory:", function() { 'use strict'; var $httpBackend, vehicles, request, Showcase; // Load the main module beforeEach(module('sc')); beforeEach(inject(function($injector, _vehicles_, _Showcase_) { $httpBackend = $injector.get('$httpBackend'); vehicles = _vehicles_; Showcase = _Showcase_; request = $httpBackend.whenGET(Showcase.API + 'vehicles').respond(200, angular.copy(VehicleMock.ALL)); $httpBackend.whenGET(Showcase.API + 'vehicles/1').respond(200, VehicleMock.DETAIL); $httpBackend.whenGET(Showcase.API + 'vehicles/compare/1').respond(200, angular.copy(VehicleMock.COMPARE)); })); it("should return 4 vehicles", function() { vehicles.getAll().then(function(response) { expect(response.length).toEqual(4); }); $httpBackend.flush(); }); it("should return Toyota as the first Brand", function() { vehicles.getAll().then(function(response) { expect(response[0].brand).toEqual('Toyota'); }); $httpBackend.flush(); }); it("should return a 404 error", function() { request.respond(404, {error: true}); $httpBackend.expectGET(Showcase.API + 'vehicles'); vehicles.getAll().catch(function(error) { expect(error.error).toBe(true); }); $httpBackend.flush(); }); it("should return vehicle detail", function() { vehicles.get(1).then(function(response) { expect(response.model).toEqual('Avalon'); }); $httpBackend.flush(); }); it("should compare 3 vehicles", function() { vehicles.compare(1,2,3).then(function(response) { expect(response.length).toEqual(2); }); $httpBackend.flush(); }); });
import { createGlobalStyle } from 'styled-components'; export const GlobalStyle = createGlobalStyle` body { margin: 0; font-family: 'Montserrat', sans-serif; } * { box-sizing: border-box; } `;
import React, { Component, PropTypes } from 'react' import cx from 'classnames' import { Icon } from '../icon' import { capitalize } from 'utils/string' import './button.view.styl' export class Button extends Component { static propTypes = { className: PropTypes.string, children: PropTypes.oneOfType([ PropTypes.element, PropTypes.string ]), icon: PropTypes.string, type: PropTypes.oneOf(['primary', 'text', 'danger', 'normal']), htmlType: PropTypes.oneOf(['submit', 'button', 'reset']), size: PropTypes.oneOf(['small', 'normal', 'large']), block: PropTypes.bool, loading: PropTypes.bool, disabled: PropTypes.bool, ghost: PropTypes.bool, onClick: PropTypes.func } static defaultProps = { type: 'primary', size: 'normal', onClick: () => {} } getRootClassNames () { const { className, type, size, block, loading, disabled, ghost } = this.props return cx( 'button', `button${capitalize(type)}`, `size${capitalize(size)}`, { isBlock: block }, { isGhost: ghost }, { isLoading: loading }, { isDisabled: disabled }, className ) } handleClick = (e) => { const { loading, disabled, onClick } = this.props if (loading || disabled) { e.preventDefault() return null } if (onClick) { onClick(e) } } render () { const { icon, htmlType, // loading, children } = this.props const iconName = icon // @OLD: loading ? 'loading' : icon const iconNode = iconName ? <Icon name={iconName} /> : null return ( <button className={this.getRootClassNames()} onClick={this.handleClick} type={htmlType || 'button'} > {iconNode}{children} </button> ) } }
'use strict'; var os = require('os'); // expose our config directly to our application using module.exports module.exports = { 'twitterAuth' : { 'consumerKey' : process.env.TWITTER_CONSUMER_KEY || 'unknown', 'consumerSecret' : process.env.TWITTER_CONSUMER_SECRET || 'unknown' , 'callbackURL' : 'http://' + os.hostname() + '/auth/twitter/callback' } };
var mySteal = require('@steal'); if (typeof window !== "undefined" && window.assert) { assert.ok(mySteal.loader == steal.loader, "The steal's loader is the loader"); done(); } else { console.log("Systems", mySteal.loader == steal.loader); }
define(function(require, exports, module) { require('jquery.cycle2'); exports.run = function() { $('.homepage-feature').cycle({ fx:"scrollHorz", slides: "> a, > img", log: "false", pauseOnHover: "true" }); $('.live-rating-course').find('.media-body').hover(function() { $( this ).find( ".rating" ).show(); }, function() { $( this ).find( ".rating" ).hide(); }); }; });
import React from 'react'; import Slider from 'material-ui/Slider'; /** * The `defaultValue` property sets the initial position of the slider. * The slider appearance changes when not at the starting position. */ const SliderTransparency = (props) => ( <Slider defaultValue={props.transparency} onChange={props.update} sliderStyle={{margin:'auto',pointerEvents:'all'}} axis='y' style={{height:'400px', paddingTop:"30px"}} data-tip={`Opacity`} data-offset="{'top': -30}" /> ); export default SliderTransparency;
import { Transform } from './transform.js'; /** * Calculate the transform for a Cornerstone enabled element * * @param {EnabledElement} enabledElement The Cornerstone Enabled Element * @param {Number} [scale] The viewport scale * @return {Transform} The current transform */ export default function (enabledElement, scale) { const transform = new Transform(); transform.translate(enabledElement.canvas.width / 2, enabledElement.canvas.height / 2); // Apply the rotation before scaling for non square pixels const angle = enabledElement.viewport.rotation; if (angle !== 0) { transform.rotate(angle * Math.PI / 180); } // Apply the scale let widthScale = enabledElement.viewport.scale; let heightScale = enabledElement.viewport.scale; if (enabledElement.image.rowPixelSpacing < enabledElement.image.columnPixelSpacing) { widthScale *= (enabledElement.image.columnPixelSpacing / enabledElement.image.rowPixelSpacing); } else if (enabledElement.image.columnPixelSpacing < enabledElement.image.rowPixelSpacing) { heightScale *= (enabledElement.image.rowPixelSpacing / enabledElement.image.columnPixelSpacing); } transform.scale(widthScale, heightScale); // Unrotate to so we can translate unrotated if (angle !== 0) { transform.rotate(-angle * Math.PI / 180); } // Apply the pan offset transform.translate(enabledElement.viewport.translation.x, enabledElement.viewport.translation.y); // Rotate again so we can apply general scale if (angle !== 0) { transform.rotate(angle * Math.PI / 180); } if (scale !== undefined) { // Apply the font scale transform.scale(scale, scale); } // Apply Flip if required if (enabledElement.viewport.hflip) { transform.scale(-1, 1); } if (enabledElement.viewport.vflip) { transform.scale(1, -1); } // Translate the origin back to the corner of the image so the event handlers can draw in image coordinate system transform.translate(-enabledElement.image.width / 2, -enabledElement.image.height / 2); return transform; }
import Express from 'express'; import compression from 'compression'; import mongoose from 'mongoose'; import bodyParser from 'body-parser'; import path from 'path'; import IntlWrapper from '../client/modules/Intl/IntlWrapper'; // Webpack Requirements import webpack from 'webpack'; import config from '../webpack.config.dev'; import webpackDevMiddleware from 'webpack-dev-middleware'; import webpackHotMiddleware from 'webpack-hot-middleware'; // Initialize the Express App const app = new Express(); // Run Webpack dev server in development mode if (process.env.NODE_ENV === 'development') { const compiler = webpack(config); app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: config.output.publicPath })); app.use(webpackHotMiddleware(compiler)); } // React And Redux Setup import { configureStore } from '../client/store'; import { Provider } from 'react-redux'; import React from 'react'; import { renderToString } from 'react-dom/server'; import { match, RouterContext } from 'react-router'; import Helmet from 'react-helmet'; // Import required modules import routes from '../client/routes'; import { fetchComponentData } from './util/fetchData'; import posts from './routes/post.routes'; import medicalRights from './routes/medicalrights.routes'; import populateDB from './routes/populateDB.routes'; import dummyData from './dummyData'; import serverConfig from './config'; // Set native promises as mongoose promise mongoose.Promise = global.Promise; // MongoDB Connection mongoose.connect(serverConfig.mongoURL, (error) => { if (error) { console.error('Please make sure Mongodb is installed and running!'); // eslint-disable-line no-console throw error; } // feed some dummy data in DB. //dummyData(); }); // Apply body Parser and server public assets and routes app.use(compression()); app.use(bodyParser.json({ limit: '20mb' })); app.use(bodyParser.urlencoded({ limit: '20mb', extended: false })); app.use(Express.static(path.resolve(__dirname, '../dist'))); app.use('/api', posts); app.use('/api', medicalRights); app.use('/api', populateDB); // Render Initial HTML const renderFullPage = (html, initialState) => { const head = Helmet.rewind(); // Import Manifests const assetsManifest = process.env.webpackAssets && JSON.parse(process.env.webpackAssets); const chunkManifest = process.env.webpackChunkAssets && JSON.parse(process.env.webpackChunkAssets); return ` <!doctype html> <html> <head> ${head.base.toString()} ${head.title.toString()} ${head.meta.toString()} ${head.link.toString()} ${head.script.toString()} ${process.env.NODE_ENV === 'production' ? `<link rel='stylesheet' href='${assetsManifest['/app.css']}' />` : ''} <link href='https://fonts.googleapis.com/css?family=Lato:400,300,700' rel='stylesheet' type='text/css'/> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/latest/css/bootstrap.min.css" type='text/css'> <link rel="shortcut icon" href="http://res.cloudinary.com/hashnode/image/upload/v1455629445/static_imgs/mern/mern-favicon-circle-fill.png" type="image/png" /> <style> /* local page styles */ html h1 { font-size: 26px; margin-left: 10px; } html h2 { font-size: 22px; margin-left: 10px; } html h3 { font-size: 14px; margin-left: 10px; } html h4 { font-size: 16px; } .progtrckr { text-align: center; padding-bottom: 16px; // border-bottom: solid 1px; } .progtrckr li { margin-bottom: 10px; } .val-err-tooltip { background-color: red; padding: 3px 5px 3px 10px; font-size: 14px; color: #fff; } .step { // background-color: #ccc; border:1px solid #e5e5e5; min-height: 437px; padding: 10px; max-width: 815px; } html .row, html .form-horizontal .form-group { margin: 0; } .footer-buttons { margin-top: 10px; margin-bottom: 50px; } html .step3 label, html .step4 label { font-size: 20px; text-align: left; } html .form-horizontal .control-label { text-align: left; } .review .txt { font-size: 20px; text-align: left; margin: 0; padding: 0; } html body .saving { background-color: #5cb85c; width: 90%; padding: 5px; font-size: 16px; } code { position: relative; left: 12px; line-height: 25px; } .eg-jump-lnk { margin-top: 50px; font-style: italic; } .lib-version { font-size: 12px; background-color: rgba(255, 255, 0, 0.38); position: absolute; right: 10px; top: 10px; padding: 5px; } html .content { margin-left: 10px; } span.red { color: #d9534f; } span.green { color: #3c763d; } span.bold { font-weight: bold; } html .hoc-alert { margin-top: 20px; } html .form-block-holder { margin-top: 20px !important; } ol.progtrckr { margin: 0; padding-bottom: 2.2rem; list-style-type: none; } ol.progtrckr li { display: inline-block; text-align: center; line-height: 4.5rem; padding: 0 0.7rem; cursor: pointer; } ol.progtrckr li span { padding: 0 1.5rem; } @media (max-width: 650px) { .progtrckr li span { display: none; } } .progtrckr em { display: none; font-weight: 700; padding-left: 1rem; } @media (max-width: 650px) { .progtrckr em { display: inline; } border-bottom: solid 1px; } @media (max-width: 650px) { .step { max-height=320px; min-height=437px; min-width=300px; } } } ol.progtrckr li.progtrckr-todo { color: silver; border-bottom: 4px solid silver; } ol.progtrckr li.progtrckr-doing { color: black; border-bottom: 4px solid #33C3F0; } ol.progtrckr li.progtrckr-done { color: black; border-bottom: 4px solid #33C3F0; } ol.progtrckr li:after { content: "\\00a0\\00a0"; } ol.progtrckr li:before { position: relative; bottom: -3.7rem; float: left; left: 50%; } ol.progtrckr li.progtrckr-todo:before { content: "\\039F"; color: silver; background-color: white; width: 1.2em; line-height: 1.4em; } ol.progtrckr li.progtrckr-todo:hover:before { color: #0FA0CE; } ol.progtrckr li.progtrckr-doing:before { content: "\\2022"; color: white; background-color: #33C3F0; width: 1.2em; line-height: 1.2em; border-radius: 1.2em; } ol.progtrckr li.progtrckr-doing:hover:before { color: #0FA0CE; } ol.progtrckr li.progtrckr-done:before { content: "\\2713"; color: white; background-color: #33C3F0; width: 1.2em; line-height: 1.2em; border-radius: 1.2em; } ol.progtrckr li.progtrckr-done:hover:before { color: #0FA0CE; } </style> </head> <body> <div id="root">${html}</div> <script> window.__INITIAL_STATE__ = ${JSON.stringify(initialState)}; ${process.env.NODE_ENV === 'production' ? `//<![CDATA[ window.webpackManifest = ${JSON.stringify(chunkManifest)}; //]]>` : ''} </script> <script src='${process.env.NODE_ENV === 'production' ? assetsManifest['/vendor.js'] : '/vendor.js'}'></script> <script src='${process.env.NODE_ENV === 'production' ? assetsManifest['/app.js'] : '/app.js'}'></script> </body> </html> `; }; const renderError = err => { const softTab = '&#32;&#32;&#32;&#32;'; const errTrace = process.env.NODE_ENV !== 'production' ? `:<br><br><pre style="color:red">${softTab}${err.stack.replace(/\n/g, `<br>${softTab}`)}</pre>` : ''; return renderFullPage(`Server Error${errTrace}`, {}); }; // Server Side Rendering based on routes matched by React-router. app.use((req, res, next) => { match({ routes, location: req.url }, (err, redirectLocation, renderProps) => { if (err) { return res.status(500).end(renderError(err)); } if (redirectLocation) { return res.redirect(302, redirectLocation.pathname + redirectLocation.search); } if (!renderProps) { return next(); } const store = configureStore(); return fetchComponentData(store, renderProps.components, renderProps.params) .then(() => { const initialView = renderToString( <Provider store={store}> <IntlWrapper> <RouterContext {...renderProps} /> </IntlWrapper> </Provider> ); const finalState = store.getState(); res .set('Content-Type', 'text/html') .status(200) .end(renderFullPage(initialView, finalState)); }) .catch((error) => next(error)); }); }); // start app app.listen(serverConfig.port, (error) => { if (!error) { console.log(`MERN is running on port: ${serverConfig.port}! Build something amazing!`); // eslint-disable-line } }); export default app;
'use strict'; const AWS = require('aws-sdk'); let x = "/delegationset/NHKXBB6SHGKLN"; console.log(x.replace('/delegationset/', '')); return; const route53 = new AWS.Route53(); route53.listHostedZones({}).promise() .then(response => { console.log(response); return response.HostedZones.find(hostedZone => { return hostedZone.Name === 'manapaho.com.'; }); }) .catch(err => { console.log(err); }) .then(hostedZone => { console.log(hostedZone); }); return; /* route53.listReusableDelegationSets({}).promise() .then(response => { return response.DelegationSets.find(delegationSet => { return delegationSet.CallerReference === 'arn:aws:lambda:us-east-1:238541850529:function:Prod-Wessels-us-east-1-Route53ReusableDelegationSet'; }); }) .catch(err => { console.log(err); }) .then(reusableDelegationSet => { console.log(reusableDelegationSet); }); return; AWS.config.update({region: 'us-east-1'}); let stackName = 'Prod-Manapaho-us-east-1-NameServerSet'; let responseStatus = "FAILED"; let responseData = {}; let cfn = new AWS.CloudFormation(); cfn.describeStacks({StackName: stackName}).promise() .then(data => { console.log('333333333333333333333', JSON.stringify(data, null, 2)); data.Stacks[0].Outputs.forEach(function (output) { responseData[output.OutputKey] = output.OutputValue; }); responseStatus = "SUCCESS"; console.log(JSON.stringify(responseData, null, 2)); }) .catch(err => { console.log('4444444444444444444444444'); console.log('FAILED TO DESCRIBE STACK:', err); }); return; const route53 = new AWS.Route53(); route53.listReusableDelegationSets({}).promise() .then(response => { console.log(response.DelegationSets.find(delegationSet => { return delegationSet.CallerReference === 'arn:aws:lambda:us-east-1:238541850529:function:Prod-Manapaho-us-east-1-Route53ReusableDelegationSet'; })); }) .catch(err => { console.log(err); }); return; route53.createReusableDelegationSet({CallerReference: 'createReusableDelegationSet'}).promise() .then(response => { console.log('XXXXXXXX', JSON.stringify(response, null, 2)); }) .catch(err => { console.log(err, err.stack); }); */
const defaultEnv = process.env.NODE_ENV || 'development'; function getEnv(name = defaultEnv) { const isProduction = name === 'production' || name === 'prod'; const isDev = !isProduction; return { name, isProduction, isDev, getEnv }; } const env = getEnv(); module.exports = env;
// Karma configuration file, see link for more information // https://karma-runner.github.io/1.0/config/configuration-file.html module.exports = function (config) { config.set({ basePath: '', frameworks: ['jasmine', '@angular-devkit/build-angular'], plugins: [ require('karma-jasmine'), require('karma-chrome-launcher'), require('karma-jasmine-html-reporter'), require('karma-coverage-istanbul-reporter'), require('@angular-devkit/build-angular/plugins/karma') ], client: { clearContext: false // leave Jasmine Spec Runner output visible in browser }, coverageIstanbulReporter: { dir: require('path').join(__dirname, './coverage/DashboardHub'), reports: ['html', 'lcovonly', 'text-summary'], fixWebpackSourcePaths: true }, reporters: ['progress', 'kjhtml'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['Chrome'], singleRun: false, restartOnFileChange: true }); };
var React = require('react-native'); var { StyleSheet, View, Animated, } = React; var Dot = React.createClass({ propTypes: { isPlacedCorrectly: React.PropTypes.bool.isRequired, }, getInitialState: function() { return { scale: new Animated.Value(this.props.isPlacedCorrectly ? 1 : 0.1), visible: this.props.isPlacedCorrectly, }; }, componentWillReceiveProps: function(nextProps) { if (!this.props.isPlacedCorrectly && nextProps.isPlacedCorrectly) { this.animateShow(); } else if (this.props.isPlacedCorrectly && !nextProps.isPlacedCorrectly) { this.animateHide(); } }, animateShow: function() { this.setState({visible: true}, () => { Animated.timing(this.state.scale, { toValue: 1, duration: 100, }).start(); }); }, animateHide: function() { Animated.timing(this.state.scale, { toValue: 0.1, duration: 100, }).start(() => this.setState({visible: false})); }, render: function() { if (!this.state.visible) { return null; } return ( <Animated.View style={[styles.dot, {transform: [{scale: this.state.scale}]}]}/> ); }, }); var styles = StyleSheet.create({ dot: { backgroundColor: '#FF3366', width: 6, height: 6, borderRadius: 3, margin: 3, }, }); module.exports = Dot;
var namespacehryky_1_1log = [ [ "AutoElapsed", "structhryky_1_1log_1_1_auto_elapsed.html", null ], [ "level_type", "namespacehryky_1_1log.html#a6005efaf1fc45416ed6aa211f939993f", null ], [ "writer_type", "namespacehryky_1_1log.html#a855ba68dea65f57a39b7a1cb03aee800", null ], [ "write", "namespacehryky_1_1log.html#a5c7e76e7e42521f83c90fc8813f1f3ea", null ] ];
/**************************************************************************** Copyright (c) 2011-2012 cocos2d-x.org Copyright (c) 2013-2014 Chukong Technologies Inc. http://www.cocos2d-x.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ /** * Base class for ccs.Bone objects. * @class * @extends ccs.Node * * @property {ccs.BoneData} boneData - The bone data * @property {ccs.Armature} armature - The armature * @property {ccs.Bone} parentBone - The parent bone * @property {ccs.Armature} childArmature - The child armature * @property {Array} childrenBone - <@readonly> All children bones * @property {ccs.Tween} tween - <@readonly> Tween * @property {ccs.FrameData} tweenData - <@readonly> The tween data * @property {ccs.ColliderFilter} colliderFilter - The collider filter * @property {ccs.DisplayManager} displayManager - The displayManager * @property {Boolean} ignoreMovementBoneData - Indicate whether force the bone to show When CCArmature play a animation and there isn't a CCMovementBoneData of this bone in this CCMovementData. * @property {String} name - The name of the bone * @property {Boolean} blendDirty - Indicate whether the blend is dirty * */ ccs.Bone = ccs.Node.extend(/** @lends ccs.Bone# */{ _boneData: null, _armature: null, _childArmature: null, _displayManager: null, ignoreMovementBoneData: false, _tween: null, _tweenData: null, _parentBone: null, _boneTransformDirty: false, _worldTransform: null, _blendFunc: 0, blendDirty: false, _worldInfo: null, _armatureParentBone: null, _dataVersion: 0, _className: "Bone", ctor: function () { cc.Node.prototype.ctor.call(this); this._tweenData = null; this._parentBone = null; this._armature = null; this._childArmature = null; this._boneData = null; this._tween = null; this._displayManager = null; this.ignoreMovementBoneData = false; this._worldTransform = cc.affineTransformMake(1, 0, 0, 1, 0, 0); this._boneTransformDirty = true; this._blendFunc = new cc.BlendFunc(cc.BLEND_SRC, cc.BLEND_DST); this.blendDirty = false; this._worldInfo = null; this._armatureParentBone = null; this._dataVersion = 0; }, /** * Initializes a CCBone with the specified name * @param {String} name * @return {Boolean} */ init: function (name) { // cc.Node.prototype.init.call(this); if (name) { this._name = name; } this._tweenData = new ccs.FrameData(); this._tween = new ccs.Tween(); this._tween.init(this); this._displayManager = new ccs.DisplayManager(); this._displayManager.init(this); this._worldInfo = new ccs.BaseData(); this._boneData = new ccs.BaseData(); return true; }, /** * set the boneData * @param {ccs.BoneData} boneData */ setBoneData: function (boneData) { cc.assert(boneData, "_boneData must not be null"); if(this._boneData != boneData) this._boneData = boneData; this.setName(this._boneData.name); this._localZOrder = this._boneData.zOrder; this._displayManager.initDisplayList(boneData); }, /** * boneData getter * @return {ccs.BoneData} */ getBoneData: function () { return this._boneData; }, /** * set the armature * @param {ccs.Armature} armature */ setArmature: function (armature) { this._armature = armature; if (armature) { this._tween.setAnimation(this._armature.getAnimation()); this._dataVersion = this._armature.getArmatureData().dataVersion; this._armatureParentBone = this._armature.getParentBone(); } else { this._armatureParentBone = null; } }, /** * armature getter * @return {ccs.Armature} */ getArmature: function () { return this._armature; }, /** * update worldTransform * @param {Number} delta */ update: function (delta) { if (this._parentBone) this._boneTransformDirty = this._boneTransformDirty || this._parentBone.isTransformDirty(); if (this._armatureParentBone && !this._boneTransformDirty) this._boneTransformDirty = this._armatureParentBone.isTransformDirty(); if (this._boneTransformDirty){ var locTweenData = this._tweenData; if (this._dataVersion >= ccs.CONST_VERSION_COMBINED){ ccs.TransformHelp.nodeConcat(locTweenData, this._boneData); locTweenData.scaleX -= 1; locTweenData.scaleY -= 1; } var locWorldInfo = this._worldInfo; locWorldInfo.copy(locTweenData); locWorldInfo.x = locTweenData.x + this._position.x; locWorldInfo.y = locTweenData.y + this._position.y; locWorldInfo.scaleX = locTweenData.scaleX * this._scaleX; locWorldInfo.scaleY = locTweenData.scaleY * this._scaleY; locWorldInfo.skewX = locTweenData.skewX + this._skewX + this._rotationX; locWorldInfo.skewY = locTweenData.skewY + this._skewY - this._rotationY; if(this._parentBone) this.applyParentTransform(this._parentBone); else { if (this._armatureParentBone) this.applyParentTransform(this._armatureParentBone); } ccs.TransformHelp.nodeToMatrix(locWorldInfo, this._worldTransform); if (this._armatureParentBone) this._worldTransform = cc.affineTransformConcat(this._worldTransform, this._armature.getNodeToParentTransform()); //TODO TransformConcat } ccs.displayFactory.updateDisplay(this, delta, this._boneTransformDirty || this._armature.getArmatureTransformDirty()); for(var i=0; i<this._children.length; i++) { var childBone = this._children[i]; childBone.update(delta); } this._boneTransformDirty = false; }, applyParentTransform: function (parent) { var locWorldInfo = this._worldInfo; var locParentWorldTransform = parent._worldTransform; var locParentWorldInfo = parent._worldInfo; var x = locWorldInfo.x; var y = locWorldInfo.y; locWorldInfo.x = x * locParentWorldTransform.a + y * locParentWorldTransform.c + locParentWorldInfo.x; locWorldInfo.y = x * locParentWorldTransform.b + y * locParentWorldTransform.d + locParentWorldInfo.y; locWorldInfo.scaleX = locWorldInfo.scaleX * locParentWorldInfo.scaleX; locWorldInfo.scaleY = locWorldInfo.scaleY * locParentWorldInfo.scaleY; locWorldInfo.skewX = locWorldInfo.skewX + locParentWorldInfo.skewX; locWorldInfo.skewY = locWorldInfo.skewY + locParentWorldInfo.skewY; }, /** * BlendFunc setter * @param {cc.BlendFunc} blendFunc */ setBlendFunc: function (blendFunc) { if (this._blendFunc.src != blendFunc.src || this._blendFunc.dst != blendFunc.dst) { this._blendFunc = blendFunc; this.blendDirty = true; } }, /** * update display color * @param {cc.Color} color */ updateDisplayedColor: function (color) { this._realColor = cc.color(255, 255, 255); cc.Node.prototype.updateDisplayedColor.call(this, color); this.updateColor(); }, /** * update display opacity * @param {Number} opacity */ updateDisplayedOpacity: function (opacity) { this._realOpacity = 255; cc.Node.prototype.updateDisplayedOpacity.call(this, opacity); this.updateColor(); }, /** * update display color */ updateColor: function () { var display = this._displayManager.getDisplayRenderNode(); if (display != null) { display.setColor( cc.color( this._displayedColor.r * this._tweenData.r / 255, this._displayedColor.g * this._tweenData.g / 255, this._displayedColor.b * this._tweenData.b / 255)); display.setOpacity(this._displayedOpacity * this._tweenData.a / 255); } }, /** * update display zOrder */ updateZOrder: function () { if (this._armature.getArmatureData().dataVersion >= ccs.CONST_VERSION_COMBINED) { var zorder = this._tweenData.zOrder + this._boneData.zOrder; this.setLocalZOrder(zorder); } else { this.setLocalZOrder(this._tweenData.zOrder); } }, /** * Add a child to this bone, and it will let this child call setParent(ccs.Bone) function to set self to it's parent * @param {ccs.Bone} child */ addChildBone: function (child) { cc.assert(child, "Argument must be non-nil"); cc.assert(!child.parentBone, "child already added. It can't be added again"); if (this._children.indexOf(child) < 0) { this._children.push(child); child.setParentBone(this); } }, /** * Removes a child bone * @param {ccs.Bone} bone * @param {Boolean} recursion */ removeChildBone: function (bone, recursion) { if (this._children.length > 0 && this._children.getIndex(bone) != -1 ) { if(recursion) { var ccbones = bone._children; for(var i=0; i<ccbones.length; i++){ var ccBone = ccbones[i]; bone.removeChildBone(ccBone, recursion); } } bone.setParentBone(null); bone.getDisplayManager().setCurrentDecorativeDisplay(null); cc.arrayRemoveObject(this._children, bone); } }, /** * Remove itself from its parent CCBone. * @param {Boolean} recursion */ removeFromParent: function (recursion) { if (this._parentBone) { this._parentBone.removeChildBone(this, recursion); } }, /** * Set parent bone. * If _parent is NUll, then also remove this bone from armature. * It will not set the CCArmature, if you want to add the bone to a CCArmature, you should use ccs.Armature.addBone(bone, parentName). * @param {ccs.Bone} parent the parent bone. */ setParentBone: function (parent) { this._parentBone = parent; }, getParentBone: function(){ return this._parentBone; }, /** * child armature setter * @param {ccs.Armature} armature */ setChildArmature: function (armature) { if (this._childArmature != armature) { if (armature == null && this._childArmature) this._childArmature.setParentBone(null); this._childArmature = armature; } }, /** * child armature getter * @return {ccs.Armature} */ getChildArmature: function () { return this._childArmature; }, /** * tween getter * @return {ccs.Tween} */ getTween: function () { return this._tween; }, /** * zOrder setter * @param {Number} zOrder */ setLocalZOrder: function (zOrder) { if (this._localZOrder != zOrder) cc.Node.prototype.setLocalZOrder.call(this, zOrder); }, getNodeToArmatureTransform: function(){ return this._worldTransform; }, getNodeToWorldTransform: function(){ return cc.affineTransformConcat(this._worldTransform, this._armature.getNodeToWorldTransform()); }, /** * get render node * @returns {cc.Node} */ getDisplayRenderNode: function () { return this._displayManager.getDisplayRenderNode(); }, /** * get render node type * @returns {Number} */ getDisplayRenderNodeType: function () { return this._displayManager.getDisplayRenderNodeType(); }, /** * Add display and use _displayData init the display. * If index already have a display, then replace it. * If index is current display index, then also change display to _index * @param {ccs.DisplayData} displayData it include the display information, like DisplayType. * If you want to create a sprite display, then create a CCSpriteDisplayData param *@param {Number} index the index of the display you want to replace or add to * -1 : append display from back */ addDisplay: function (displayData, index) { index = index || 0; return this._displayManager.addDisplay(displayData, index); }, /** * remove display * @param {Number} index */ removeDisplay: function (index) { this._displayManager.removeDisplay(index); }, /** * change display by index * @param {Number} index * @param {Boolean} force */ changeDisplayByIndex: function (index, force) { cc.log("changeDisplayByIndex is deprecated. Use changeDisplayWithIndex instead."); this.changeDisplayWithIndex(index, force); }, changeDisplayByName: function(name, force){ this.changeDisplayWithName(name, force); }, /** * change display with index * @param {Number} index * @param {Boolean} force */ changeDisplayWithIndex: function (index, force) { this._displayManager.changeDisplayWithIndex(index, force); }, /** * change display with name * @param {String} name * @param {Boolean} force */ changeDisplayWithName: function (name, force) { this._displayManager.changeDisplayWithName(name, force); }, getColliderDetector: function(){ var decoDisplay = this._displayManager.getCurrentDecorativeDisplay(); if (decoDisplay){ var detector = decoDisplay.getColliderDetector(); if (detector) return detector; } return null; }, /** * collider filter setter * @param {cc.ColliderFilter} filter */ setColliderFilter: function (filter) { var displayList = this._displayManager.getDecorativeDisplayList(); for (var i = 0; i < displayList.length; i++) { var locDecoDisplay = displayList[i]; var locDetector = locDecoDisplay.getColliderDetector(); if (locDetector) { locDetector.setColliderFilter(filter); } } }, /** * collider filter getter * @returns {cc.ColliderFilter} */ getColliderFilter: function () { var decoDisplay = this.displayManager.getCurrentDecorativeDisplay(); if (decoDisplay) { var detector = decoDisplay.getColliderDetector(); if (detector) return detector.getColliderFilter(); } return null; }, /** * transform dirty setter * @param {Boolean} dirty */ setTransformDirty: function (dirty) { this._boneTransformDirty = dirty; }, /** * transform dirty getter * @return {Boolean} */ isTransformDirty: function () { return this._boneTransformDirty; }, /** * displayManager dirty getter * @return {ccs.DisplayManager} */ getDisplayManager: function () { return this._displayManager; }, /** * When CCArmature play a animation, if there is not a CCMovementBoneData of this bone in this CCMovementData, this bone will hide. * Set IgnoreMovementBoneData to true, then this bone will also show. * @param {Boolean} bool */ setIgnoreMovementBoneData: function (bool) { this._ignoreMovementBoneData = bool; }, isIgnoreMovementBoneData: function(){ return this._ignoreMovementBoneData; }, /** * blendType getter * @return {cc.BlendFunc} */ getBlendFunc: function () { return this._blendFunc; }, setBlendDirty: function (dirty) { this._blendDirty = dirty; }, isBlendDirty: function () { return this._blendDirty; }, /** * tweenData getter * @return {ccs.FrameData} */ getTweenData: function () { return this._tweenData; }, getWorldInfo: function(){ return this._worldInfo; }, /** * child bone getter * @return {Array} * @deprecated */ getChildrenBone: function () { return this._children; }, /** * @deprecated * return world transform * @return {{a:0.b:0,c:0,d:0,tx:0,ty:0}} */ nodeToArmatureTransform: function () { return this.getNodeToArmatureTransform(); }, /** * @deprecated * Returns the world affine transform matrix. The matrix is in Pixels. * @returns {cc.AffineTransform} */ nodeToWorldTransform: function () { return this.getNodeToWorldTransform(); }, /** * @deprecated * get the collider body list in this bone. * @returns {*} */ getColliderBodyList: function () { var detector = this.getColliderDetector(); if(detector) return detector.getColliderBodyList(); return null; }, /** * ignoreMovementBoneData getter * @return {Boolean} */ getIgnoreMovementBoneData: function () { return this.isIgnoreMovementBoneData(); } }); var _p = ccs.Bone.prototype; // Extended properties /** @expose */ _p.boneData; cc.defineGetterSetter(_p, "boneData", _p.getBoneData, _p.setBoneData); /** @expose */ _p.armature; cc.defineGetterSetter(_p, "armature", _p.getArmature, _p.setArmature); /** @expose */ _p.childArmature; cc.defineGetterSetter(_p, "childArmature", _p.getChildArmature, _p.setChildArmature); /** @expose */ _p.childrenBone; cc.defineGetterSetter(_p, "childrenBone", _p.getChildrenBone); /** @expose */ _p.tween; cc.defineGetterSetter(_p, "tween", _p.getTween); /** @expose */ _p.tweenData; cc.defineGetterSetter(_p, "tweenData", _p.getTweenData); /** @expose */ _p.colliderFilter; cc.defineGetterSetter(_p, "colliderFilter", _p.getColliderFilter, _p.setColliderFilter); _p = null; /** * allocates and initializes a bone. * @constructs * @return {ccs.Bone} * @example * // example * var bone = ccs.Bone.create(); */ ccs.Bone.create = function (name) { var bone = new ccs.Bone(); if (bone && bone.init(name)) return bone; return null; };
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ 'use strict'; var util = require('util'); var msRest = require('ms-rest'); var WebResource = msRest.WebResource; /** * @class * Implicit * __NOTE__: An instance of this class is automatically created for an * instance of the AutoRestRequiredOptionalTestService. * Initializes a new instance of the Implicit class. * @constructor * * @param {AutoRestRequiredOptionalTestService} client Reference to the service client. */ function Implicit(client) { this.client = client; } /** * Test implicitly required path parameter * * @param {string} pathParameter * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} callback * * @returns {function} callback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {object} [result] - The deserialized result object. * See {@link ErrorModel} for more information. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ Implicit.prototype.getRequiredPath = function (pathParameter, options, callback) { var client = this.client; if(!callback && typeof options === 'function') { callback = options; options = null; } if (!callback) { throw new Error('callback cannot be null.'); } // Validate try { if (pathParameter === null || pathParameter === undefined || typeof pathParameter.valueOf() !== 'string') { throw new Error('pathParameter cannot be null or undefined and it must be of type string.'); } } catch (error) { return callback(error); } // Construct URL var baseUrl = this.client.baseUri; var requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'reqopt/implicit/required/path/{pathParameter}'; requestUrl = requestUrl.replace('{pathParameter}', encodeURIComponent(pathParameter)); // Create HTTP transport objects var httpRequest = new WebResource(); httpRequest.method = 'GET'; httpRequest.headers = {}; httpRequest.url = requestUrl; // Set Headers if(options) { for(var headerName in options['customHeaders']) { if (options['customHeaders'].hasOwnProperty(headerName)) { httpRequest.headers[headerName] = options['customHeaders'][headerName]; } } } httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8'; httpRequest.body = null; // Send Request return client.pipeline(httpRequest, function (err, response, responseBody) { if (err) { return callback(err); } var statusCode = response.statusCode; if (statusCode < 200 || statusCode >= 300) { var error = new Error(responseBody); error.statusCode = response.statusCode; error.request = msRest.stripRequest(httpRequest); error.response = msRest.stripResponse(response); if (responseBody === '') responseBody = null; var parsedErrorResponse; try { parsedErrorResponse = JSON.parse(responseBody); if (parsedErrorResponse) { if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error; if (parsedErrorResponse.code) error.code = parsedErrorResponse.code; if (parsedErrorResponse.message) error.message = parsedErrorResponse.message; } if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) { var resultMapper = new client.models['ErrorModel']().mapper(); error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body'); } } catch (defaultError) { error.message = util.format('Error "%s" occurred in deserializing the responseBody ' + '- "%s" for the default response.', defaultError.message, responseBody); return callback(error); } return callback(error); } // Create Result var result = null; if (responseBody === '') responseBody = null; var parsedResponse = null; try { parsedResponse = JSON.parse(responseBody); result = JSON.parse(responseBody); if (parsedResponse !== null && parsedResponse !== undefined) { var resultMapper = new client.models['ErrorModel']().mapper(); result = client.deserialize(resultMapper, parsedResponse, 'result'); } } catch (error) { var deserializationError = new Error(util.format('Error "%s" occurred in deserializing the responseBody - "%s"', error, responseBody)); deserializationError.request = msRest.stripRequest(httpRequest); deserializationError.response = msRest.stripResponse(response); return callback(deserializationError); } return callback(null, result, httpRequest, response); }); }; /** * Test implicitly optional query parameter * * @param {object} [options] Optional Parameters. * * @param {string} [options.queryParameter] * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} callback * * @returns {function} callback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ Implicit.prototype.putOptionalQuery = function (options, callback) { var client = this.client; if(!callback && typeof options === 'function') { callback = options; options = null; } if (!callback) { throw new Error('callback cannot be null.'); } var queryParameter = (options && options.queryParameter !== undefined) ? options.queryParameter : undefined; // Validate try { if (queryParameter !== null && queryParameter !== undefined && typeof queryParameter.valueOf() !== 'string') { throw new Error('queryParameter must be of type string.'); } } catch (error) { return callback(error); } // Construct URL var baseUrl = this.client.baseUri; var requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'reqopt/implicit/optional/query'; var queryParameters = []; if (queryParameter !== null && queryParameter !== undefined) { queryParameters.push('queryParameter=' + encodeURIComponent(queryParameter)); } if (queryParameters.length > 0) { requestUrl += '?' + queryParameters.join('&'); } // Create HTTP transport objects var httpRequest = new WebResource(); httpRequest.method = 'PUT'; httpRequest.headers = {}; httpRequest.url = requestUrl; // Set Headers if(options) { for(var headerName in options['customHeaders']) { if (options['customHeaders'].hasOwnProperty(headerName)) { httpRequest.headers[headerName] = options['customHeaders'][headerName]; } } } httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8'; httpRequest.body = null; // Send Request return client.pipeline(httpRequest, function (err, response, responseBody) { if (err) { return callback(err); } var statusCode = response.statusCode; if (statusCode !== 200) { var error = new Error(responseBody); error.statusCode = response.statusCode; error.request = msRest.stripRequest(httpRequest); error.response = msRest.stripResponse(response); if (responseBody === '') responseBody = null; var parsedErrorResponse; try { parsedErrorResponse = JSON.parse(responseBody); if (parsedErrorResponse) { if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error; if (parsedErrorResponse.code) error.code = parsedErrorResponse.code; if (parsedErrorResponse.message) error.message = parsedErrorResponse.message; } if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) { var resultMapper = new client.models['ErrorModel']().mapper(); error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body'); } } catch (defaultError) { error.message = util.format('Error "%s" occurred in deserializing the responseBody ' + '- "%s" for the default response.', defaultError.message, responseBody); return callback(error); } return callback(error); } // Create Result var result = null; if (responseBody === '') responseBody = null; return callback(null, result, httpRequest, response); }); }; /** * Test implicitly optional header parameter * * @param {object} [options] Optional Parameters. * * @param {string} [options.queryParameter] * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} callback * * @returns {function} callback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ Implicit.prototype.putOptionalHeader = function (options, callback) { var client = this.client; if(!callback && typeof options === 'function') { callback = options; options = null; } if (!callback) { throw new Error('callback cannot be null.'); } var queryParameter = (options && options.queryParameter !== undefined) ? options.queryParameter : undefined; // Validate try { if (queryParameter !== null && queryParameter !== undefined && typeof queryParameter.valueOf() !== 'string') { throw new Error('queryParameter must be of type string.'); } } catch (error) { return callback(error); } // Construct URL var baseUrl = this.client.baseUri; var requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'reqopt/implicit/optional/header'; // Create HTTP transport objects var httpRequest = new WebResource(); httpRequest.method = 'PUT'; httpRequest.headers = {}; httpRequest.url = requestUrl; // Set Headers if (queryParameter !== undefined && queryParameter !== null) { httpRequest.headers['queryParameter'] = queryParameter; } if(options) { for(var headerName in options['customHeaders']) { if (options['customHeaders'].hasOwnProperty(headerName)) { httpRequest.headers[headerName] = options['customHeaders'][headerName]; } } } httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8'; httpRequest.body = null; // Send Request return client.pipeline(httpRequest, function (err, response, responseBody) { if (err) { return callback(err); } var statusCode = response.statusCode; if (statusCode !== 200) { var error = new Error(responseBody); error.statusCode = response.statusCode; error.request = msRest.stripRequest(httpRequest); error.response = msRest.stripResponse(response); if (responseBody === '') responseBody = null; var parsedErrorResponse; try { parsedErrorResponse = JSON.parse(responseBody); if (parsedErrorResponse) { if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error; if (parsedErrorResponse.code) error.code = parsedErrorResponse.code; if (parsedErrorResponse.message) error.message = parsedErrorResponse.message; } if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) { var resultMapper = new client.models['ErrorModel']().mapper(); error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body'); } } catch (defaultError) { error.message = util.format('Error "%s" occurred in deserializing the responseBody ' + '- "%s" for the default response.', defaultError.message, responseBody); return callback(error); } return callback(error); } // Create Result var result = null; if (responseBody === '') responseBody = null; return callback(null, result, httpRequest, response); }); }; /** * Test implicitly optional body parameter * * @param {object} [options] Optional Parameters. * * @param {string} [options.bodyParameter] * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} callback * * @returns {function} callback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ Implicit.prototype.putOptionalBody = function (options, callback) { var client = this.client; if(!callback && typeof options === 'function') { callback = options; options = null; } if (!callback) { throw new Error('callback cannot be null.'); } var bodyParameter = (options && options.bodyParameter !== undefined) ? options.bodyParameter : undefined; // Validate try { if (bodyParameter !== null && bodyParameter !== undefined && typeof bodyParameter.valueOf() !== 'string') { throw new Error('bodyParameter must be of type string.'); } } catch (error) { return callback(error); } // Construct URL var baseUrl = this.client.baseUri; var requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'reqopt/implicit/optional/body'; // Create HTTP transport objects var httpRequest = new WebResource(); httpRequest.method = 'PUT'; httpRequest.headers = {}; httpRequest.url = requestUrl; // Set Headers if(options) { for(var headerName in options['customHeaders']) { if (options['customHeaders'].hasOwnProperty(headerName)) { httpRequest.headers[headerName] = options['customHeaders'][headerName]; } } } httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8'; // Serialize Request var requestContent = null; var requestModel = null; try { if (bodyParameter !== null && bodyParameter !== undefined) { var requestModelMapper = { required: false, serializedName: 'bodyParameter', type: { name: 'String' } }; requestModel = client.serialize(requestModelMapper, bodyParameter, 'bodyParameter'); requestContent = JSON.stringify(requestModel); } } catch (error) { var serializationError = new Error(util.format('Error "%s" occurred in serializing the ' + 'payload - "%s"', error.message, util.inspect(bodyParameter, {depth: null}))); return callback(serializationError); } httpRequest.body = requestContent; // Send Request return client.pipeline(httpRequest, function (err, response, responseBody) { if (err) { return callback(err); } var statusCode = response.statusCode; if (statusCode !== 200) { var error = new Error(responseBody); error.statusCode = response.statusCode; error.request = msRest.stripRequest(httpRequest); error.response = msRest.stripResponse(response); if (responseBody === '') responseBody = null; var parsedErrorResponse; try { parsedErrorResponse = JSON.parse(responseBody); if (parsedErrorResponse) { if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error; if (parsedErrorResponse.code) error.code = parsedErrorResponse.code; if (parsedErrorResponse.message) error.message = parsedErrorResponse.message; } if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) { var resultMapper = new client.models['ErrorModel']().mapper(); error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body'); } } catch (defaultError) { error.message = util.format('Error "%s" occurred in deserializing the responseBody ' + '- "%s" for the default response.', defaultError.message, responseBody); return callback(error); } return callback(error); } // Create Result var result = null; if (responseBody === '') responseBody = null; return callback(null, result, httpRequest, response); }); }; /** * Test implicitly required path parameter * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} callback * * @returns {function} callback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {object} [result] - The deserialized result object. * See {@link ErrorModel} for more information. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ Implicit.prototype.getRequiredGlobalPath = function (options, callback) { var client = this.client; if(!callback && typeof options === 'function') { callback = options; options = null; } if (!callback) { throw new Error('callback cannot be null.'); } // Validate try { if (this.client.requiredGlobalPath === null || this.client.requiredGlobalPath === undefined || typeof this.client.requiredGlobalPath.valueOf() !== 'string') { throw new Error('this.client.requiredGlobalPath cannot be null or undefined and it must be of type string.'); } } catch (error) { return callback(error); } // Construct URL var baseUrl = this.client.baseUri; var requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'reqopt/global/required/path/{required-global-path}'; requestUrl = requestUrl.replace('{required-global-path}', encodeURIComponent(this.client.requiredGlobalPath)); // Create HTTP transport objects var httpRequest = new WebResource(); httpRequest.method = 'GET'; httpRequest.headers = {}; httpRequest.url = requestUrl; // Set Headers if(options) { for(var headerName in options['customHeaders']) { if (options['customHeaders'].hasOwnProperty(headerName)) { httpRequest.headers[headerName] = options['customHeaders'][headerName]; } } } httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8'; httpRequest.body = null; // Send Request return client.pipeline(httpRequest, function (err, response, responseBody) { if (err) { return callback(err); } var statusCode = response.statusCode; if (statusCode < 200 || statusCode >= 300) { var error = new Error(responseBody); error.statusCode = response.statusCode; error.request = msRest.stripRequest(httpRequest); error.response = msRest.stripResponse(response); if (responseBody === '') responseBody = null; var parsedErrorResponse; try { parsedErrorResponse = JSON.parse(responseBody); if (parsedErrorResponse) { if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error; if (parsedErrorResponse.code) error.code = parsedErrorResponse.code; if (parsedErrorResponse.message) error.message = parsedErrorResponse.message; } if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) { var resultMapper = new client.models['ErrorModel']().mapper(); error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body'); } } catch (defaultError) { error.message = util.format('Error "%s" occurred in deserializing the responseBody ' + '- "%s" for the default response.', defaultError.message, responseBody); return callback(error); } return callback(error); } // Create Result var result = null; if (responseBody === '') responseBody = null; var parsedResponse = null; try { parsedResponse = JSON.parse(responseBody); result = JSON.parse(responseBody); if (parsedResponse !== null && parsedResponse !== undefined) { var resultMapper = new client.models['ErrorModel']().mapper(); result = client.deserialize(resultMapper, parsedResponse, 'result'); } } catch (error) { var deserializationError = new Error(util.format('Error "%s" occurred in deserializing the responseBody - "%s"', error, responseBody)); deserializationError.request = msRest.stripRequest(httpRequest); deserializationError.response = msRest.stripResponse(response); return callback(deserializationError); } return callback(null, result, httpRequest, response); }); }; /** * Test implicitly required query parameter * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} callback * * @returns {function} callback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {object} [result] - The deserialized result object. * See {@link ErrorModel} for more information. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ Implicit.prototype.getRequiredGlobalQuery = function (options, callback) { var client = this.client; if(!callback && typeof options === 'function') { callback = options; options = null; } if (!callback) { throw new Error('callback cannot be null.'); } // Validate try { if (this.client.requiredGlobalQuery === null || this.client.requiredGlobalQuery === undefined || typeof this.client.requiredGlobalQuery.valueOf() !== 'string') { throw new Error('this.client.requiredGlobalQuery cannot be null or undefined and it must be of type string.'); } } catch (error) { return callback(error); } // Construct URL var baseUrl = this.client.baseUri; var requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'reqopt/global/required/query'; var queryParameters = []; queryParameters.push('required-global-query=' + encodeURIComponent(this.client.requiredGlobalQuery)); if (queryParameters.length > 0) { requestUrl += '?' + queryParameters.join('&'); } // Create HTTP transport objects var httpRequest = new WebResource(); httpRequest.method = 'GET'; httpRequest.headers = {}; httpRequest.url = requestUrl; // Set Headers if(options) { for(var headerName in options['customHeaders']) { if (options['customHeaders'].hasOwnProperty(headerName)) { httpRequest.headers[headerName] = options['customHeaders'][headerName]; } } } httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8'; httpRequest.body = null; // Send Request return client.pipeline(httpRequest, function (err, response, responseBody) { if (err) { return callback(err); } var statusCode = response.statusCode; if (statusCode < 200 || statusCode >= 300) { var error = new Error(responseBody); error.statusCode = response.statusCode; error.request = msRest.stripRequest(httpRequest); error.response = msRest.stripResponse(response); if (responseBody === '') responseBody = null; var parsedErrorResponse; try { parsedErrorResponse = JSON.parse(responseBody); if (parsedErrorResponse) { if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error; if (parsedErrorResponse.code) error.code = parsedErrorResponse.code; if (parsedErrorResponse.message) error.message = parsedErrorResponse.message; } if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) { var resultMapper = new client.models['ErrorModel']().mapper(); error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body'); } } catch (defaultError) { error.message = util.format('Error "%s" occurred in deserializing the responseBody ' + '- "%s" for the default response.', defaultError.message, responseBody); return callback(error); } return callback(error); } // Create Result var result = null; if (responseBody === '') responseBody = null; var parsedResponse = null; try { parsedResponse = JSON.parse(responseBody); result = JSON.parse(responseBody); if (parsedResponse !== null && parsedResponse !== undefined) { var resultMapper = new client.models['ErrorModel']().mapper(); result = client.deserialize(resultMapper, parsedResponse, 'result'); } } catch (error) { var deserializationError = new Error(util.format('Error "%s" occurred in deserializing the responseBody - "%s"', error, responseBody)); deserializationError.request = msRest.stripRequest(httpRequest); deserializationError.response = msRest.stripResponse(response); return callback(deserializationError); } return callback(null, result, httpRequest, response); }); }; /** * Test implicitly optional query parameter * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} callback * * @returns {function} callback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {object} [result] - The deserialized result object. * See {@link ErrorModel} for more information. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ Implicit.prototype.getOptionalGlobalQuery = function (options, callback) { var client = this.client; if(!callback && typeof options === 'function') { callback = options; options = null; } if (!callback) { throw new Error('callback cannot be null.'); } // Validate try { if (this.client.optionalGlobalQuery !== null && this.client.optionalGlobalQuery !== undefined && typeof this.client.optionalGlobalQuery !== 'number') { throw new Error('this.client.optionalGlobalQuery must be of type number.'); } } catch (error) { return callback(error); } // Construct URL var baseUrl = this.client.baseUri; var requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'reqopt/global/optional/query'; var queryParameters = []; if (this.client.optionalGlobalQuery !== null && this.client.optionalGlobalQuery !== undefined) { queryParameters.push('optional-global-query=' + encodeURIComponent(this.client.optionalGlobalQuery.toString())); } if (queryParameters.length > 0) { requestUrl += '?' + queryParameters.join('&'); } // Create HTTP transport objects var httpRequest = new WebResource(); httpRequest.method = 'GET'; httpRequest.headers = {}; httpRequest.url = requestUrl; // Set Headers if(options) { for(var headerName in options['customHeaders']) { if (options['customHeaders'].hasOwnProperty(headerName)) { httpRequest.headers[headerName] = options['customHeaders'][headerName]; } } } httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8'; httpRequest.body = null; // Send Request return client.pipeline(httpRequest, function (err, response, responseBody) { if (err) { return callback(err); } var statusCode = response.statusCode; if (statusCode < 200 || statusCode >= 300) { var error = new Error(responseBody); error.statusCode = response.statusCode; error.request = msRest.stripRequest(httpRequest); error.response = msRest.stripResponse(response); if (responseBody === '') responseBody = null; var parsedErrorResponse; try { parsedErrorResponse = JSON.parse(responseBody); if (parsedErrorResponse) { if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error; if (parsedErrorResponse.code) error.code = parsedErrorResponse.code; if (parsedErrorResponse.message) error.message = parsedErrorResponse.message; } if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) { var resultMapper = new client.models['ErrorModel']().mapper(); error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body'); } } catch (defaultError) { error.message = util.format('Error "%s" occurred in deserializing the responseBody ' + '- "%s" for the default response.', defaultError.message, responseBody); return callback(error); } return callback(error); } // Create Result var result = null; if (responseBody === '') responseBody = null; var parsedResponse = null; try { parsedResponse = JSON.parse(responseBody); result = JSON.parse(responseBody); if (parsedResponse !== null && parsedResponse !== undefined) { var resultMapper = new client.models['ErrorModel']().mapper(); result = client.deserialize(resultMapper, parsedResponse, 'result'); } } catch (error) { var deserializationError = new Error(util.format('Error "%s" occurred in deserializing the responseBody - "%s"', error, responseBody)); deserializationError.request = msRest.stripRequest(httpRequest); deserializationError.response = msRest.stripResponse(response); return callback(deserializationError); } return callback(null, result, httpRequest, response); }); }; module.exports = Implicit;
/*! * Bootstrap v3.3.6 (http://getbootstrap.com) * Copyright 2011-2015 Twitter, Inc. * Licensed under the MIT license */ if (typeof jQuery === 'undefined') { throw new Error('Bootstrap\'s JavaScript requires jQuery') } + function($) { 'use strict'; var version = $.fn.jquery.split(' ')[0].split('.') if ((version[0] < 2 && version[1] < 9) || (version[0] == 1 && version[1] == 9 && version[2] < 1) || (version[0] > 2)) { throw new Error('Bootstrap\'s JavaScript requires jQuery version 1.9.1 or higher, but lower than version 3') } }(jQuery); /* ======================================================================== * Bootstrap: transition.js v3.3.6 * http://getbootstrap.com/javascript/#transitions * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ + function($) { 'use strict'; // CSS TRANSITION SUPPORT (Shoutout: http://www.modernizr.com/) // ============================================================ function transitionEnd() { var el = document.createElement('bootstrap') var transEndEventNames = { WebkitTransition: 'webkitTransitionEnd', MozTransition: 'transitionend', OTransition: 'oTransitionEnd otransitionend', transition: 'transitionend' } for (var name in transEndEventNames) { if (el.style[name] !== undefined) { return { end: transEndEventNames[name] } } } return false // explicit for ie8 ( ._.) } // http://blog.alexmaccaw.com/css-transitions $.fn.emulateTransitionEnd = function(duration) { var called = false var $el = this $(this).one('bsTransitionEnd', function() { called = true }) var callback = function() { if (!called) $($el).trigger($.support.transition.end) } setTimeout(callback, duration) return this } $(function() { $.support.transition = transitionEnd() if (!$.support.transition) return $.event.special.bsTransitionEnd = { bindType: $.support.transition.end, delegateType: $.support.transition.end, handle: function(e) { if ($(e.target).is(this)) return e.handleObj.handler.apply(this, arguments) } } }) }(jQuery); /* ======================================================================== * Bootstrap: alert.js v3.3.6 * http://getbootstrap.com/javascript/#alerts * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ + function($) { 'use strict'; // ALERT CLASS DEFINITION // ====================== var dismiss = '[data-dismiss="alert"]' var Alert = function(el) { $(el).on('click', dismiss, this.close) } Alert.VERSION = '3.3.6' Alert.TRANSITION_DURATION = 150 Alert.prototype.close = function(e) { var $this = $(this) var selector = $this.attr('data-target') if (!selector) { selector = $this.attr('href') selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7 } var $parent = $(selector) if (e) e.preventDefault() if (!$parent.length) { $parent = $this.closest('.alert') } $parent.trigger(e = $.Event('close.bs.alert')) if (e.isDefaultPrevented()) return $parent.removeClass('in') function removeElement() { // detach from parent, fire event then clean up data $parent.detach().trigger('closed.bs.alert').remove() } $.support.transition && $parent.hasClass('fade') ? $parent .one('bsTransitionEnd', removeElement) .emulateTransitionEnd(Alert.TRANSITION_DURATION) : removeElement() } // ALERT PLUGIN DEFINITION // ======================= function Plugin(option) { return this.each(function() { var $this = $(this) var data = $this.data('bs.alert') if (!data) $this.data('bs.alert', (data = new Alert(this))) if (typeof option == 'string') data[option].call($this) }) } var old = $.fn.alert $.fn.alert = Plugin $.fn.alert.Constructor = Alert // ALERT NO CONFLICT // ================= $.fn.alert.noConflict = function() { $.fn.alert = old return this } // ALERT DATA-API // ============== $(document).on('click.bs.alert.data-api', dismiss, Alert.prototype.close) }(jQuery); /* ======================================================================== * Bootstrap: button.js v3.3.6 * http://getbootstrap.com/javascript/#buttons * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ + function($) { 'use strict'; // BUTTON PUBLIC CLASS DEFINITION // ============================== var Button = function(element, options) { this.$element = $(element) this.options = $.extend({}, Button.DEFAULTS, options) this.isLoading = false } Button.VERSION = '3.3.6' Button.DEFAULTS = { loadingText: 'loading...' } Button.prototype.setState = function(state) { var d = 'disabled' var $el = this.$element var val = $el.is('input') ? 'val' : 'html' var data = $el.data() state += 'Text' if (data.resetText == null) $el.data('resetText', $el[val]()) // push to event loop to allow forms to submit setTimeout($.proxy(function() { $el[val](data[state] == null ? this.options[state] : data[state]) if (state == 'loadingText') { this.isLoading = true $el.addClass(d).attr(d, d) } else if (this.isLoading) { this.isLoading = false $el.removeClass(d).removeAttr(d) } }, this), 0) } Button.prototype.toggle = function() { var changed = true var $parent = this.$element.closest('[data-toggle="buttons"]') if ($parent.length) { var $input = this.$element.find('input') if ($input.prop('type') == 'radio') { if ($input.prop('checked')) changed = false $parent.find('.active').removeClass('active') this.$element.addClass('active') } else if ($input.prop('type') == 'checkbox') { if (($input.prop('checked')) !== this.$element.hasClass('active')) changed = false this.$element.toggleClass('active') } $input.prop('checked', this.$element.hasClass('active')) if (changed) $input.trigger('change') } else { this.$element.attr('aria-pressed', !this.$element.hasClass('active')) this.$element.toggleClass('active') } } // BUTTON PLUGIN DEFINITION // ======================== function Plugin(option) { return this.each(function() { var $this = $(this) var data = $this.data('bs.button') var options = typeof option == 'object' && option if (!data) $this.data('bs.button', (data = new Button(this, options))) if (option == 'toggle') data.toggle() else if (option) data.setState(option) }) } var old = $.fn.button $.fn.button = Plugin $.fn.button.Constructor = Button // BUTTON NO CONFLICT // ================== $.fn.button.noConflict = function() { $.fn.button = old return this } // BUTTON DATA-API // =============== $(document) .on('click.bs.button.data-api', '[data-toggle^="button"]', function(e) { var $btn = $(e.target) if (!$btn.hasClass('btn')) $btn = $btn.closest('.btn') Plugin.call($btn, 'toggle') if (!($(e.target).is('input[type="radio"]') || $(e.target).is('input[type="checkbox"]'))) e.preventDefault() }) .on('focus.bs.button.data-api blur.bs.button.data-api', '[data-toggle^="button"]', function(e) { $(e.target).closest('.btn').toggleClass('focus', /^focus(in)?$/.test(e.type)) }) }(jQuery); /* ======================================================================== * Bootstrap: carousel.js v3.3.6 * http://getbootstrap.com/javascript/#carousel * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ + function($) { 'use strict'; // CAROUSEL CLASS DEFINITION // ========================= var Carousel = function(element, options) { this.$element = $(element) this.$indicators = this.$element.find('.carousel-indicators') this.options = options this.paused = null this.sliding = null this.interval = null this.$active = null this.$items = null this.options.keyboard && this.$element.on('keydown.bs.carousel', $.proxy(this.keydown, this)) this.options.pause == 'hover' && !('ontouchstart' in document.documentElement) && this.$element .on('mouseenter.bs.carousel', $.proxy(this.pause, this)) .on('mouseleave.bs.carousel', $.proxy(this.cycle, this)) } Carousel.VERSION = '3.3.6' Carousel.TRANSITION_DURATION = 600 Carousel.DEFAULTS = { interval: 5000, pause: 'hover', wrap: true, keyboard: true } Carousel.prototype.keydown = function(e) { if (/input|textarea/i.test(e.target.tagName)) return switch (e.which) { case 37: this.prev(); break case 39: this.next(); break default: return } e.preventDefault() } Carousel.prototype.cycle = function(e) { e || (this.paused = false) this.interval && clearInterval(this.interval) this.options.interval && !this.paused && (this.interval = setInterval($.proxy(this.next, this), this.options.interval)) return this } Carousel.prototype.getItemIndex = function(item) { this.$items = item.parent().children('.item') return this.$items.index(item || this.$active) } Carousel.prototype.getItemForDirection = function(direction, active) { var activeIndex = this.getItemIndex(active) var willWrap = (direction == 'prev' && activeIndex === 0) || (direction == 'next' && activeIndex == (this.$items.length - 1)) if (willWrap && !this.options.wrap) return active var delta = direction == 'prev' ? -1 : 1 var itemIndex = (activeIndex + delta) % this.$items.length return this.$items.eq(itemIndex) } Carousel.prototype.to = function(pos) { var that = this var activeIndex = this.getItemIndex(this.$active = this.$element.find('.item.active')) if (pos > (this.$items.length - 1) || pos < 0) return if (this.sliding) return this.$element.one('slid.bs.carousel', function() { that.to(pos) }) // yes, "slid" if (activeIndex == pos) return this.pause().cycle() return this.slide(pos > activeIndex ? 'next' : 'prev', this.$items.eq(pos)) } Carousel.prototype.pause = function(e) { e || (this.paused = true) if (this.$element.find('.next, .prev').length && $.support.transition) { this.$element.trigger($.support.transition.end) this.cycle(true) } this.interval = clearInterval(this.interval) return this } Carousel.prototype.next = function() { if (this.sliding) return return this.slide('next') } Carousel.prototype.prev = function() { if (this.sliding) return return this.slide('prev') } Carousel.prototype.slide = function(type, next) { var $active = this.$element.find('.item.active') var $next = next || this.getItemForDirection(type, $active) var isCycling = this.interval var direction = type == 'next' ? 'left' : 'right' var that = this if ($next.hasClass('active')) return (this.sliding = false) var relatedTarget = $next[0] var slideEvent = $.Event('slide.bs.carousel', { relatedTarget: relatedTarget, direction: direction }) this.$element.trigger(slideEvent) if (slideEvent.isDefaultPrevented()) return this.sliding = true isCycling && this.pause() if (this.$indicators.length) { this.$indicators.find('.active').removeClass('active') var $nextIndicator = $(this.$indicators.children()[this.getItemIndex($next)]) $nextIndicator && $nextIndicator.addClass('active') } var slidEvent = $.Event('slid.bs.carousel', { relatedTarget: relatedTarget, direction: direction }) // yes, "slid" if ($.support.transition && this.$element.hasClass('slide')) { $next.addClass(type) $next[0].offsetWidth // force reflow $active.addClass(direction) $next.addClass(direction) $active .one('bsTransitionEnd', function() { $next.removeClass([type, direction].join(' ')).addClass('active') $active.removeClass(['active', direction].join(' ')) that.sliding = false setTimeout(function() { that.$element.trigger(slidEvent) }, 0) }) .emulateTransitionEnd(Carousel.TRANSITION_DURATION) } else { $active.removeClass('active') $next.addClass('active') this.sliding = false this.$element.trigger(slidEvent) } isCycling && this.cycle() return this } // CAROUSEL PLUGIN DEFINITION // ========================== function Plugin(option) { return this.each(function() { var $this = $(this) var data = $this.data('bs.carousel') var options = $.extend({}, Carousel.DEFAULTS, $this.data(), typeof option == 'object' && option) var action = typeof option == 'string' ? option : options.slide if (!data) $this.data('bs.carousel', (data = new Carousel(this, options))) if (typeof option == 'number') data.to(option) else if (action) data[action]() else if (options.interval) data.pause().cycle() }) } var old = $.fn.carousel $.fn.carousel = Plugin $.fn.carousel.Constructor = Carousel // CAROUSEL NO CONFLICT // ==================== $.fn.carousel.noConflict = function() { $.fn.carousel = old return this } // CAROUSEL DATA-API // ================= var clickHandler = function(e) { var href var $this = $(this) var $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) // strip for ie7 if (!$target.hasClass('carousel')) return var options = $.extend({}, $target.data(), $this.data()) var slideIndex = $this.attr('data-slide-to') if (slideIndex) options.interval = false Plugin.call($target, options) if (slideIndex) { $target.data('bs.carousel').to(slideIndex) } e.preventDefault() } $(document) .on('click.bs.carousel.data-api', '[data-slide]', clickHandler) .on('click.bs.carousel.data-api', '[data-slide-to]', clickHandler) $(window).on('load', function() { $('[data-ride="carousel"]').each(function() { var $carousel = $(this) Plugin.call($carousel, $carousel.data()) }) }) }(jQuery); /* ======================================================================== * Bootstrap: collapse.js v3.3.6 * http://getbootstrap.com/javascript/#collapse * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ + function($) { 'use strict'; // COLLAPSE PUBLIC CLASS DEFINITION // ================================ var Collapse = function(element, options) { this.$element = $(element) this.options = $.extend({}, Collapse.DEFAULTS, options) this.$trigger = $('[data-toggle="collapse"][href="#' + element.id + '"],' + '[data-toggle="collapse"][data-target="#' + element.id + '"]') this.transitioning = null if (this.options.parent) { this.$parent = this.getParent() } else { this.addAriaAndCollapsedClass(this.$element, this.$trigger) } if (this.options.toggle) this.toggle() } Collapse.VERSION = '3.3.6' Collapse.TRANSITION_DURATION = 350 Collapse.DEFAULTS = { toggle: true } Collapse.prototype.dimension = function() { var hasWidth = this.$element.hasClass('width') return hasWidth ? 'width' : 'height' } Collapse.prototype.show = function() { if (this.transitioning || this.$element.hasClass('in')) return var activesData var actives = this.$parent && this.$parent.children('.panel').children('.in, .collapsing') if (actives && actives.length) { activesData = actives.data('bs.collapse') if (activesData && activesData.transitioning) return } var startEvent = $.Event('show.bs.collapse') this.$element.trigger(startEvent) if (startEvent.isDefaultPrevented()) return if (actives && actives.length) { Plugin.call(actives, 'hide') activesData || actives.data('bs.collapse', null) } var dimension = this.dimension() this.$element .removeClass('collapse') .addClass('collapsing')[dimension](0) .attr('aria-expanded', true) this.$trigger .removeClass('collapsed') .attr('aria-expanded', true) this.transitioning = 1 var complete = function() { this.$element .removeClass('collapsing') .addClass('collapse in')[dimension]('') this.transitioning = 0 this.$element .trigger('shown.bs.collapse') } if (!$.support.transition) return complete.call(this) var scrollSize = $.camelCase(['scroll', dimension].join('-')) this.$element .one('bsTransitionEnd', $.proxy(complete, this)) .emulateTransitionEnd(Collapse.TRANSITION_DURATION)[dimension](this.$element[0][scrollSize]) } Collapse.prototype.hide = function() { if (this.transitioning || !this.$element.hasClass('in')) return var startEvent = $.Event('hide.bs.collapse') this.$element.trigger(startEvent) if (startEvent.isDefaultPrevented()) return var dimension = this.dimension() this.$element[dimension](this.$element[dimension]())[0].offsetHeight this.$element .addClass('collapsing') .removeClass('collapse in') .attr('aria-expanded', false) this.$trigger .addClass('collapsed') .attr('aria-expanded', false) this.transitioning = 1 var complete = function() { this.transitioning = 0 this.$element .removeClass('collapsing') .addClass('collapse') .trigger('hidden.bs.collapse') } if (!$.support.transition) return complete.call(this) this.$element[dimension](0) .one('bsTransitionEnd', $.proxy(complete, this)) .emulateTransitionEnd(Collapse.TRANSITION_DURATION) } Collapse.prototype.toggle = function() { this[this.$element.hasClass('in') ? 'hide' : 'show']() } Collapse.prototype.getParent = function() { return $(this.options.parent) .find('[data-toggle="collapse"][data-parent="' + this.options.parent + '"]') .each($.proxy(function(i, element) { var $element = $(element) this.addAriaAndCollapsedClass(getTargetFromTrigger($element), $element) }, this)) .end() } Collapse.prototype.addAriaAndCollapsedClass = function($element, $trigger) { var isOpen = $element.hasClass('in') $element.attr('aria-expanded', isOpen) $trigger .toggleClass('collapsed', !isOpen) .attr('aria-expanded', isOpen) } function getTargetFromTrigger($trigger) { var href var target = $trigger.attr('data-target') || (href = $trigger.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') // strip for ie7 return $(target) } // COLLAPSE PLUGIN DEFINITION // ========================== function Plugin(option) { return this.each(function() { var $this = $(this) var data = $this.data('bs.collapse') var options = $.extend({}, Collapse.DEFAULTS, $this.data(), typeof option == 'object' && option) if (!data && options.toggle && /show|hide/.test(option)) options.toggle = false if (!data) $this.data('bs.collapse', (data = new Collapse(this, options))) if (typeof option == 'string') data[option]() }) } var old = $.fn.collapse $.fn.collapse = Plugin $.fn.collapse.Constructor = Collapse // COLLAPSE NO CONFLICT // ==================== $.fn.collapse.noConflict = function() { $.fn.collapse = old return this } // COLLAPSE DATA-API // ================= $(document).on('click.bs.collapse.data-api', '[data-toggle="collapse"]', function(e) { var $this = $(this) if (!$this.attr('data-target')) e.preventDefault() var $target = getTargetFromTrigger($this) var data = $target.data('bs.collapse') var option = data ? 'toggle' : $this.data() Plugin.call($target, option) }) }(jQuery); /* ======================================================================== * Bootstrap: dropdown.js v3.3.6 * http://getbootstrap.com/javascript/#dropdowns * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ + function($) { 'use strict'; // DROPDOWN CLASS DEFINITION // ========================= var backdrop = '.dropdown-backdrop' var toggle = '[data-toggle="dropdown"]' var Dropdown = function(element) { $(element).on('click.bs.dropdown', this.toggle) } Dropdown.VERSION = '3.3.6' function getParent($this) { var selector = $this.attr('data-target') if (!selector) { selector = $this.attr('href') selector = selector && /#[A-Za-z]/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7 } var $parent = selector && $(selector) return $parent && $parent.length ? $parent : $this.parent() } function clearMenus(e) { if (e && e.which === 3) return $(backdrop).remove() $(toggle).each(function() { var $this = $(this) var $parent = getParent($this) var relatedTarget = { relatedTarget: this } if (!$parent.hasClass('open')) return if (e && e.type == 'click' && /input|textarea/i.test(e.target.tagName) && $.contains($parent[0], e.target)) return $parent.trigger(e = $.Event('hide.bs.dropdown', relatedTarget)) if (e.isDefaultPrevented()) return $this.attr('aria-expanded', 'false') $parent.removeClass('open').trigger($.Event('hidden.bs.dropdown', relatedTarget)) }) } Dropdown.prototype.toggle = function(e) { var $this = $(this) if ($this.is('.disabled, :disabled')) return var $parent = getParent($this) var isActive = $parent.hasClass('open') clearMenus() if (!isActive) { if ('ontouchstart' in document.documentElement && !$parent.closest('.navbar-nav').length) { // if mobile we use a backdrop because click events don't delegate $(document.createElement('div')) .addClass('dropdown-backdrop') .insertAfter($(this)) .on('click', clearMenus) } var relatedTarget = { relatedTarget: this } $parent.trigger(e = $.Event('show.bs.dropdown', relatedTarget)) if (e.isDefaultPrevented()) return $this .trigger('focus') .attr('aria-expanded', 'true') $parent .toggleClass('open') .trigger($.Event('shown.bs.dropdown', relatedTarget)) } return false } Dropdown.prototype.keydown = function(e) { if (!/(38|40|27|32)/.test(e.which) || /input|textarea/i.test(e.target.tagName)) return var $this = $(this) e.preventDefault() e.stopPropagation() if ($this.is('.disabled, :disabled')) return var $parent = getParent($this) var isActive = $parent.hasClass('open') if (!isActive && e.which != 27 || isActive && e.which == 27) { if (e.which == 27) $parent.find(toggle).trigger('focus') return $this.trigger('click') } var desc = ' li:not(.disabled):visible a' var $items = $parent.find('.dropdown-menu' + desc) if (!$items.length) return var index = $items.index(e.target) if (e.which == 38 && index > 0) index-- // up if (e.which == 40 && index < $items.length - 1) index++ // down if (!~index) index = 0 $items.eq(index).trigger('focus') } // DROPDOWN PLUGIN DEFINITION // ========================== function Plugin(option) { return this.each(function() { var $this = $(this) var data = $this.data('bs.dropdown') if (!data) $this.data('bs.dropdown', (data = new Dropdown(this))) if (typeof option == 'string') data[option].call($this) }) } var old = $.fn.dropdown $.fn.dropdown = Plugin $.fn.dropdown.Constructor = Dropdown // DROPDOWN NO CONFLICT // ==================== $.fn.dropdown.noConflict = function() { $.fn.dropdown = old return this } // APPLY TO STANDARD DROPDOWN ELEMENTS // =================================== $(document) .on('click.bs.dropdown.data-api', clearMenus) .on('click.bs.dropdown.data-api', '.dropdown form', function(e) { e.stopPropagation() }) .on('click.bs.dropdown.data-api', toggle, Dropdown.prototype.toggle) .on('keydown.bs.dropdown.data-api', toggle, Dropdown.prototype.keydown) .on('keydown.bs.dropdown.data-api', '.dropdown-menu', Dropdown.prototype.keydown) }(jQuery); /* ======================================================================== * Bootstrap: modal.js v3.3.6 * http://getbootstrap.com/javascript/#modals * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ + function($) { 'use strict'; // MODAL CLASS DEFINITION // ====================== var Modal = function(element, options) { this.options = options this.$body = $(document.body) this.$element = $(element) this.$dialog = this.$element.find('.modal-dialog') this.$backdrop = null this.isShown = null this.originalBodyPad = null this.scrollbarWidth = 0 this.ignoreBackdropClick = false if (this.options.remote) { this.$element .find('.modal-content') .load(this.options.remote, $.proxy(function() { this.$element.trigger('loaded.bs.modal') }, this)) } } Modal.VERSION = '3.3.6' Modal.TRANSITION_DURATION = 300 Modal.BACKDROP_TRANSITION_DURATION = 150 Modal.DEFAULTS = { backdrop: true, keyboard: true, show: true } Modal.prototype.toggle = function(_relatedTarget) { return this.isShown ? this.hide() : this.show(_relatedTarget) } Modal.prototype.show = function(_relatedTarget) { var that = this var e = $.Event('show.bs.modal', { relatedTarget: _relatedTarget }) this.$element.trigger(e) if (this.isShown || e.isDefaultPrevented()) return this.isShown = true this.checkScrollbar() this.setScrollbar() this.$body.addClass('modal-open') this.escape() this.resize() this.$element.on('click.dismiss.bs.modal', '[data-dismiss="modal"]', $.proxy(this.hide, this)) this.$dialog.on('mousedown.dismiss.bs.modal', function() { that.$element.one('mouseup.dismiss.bs.modal', function(e) { if ($(e.target).is(that.$element)) that.ignoreBackdropClick = true }) }) this.backdrop(function() { var transition = $.support.transition && that.$element.hasClass('fade') if (!that.$element.parent().length) { that.$element.appendTo(that.$body) // don't move modals dom position } that.$element .show() .scrollTop(0) that.adjustDialog() if (transition) { that.$element[0].offsetWidth // force reflow } that.$element.addClass('in') that.enforceFocus() var e = $.Event('shown.bs.modal', { relatedTarget: _relatedTarget }) transition ? that.$dialog // wait for modal to slide in .one('bsTransitionEnd', function() { that.$element.trigger('focus').trigger(e) }) .emulateTransitionEnd(Modal.TRANSITION_DURATION) : that.$element.trigger('focus').trigger(e) }) } Modal.prototype.hide = function(e) { if (e) e.preventDefault() e = $.Event('hide.bs.modal') this.$element.trigger(e) if (!this.isShown || e.isDefaultPrevented()) return this.isShown = false this.escape() this.resize() $(document).off('focusin.bs.modal') this.$element .removeClass('in') .off('click.dismiss.bs.modal') .off('mouseup.dismiss.bs.modal') this.$dialog.off('mousedown.dismiss.bs.modal') $.support.transition && this.$element.hasClass('fade') ? this.$element .one('bsTransitionEnd', $.proxy(this.hideModal, this)) .emulateTransitionEnd(Modal.TRANSITION_DURATION) : this.hideModal() } Modal.prototype.enforceFocus = function() { $(document) .off('focusin.bs.modal') // guard against infinite focus loop .on('focusin.bs.modal', $.proxy(function(e) { if (this.$element[0] !== e.target && !this.$element.has(e.target).length) { this.$element.trigger('focus') } }, this)) } Modal.prototype.escape = function() { if (this.isShown && this.options.keyboard) { this.$element.on('keydown.dismiss.bs.modal', $.proxy(function(e) { e.which == 27 && this.hide() }, this)) } else if (!this.isShown) { this.$element.off('keydown.dismiss.bs.modal') } } Modal.prototype.resize = function() { if (this.isShown) { $(window).on('resize.bs.modal', $.proxy(this.handleUpdate, this)) } else { $(window).off('resize.bs.modal') } } Modal.prototype.hideModal = function() { var that = this this.$element.hide() this.backdrop(function() { that.$body.removeClass('modal-open') that.resetAdjustments() that.resetScrollbar() that.$element.trigger('hidden.bs.modal') }) } Modal.prototype.removeBackdrop = function() { this.$backdrop && this.$backdrop.remove() this.$backdrop = null } Modal.prototype.backdrop = function(callback) { var that = this var animate = this.$element.hasClass('fade') ? 'fade' : '' if (this.isShown && this.options.backdrop) { var doAnimate = $.support.transition && animate this.$backdrop = $(document.createElement('div')) .addClass('modal-backdrop ' + animate) .appendTo(this.$body) this.$element.on('click.dismiss.bs.modal', $.proxy(function(e) { if (this.ignoreBackdropClick) { this.ignoreBackdropClick = false return } if (e.target !== e.currentTarget) return this.options.backdrop == 'static' ? this.$element[0].focus() : this.hide() }, this)) if (doAnimate) this.$backdrop[0].offsetWidth // force reflow this.$backdrop.addClass('in') if (!callback) return doAnimate ? this.$backdrop .one('bsTransitionEnd', callback) .emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) : callback() } else if (!this.isShown && this.$backdrop) { this.$backdrop.removeClass('in') var callbackRemove = function() { that.removeBackdrop() callback && callback() } $.support.transition && this.$element.hasClass('fade') ? this.$backdrop .one('bsTransitionEnd', callbackRemove) .emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) : callbackRemove() } else if (callback) { callback() } } // these following methods are used to handle overflowing modals Modal.prototype.handleUpdate = function() { this.adjustDialog() } Modal.prototype.adjustDialog = function() { var modalIsOverflowing = this.$element[0].scrollHeight > document.documentElement.clientHeight this.$element.css({ paddingLeft: !this.bodyIsOverflowing && modalIsOverflowing ? this.scrollbarWidth : '', paddingRight: this.bodyIsOverflowing && !modalIsOverflowing ? this.scrollbarWidth : '' }) } Modal.prototype.resetAdjustments = function() { this.$element.css({ paddingLeft: '', paddingRight: '' }) } Modal.prototype.checkScrollbar = function() { var fullWindowWidth = window.innerWidth if (!fullWindowWidth) { // workaround for missing window.innerWidth in IE8 var documentElementRect = document.documentElement.getBoundingClientRect() fullWindowWidth = documentElementRect.right - Math.abs(documentElementRect.left) } this.bodyIsOverflowing = document.body.clientWidth < fullWindowWidth this.scrollbarWidth = this.measureScrollbar() } Modal.prototype.setScrollbar = function() { var bodyPad = parseInt((this.$body.css('padding-right') || 0), 10) this.originalBodyPad = document.body.style.paddingRight || '' if (this.bodyIsOverflowing) this.$body.css('padding-right', bodyPad + this.scrollbarWidth) } Modal.prototype.resetScrollbar = function() { this.$body.css('padding-right', this.originalBodyPad) } Modal.prototype.measureScrollbar = function() { // thx walsh var scrollDiv = document.createElement('div') scrollDiv.className = 'modal-scrollbar-measure' this.$body.append(scrollDiv) var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth this.$body[0].removeChild(scrollDiv) return scrollbarWidth } // MODAL PLUGIN DEFINITION // ======================= function Plugin(option, _relatedTarget) { return this.each(function() { var $this = $(this) var data = $this.data('bs.modal') var options = $.extend({}, Modal.DEFAULTS, $this.data(), typeof option == 'object' && option) if (!data) $this.data('bs.modal', (data = new Modal(this, options))) if (typeof option == 'string') data[option](_relatedTarget) else if (options.show) data.show(_relatedTarget) }) } var old = $.fn.modal $.fn.modal = Plugin $.fn.modal.Constructor = Modal // MODAL NO CONFLICT // ================= $.fn.modal.noConflict = function() { $.fn.modal = old return this } // MODAL DATA-API // ============== $(document).on('click.bs.modal.data-api', '[data-toggle="modal"]', function(e) { var $this = $(this) var href = $this.attr('href') var $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) // strip for ie7 var option = $target.data('bs.modal') ? 'toggle' : $.extend({ remote: !/#/.test(href) && href }, $target.data(), $this.data()) if ($this.is('a')) e.preventDefault() $target.one('show.bs.modal', function(showEvent) { if (showEvent.isDefaultPrevented()) return // only register focus restorer if modal will actually get shown $target.one('hidden.bs.modal', function() { $this.is(':visible') && $this.trigger('focus') }) }) Plugin.call($target, option, this) }) }(jQuery); /* ======================================================================== * Bootstrap: tooltip.js v3.3.6 * http://getbootstrap.com/javascript/#tooltip * Inspired by the original jQuery.tipsy by Jason Frame * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ + function($) { 'use strict'; // TOOLTIP PUBLIC CLASS DEFINITION // =============================== var Tooltip = function(element, options) { this.type = null this.options = null this.enabled = null this.timeout = null this.hoverState = null this.$element = null this.inState = null this.init('tooltip', element, options) } Tooltip.VERSION = '3.3.6' Tooltip.TRANSITION_DURATION = 150 Tooltip.DEFAULTS = { animation: true, placement: 'top', selector: false, template: '<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>', trigger: 'hover focus', title: '', delay: 0, html: false, container: false, viewport: { selector: 'body', padding: 0 } } Tooltip.prototype.init = function(type, element, options) { this.enabled = true this.type = type this.$element = $(element) this.options = this.getOptions(options) this.$viewport = this.options.viewport && $($.isFunction(this.options.viewport) ? this.options.viewport.call(this, this.$element) : (this.options.viewport.selector || this.options.viewport)) this.inState = { click: false, hover: false, focus: false } if (this.$element[0] instanceof document.constructor && !this.options.selector) { throw new Error('`selector` option must be specified when initializing ' + this.type + ' on the window.document object!') } var triggers = this.options.trigger.split(' ') for (var i = triggers.length; i--;) { var trigger = triggers[i] if (trigger == 'click') { this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this)) } else if (trigger != 'manual') { var eventIn = trigger == 'hover' ? 'mouseenter' : 'focusin' var eventOut = trigger == 'hover' ? 'mouseleave' : 'focusout' this.$element.on(eventIn + '.' + this.type, this.options.selector, $.proxy(this.enter, this)) this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this)) } } this.options.selector ? (this._options = $.extend({}, this.options, { trigger: 'manual', selector: '' })) : this.fixTitle() } Tooltip.prototype.getDefaults = function() { return Tooltip.DEFAULTS } Tooltip.prototype.getOptions = function(options) { options = $.extend({}, this.getDefaults(), this.$element.data(), options) if (options.delay && typeof options.delay == 'number') { options.delay = { show: options.delay, hide: options.delay } } return options } Tooltip.prototype.getDelegateOptions = function() { var options = {} var defaults = this.getDefaults() this._options && $.each(this._options, function(key, value) { if (defaults[key] != value) options[key] = value }) return options } Tooltip.prototype.enter = function(obj) { var self = obj instanceof this.constructor ? obj : $(obj.currentTarget).data('bs.' + this.type) if (!self) { self = new this.constructor(obj.currentTarget, this.getDelegateOptions()) $(obj.currentTarget).data('bs.' + this.type, self) } if (obj instanceof $.Event) { self.inState[obj.type == 'focusin' ? 'focus' : 'hover'] = true } if (self.tip().hasClass('in') || self.hoverState == 'in') { self.hoverState = 'in' return } clearTimeout(self.timeout) self.hoverState = 'in' if (!self.options.delay || !self.options.delay.show) return self.show() self.timeout = setTimeout(function() { if (self.hoverState == 'in') self.show() }, self.options.delay.show) } Tooltip.prototype.isInStateTrue = function() { for (var key in this.inState) { if (this.inState[key]) return true } return false } Tooltip.prototype.leave = function(obj) { var self = obj instanceof this.constructor ? obj : $(obj.currentTarget).data('bs.' + this.type) if (!self) { self = new this.constructor(obj.currentTarget, this.getDelegateOptions()) $(obj.currentTarget).data('bs.' + this.type, self) } if (obj instanceof $.Event) { self.inState[obj.type == 'focusout' ? 'focus' : 'hover'] = false } if (self.isInStateTrue()) return clearTimeout(self.timeout) self.hoverState = 'out' if (!self.options.delay || !self.options.delay.hide) return self.hide() self.timeout = setTimeout(function() { if (self.hoverState == 'out') self.hide() }, self.options.delay.hide) } Tooltip.prototype.show = function() { var e = $.Event('show.bs.' + this.type) if (this.hasContent() && this.enabled) { this.$element.trigger(e) var inDom = $.contains(this.$element[0].ownerDocument.documentElement, this.$element[0]) if (e.isDefaultPrevented() || !inDom) return var that = this var $tip = this.tip() var tipId = this.getUID(this.type) this.setContent() $tip.attr('id', tipId) this.$element.attr('aria-describedby', tipId) if (this.options.animation) $tip.addClass('fade') var placement = typeof this.options.placement == 'function' ? this.options.placement.call(this, $tip[0], this.$element[0]) : this.options.placement var autoToken = /\s?auto?\s?/i var autoPlace = autoToken.test(placement) if (autoPlace) placement = placement.replace(autoToken, '') || 'top' $tip .detach() .css({ top: 0, left: 0, display: 'block' }) .addClass(placement) .data('bs.' + this.type, this) this.options.container ? $tip.appendTo(this.options.container) : $tip.insertAfter(this.$element) this.$element.trigger('inserted.bs.' + this.type) var pos = this.getPosition() var actualWidth = $tip[0].offsetWidth var actualHeight = $tip[0].offsetHeight if (autoPlace) { var orgPlacement = placement var viewportDim = this.getPosition(this.$viewport) placement = placement == 'bottom' && pos.bottom + actualHeight > viewportDim.bottom ? 'top' : placement == 'top' && pos.top - actualHeight < viewportDim.top ? 'bottom' : placement == 'right' && pos.right + actualWidth > viewportDim.width ? 'left' : placement == 'left' && pos.left - actualWidth < viewportDim.left ? 'right' : placement $tip .removeClass(orgPlacement) .addClass(placement) } var calculatedOffset = this.getCalculatedOffset(placement, pos, actualWidth, actualHeight) this.applyPlacement(calculatedOffset, placement) var complete = function() { var prevHoverState = that.hoverState that.$element.trigger('shown.bs.' + that.type) that.hoverState = null if (prevHoverState == 'out') that.leave(that) } $.support.transition && this.$tip.hasClass('fade') ? $tip .one('bsTransitionEnd', complete) .emulateTransitionEnd(Tooltip.TRANSITION_DURATION) : complete() } } Tooltip.prototype.applyPlacement = function(offset, placement) { var $tip = this.tip() var width = $tip[0].offsetWidth var height = $tip[0].offsetHeight // manually read margins because getBoundingClientRect includes difference var marginTop = parseInt($tip.css('margin-top'), 10) var marginLeft = parseInt($tip.css('margin-left'), 10) // we must check for NaN for ie 8/9 if (isNaN(marginTop)) marginTop = 0 if (isNaN(marginLeft)) marginLeft = 0 offset.top += marginTop offset.left += marginLeft // $.fn.offset doesn't round pixel values // so we use setOffset directly with our own function B-0 $.offset.setOffset($tip[0], $.extend({ using: function(props) { $tip.css({ top: Math.round(props.top), left: Math.round(props.left) }) } }, offset), 0) $tip.addClass('in') // check to see if placing tip in new offset caused the tip to resize itself var actualWidth = $tip[0].offsetWidth var actualHeight = $tip[0].offsetHeight if (placement == 'top' && actualHeight != height) { offset.top = offset.top + height - actualHeight } var delta = this.getViewportAdjustedDelta(placement, offset, actualWidth, actualHeight) if (delta.left) offset.left += delta.left else offset.top += delta.top var isVertical = /top|bottom/.test(placement) var arrowDelta = isVertical ? delta.left * 2 - width + actualWidth : delta.top * 2 - height + actualHeight var arrowOffsetPosition = isVertical ? 'offsetWidth' : 'offsetHeight' $tip.offset(offset) this.replaceArrow(arrowDelta, $tip[0][arrowOffsetPosition], isVertical) } Tooltip.prototype.replaceArrow = function(delta, dimension, isVertical) { this.arrow() .css(isVertical ? 'left' : 'top', 50 * (1 - delta / dimension) + '%') .css(isVertical ? 'top' : 'left', '') } Tooltip.prototype.setContent = function() { var $tip = this.tip() var title = this.getTitle() $tip.find('.tooltip-inner')[this.options.html ? 'html' : 'text'](title) $tip.removeClass('fade in top bottom left right') } Tooltip.prototype.hide = function(callback) { var that = this var $tip = $(this.$tip) var e = $.Event('hide.bs.' + this.type) function complete() { if (that.hoverState != 'in') $tip.detach() that.$element .removeAttr('aria-describedby') .trigger('hidden.bs.' + that.type) callback && callback() } this.$element.trigger(e) if (e.isDefaultPrevented()) return $tip.removeClass('in') $.support.transition && $tip.hasClass('fade') ? $tip .one('bsTransitionEnd', complete) .emulateTransitionEnd(Tooltip.TRANSITION_DURATION) : complete() this.hoverState = null return this } Tooltip.prototype.fixTitle = function() { var $e = this.$element if ($e.attr('title') || typeof $e.attr('data-original-title') != 'string') { $e.attr('data-original-title', $e.attr('title') || '').attr('title', '') } } Tooltip.prototype.hasContent = function() { return this.getTitle() } Tooltip.prototype.getPosition = function($element) { $element = $element || this.$element var el = $element[0] var isBody = el.tagName == 'BODY' var elRect = el.getBoundingClientRect() if (elRect.width == null) { // width and height are missing in IE8, so compute them manually; see https://github.com/twbs/bootstrap/issues/14093 elRect = $.extend({}, elRect, { width: elRect.right - elRect.left, height: elRect.bottom - elRect.top }) } var elOffset = isBody ? { top: 0, left: 0 } : $element.offset() var scroll = { scroll: isBody ? document.documentElement.scrollTop || document.body.scrollTop : $element.scrollTop() } var outerDims = isBody ? { width: $(window).width(), height: $(window).height() } : null return $.extend({}, elRect, scroll, outerDims, elOffset) } Tooltip.prototype.getCalculatedOffset = function(placement, pos, actualWidth, actualHeight) { return placement == 'bottom' ? { top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2 } : placement == 'top' ? { top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2 } : placement == 'left' ? { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth } : /* placement == 'right' */ { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width } } Tooltip.prototype.getViewportAdjustedDelta = function(placement, pos, actualWidth, actualHeight) { var delta = { top: 0, left: 0 } if (!this.$viewport) return delta var viewportPadding = this.options.viewport && this.options.viewport.padding || 0 var viewportDimensions = this.getPosition(this.$viewport) if (/right|left/.test(placement)) { var topEdgeOffset = pos.top - viewportPadding - viewportDimensions.scroll var bottomEdgeOffset = pos.top + viewportPadding - viewportDimensions.scroll + actualHeight if (topEdgeOffset < viewportDimensions.top) { // top overflow delta.top = viewportDimensions.top - topEdgeOffset } else if (bottomEdgeOffset > viewportDimensions.top + viewportDimensions.height) { // bottom overflow delta.top = viewportDimensions.top + viewportDimensions.height - bottomEdgeOffset } } else { var leftEdgeOffset = pos.left - viewportPadding var rightEdgeOffset = pos.left + viewportPadding + actualWidth if (leftEdgeOffset < viewportDimensions.left) { // left overflow delta.left = viewportDimensions.left - leftEdgeOffset } else if (rightEdgeOffset > viewportDimensions.right) { // right overflow delta.left = viewportDimensions.left + viewportDimensions.width - rightEdgeOffset } } return delta } Tooltip.prototype.getTitle = function() { var title var $e = this.$element var o = this.options title = $e.attr('data-original-title') || (typeof o.title == 'function' ? o.title.call($e[0]) : o.title) return title } Tooltip.prototype.getUID = function(prefix) { do prefix += ~~(Math.random() * 1000000) while (document.getElementById(prefix)) return prefix } Tooltip.prototype.tip = function() { if (!this.$tip) { this.$tip = $(this.options.template) if (this.$tip.length != 1) { throw new Error(this.type + ' `template` option must consist of exactly 1 top-level element!') } } return this.$tip } Tooltip.prototype.arrow = function() { return (this.$arrow = this.$arrow || this.tip().find('.tooltip-arrow')) } Tooltip.prototype.enable = function() { this.enabled = true } Tooltip.prototype.disable = function() { this.enabled = false } Tooltip.prototype.toggleEnabled = function() { this.enabled = !this.enabled } Tooltip.prototype.toggle = function(e) { var self = this if (e) { self = $(e.currentTarget).data('bs.' + this.type) if (!self) { self = new this.constructor(e.currentTarget, this.getDelegateOptions()) $(e.currentTarget).data('bs.' + this.type, self) } } if (e) { self.inState.click = !self.inState.click if (self.isInStateTrue()) self.enter(self) else self.leave(self) } else { self.tip().hasClass('in') ? self.leave(self) : self.enter(self) } } Tooltip.prototype.destroy = function() { var that = this clearTimeout(this.timeout) this.hide(function() { that.$element.off('.' + that.type).removeData('bs.' + that.type) if (that.$tip) { that.$tip.detach() } that.$tip = null that.$arrow = null that.$viewport = null }) } // TOOLTIP PLUGIN DEFINITION // ========================= function Plugin(option) { return this.each(function() { var $this = $(this) var data = $this.data('bs.tooltip') var options = typeof option == 'object' && option if (!data && /destroy|hide/.test(option)) return if (!data) $this.data('bs.tooltip', (data = new Tooltip(this, options))) if (typeof option == 'string') data[option]() }) } var old = $.fn.tooltip $.fn.tooltip = Plugin $.fn.tooltip.Constructor = Tooltip // TOOLTIP NO CONFLICT // =================== $.fn.tooltip.noConflict = function() { $.fn.tooltip = old return this } }(jQuery); /* ======================================================================== * Bootstrap: popover.js v3.3.6 * http://getbootstrap.com/javascript/#popovers * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ + function($) { 'use strict'; // POPOVER PUBLIC CLASS DEFINITION // =============================== var Popover = function(element, options) { this.init('popover', element, options) } if (!$.fn.tooltip) throw new Error('Popover requires tooltip.js') Popover.VERSION = '3.3.6' Popover.DEFAULTS = $.extend({}, $.fn.tooltip.Constructor.DEFAULTS, { placement: 'right', trigger: 'click', content: '', template: '<div class="popover" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>' }) // NOTE: POPOVER EXTENDS tooltip.js // ================================ Popover.prototype = $.extend({}, $.fn.tooltip.Constructor.prototype) Popover.prototype.constructor = Popover Popover.prototype.getDefaults = function() { return Popover.DEFAULTS } Popover.prototype.setContent = function() { var $tip = this.tip() var title = this.getTitle() var content = this.getContent() $tip.find('.popover-title')[this.options.html ? 'html' : 'text'](title) $tip.find('.popover-content').children().detach().end()[ // we use append for html objects to maintain js events this.options.html ? (typeof content == 'string' ? 'html' : 'append') : 'text' ](content) $tip.removeClass('fade top bottom left right in') // IE8 doesn't accept hiding via the `:empty` pseudo selector, we have to do // this manually by checking the contents. if (!$tip.find('.popover-title').html()) $tip.find('.popover-title').hide() } Popover.prototype.hasContent = function() { return this.getTitle() || this.getContent() } Popover.prototype.getContent = function() { var $e = this.$element var o = this.options return $e.attr('data-content') || (typeof o.content == 'function' ? o.content.call($e[0]) : o.content) } Popover.prototype.arrow = function() { return (this.$arrow = this.$arrow || this.tip().find('.arrow')) } // POPOVER PLUGIN DEFINITION // ========================= function Plugin(option) { return this.each(function() { var $this = $(this) var data = $this.data('bs.popover') var options = typeof option == 'object' && option if (!data && /destroy|hide/.test(option)) return if (!data) $this.data('bs.popover', (data = new Popover(this, options))) if (typeof option == 'string') data[option]() }) } var old = $.fn.popover $.fn.popover = Plugin $.fn.popover.Constructor = Popover // POPOVER NO CONFLICT // =================== $.fn.popover.noConflict = function() { $.fn.popover = old return this } }(jQuery); /* ======================================================================== * Bootstrap: scrollspy.js v3.3.6 * http://getbootstrap.com/javascript/#scrollspy * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ + function($) { 'use strict'; // SCROLLSPY CLASS DEFINITION // ========================== function ScrollSpy(element, options) { this.$body = $(document.body) this.$scrollElement = $(element).is(document.body) ? $(window) : $(element) this.options = $.extend({}, ScrollSpy.DEFAULTS, options) this.selector = (this.options.target || '') + ' .nav li > a' this.offsets = [] this.targets = [] this.activeTarget = null this.scrollHeight = 0 this.$scrollElement.on('scroll.bs.scrollspy', $.proxy(this.process, this)) this.refresh() this.process() } ScrollSpy.VERSION = '3.3.6' ScrollSpy.DEFAULTS = { offset: 10 } ScrollSpy.prototype.getScrollHeight = function() { return this.$scrollElement[0].scrollHeight || Math.max(this.$body[0].scrollHeight, document.documentElement.scrollHeight) } ScrollSpy.prototype.refresh = function() { var that = this var offsetMethod = 'offset' var offsetBase = 0 this.offsets = [] this.targets = [] this.scrollHeight = this.getScrollHeight() if (!$.isWindow(this.$scrollElement[0])) { offsetMethod = 'position' offsetBase = this.$scrollElement.scrollTop() } this.$body .find(this.selector) .map(function() { var $el = $(this) var href = $el.data('target') || $el.attr('href') var $href = /^#./.test(href) && $(href) return ($href && $href.length && $href.is(':visible') && [ [$href[offsetMethod]().top + offsetBase, href] ]) || null }) .sort(function(a, b) { return a[0] - b[0] }) .each(function() { that.offsets.push(this[0]) that.targets.push(this[1]) }) } ScrollSpy.prototype.process = function() { var scrollTop = this.$scrollElement.scrollTop() + this.options.offset var scrollHeight = this.getScrollHeight() var maxScroll = this.options.offset + scrollHeight - this.$scrollElement.height() var offsets = this.offsets var targets = this.targets var activeTarget = this.activeTarget var i if (this.scrollHeight != scrollHeight) { this.refresh() } if (scrollTop >= maxScroll) { return activeTarget != (i = targets[targets.length - 1]) && this.activate(i) } if (activeTarget && scrollTop < offsets[0]) { this.activeTarget = null return this.clear() } for (i = offsets.length; i--;) { activeTarget != targets[i] && scrollTop >= offsets[i] && (offsets[i + 1] === undefined || scrollTop < offsets[i + 1]) && this.activate(targets[i]) } } ScrollSpy.prototype.activate = function(target) { this.activeTarget = target this.clear() var selector = this.selector + '[data-target="' + target + '"],' + this.selector + '[href="' + target + '"]' var active = $(selector) .parents('li') .addClass('active') if (active.parent('.dropdown-menu').length) { active = active .closest('li.dropdown') .addClass('active') } active.trigger('activate.bs.scrollspy') } ScrollSpy.prototype.clear = function() { $(this.selector) .parentsUntil(this.options.target, '.active') .removeClass('active') } // SCROLLSPY PLUGIN DEFINITION // =========================== function Plugin(option) { return this.each(function() { var $this = $(this) var data = $this.data('bs.scrollspy') var options = typeof option == 'object' && option if (!data) $this.data('bs.scrollspy', (data = new ScrollSpy(this, options))) if (typeof option == 'string') data[option]() }) } var old = $.fn.scrollspy $.fn.scrollspy = Plugin $.fn.scrollspy.Constructor = ScrollSpy // SCROLLSPY NO CONFLICT // ===================== $.fn.scrollspy.noConflict = function() { $.fn.scrollspy = old return this } // SCROLLSPY DATA-API // ================== $(window).on('load.bs.scrollspy.data-api', function() { $('[data-spy="scroll"]').each(function() { var $spy = $(this) Plugin.call($spy, $spy.data()) }) }) }(jQuery); /* ======================================================================== * Bootstrap: tab.js v3.3.6 * http://getbootstrap.com/javascript/#tabs * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ + function($) { 'use strict'; // TAB CLASS DEFINITION // ==================== var Tab = function(element) { // jscs:disable requireDollarBeforejQueryAssignment this.element = $(element) // jscs:enable requireDollarBeforejQueryAssignment } Tab.VERSION = '3.3.6' Tab.TRANSITION_DURATION = 150 Tab.prototype.show = function() { var $this = this.element var $ul = $this.closest('ul:not(.dropdown-menu)') var selector = $this.data('target') if (!selector) { selector = $this.attr('href') selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7 } if ($this.parent('li').hasClass('active')) return var $previous = $ul.find('.active:last a') var hideEvent = $.Event('hide.bs.tab', { relatedTarget: $this[0] }) var showEvent = $.Event('show.bs.tab', { relatedTarget: $previous[0] }) $previous.trigger(hideEvent) $this.trigger(showEvent) if (showEvent.isDefaultPrevented() || hideEvent.isDefaultPrevented()) return var $target = $(selector) this.activate($this.closest('li'), $ul) this.activate($target, $target.parent(), function() { $previous.trigger({ type: 'hidden.bs.tab', relatedTarget: $this[0] }) $this.trigger({ type: 'shown.bs.tab', relatedTarget: $previous[0] }) }) } Tab.prototype.activate = function(element, container, callback) { var $active = container.find('> .active') var transition = callback && $.support.transition && ($active.length && $active.hasClass('fade') || !!container.find('> .fade').length) function next() { $active .removeClass('active') .find('> .dropdown-menu > .active') .removeClass('active') .end() .find('[data-toggle="tab"]') .attr('aria-expanded', false) element .addClass('active') .find('[data-toggle="tab"]') .attr('aria-expanded', true) if (transition) { element[0].offsetWidth // reflow for transition element.addClass('in') } else { element.removeClass('fade') } if (element.parent('.dropdown-menu').length) { element .closest('li.dropdown') .addClass('active') .end() .find('[data-toggle="tab"]') .attr('aria-expanded', true) } callback && callback() } $active.length && transition ? $active .one('bsTransitionEnd', next) .emulateTransitionEnd(Tab.TRANSITION_DURATION) : next() $active.removeClass('in') } // TAB PLUGIN DEFINITION // ===================== function Plugin(option) { return this.each(function() { var $this = $(this) var data = $this.data('bs.tab') if (!data) $this.data('bs.tab', (data = new Tab(this))) if (typeof option == 'string') data[option]() }) } var old = $.fn.tab $.fn.tab = Plugin $.fn.tab.Constructor = Tab // TAB NO CONFLICT // =============== $.fn.tab.noConflict = function() { $.fn.tab = old return this } // TAB DATA-API // ============ var clickHandler = function(e) { e.preventDefault() Plugin.call($(this), 'show') } $(document) .on('click.bs.tab.data-api', '[data-toggle="tab"]', clickHandler) .on('click.bs.tab.data-api', '[data-toggle="pill"]', clickHandler) }(jQuery); /* ======================================================================== * Bootstrap: affix.js v3.3.6 * http://getbootstrap.com/javascript/#affix * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ + function($) { 'use strict'; // AFFIX CLASS DEFINITION // ====================== var Affix = function(element, options) { this.options = $.extend({}, Affix.DEFAULTS, options) this.$target = $(this.options.target) .on('scroll.bs.affix.data-api', $.proxy(this.checkPosition, this)) .on('click.bs.affix.data-api', $.proxy(this.checkPositionWithEventLoop, this)) this.$element = $(element) this.affixed = null this.unpin = null this.pinnedOffset = null this.checkPosition() } Affix.VERSION = '3.3.6' Affix.RESET = 'affix affix-top affix-bottom' Affix.DEFAULTS = { offset: 0, target: window } Affix.prototype.getState = function(scrollHeight, height, offsetTop, offsetBottom) { var scrollTop = this.$target.scrollTop() var position = this.$element.offset() var targetHeight = this.$target.height() if (offsetTop != null && this.affixed == 'top') return scrollTop < offsetTop ? 'top' : false if (this.affixed == 'bottom') { if (offsetTop != null) return (scrollTop + this.unpin <= position.top) ? false : 'bottom' return (scrollTop + targetHeight <= scrollHeight - offsetBottom) ? false : 'bottom' } var initializing = this.affixed == null var colliderTop = initializing ? scrollTop : position.top var colliderHeight = initializing ? targetHeight : height if (offsetTop != null && scrollTop <= offsetTop) return 'top' if (offsetBottom != null && (colliderTop + colliderHeight >= scrollHeight - offsetBottom)) return 'bottom' return false } Affix.prototype.getPinnedOffset = function() { if (this.pinnedOffset) return this.pinnedOffset this.$element.removeClass(Affix.RESET).addClass('affix') var scrollTop = this.$target.scrollTop() var position = this.$element.offset() return (this.pinnedOffset = position.top - scrollTop) } Affix.prototype.checkPositionWithEventLoop = function() { setTimeout($.proxy(this.checkPosition, this), 1) } Affix.prototype.checkPosition = function() { if (!this.$element.is(':visible')) return var height = this.$element.height() var offset = this.options.offset var offsetTop = offset.top var offsetBottom = offset.bottom var scrollHeight = Math.max($(document).height(), $(document.body).height()) if (typeof offset != 'object') offsetBottom = offsetTop = offset if (typeof offsetTop == 'function') offsetTop = offset.top(this.$element) if (typeof offsetBottom == 'function') offsetBottom = offset.bottom(this.$element) var affix = this.getState(scrollHeight, height, offsetTop, offsetBottom) if (this.affixed != affix) { if (this.unpin != null) this.$element.css('top', '') var affixType = 'affix' + (affix ? '-' + affix : '') var e = $.Event(affixType + '.bs.affix') this.$element.trigger(e) if (e.isDefaultPrevented()) return this.affixed = affix this.unpin = affix == 'bottom' ? this.getPinnedOffset() : null this.$element .removeClass(Affix.RESET) .addClass(affixType) .trigger(affixType.replace('affix', 'affixed') + '.bs.affix') } if (affix == 'bottom') { this.$element.offset({ top: scrollHeight - height - offsetBottom }) } } // AFFIX PLUGIN DEFINITION // ======================= function Plugin(option) { return this.each(function() { var $this = $(this) var data = $this.data('bs.affix') var options = typeof option == 'object' && option if (!data) $this.data('bs.affix', (data = new Affix(this, options))) if (typeof option == 'string') data[option]() }) } var old = $.fn.affix $.fn.affix = Plugin $.fn.affix.Constructor = Affix // AFFIX NO CONFLICT // ================= $.fn.affix.noConflict = function() { $.fn.affix = old return this } // AFFIX DATA-API // ============== $(window).on('load', function() { $('[data-spy="affix"]').each(function() { var $spy = $(this) var data = $spy.data() data.offset = data.offset || {} if (data.offsetBottom != null) data.offset.bottom = data.offsetBottom if (data.offsetTop != null) data.offset.top = data.offsetTop Plugin.call($spy, data) }) }) }(jQuery);
var assert = require('assert'); describe('src/components/model/classes/Collection', function () { var Collection = require('../../../../src/components/model/classes/Collection'); var collection; var handler = function (event, changes) { callbacks[event]++; }; var callbacks = { add: 0, remove: 0, change: 0 }; describe.only('new Collection(obj)', function () { it('Should return a new Collection instance', function (done) { collection = new Collection([1, 2, 3], handler); done(); }); }); describe.only('.push(item)', function () { it('Should call "add" callback', function (done) { collection.push(4); assert(callbacks.add, 1); done(); }); }); describe.only('.unshift(item)', function () { it('Should call "add" callback', function (done) { collection.unshift(0); assert(callbacks.add, 2); done(); }); }); describe.only('.pop()', function () { it('Should call "remove" callback', function (done) { collection.pop(); assert(callbacks.remove, 1); done(); }); }); describe.only('.shift()', function () { it('Should call "remove" callback', function (done) { collection.shift(); assert(callbacks.remove, 2); done(); }); }); describe.only('.splice(index, number)', function () { it('Should call "remove" callback', function (done) { collection.splice(0, 1); assert(callbacks.remove, 3); done(); }); }); describe.only('.reverse()', function () { it('Should call "change" callback', function (done) { collection.reverse(); assert(callbacks.change, 1); done(); }); }); describe.only('.sort()', function () { it('Should call "change" callback', function (done) { collection.sort(function (a, b) { return -1; }); assert(callbacks.change, 2); done(); }); }); });
/** * boot/middleware.js * Express middleware */
import React from 'react'; import Status from 'components/Status'; import renderer from 'react-test-renderer'; describe('Status component', () => { function getComponent(piecesLeftCount) { return renderer.create( <Status piecesLeftCount={piecesLeftCount} /> ); } it('should show pieces left', () => { expect(getComponent(9).toJSON()).toMatchSnapshot(); }); it('should show "Done" when no pieces left', () => { expect(getComponent(0).toJSON()).toMatchSnapshot(); }); });
var struct_l_p_c___r_t_c___type_def = [ [ "ALDOM", "struct_l_p_c___r_t_c___type_def.html#aae1199a3f1f40f90aba18aee4d6325fd", null ], [ "ALDOW", "struct_l_p_c___r_t_c___type_def.html#a5f56710f005f96878defbdb8ef1333c2", null ], [ "ALDOY", "struct_l_p_c___r_t_c___type_def.html#a4c7ceb477c4a865ae51f5052dd558667", null ], [ "ALHOUR", "struct_l_p_c___r_t_c___type_def.html#ac56690c26258c2cf9d28d09cc3447c1d", null ], [ "ALMIN", "struct_l_p_c___r_t_c___type_def.html#a7e45902fca36066b22f41d0ef60d3c36", null ], [ "ALMON", "struct_l_p_c___r_t_c___type_def.html#ad22f635b8c8b51dad2956e797a4dd9d3", null ], [ "ALSEC", "struct_l_p_c___r_t_c___type_def.html#af3ff64ab3671109971425a05194acc7c", null ], [ "ALYEAR", "struct_l_p_c___r_t_c___type_def.html#ab7f49ad885a354164adc263629d3a555", null ], [ "AMR", "struct_l_p_c___r_t_c___type_def.html#a13f4e9721184b326043e6c6596f87790", null ], [ "CALIBRATION", "struct_l_p_c___r_t_c___type_def.html#abe224f8608ae3d2c5b1036bf943b6c27", null ], [ "CCR", "struct_l_p_c___r_t_c___type_def.html#af959ddb88caef28108c2926e310a72bd", null ], [ "CIIR", "struct_l_p_c___r_t_c___type_def.html#a0df12e53986b72fbfcdceb537f7bf20e", null ], [ "CTIME0", "struct_l_p_c___r_t_c___type_def.html#a97fa06b91b698236cb770d9618707bef", null ], [ "CTIME1", "struct_l_p_c___r_t_c___type_def.html#a5b1a1b981a72c6d1cd482e75f1d44de4", null ], [ "CTIME2", "struct_l_p_c___r_t_c___type_def.html#a411e06dfdcddd3fc19170231aa3a98be", null ], [ "DOM", "struct_l_p_c___r_t_c___type_def.html#a7c70513eabbefbc5c5dd865a01ecc487", null ], [ "DOW", "struct_l_p_c___r_t_c___type_def.html#a61f22d3ccb1c82db258f66d7d930db35", null ], [ "DOY", "struct_l_p_c___r_t_c___type_def.html#a7b4a3d5692df3c5062ec927cedd16734", null ], [ "GPREG0", "struct_l_p_c___r_t_c___type_def.html#ac42f0d8452c678fa007f0e0b862fb0c6", null ], [ "GPREG1", "struct_l_p_c___r_t_c___type_def.html#abee4ae6eab2c33bdf38985d3b8a439f1", null ], [ "GPREG2", "struct_l_p_c___r_t_c___type_def.html#a75f852bb2980febd2af7cc583e1445ec", null ], [ "GPREG3", "struct_l_p_c___r_t_c___type_def.html#aad058be0cc120fffbbc66ad6f7c0c731", null ], [ "GPREG4", "struct_l_p_c___r_t_c___type_def.html#afcc8f7898dce77fdb1082ff681387692", null ], [ "HOUR", "struct_l_p_c___r_t_c___type_def.html#a76b8d6a8b13febe4289797f34ba73998", null ], [ "ILR", "struct_l_p_c___r_t_c___type_def.html#aba869620e961b6eb9280229dad81e458", null ], [ "MIN", "struct_l_p_c___r_t_c___type_def.html#a7a07167f54a5412387ee581fcd6dd2e0", null ], [ "MONTH", "struct_l_p_c___r_t_c___type_def.html#a28fb9798e07b54b1098e9efe96ac244a", null ], [ "RESERVED0", "struct_l_p_c___r_t_c___type_def.html#ad539ffa4484980685ca2da36b54fe61d", null ], [ "RESERVED1", "struct_l_p_c___r_t_c___type_def.html#ad9fb3ef44fb733b524dcad0dfe34290e", null ], [ "RESERVED10", "struct_l_p_c___r_t_c___type_def.html#a2d9caf1d8be9f2169521470b6ccd0377", null ], [ "RESERVED11", "struct_l_p_c___r_t_c___type_def.html#a11e504ee49142f46dcc67740ae9235e5", null ], [ "RESERVED12", "struct_l_p_c___r_t_c___type_def.html#a06137f06d699f26661c55209218bcada", null ], [ "RESERVED13", "struct_l_p_c___r_t_c___type_def.html#a17672e7a5546cef19ee778266224c193", null ], [ "RESERVED14", "struct_l_p_c___r_t_c___type_def.html#a1b9781efee5466ce7886eae907f24e60", null ], [ "RESERVED15", "struct_l_p_c___r_t_c___type_def.html#a781148146471db4cd7d04029e383d115", null ], [ "RESERVED16", "struct_l_p_c___r_t_c___type_def.html#af3ff60ce094e476f447a8046d873acb0", null ], [ "RESERVED17", "struct_l_p_c___r_t_c___type_def.html#ae98d0c41e0bb8aef875fa8b53b25af54", null ], [ "RESERVED18", "struct_l_p_c___r_t_c___type_def.html#aae0a4a7536dc03a352e8c48436b10263", null ], [ "RESERVED19", "struct_l_p_c___r_t_c___type_def.html#a5552e97d80fc1a5bd195a9c81b270ffc", null ], [ "RESERVED2", "struct_l_p_c___r_t_c___type_def.html#aff8b921ce3122ac6c22dc654a4f1b7ca", null ], [ "RESERVED20", "struct_l_p_c___r_t_c___type_def.html#af7fcad34b88077879694c020956bf69b", null ], [ "RESERVED21", "struct_l_p_c___r_t_c___type_def.html#ae26a65f4079b1f3af0490c463e6f6e90", null ], [ "RESERVED3", "struct_l_p_c___r_t_c___type_def.html#a1936698394c9e65033538255b609f5d5", null ], [ "RESERVED4", "struct_l_p_c___r_t_c___type_def.html#a23568af560875ec74b660f1860e06d3b", null ], [ "RESERVED5", "struct_l_p_c___r_t_c___type_def.html#a17b8ef27f4663f5d6b0fe9c46ab9bc3d", null ], [ "RESERVED6", "struct_l_p_c___r_t_c___type_def.html#a585b017c54971fb297a30e3927437015", null ], [ "RESERVED7", "struct_l_p_c___r_t_c___type_def.html#af2e6e355909e4223f7665881b0514716", null ], [ "RESERVED8", "struct_l_p_c___r_t_c___type_def.html#a8cb0d97b1d31d1921acc7aa587d1c60b", null ], [ "RESERVED9", "struct_l_p_c___r_t_c___type_def.html#ad8b1fadb520f7a200ee0046e110edc79", null ], [ "RTC_AUX", "struct_l_p_c___r_t_c___type_def.html#a8a91a5b909fbba65b28d972c3164a4ed", null ], [ "RTC_AUXEN", "struct_l_p_c___r_t_c___type_def.html#a4f807cc73e86fa24a247e0dce31512a4", null ], [ "SEC", "struct_l_p_c___r_t_c___type_def.html#a77f4a78b486ec068e5ced41419805802", null ], [ "YEAR", "struct_l_p_c___r_t_c___type_def.html#aaf0ddcf6e202e34e9cf7b35c584f9849", null ] ];
/** * @author Richard Davey <[email protected]> * @copyright 2018 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ var RemoveTileAt = require('./RemoveTileAt'); var WorldToTileX = require('./WorldToTileX'); var WorldToTileY = require('./WorldToTileY'); /** * Removes the tile at the given world coordinates in the specified layer and updates the layer's * collision information. * * @function Phaser.Tilemaps.Components.RemoveTileAtWorldXY * @private * @since 3.0.0 * * @param {number} worldX - [description] * @param {number} worldY - [description] * @param {boolean} [replaceWithNull=true] - If true, this will replace the tile at the specified * location with null instead of a Tile with an index of -1. * @param {boolean} [recalculateFaces=true] - [description] * @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - [description] * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. * * @return {Phaser.Tilemaps.Tile} The Tile object that was removed. */ var RemoveTileAtWorldXY = function (worldX, worldY, replaceWithNull, recalculateFaces, camera, layer) { var tileX = WorldToTileX(worldX, true, camera, layer); var tileY = WorldToTileY(worldY, true, camera, layer); return RemoveTileAt(tileX, tileY, replaceWithNull, recalculateFaces, layer); }; module.exports = RemoveTileAtWorldXY;
/** * Created by JiaHao on 27/10/15. */ var fs = require('fs'); var path = require('path'); var normalizeNewline = require('normalize-newline'); function occurenceIndexes(inp, toFind) { var indices = []; var element = toFind; var idx = inp.indexOf(element); while (idx != -1) { indices.push(idx); idx = inp.indexOf(element, idx + 1); } return indices; } const ANNONATION = { start: '{', end: '}' }; /** * Parses a file at a path * @param path * @returns {Array} * @param annotation */ function parseText(path, annotation) { var rawText = normalizeNewline(fs.readFileSync(path).toString()); var annotationToken = annotation || ANNONATION; var startOccurances = occurenceIndexes(rawText, annotationToken.start); var endOccurances = occurenceIndexes(rawText, annotationToken.end); var allOccurances = startOccurances.concat(endOccurances).sort(function(a, b){return a-b}); var subtractIndexes = {}; for (var i = 0; i < allOccurances.length; i++) { subtractIndexes[allOccurances[i]] = i; } var result = []; var stack = []; // stack of start occurances var counter = 0; var startOccuranceCounter = 0; var endOccuranceCounter = 0; var startOccuranceNext; var endOccuranceNext; while (counter < rawText.length) { startOccuranceNext = startOccurances[startOccuranceCounter]; endOccuranceNext = endOccurances[endOccuranceCounter]; if (counter === startOccuranceNext) { stack.push(startOccuranceNext); startOccuranceCounter+=1; } else if (counter === endOccuranceNext) { var stackNext = stack.pop(); result.push([stackNext, endOccuranceNext]); endOccuranceCounter+=1; } counter += 1; } var subtractFunction = function (element) { return element - subtractIndexes[element]; }; result = result.map(function (tuple) { return tuple.map(subtractFunction); }); return result; } module.exports = parseText; if (require.main === module) { var expected = [ [6, 10], [35, 39], [71, 76], [296, 303], [356,362] ]; var toParsePath = path.join(__dirname, '../', 'examples/annotatedData.txt'); var result = parseText(toParsePath); }
module.exports.sum = function (arr, prop, exp) { var total = 0 for (var i = 0, _len = arr.length; i < _len; i++) { var value = arr[i][prop]; if (exp) { if (arr[i][exp.field] == exp.value) { total += value * 1; } } else { total += value * 1; } } return total };
describe('Modules.Ellipsis.js', function() { it('should exist with expected constructures', function() { expect(moj.Modules.CaseCreation.init).toBeDefined(); }); });
import React, { Component } from 'react' import { Circle, FeatureGroup, LayerGroup, Map, Popup, Rectangle, TileLayer, } from '../../src' export default class OtherLayersExample extends Component { render () { const center = [51.505, -0.09] const rectangle = [ [51.49, -0.08], [51.5, -0.06], ] return ( <Map center={center} zoom={13}> <TileLayer attribution='&copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors' url='http://{s}.tile.osm.org/{z}/{x}/{y}.png' /> <LayerGroup> <Circle center={center} fillColor='blue' radius={200} /> <Circle center={center} fillColor='red' radius={100} stroke={false} /> <LayerGroup> <Circle center={[51.51, -0.08]} color='green' fillColor='green' radius={100} /> </LayerGroup> </LayerGroup> <FeatureGroup color='purple'> <Popup> <span>Popup in FeatureGroup</span> </Popup> <Circle center={[51.51, -0.06]} radius={200} /> <Rectangle bounds={rectangle} /> </FeatureGroup> </Map> ) } }
/** * @author shirishgoyal * created on 16.12.2015 */ (function () { 'use strict'; angular.module('BlurAdmin.pages.auth', [ 'BlurAdmin.services' ]) .config(routeConfig); /** @ngInject */ function routeConfig($stateProvider) { $stateProvider .state('auth', { url: '/auth', abstract: true, views: { 'full_screen': { templateUrl: 'static/app/pages/auth/auth.html' } }, authenticate: false }) // .state('auth.register', { // url: '/register', // templateUrl: 'static/app/pages/auth/register.html', // controller: 'RegisterPageCtrl', // controllerAs: 'vm' // }) // .state('auth.login', { // url: '/login', // templateUrl: 'static/app/pages/auth/login.html', // controller: 'LoginPageCtrl', // controllerAs: 'vm' // }) ; } })();
/** * Base js functions */ $(document).ready(function(){ //Init jQuery Masonry layout init_masonry(); //Select menu onchange $("#collapsed-navbar").change(function () { window.location = $(this).val(); }); }); function init_masonry(){ var $container = $('#content'); $container.imagesLoaded( function(){ $container.masonry({ itemSelector: '.box', isAnimated: true }); }); } */ $(document).ready(function(){ //Start carousel $('.carousel').carousel({interval:false}); });
var React = require('react'); var RulePicker = require('./RulePicker.js'); var TimePicker = require('react-time-picker'); var DatePicker = require('react-date-picker'); var RuleSummary = require("./RuleSummary.js"); var moment = require('moment'); var Tabs = require('react-simpletabs'); var RecurringSelect = React.createClass({displayName: "RecurringSelect", getInitialState: function() { return ({ rule: "daily", interval: 1, validations: null, until: moment().format('YYYY-MM-DD'), startTime: "10:00 AM" }); }, handleRuleChange: function(e) { var rule = e.target.value; var validations = null; if (rule === "weekly") validations = []; if (rule === "monthly (by day of week)") { rule = "monthly"; validations = {1: [], 2: [], 3: [], 4: []}; } if (rule === "monthly (by day of month)") { rule = "monthly"; validations = []; } this.setState({ rule: rule, validations: validations }); }, handleIntervalChange: function(e) { var interval; if (e.target.value != "") { interval = parseInt(e.target.value); } else { interval = 0; } this.setState({ interval: interval }); }, handleValidationsChange: function(validations) { this.setState({ validations: validations }); }, handleEndDateChange: function (date) { this.setState({ until: date }); }, handleTimeChange: function(time) { this.setState({ startTime: time }); }, handleSave: function(e) { var hash = this.state; console.log(hash.validations); var iceCubeHash = {}; var start = moment(hash.startTime, "hh:mm a A"); var minute = start.minute(); var hour = start.hour(); var rule_type; switch (hash.rule) { case 'daily': rule_type = "IceCube::DailyRule"; break; case 'weekly': rule_type = "IceCube::WeeklyRule"; break; case 'monthly': rule_type = "IceCube::MonthlyRule"; break; case 'yearly': rule_type = "IceCube::YearlyRule"; break; } var interval = hash.interval; var validations = hash.validations == null ? {} : hash.validations; var newValidations = {}; if (Array.isArray(validations) && rule_type == "IceCube::WeeklyRule") { newValidations["day"] = validations } else if (Array.isArray(validations) && rule_type == "IceCube::MonthlyRule") { newValidations["day_of_month"] = validations; } else if (rule_type == "IceCube::MonthlyRule") { newValidations["day_of_week"] = validations; } newValidations["hour_of_day"] = hour; newValidations["minute_of_hour"] = minute; var until = hash.until; iceCubeHash["rule_type"] = rule_type; iceCubeHash["interval"] = interval; iceCubeHash["validations"] = newValidations; iceCubeHash["until"] = until; this.props.onSave(JSON.stringify(iceCubeHash)); }, render: function() { return ( React.createElement("div", {className: "recurring-select"}, React.createElement(Tabs, null, React.createElement(Tabs.Panel, {title: "Recurrence Rule"}, React.createElement(RulePicker, { rule: this.state.rule, interval: this.state.interval, validations: this.state.validations, onRuleChange: this.handleRuleChange, onIntervalChange: this.handleIntervalChange, onValidationsChange: this.handleValidationsChange}) ), React.createElement(Tabs.Panel, {title: "Occurence Time"}, React.createElement(TimePicker, {value: this.state.startTime, onChange: this.handleTimeChange}) ), React.createElement(Tabs.Panel, {title: "Recurring Until"}, React.createElement(DatePicker, {minDate: moment().format("YYYY-MM-DD"), date: this.state.until, onChange: this.handleEndDateChange}) ) ), React.createElement("hr", null), React.createElement(RuleSummary, {fields: this.state}), React.createElement("button", {className: "btn save", onClick: this.handleSave}, "Save") ) ); } }); module.exports = RecurringSelect;
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = eachLimit; var _eachOfLimit = require('./internal/eachOfLimit'); var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); var _withoutIndex = require('./internal/withoutIndex'); var _withoutIndex2 = _interopRequireDefault(_withoutIndex); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * The same as [`each`]{@link module:Collections.each} but runs a maximum of `limit` async operations at a time. * * @name eachLimit * @static * @memberOf module:Collections * @method * @see [async.each]{@link module:Collections.each} * @alias forEachLimit * @category Collection * @param {Array|Iterable|Object} coll - A colleciton to iterate over. * @param {number} limit - The maximum number of async operations at a time. * @param {Function} iteratee - A function to apply to each item in `coll`. The * iteratee is passed a `callback(err)` which must be called once it has * completed. If no error has occurred, the `callback` should be run without * arguments or with an explicit `null` argument. The array index is not passed * to the iteratee. Invoked with (item, callback). If you need the index, use * `eachOfLimit`. * @param {Function} [callback] - A callback which is called when all * `iteratee` functions have finished, or an error occurs. Invoked with (err). */ function eachLimit(coll, limit, iteratee, callback) { (0, _eachOfLimit2.default)(limit)(coll, (0, _withoutIndex2.default)(iteratee), callback); } module.exports = exports['default'];
angular.module('green-streak.controllers', ['LocalStorageModule']) .controller('MenuController', function ($scope, $location, MenuService) { // "MenuService" is a service returning mock data (services.js) $scope.list = MenuService.all(); $scope.goTo = function (page) { console.log('Going to ' + page); $scope.sideMenuController.toggleLeft(); $location.url('/' + page); }; }) .controller('AuthController', function ($scope, $ionicPlatform, $state, localStorageService) { $scope.leftButtons = [ { type: 'button-icon icon ion-navicon', tap: function (e) { $scope.sideMenuController.toggleLeft(); } } ]; $scope.rightButtons = []; }) .controller('IndexController', function ($scope, $ionicPlatform, $state, localStorageService) { // var authenticated = localStorageService.get('authenticated'); // if (authenticated) // { // $state.go('one'); // } $scope.navTitle = "Green Streak"; $scope.user = {userName: ''}; $scope.search = function () { console.log("Searching for userName: " + $scope.user.userName) localStorageService.set("userName", $scope.user.userName); $state.go('square'); }; $scope.leftButtons = [ { type: 'button-icon icon ion-navicon', tap: function (e) { $scope.sideMenuController.toggleLeft(); } } ]; $scope.rightButtons = []; }) .controller("CallbackController", function ($scope, $location, $state, AuthService, localStorageService) { $scope.currentURL = $location.absUrl(); var paramPartOfURL = $scope.currentURL.slice($scope.currentURL.indexOf('code=') + 5); var indexOfSlash = paramPartOfURL.indexOf('/'); var oAuthCode = paramPartOfURL.slice(0, indexOfSlash) AuthService.get({'tokenId': oAuthCode}, function (success) { localStorageService.add("authenticated", true); $state.go('one'); }, function (error) { // error callback localStorageService.remove("authenticated"); }); }) .controller('OneController', function ($scope, LanguageCountService) { $scope.navTitle = "Language Data by count"; $scope.d3Data = LanguageCountService.query(); $scope.d3OnClick = function (item) { // alert(item.name); }; $scope.leftButtons = [ { type: 'button-icon icon ion-navicon', tap: function (e) { $scope.sideMenuController.toggleLeft(); } } ]; $scope.rightButtons = []; }) .controller('SquareController', function ($scope, ContributionsService, localStorageService) { $scope.navTitle = "Daily Contribution"; $scope.contributionData = ContributionsService.list({'userId': localStorageService.get("userName")}, function (success) { var result = []; for (var i = 0; i < success.length; i++) { result.push(success[i][1]); } console.log("returning results") $scope.contributionData = result; }); $scope.deviceWidth = window.innerWidth || document.body.clientWidth; $scope.deviceHeight = window.innerHeight || document.body.clientHeight; $scope.leftButtons = [ { type: 'button-icon icon ion-navicon', tap: function (e) { $scope.sideMenuController.toggleLeft(); } } ]; $scope.rightButtons = []; }) .controller('ThreeController', function ($scope) { $scope.navTitle = "Page Three Title"; $scope.leftButtons = [ { type: 'button-icon icon ion-navicon', tap: function (e) { $scope.sideMenuController.toggleLeft(); } } ]; $scope.rightButtons = []; });
import templateUrl from './image.html'; import controller from './image-controller'; export default { name: 'image', url: '/:image', templateUrl, controller, controllerAs: 'image', resolve: { image: ['$http', '$stateParams', function($http, $stateParams){ const config = { method: 'GET', url: 'api/images/'+$stateParams.image, params: {metadata: true} }; return $http(config); }] } };
const mongoose = require('mongoose') let literatureSchema = mongoose.Schema({ category: { type: String, required: true}, name: { type: String, required: true }, description: { type: String }, content: { type: String, required: true }, author: { type: mongoose.Schema.Types.ObjectId, required: true, ref: 'User' }, comments: [{type: mongoose.Schema.Types.ObjectId, ref: 'Comment'}], views: {type: Number}, date: { type: String } }) literatureSchema.method({ prepareDelete: function () { let User = mongoose.model('User') User.findById(this.author).then(user => { "use strict"; if (user) { user.literature.remove(this.id) user.save() } }) let Comment = mongoose.model('Comment') for (let commentId of this.comments) { Comment.findOneAndRemove(commentId).populate('author').then(comment => { "use strict"; if (comment) { let author = comment.author let index = author.comments.indexOf(commentId) let count = 1 author.comments.splice(index, count); author.save() comment.save() } }) } } }) literatureSchema.set('versionKey', false); const Literature = mongoose.model('Literature', literatureSchema) module.exports = Literature
// Saves options to chrome.storage function save_options () { var saveDict = [] var i = 1 $('input').map(function () { var dict = { id: 'scbcc' + i, value: this.value } i++ console.log('save: ', dict) ga('send', 'event', 'setting', 'save', this.value) saveDict.push(dict) }).get() chrome.storage.sync.set({ scbccRegexDict: saveDict }) } // Restores select box and checkbox state using the preferences // stored in chrome.storage. function restore_options () { chrome.storage.sync.get({ scbccRegexDict: [] }, function (items) { $('#field1').attr('value', items.scbccRegexDict[0].value) for (var i = 0; i < items.scbccRegexDict.length; i++) { var value = items.scbccRegexDict[i].value var next = i var addto = '#remove' + next var addRemove = '#field' + (next + 1) next = next + 1 var newIn = '<input autocomplete="off" placeholder="e.g. /this is test/g" id="field' + next + '" name="field' + next + '" type="text" tabindex="1" value=' + value + '>' var newInput = $(newIn) var removeBtn = '<button id="remove' + (next) + '" class="btn btn-danger remove-me" >-</button>' var removeButton = $(removeBtn) $(addto).after(newInput) if (i !== 0) { $(addRemove).after(removeButton) } $('#count').val(next) $('.remove-me').click(function (e) { e.preventDefault() ga('send', 'event', 'setting', 'remove_regex') var fieldNum = this.id.charAt(this.id.length - 1) var fieldID = '#field' + fieldNum $(this).remove() $(fieldID).remove() $('#style').attr('href', 'extra/styles.css') }) } var next = items.scbccRegexDict.length || 1 $('.add-more').click(function (e) { ga('send', 'event', 'setting', 'add_regex') e.preventDefault() var addto = '#remove' + next var addRemove = '#field' + (next + 1) next = next + 1 var newIn = '<input autocomplete="off" placeholder="e.g. /this is test/g" id="field' + next + '" name="field' + next + '" type="text" tabindex="1">' var newInput = $(newIn) var removeBtn = '<button id="remove' + (next) + '" class="btn btn-danger remove-me" >-</button>' var removeButton = $(removeBtn) $(addto).after(newInput) $(addRemove).after(removeButton) $('#count').val(next) $('.remove-me').click(function (e) { e.preventDefault() ga('send', 'event', 'setting', 'remove_regex') var fieldNum = this.id.charAt(this.id.length - 1) var fieldID = '#field' + fieldNum $(this).remove() $(fieldID).remove() $('#style').attr('href', 'extra/styles.css') }) }) }) } document.addEventListener('DOMContentLoaded', restore_options) document.getElementById('save').addEventListener('click', save_options)
'use strict'; module.exports = { colors: { black: '#000000', red: '#D54E53', green: '#B9CA4A', yellow: '#E7C547', blue: '#7AA6DA', magenta: '#C397D8', cyan: '#70C0B1', white: '#EAEAEA', lightBlack: '#969896', lightRed: '#D54E53', lightGreen: '#B9CA4A', lightYellow: '#E7C547', lightBlue: '#7AA6DA', lightMagenta: '#C397D8', lightCyan: '#70C0B1', lightWhite: '#EAEAEA', }, // Default backgroundColor: '#000000', foregroundColor: '#EAEAEA', cursorColor: '#EAEAEA', borderColor: '#171717', // Accent color accentColor: '#7AA6DA', // Other tabTitleColor: 'rgba(255, 255, 255, 0.2)', selectedTabTitleColor: '#EAEAEA', };
/** * @Author: Yingya Zhang <zyy> * @Date: 2016-07-08 11:29:00 * @Email: [email protected] * @Last modified by: zyy * @Last modified time: 2016-07-10 22:18:85 */ import { notexist, isEmpty } from 'type' import { calcHeight, remove, dataset } from 'dom' describe('dom', () => { it('calcHeight', () => { const height = 42 const p = document.createElement('p') p.id = 'calcHeight-' + (+new Date()) p.style.margin = 0 p.style.padding = 0 p.style.lineHeight = height + 'px' p.style.fontSize = '18px' const textNode = document.createTextNode('text') p.appendChild(textNode) const height1 = calcHeight(p) expect(height1).toBe(height) }) it('remove', () => { const domStr = '<div id="divRemove"></div>' document.body.innerHTML += domStr const div = document.getElementById('divRemove') expect(div.parentNode).toEqual(jasmine.anything()) remove(div) expect(notexist(div.parentNode)).toBe(true) }) it('dataset', () => { const domStr = '<div id="divDataset"></div>' document.body.innerHTML += domStr const div = document.getElementById('divDataset') const name = dataset(div, 'name') expect(isEmpty(name)).toBe(true) dataset(div, 'name', 'foo') expect(dataset(div, 'name')).toBe('foo') remove(div) }) // TODO html2node })
/* http://fiidmi.fi/documentation/customer_order_history */ module.exports = { "bonus": { "type": "object", "properties": { "session_id": { "type": "string", "minLength": 2, "maxLength": 50 }, "restaurant_id": { "type": "string", "minLength": 1, "maxLength": 50 } }, "required": ["session_id", "restaurant_id"] }, "po_credit": { "type": "object", "properties": { "session_id": { "type": "string", "minLength": 2, "maxLength": 50 } }, "required": ["session_id", "order_id"] } };
export function Fragment(props, ...children) { return collect(children); } const ATTR_PROPS = '_props'; function collect(children) { const ch = []; const push = (c) => { if (c !== null && c !== undefined && c !== '' && c !== false) { ch.push((typeof c === 'function' || typeof c === 'object') ? c : `${c}`); } }; children && children.forEach(c => { if (Array.isArray(c)) { c.forEach(i => push(i)); } else { push(c); } }); return ch; } export function createElement(tag, props, ...children) { const ch = collect(children); if (typeof tag === 'string') return { tag, props, children: ch }; else if (Array.isArray(tag)) return tag; // JSX fragments - babel else if (tag === undefined && children) return ch; // JSX fragments - typescript else if (Object.getPrototypeOf(tag).__isAppRunComponent) return { tag, props, children: ch }; // createComponent(tag, { ...props, children }); else if (typeof tag === 'function') return tag(props, ch); else throw new Error(`Unknown tag in vdom ${tag}`); } ; const keyCache = new WeakMap(); export const updateElement = render; export function render(element, nodes, parent = {}) { // console.log('render', element, node); // tslint:disable-next-line if (nodes == null || nodes === false) return; nodes = createComponent(nodes, parent); const isSvg = (element === null || element === void 0 ? void 0 : element.nodeName) === "SVG"; if (!element) return; if (Array.isArray(nodes)) { updateChildren(element, nodes, isSvg); } else { updateChildren(element, [nodes], isSvg); } } function same(el, node) { // if (!el || !node) return false; const key1 = el.nodeName; const key2 = `${node.tag || ''}`; return key1.toUpperCase() === key2.toUpperCase(); } function update(element, node, isSvg) { if (node['_op'] === 3) return; // console.assert(!!element); isSvg = isSvg || node.tag === "svg"; if (!same(element, node)) { element.parentNode.replaceChild(create(node, isSvg), element); return; } !(node['_op'] & 2) && updateChildren(element, node.children, isSvg); !(node['_op'] & 1) && updateProps(element, node.props, isSvg); } function updateChildren(element, children, isSvg) { var _a; const old_len = ((_a = element.childNodes) === null || _a === void 0 ? void 0 : _a.length) || 0; const new_len = (children === null || children === void 0 ? void 0 : children.length) || 0; const len = Math.min(old_len, new_len); for (let i = 0; i < len; i++) { const child = children[i]; if (child['_op'] === 3) continue; const el = element.childNodes[i]; if (typeof child === 'string') { if (el.textContent !== child) { if (el.nodeType === 3) { el.nodeValue = child; } else { element.replaceChild(createText(child), el); } } } else if (child instanceof HTMLElement || child instanceof SVGElement) { element.insertBefore(child, el); } else { const key = child.props && child.props['key']; if (key) { if (el.key === key) { update(element.childNodes[i], child, isSvg); } else { // console.log(el.key, key); const old = keyCache[key]; if (old) { const temp = old.nextSibling; element.insertBefore(old, el); temp ? element.insertBefore(el, temp) : element.appendChild(el); update(element.childNodes[i], child, isSvg); } else { element.replaceChild(create(child, isSvg), el); } } } else { update(element.childNodes[i], child, isSvg); } } } let n = element.childNodes.length; while (n > len) { element.removeChild(element.lastChild); n--; } if (new_len > len) { const d = document.createDocumentFragment(); for (let i = len; i < children.length; i++) { d.appendChild(create(children[i], isSvg)); } element.appendChild(d); } } function createText(node) { if ((node === null || node === void 0 ? void 0 : node.indexOf('_html:')) === 0) { // ? const div = document.createElement('div'); div.insertAdjacentHTML('afterbegin', node.substring(6)); return div; } else { return document.createTextNode(node !== null && node !== void 0 ? node : ''); } } function create(node, isSvg) { // console.assert(node !== null && node !== undefined); if ((node instanceof HTMLElement) || (node instanceof SVGElement)) return node; if (typeof node === "string") return createText(node); if (!node.tag || (typeof node.tag === 'function')) return createText(JSON.stringify(node)); isSvg = isSvg || node.tag === "svg"; const element = isSvg ? document.createElementNS("http://www.w3.org/2000/svg", node.tag) : document.createElement(node.tag); updateProps(element, node.props, isSvg); if (node.children) node.children.forEach(child => element.appendChild(create(child, isSvg))); return element; } function mergeProps(oldProps, newProps) { newProps['class'] = newProps['class'] || newProps['className']; delete newProps['className']; const props = {}; if (oldProps) Object.keys(oldProps).forEach(p => props[p] = null); if (newProps) Object.keys(newProps).forEach(p => props[p] = newProps[p]); return props; } export function updateProps(element, props, isSvg) { // console.assert(!!element); const cached = element[ATTR_PROPS] || {}; props = mergeProps(cached, props || {}); element[ATTR_PROPS] = props; for (const name in props) { const value = props[name]; // if (cached[name] === value) continue; // console.log('updateProps', name, value); if (name.startsWith('data-')) { const dname = name.substring(5); const cname = dname.replace(/-(\w)/g, (match) => match[1].toUpperCase()); if (element.dataset[cname] !== value) { if (value || value === "") element.dataset[cname] = value; else delete element.dataset[cname]; } } else if (name === 'style') { if (element.style.cssText) element.style.cssText = ''; if (typeof value === 'string') element.style.cssText = value; else { for (const s in value) { if (element.style[s] !== value[s]) element.style[s] = value[s]; } } } else if (name.startsWith('xlink')) { const xname = name.replace('xlink', '').toLowerCase(); if (value == null || value === false) { element.removeAttributeNS('http://www.w3.org/1999/xlink', xname); } else { element.setAttributeNS('http://www.w3.org/1999/xlink', xname, value); } } else if (name.startsWith('on')) { if (!value || typeof value === 'function') { element[name] = value; } else if (typeof value === 'string') { if (value) element.setAttribute(name, value); else element.removeAttribute(name); } } else if (/^id$|^class$|^list$|^readonly$|^contenteditable$|^role|-/g.test(name) || isSvg) { if (element.getAttribute(name) !== value) { if (value) element.setAttribute(name, value); else element.removeAttribute(name); } } else if (element[name] !== value) { element[name] = value; } if (name === 'key' && value) keyCache[value] = element; } if (props && typeof props['ref'] === 'function') { window.requestAnimationFrame(() => props['ref'](element)); } } function render_component(node, parent, idx) { const { tag, props, children } = node; let key = `_${idx}`; let id = props && props['id']; if (!id) id = `_${idx}${Date.now()}`; else key = id; let asTag = 'section'; if (props && props['as']) { asTag = props['as']; delete props['as']; } if (!parent.__componentCache) parent.__componentCache = {}; let component = parent.__componentCache[key]; if (!component || !(component instanceof tag) || !component.element) { const element = document.createElement(asTag); component = parent.__componentCache[key] = new tag(Object.assign(Object.assign({}, props), { children })).start(element); } if (component.mounted) { const new_state = component.mounted(props, children, component.state); (typeof new_state !== 'undefined') && component.setState(new_state); } updateProps(component.element, props, false); return component.element; } function createComponent(node, parent, idx = 0) { var _a; if (typeof node === 'string') return node; if (Array.isArray(node)) return node.map(child => createComponent(child, parent, idx++)); let vdom = node; if (node && typeof node.tag === 'function' && Object.getPrototypeOf(node.tag).__isAppRunComponent) { vdom = render_component(node, parent, idx); } if (vdom && Array.isArray(vdom.children)) { const new_parent = (_a = vdom.props) === null || _a === void 0 ? void 0 : _a._component; if (new_parent) { let i = 0; vdom.children = vdom.children.map(child => createComponent(child, new_parent, i++)); } else { vdom.children = vdom.children.map(child => createComponent(child, parent, idx++)); } } return vdom; } //# sourceMappingURL=vdom-my.js.map
var ItineraryWalkStep = require('./itinerary-walk-step') var Backbone = window.Backbone var ItineraryWalkSteps = Backbone.Collection.extend({ model: ItineraryWalkStep }) module.exports = ItineraryWalkSteps
/* * Copyright (c) 2015 by Greg Reimer <[email protected]> * MIT License. See license.txt for more info. */ var stream = require('stream') , util = require('util') , co = require('co') , unresolved = require('./unresolved') // ----------------------------------------------------- function Readable(opts, sender) { stream.Readable.call(this, opts); this._ponySending = unresolved(); var self = this; function output(data, enc) { return self._ponySending.then(function() { if (!self.push(data, enc)) { self._ponySending = unresolved(); } }); } co(sender.bind(this, output)) .then(function() { self.push(null); }) .catch(function(err) { self.emit('error', err); }); } util.inherits(Readable, stream.Readable); Readable.prototype._read = function() { this._ponySending.resolve(); }; // ----------------------------------------------------- module.exports = Readable;
// flow-typed signature: 382f7ff956662b19ae5c130ba0ebece6 // flow-typed version: <<STUB>>/deepclone_v1.0.2/flow_v0.56.0 /** * This is an autogenerated libdef stub for: * * 'deepclone' * * Fill this stub out by replacing all the `any` types. * * Once filled out, we encourage you to share your work with the * community by sending a pull request to: * https://github.com/flowtype/flow-typed */ declare module 'deepclone' { declare module.exports: any; }
'use strict'; describe('E2E testing: Change password', function () { var constants = require('../../../testConstants'); var loginPage = require('../../pages/loginPage'); var header = require('../../pages/pageHeader'); var changePasswordPage = require('../../pages/changePasswordPage'); var expectedCondition = protractor.ExpectedConditions; var CONDITION_TIMEOUT = 3000; var newPassword = '12345678'; it('setup: login as user, go to change password page', function () { loginPage.loginAsUser(); changePasswordPage.get(); }); it('refuses to allow form submission if the confirm input does not match', function () { changePasswordPage.password.sendKeys(newPassword); changePasswordPage.confirm.sendKeys('blah12345'); expect(changePasswordPage.submitButton.isEnabled()).toBeFalsy(); changePasswordPage.password.clear(); changePasswordPage.confirm.clear(); }); it('allows form submission if the confirm input matches', function () { changePasswordPage.password.sendKeys(newPassword); changePasswordPage.confirm.sendKeys(newPassword); expect(changePasswordPage.submitButton.isEnabled()).toBeTruthy(); changePasswordPage.password.clear(); changePasswordPage.confirm.clear(); }); /* cant test this yet because I don't know how to test for HTML 5 form validation - cjh 2014-06 it('should not allow a password less than 7 characters', function() { var shortPassword = '12345'; changePasswordPage.password.sendKeys(shortPassword); changePasswordPage.confirm.sendKeys(shortPassword); expect(changePasswordPage.submitButton.isEnabled()).toBe(false); changePasswordPage.password.clear(); changePasswordPage.confirm.clear(); }); */ it('can successfully changes user\'s password after form submission', function () { changePasswordPage.password.sendKeys(newPassword); changePasswordPage.confirm.sendKeys(newPassword); browser.wait(expectedCondition.visibilityOf(changePasswordPage.passwordMatchImage), CONDITION_TIMEOUT); browser.wait(expectedCondition.elementToBeClickable(changePasswordPage.submitButton), CONDITION_TIMEOUT); changePasswordPage.submitButton.click(); expect(changePasswordPage.noticeList.count()).toBe(1); expect(changePasswordPage.noticeList.first().getText()).toContain('Password Updated'); loginPage.logout(); loginPage.login(constants.memberUsername, newPassword); browser.wait(expectedCondition.visibilityOf(header.myProjects.button), CONDITION_TIMEOUT); expect(header.myProjects.button.isDisplayed()).toBe(true); // reset password back to original changePasswordPage.get(); changePasswordPage.password.sendKeys(constants.memberPassword); changePasswordPage.confirm.sendKeys(constants.memberPassword); browser.wait(expectedCondition.visibilityOf(changePasswordPage.passwordMatchImage), CONDITION_TIMEOUT); browser.wait(expectedCondition.elementToBeClickable(changePasswordPage.submitButton), CONDITION_TIMEOUT); changePasswordPage.submitButton.click(); }); });
/** * The MIT License (MIT) * * Copyright (c) 2014-2022 Mickael Jeanroy * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import {isNumber} from './is-number.js'; /** * Check that a given value is a falsy value. * * @param {*} a Value to check. * @return {boolean} `true` if parameter is a falsy value. */ export function isFiniteNumber(a) { return isNumber(a) && isFinite(a); }
/** * Created by TC on 2016/10/10. */ import React, { Component, } from 'react' import { Image, View, ToastAndroid, ActivityIndicator, } from 'react-native' import PixelRatio from "react-native/Libraries/Utilities/PixelRatio"; class GirlComponent extends Component { constructor(props) { super(props); this.state = { imgUrl: '' } } loadImage() { this.setState({imgUrl: ''}); this.getImage(); } componentWillMount() { this.getImage(); } getImage() { fetch('http://gank.io/api/data/福利/100/1')//异步请求图片 .then((response) => { return response.json(); }) .then((responseJson) => { if (responseJson.results) { const index = Math.ceil(Math.random() * 100 - 1);//随机取一张福利图 this.setState({imgUrl: responseJson.results[index].url}); } }).catch((error) => console.error(error)) .done(); } render() { if (this.state.imgUrl.length == 0) { return ( <View style={ {flex: 1, flexDirection: 'row', justifyContent: 'center', alignItems: 'center'}}> <ActivityIndicator size='large' color='#00BCD4'/> </View> ); } else { return ( <View style={{flexDirection: 'column', flex: 1}}> <Image source={{uri: this.state.imgUrl}} style={{width: 200 * PixelRatio.get(), height: 200 * PixelRatio.get()}}/> </View> ); } } } export default GirlComponent;
export * from '../common'; export NodeBundle from './NodeBundle'; export CommonJsResolver from './CommonJsResolver';
/*! * maptalks.snapto v0.1.11 * LICENSE : MIT * (c) 2016-2018 maptalks.org */ /*! * requires maptalks@^0.33.1 */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('maptalks')) : typeof define === 'function' && define.amd ? define(['exports', 'maptalks'], factory) : (factory((global.maptalks = global.maptalks || {}),global.maptalks)); }(this, (function (exports,maptalks) { 'use strict'; var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; function createCommonjsModule(fn, module) { return module = { exports: {} }, fn(module, module.exports), module.exports; } var quickselect$1 = createCommonjsModule(function (module, exports) { (function (global, factory) { module.exports = factory(); })(commonjsGlobal, function () { 'use strict'; function quickselect(arr, k, left, right, compare) { quickselectStep(arr, k, left || 0, right || arr.length - 1, compare || defaultCompare); } function quickselectStep(arr, k, left, right, compare) { while (right > left) { if (right - left > 600) { var n = right - left + 1; var m = k - left + 1; var z = Math.log(n); var s = 0.5 * Math.exp(2 * z / 3); var sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1); var newLeft = Math.max(left, Math.floor(k - m * s / n + sd)); var newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd)); quickselectStep(arr, k, newLeft, newRight, compare); } var t = arr[k]; var i = left; var j = right; swap(arr, left, k); if (compare(arr[right], t) > 0) swap(arr, left, right); while (i < j) { swap(arr, i, j); i++; j--; while (compare(arr[i], t) < 0) { i++; }while (compare(arr[j], t) > 0) { j--; } } if (compare(arr[left], t) === 0) swap(arr, left, j);else { j++; swap(arr, j, right); } if (j <= k) left = j + 1; if (k <= j) right = j - 1; } } function swap(arr, i, j) { var tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; } function defaultCompare(a, b) { return a < b ? -1 : a > b ? 1 : 0; } return quickselect; }); }); var index$1 = rbush$2; var default_1 = rbush$2; var quickselect = quickselect$1; function rbush$2(maxEntries, format) { if (!(this instanceof rbush$2)) return new rbush$2(maxEntries, format); // max entries in a node is 9 by default; min node fill is 40% for best performance this._maxEntries = Math.max(4, maxEntries || 9); this._minEntries = Math.max(2, Math.ceil(this._maxEntries * 0.4)); if (format) { this._initFormat(format); } this.clear(); } rbush$2.prototype = { all: function all() { return this._all(this.data, []); }, search: function search(bbox) { var node = this.data, result = [], toBBox = this.toBBox; if (!intersects(bbox, node)) return result; var nodesToSearch = [], i, len, child, childBBox; while (node) { for (i = 0, len = node.children.length; i < len; i++) { child = node.children[i]; childBBox = node.leaf ? toBBox(child) : child; if (intersects(bbox, childBBox)) { if (node.leaf) result.push(child);else if (contains(bbox, childBBox)) this._all(child, result);else nodesToSearch.push(child); } } node = nodesToSearch.pop(); } return result; }, collides: function collides(bbox) { var node = this.data, toBBox = this.toBBox; if (!intersects(bbox, node)) return false; var nodesToSearch = [], i, len, child, childBBox; while (node) { for (i = 0, len = node.children.length; i < len; i++) { child = node.children[i]; childBBox = node.leaf ? toBBox(child) : child; if (intersects(bbox, childBBox)) { if (node.leaf || contains(bbox, childBBox)) return true; nodesToSearch.push(child); } } node = nodesToSearch.pop(); } return false; }, load: function load(data) { if (!(data && data.length)) return this; if (data.length < this._minEntries) { for (var i = 0, len = data.length; i < len; i++) { this.insert(data[i]); } return this; } // recursively build the tree with the given data from scratch using OMT algorithm var node = this._build(data.slice(), 0, data.length - 1, 0); if (!this.data.children.length) { // save as is if tree is empty this.data = node; } else if (this.data.height === node.height) { // split root if trees have the same height this._splitRoot(this.data, node); } else { if (this.data.height < node.height) { // swap trees if inserted one is bigger var tmpNode = this.data; this.data = node; node = tmpNode; } // insert the small tree into the large tree at appropriate level this._insert(node, this.data.height - node.height - 1, true); } return this; }, insert: function insert(item) { if (item) this._insert(item, this.data.height - 1); return this; }, clear: function clear() { this.data = createNode([]); return this; }, remove: function remove(item, equalsFn) { if (!item) return this; var node = this.data, bbox = this.toBBox(item), path = [], indexes = [], i, parent, index, goingUp; // depth-first iterative tree traversal while (node || path.length) { if (!node) { // go up node = path.pop(); parent = path[path.length - 1]; i = indexes.pop(); goingUp = true; } if (node.leaf) { // check current node index = findItem(item, node.children, equalsFn); if (index !== -1) { // item found, remove the item and condense tree upwards node.children.splice(index, 1); path.push(node); this._condense(path); return this; } } if (!goingUp && !node.leaf && contains(node, bbox)) { // go down path.push(node); indexes.push(i); i = 0; parent = node; node = node.children[0]; } else if (parent) { // go right i++; node = parent.children[i]; goingUp = false; } else node = null; // nothing found } return this; }, toBBox: function toBBox(item) { return item; }, compareMinX: compareNodeMinX, compareMinY: compareNodeMinY, toJSON: function toJSON() { return this.data; }, fromJSON: function fromJSON(data) { this.data = data; return this; }, _all: function _all(node, result) { var nodesToSearch = []; while (node) { if (node.leaf) result.push.apply(result, node.children);else nodesToSearch.push.apply(nodesToSearch, node.children); node = nodesToSearch.pop(); } return result; }, _build: function _build(items, left, right, height) { var N = right - left + 1, M = this._maxEntries, node; if (N <= M) { // reached leaf level; return leaf node = createNode(items.slice(left, right + 1)); calcBBox(node, this.toBBox); return node; } if (!height) { // target height of the bulk-loaded tree height = Math.ceil(Math.log(N) / Math.log(M)); // target number of root entries to maximize storage utilization M = Math.ceil(N / Math.pow(M, height - 1)); } node = createNode([]); node.leaf = false; node.height = height; // split the items into M mostly square tiles var N2 = Math.ceil(N / M), N1 = N2 * Math.ceil(Math.sqrt(M)), i, j, right2, right3; multiSelect(items, left, right, N1, this.compareMinX); for (i = left; i <= right; i += N1) { right2 = Math.min(i + N1 - 1, right); multiSelect(items, i, right2, N2, this.compareMinY); for (j = i; j <= right2; j += N2) { right3 = Math.min(j + N2 - 1, right2); // pack each entry recursively node.children.push(this._build(items, j, right3, height - 1)); } } calcBBox(node, this.toBBox); return node; }, _chooseSubtree: function _chooseSubtree(bbox, node, level, path) { var i, len, child, targetNode, area, enlargement, minArea, minEnlargement; while (true) { path.push(node); if (node.leaf || path.length - 1 === level) break; minArea = minEnlargement = Infinity; for (i = 0, len = node.children.length; i < len; i++) { child = node.children[i]; area = bboxArea(child); enlargement = enlargedArea(bbox, child) - area; // choose entry with the least area enlargement if (enlargement < minEnlargement) { minEnlargement = enlargement; minArea = area < minArea ? area : minArea; targetNode = child; } else if (enlargement === minEnlargement) { // otherwise choose one with the smallest area if (area < minArea) { minArea = area; targetNode = child; } } } node = targetNode || node.children[0]; } return node; }, _insert: function _insert(item, level, isNode) { var toBBox = this.toBBox, bbox = isNode ? item : toBBox(item), insertPath = []; // find the best node for accommodating the item, saving all nodes along the path too var node = this._chooseSubtree(bbox, this.data, level, insertPath); // put the item into the node node.children.push(item); extend(node, bbox); // split on node overflow; propagate upwards if necessary while (level >= 0) { if (insertPath[level].children.length > this._maxEntries) { this._split(insertPath, level); level--; } else break; } // adjust bboxes along the insertion path this._adjustParentBBoxes(bbox, insertPath, level); }, // split overflowed node into two _split: function _split(insertPath, level) { var node = insertPath[level], M = node.children.length, m = this._minEntries; this._chooseSplitAxis(node, m, M); var splitIndex = this._chooseSplitIndex(node, m, M); var newNode = createNode(node.children.splice(splitIndex, node.children.length - splitIndex)); newNode.height = node.height; newNode.leaf = node.leaf; calcBBox(node, this.toBBox); calcBBox(newNode, this.toBBox); if (level) insertPath[level - 1].children.push(newNode);else this._splitRoot(node, newNode); }, _splitRoot: function _splitRoot(node, newNode) { // split root node this.data = createNode([node, newNode]); this.data.height = node.height + 1; this.data.leaf = false; calcBBox(this.data, this.toBBox); }, _chooseSplitIndex: function _chooseSplitIndex(node, m, M) { var i, bbox1, bbox2, overlap, area, minOverlap, minArea, index; minOverlap = minArea = Infinity; for (i = m; i <= M - m; i++) { bbox1 = distBBox(node, 0, i, this.toBBox); bbox2 = distBBox(node, i, M, this.toBBox); overlap = intersectionArea(bbox1, bbox2); area = bboxArea(bbox1) + bboxArea(bbox2); // choose distribution with minimum overlap if (overlap < minOverlap) { minOverlap = overlap; index = i; minArea = area < minArea ? area : minArea; } else if (overlap === minOverlap) { // otherwise choose distribution with minimum area if (area < minArea) { minArea = area; index = i; } } } return index; }, // sorts node children by the best axis for split _chooseSplitAxis: function _chooseSplitAxis(node, m, M) { var compareMinX = node.leaf ? this.compareMinX : compareNodeMinX, compareMinY = node.leaf ? this.compareMinY : compareNodeMinY, xMargin = this._allDistMargin(node, m, M, compareMinX), yMargin = this._allDistMargin(node, m, M, compareMinY); // if total distributions margin value is minimal for x, sort by minX, // otherwise it's already sorted by minY if (xMargin < yMargin) node.children.sort(compareMinX); }, // total margin of all possible split distributions where each node is at least m full _allDistMargin: function _allDistMargin(node, m, M, compare) { node.children.sort(compare); var toBBox = this.toBBox, leftBBox = distBBox(node, 0, m, toBBox), rightBBox = distBBox(node, M - m, M, toBBox), margin = bboxMargin(leftBBox) + bboxMargin(rightBBox), i, child; for (i = m; i < M - m; i++) { child = node.children[i]; extend(leftBBox, node.leaf ? toBBox(child) : child); margin += bboxMargin(leftBBox); } for (i = M - m - 1; i >= m; i--) { child = node.children[i]; extend(rightBBox, node.leaf ? toBBox(child) : child); margin += bboxMargin(rightBBox); } return margin; }, _adjustParentBBoxes: function _adjustParentBBoxes(bbox, path, level) { // adjust bboxes along the given tree path for (var i = level; i >= 0; i--) { extend(path[i], bbox); } }, _condense: function _condense(path) { // go through the path, removing empty nodes and updating bboxes for (var i = path.length - 1, siblings; i >= 0; i--) { if (path[i].children.length === 0) { if (i > 0) { siblings = path[i - 1].children; siblings.splice(siblings.indexOf(path[i]), 1); } else this.clear(); } else calcBBox(path[i], this.toBBox); } }, _initFormat: function _initFormat(format) { // data format (minX, minY, maxX, maxY accessors) // uses eval-type function compilation instead of just accepting a toBBox function // because the algorithms are very sensitive to sorting functions performance, // so they should be dead simple and without inner calls var compareArr = ['return a', ' - b', ';']; this.compareMinX = new Function('a', 'b', compareArr.join(format[0])); this.compareMinY = new Function('a', 'b', compareArr.join(format[1])); this.toBBox = new Function('a', 'return {minX: a' + format[0] + ', minY: a' + format[1] + ', maxX: a' + format[2] + ', maxY: a' + format[3] + '};'); } }; function findItem(item, items, equalsFn) { if (!equalsFn) return items.indexOf(item); for (var i = 0; i < items.length; i++) { if (equalsFn(item, items[i])) return i; } return -1; } // calculate node's bbox from bboxes of its children function calcBBox(node, toBBox) { distBBox(node, 0, node.children.length, toBBox, node); } // min bounding rectangle of node children from k to p-1 function distBBox(node, k, p, toBBox, destNode) { if (!destNode) destNode = createNode(null); destNode.minX = Infinity; destNode.minY = Infinity; destNode.maxX = -Infinity; destNode.maxY = -Infinity; for (var i = k, child; i < p; i++) { child = node.children[i]; extend(destNode, node.leaf ? toBBox(child) : child); } return destNode; } function extend(a, b) { a.minX = Math.min(a.minX, b.minX); a.minY = Math.min(a.minY, b.minY); a.maxX = Math.max(a.maxX, b.maxX); a.maxY = Math.max(a.maxY, b.maxY); return a; } function compareNodeMinX(a, b) { return a.minX - b.minX; } function compareNodeMinY(a, b) { return a.minY - b.minY; } function bboxArea(a) { return (a.maxX - a.minX) * (a.maxY - a.minY); } function bboxMargin(a) { return a.maxX - a.minX + (a.maxY - a.minY); } function enlargedArea(a, b) { return (Math.max(b.maxX, a.maxX) - Math.min(b.minX, a.minX)) * (Math.max(b.maxY, a.maxY) - Math.min(b.minY, a.minY)); } function intersectionArea(a, b) { var minX = Math.max(a.minX, b.minX), minY = Math.max(a.minY, b.minY), maxX = Math.min(a.maxX, b.maxX), maxY = Math.min(a.maxY, b.maxY); return Math.max(0, maxX - minX) * Math.max(0, maxY - minY); } function contains(a, b) { return a.minX <= b.minX && a.minY <= b.minY && b.maxX <= a.maxX && b.maxY <= a.maxY; } function intersects(a, b) { return b.minX <= a.maxX && b.minY <= a.maxY && b.maxX >= a.minX && b.maxY >= a.minY; } function createNode(children) { return { children: children, height: 1, leaf: true, minX: Infinity, minY: Infinity, maxX: -Infinity, maxY: -Infinity }; } // sort an array so that items come in groups of n unsorted items, with groups sorted between each other; // combines selection algorithm with binary divide & conquer approach function multiSelect(arr, left, right, n, compare) { var stack = [left, right], mid; while (stack.length) { right = stack.pop(); left = stack.pop(); if (right - left <= n) continue; mid = left + Math.ceil((right - left) / n / 2) * n; quickselect(arr, mid, left, right, compare); stack.push(left, mid, mid, right); } } index$1.default = default_1; /** * GeoJSON BBox * * @private * @typedef {[number, number, number, number]} BBox */ /** * GeoJSON Id * * @private * @typedef {(number|string)} Id */ /** * GeoJSON FeatureCollection * * @private * @typedef {Object} FeatureCollection * @property {string} type * @property {?Id} id * @property {?BBox} bbox * @property {Feature[]} features */ /** * GeoJSON Feature * * @private * @typedef {Object} Feature * @property {string} type * @property {?Id} id * @property {?BBox} bbox * @property {*} properties * @property {Geometry} geometry */ /** * GeoJSON Geometry * * @private * @typedef {Object} Geometry * @property {string} type * @property {any[]} coordinates */ /** * Callback for coordEach * * @callback coordEachCallback * @param {Array<number>} currentCoord The current coordinate being processed. * @param {number} coordIndex The current index of the coordinate being processed. * Starts at index 0. * @param {number} featureIndex The current index of the feature being processed. * @param {number} featureSubIndex The current subIndex of the feature being processed. */ /** * Iterate over coordinates in any GeoJSON object, similar to Array.forEach() * * @name coordEach * @param {(FeatureCollection|Feature|Geometry)} geojson any GeoJSON object * @param {Function} callback a method that takes (currentCoord, coordIndex, featureIndex, featureSubIndex) * @param {boolean} [excludeWrapCoord=false] whether or not to include the final coordinate of LinearRings that wraps the ring in its iteration. * @example * var features = turf.featureCollection([ * turf.point([26, 37], {"foo": "bar"}), * turf.point([36, 53], {"hello": "world"}) * ]); * * turf.coordEach(features, function (currentCoord, coordIndex, featureIndex, featureSubIndex) { * //=currentCoord * //=coordIndex * //=featureIndex * //=featureSubIndex * }); */ function coordEach$1(geojson, callback, excludeWrapCoord) { // Handles null Geometry -- Skips this GeoJSON if (geojson === null) return; var featureIndex, geometryIndex, j, k, l, geometry, stopG, coords, geometryMaybeCollection, wrapShrink = 0, coordIndex = 0, isGeometryCollection, type = geojson.type, isFeatureCollection = type === 'FeatureCollection', isFeature = type === 'Feature', stop = isFeatureCollection ? geojson.features.length : 1; // This logic may look a little weird. The reason why it is that way // is because it's trying to be fast. GeoJSON supports multiple kinds // of objects at its root: FeatureCollection, Features, Geometries. // This function has the responsibility of handling all of them, and that // means that some of the `for` loops you see below actually just don't apply // to certain inputs. For instance, if you give this just a // Point geometry, then both loops are short-circuited and all we do // is gradually rename the input until it's called 'geometry'. // // This also aims to allocate as few resources as possible: just a // few numbers and booleans, rather than any temporary arrays as would // be required with the normalization approach. for (featureIndex = 0; featureIndex < stop; featureIndex++) { geometryMaybeCollection = isFeatureCollection ? geojson.features[featureIndex].geometry : isFeature ? geojson.geometry : geojson; isGeometryCollection = geometryMaybeCollection ? geometryMaybeCollection.type === 'GeometryCollection' : false; stopG = isGeometryCollection ? geometryMaybeCollection.geometries.length : 1; for (geometryIndex = 0; geometryIndex < stopG; geometryIndex++) { var featureSubIndex = 0; geometry = isGeometryCollection ? geometryMaybeCollection.geometries[geometryIndex] : geometryMaybeCollection; // Handles null Geometry -- Skips this geometry if (geometry === null) continue; coords = geometry.coordinates; var geomType = geometry.type; wrapShrink = excludeWrapCoord && (geomType === 'Polygon' || geomType === 'MultiPolygon') ? 1 : 0; switch (geomType) { case null: break; case 'Point': callback(coords, coordIndex, featureIndex, featureSubIndex); coordIndex++; featureSubIndex++; break; case 'LineString': case 'MultiPoint': for (j = 0; j < coords.length; j++) { callback(coords[j], coordIndex, featureIndex, featureSubIndex); coordIndex++; if (geomType === 'MultiPoint') featureSubIndex++; } if (geomType === 'LineString') featureSubIndex++; break; case 'Polygon': case 'MultiLineString': for (j = 0; j < coords.length; j++) { for (k = 0; k < coords[j].length - wrapShrink; k++) { callback(coords[j][k], coordIndex, featureIndex, featureSubIndex); coordIndex++; } if (geomType === 'MultiLineString') featureSubIndex++; } if (geomType === 'Polygon') featureSubIndex++; break; case 'MultiPolygon': for (j = 0; j < coords.length; j++) { for (k = 0; k < coords[j].length; k++) { for (l = 0; l < coords[j][k].length - wrapShrink; l++) { callback(coords[j][k][l], coordIndex, featureIndex, featureSubIndex); coordIndex++; } }featureSubIndex++; } break; case 'GeometryCollection': for (j = 0; j < geometry.geometries.length; j++) { coordEach$1(geometry.geometries[j], callback, excludeWrapCoord); }break; default: throw new Error('Unknown Geometry Type'); } } } } /** * Callback for coordReduce * * The first time the callback function is called, the values provided as arguments depend * on whether the reduce method has an initialValue argument. * * If an initialValue is provided to the reduce method: * - The previousValue argument is initialValue. * - The currentValue argument is the value of the first element present in the array. * * If an initialValue is not provided: * - The previousValue argument is the value of the first element present in the array. * - The currentValue argument is the value of the second element present in the array. * * @callback coordReduceCallback * @param {*} previousValue The accumulated value previously returned in the last invocation * of the callback, or initialValue, if supplied. * @param {Array<number>} currentCoord The current coordinate being processed. * @param {number} coordIndex The current index of the coordinate being processed. * Starts at index 0, if an initialValue is provided, and at index 1 otherwise. * @param {number} featureIndex The current index of the feature being processed. * @param {number} featureSubIndex The current subIndex of the feature being processed. */ /** * Reduce coordinates in any GeoJSON object, similar to Array.reduce() * * @name coordReduce * @param {FeatureCollection|Geometry|Feature} geojson any GeoJSON object * @param {Function} callback a method that takes (previousValue, currentCoord, coordIndex) * @param {*} [initialValue] Value to use as the first argument to the first call of the callback. * @param {boolean} [excludeWrapCoord=false] whether or not to include the final coordinate of LinearRings that wraps the ring in its iteration. * @returns {*} The value that results from the reduction. * @example * var features = turf.featureCollection([ * turf.point([26, 37], {"foo": "bar"}), * turf.point([36, 53], {"hello": "world"}) * ]); * * turf.coordReduce(features, function (previousValue, currentCoord, coordIndex, featureIndex, featureSubIndex) { * //=previousValue * //=currentCoord * //=coordIndex * //=featureIndex * //=featureSubIndex * return currentCoord; * }); */ function coordReduce(geojson, callback, initialValue, excludeWrapCoord) { var previousValue = initialValue; coordEach$1(geojson, function (currentCoord, coordIndex, featureIndex, featureSubIndex) { if (coordIndex === 0 && initialValue === undefined) previousValue = currentCoord;else previousValue = callback(previousValue, currentCoord, coordIndex, featureIndex, featureSubIndex); }, excludeWrapCoord); return previousValue; } /** * Callback for propEach * * @callback propEachCallback * @param {Object} currentProperties The current properties being processed. * @param {number} featureIndex The index of the current element being processed in the * array.Starts at index 0, if an initialValue is provided, and at index 1 otherwise. */ /** * Iterate over properties in any GeoJSON object, similar to Array.forEach() * * @name propEach * @param {(FeatureCollection|Feature)} geojson any GeoJSON object * @param {Function} callback a method that takes (currentProperties, featureIndex) * @example * var features = turf.featureCollection([ * turf.point([26, 37], {foo: 'bar'}), * turf.point([36, 53], {hello: 'world'}) * ]); * * turf.propEach(features, function (currentProperties, featureIndex) { * //=currentProperties * //=featureIndex * }); */ function propEach(geojson, callback) { var i; switch (geojson.type) { case 'FeatureCollection': for (i = 0; i < geojson.features.length; i++) { callback(geojson.features[i].properties, i); } break; case 'Feature': callback(geojson.properties, 0); break; } } /** * Callback for propReduce * * The first time the callback function is called, the values provided as arguments depend * on whether the reduce method has an initialValue argument. * * If an initialValue is provided to the reduce method: * - The previousValue argument is initialValue. * - The currentValue argument is the value of the first element present in the array. * * If an initialValue is not provided: * - The previousValue argument is the value of the first element present in the array. * - The currentValue argument is the value of the second element present in the array. * * @callback propReduceCallback * @param {*} previousValue The accumulated value previously returned in the last invocation * of the callback, or initialValue, if supplied. * @param {*} currentProperties The current properties being processed. * @param {number} featureIndex The index of the current element being processed in the * array.Starts at index 0, if an initialValue is provided, and at index 1 otherwise. */ /** * Reduce properties in any GeoJSON object into a single value, * similar to how Array.reduce works. However, in this case we lazily run * the reduction, so an array of all properties is unnecessary. * * @name propReduce * @param {(FeatureCollection|Feature)} geojson any GeoJSON object * @param {Function} callback a method that takes (previousValue, currentProperties, featureIndex) * @param {*} [initialValue] Value to use as the first argument to the first call of the callback. * @returns {*} The value that results from the reduction. * @example * var features = turf.featureCollection([ * turf.point([26, 37], {foo: 'bar'}), * turf.point([36, 53], {hello: 'world'}) * ]); * * turf.propReduce(features, function (previousValue, currentProperties, featureIndex) { * //=previousValue * //=currentProperties * //=featureIndex * return currentProperties * }); */ function propReduce(geojson, callback, initialValue) { var previousValue = initialValue; propEach(geojson, function (currentProperties, featureIndex) { if (featureIndex === 0 && initialValue === undefined) previousValue = currentProperties;else previousValue = callback(previousValue, currentProperties, featureIndex); }); return previousValue; } /** * Callback for featureEach * * @callback featureEachCallback * @param {Feature<any>} currentFeature The current feature being processed. * @param {number} featureIndex The index of the current element being processed in the * array.Starts at index 0, if an initialValue is provided, and at index 1 otherwise. */ /** * Iterate over features in any GeoJSON object, similar to * Array.forEach. * * @name featureEach * @param {(FeatureCollection|Feature|Geometry)} geojson any GeoJSON object * @param {Function} callback a method that takes (currentFeature, featureIndex) * @example * var features = turf.featureCollection([ * turf.point([26, 37], {foo: 'bar'}), * turf.point([36, 53], {hello: 'world'}) * ]); * * turf.featureEach(features, function (currentFeature, featureIndex) { * //=currentFeature * //=featureIndex * }); */ function featureEach$1(geojson, callback) { if (geojson.type === 'Feature') { callback(geojson, 0); } else if (geojson.type === 'FeatureCollection') { for (var i = 0; i < geojson.features.length; i++) { callback(geojson.features[i], i); } } } /** * Callback for featureReduce * * The first time the callback function is called, the values provided as arguments depend * on whether the reduce method has an initialValue argument. * * If an initialValue is provided to the reduce method: * - The previousValue argument is initialValue. * - The currentValue argument is the value of the first element present in the array. * * If an initialValue is not provided: * - The previousValue argument is the value of the first element present in the array. * - The currentValue argument is the value of the second element present in the array. * * @callback featureReduceCallback * @param {*} previousValue The accumulated value previously returned in the last invocation * of the callback, or initialValue, if supplied. * @param {Feature} currentFeature The current Feature being processed. * @param {number} featureIndex The index of the current element being processed in the * array.Starts at index 0, if an initialValue is provided, and at index 1 otherwise. */ /** * Reduce features in any GeoJSON object, similar to Array.reduce(). * * @name featureReduce * @param {(FeatureCollection|Feature|Geometry)} geojson any GeoJSON object * @param {Function} callback a method that takes (previousValue, currentFeature, featureIndex) * @param {*} [initialValue] Value to use as the first argument to the first call of the callback. * @returns {*} The value that results from the reduction. * @example * var features = turf.featureCollection([ * turf.point([26, 37], {"foo": "bar"}), * turf.point([36, 53], {"hello": "world"}) * ]); * * turf.featureReduce(features, function (previousValue, currentFeature, featureIndex) { * //=previousValue * //=currentFeature * //=featureIndex * return currentFeature * }); */ function featureReduce(geojson, callback, initialValue) { var previousValue = initialValue; featureEach$1(geojson, function (currentFeature, featureIndex) { if (featureIndex === 0 && initialValue === undefined) previousValue = currentFeature;else previousValue = callback(previousValue, currentFeature, featureIndex); }); return previousValue; } /** * Get all coordinates from any GeoJSON object. * * @name coordAll * @param {(FeatureCollection|Feature|Geometry)} geojson any GeoJSON object * @returns {Array<Array<number>>} coordinate position array * @example * var features = turf.featureCollection([ * turf.point([26, 37], {foo: 'bar'}), * turf.point([36, 53], {hello: 'world'}) * ]); * * var coords = turf.coordAll(features); * //= [[26, 37], [36, 53]] */ function coordAll(geojson) { var coords = []; coordEach$1(geojson, function (coord) { coords.push(coord); }); return coords; } /** * Callback for geomEach * * @callback geomEachCallback * @param {Geometry} currentGeometry The current geometry being processed. * @param {number} currentIndex The index of the current element being processed in the * array. Starts at index 0, if an initialValue is provided, and at index 1 otherwise. * @param {number} currentProperties The current feature properties being processed. */ /** * Iterate over each geometry in any GeoJSON object, similar to Array.forEach() * * @name geomEach * @param {(FeatureCollection|Feature|Geometry)} geojson any GeoJSON object * @param {Function} callback a method that takes (currentGeometry, featureIndex, currentProperties) * @example * var features = turf.featureCollection([ * turf.point([26, 37], {foo: 'bar'}), * turf.point([36, 53], {hello: 'world'}) * ]); * * turf.geomEach(features, function (currentGeometry, featureIndex, currentProperties) { * //=currentGeometry * //=featureIndex * //=currentProperties * }); */ function geomEach(geojson, callback) { var i, j, g, geometry, stopG, geometryMaybeCollection, isGeometryCollection, geometryProperties, featureIndex = 0, isFeatureCollection = geojson.type === 'FeatureCollection', isFeature = geojson.type === 'Feature', stop = isFeatureCollection ? geojson.features.length : 1; // This logic may look a little weird. The reason why it is that way // is because it's trying to be fast. GeoJSON supports multiple kinds // of objects at its root: FeatureCollection, Features, Geometries. // This function has the responsibility of handling all of them, and that // means that some of the `for` loops you see below actually just don't apply // to certain inputs. For instance, if you give this just a // Point geometry, then both loops are short-circuited and all we do // is gradually rename the input until it's called 'geometry'. // // This also aims to allocate as few resources as possible: just a // few numbers and booleans, rather than any temporary arrays as would // be required with the normalization approach. for (i = 0; i < stop; i++) { geometryMaybeCollection = isFeatureCollection ? geojson.features[i].geometry : isFeature ? geojson.geometry : geojson; geometryProperties = isFeatureCollection ? geojson.features[i].properties : isFeature ? geojson.properties : {}; isGeometryCollection = geometryMaybeCollection ? geometryMaybeCollection.type === 'GeometryCollection' : false; stopG = isGeometryCollection ? geometryMaybeCollection.geometries.length : 1; for (g = 0; g < stopG; g++) { geometry = isGeometryCollection ? geometryMaybeCollection.geometries[g] : geometryMaybeCollection; // Handle null Geometry if (geometry === null) { callback(null, featureIndex, geometryProperties); continue; } switch (geometry.type) { case 'Point': case 'LineString': case 'MultiPoint': case 'Polygon': case 'MultiLineString': case 'MultiPolygon': { callback(geometry, featureIndex, geometryProperties); break; } case 'GeometryCollection': { for (j = 0; j < geometry.geometries.length; j++) { callback(geometry.geometries[j], featureIndex, geometryProperties); } break; } default: throw new Error('Unknown Geometry Type'); } } // Only increase `featureIndex` per each feature featureIndex++; } } /** * Callback for geomReduce * * The first time the callback function is called, the values provided as arguments depend * on whether the reduce method has an initialValue argument. * * If an initialValue is provided to the reduce method: * - The previousValue argument is initialValue. * - The currentValue argument is the value of the first element present in the array. * * If an initialValue is not provided: * - The previousValue argument is the value of the first element present in the array. * - The currentValue argument is the value of the second element present in the array. * * @callback geomReduceCallback * @param {*} previousValue The accumulated value previously returned in the last invocation * of the callback, or initialValue, if supplied. * @param {Geometry} currentGeometry The current Feature being processed. * @param {number} currentIndex The index of the current element being processed in the * array.Starts at index 0, if an initialValue is provided, and at index 1 otherwise. * @param {Object} currentProperties The current feature properties being processed. */ /** * Reduce geometry in any GeoJSON object, similar to Array.reduce(). * * @name geomReduce * @param {(FeatureCollection|Feature|Geometry)} geojson any GeoJSON object * @param {Function} callback a method that takes (previousValue, currentGeometry, featureIndex, currentProperties) * @param {*} [initialValue] Value to use as the first argument to the first call of the callback. * @returns {*} The value that results from the reduction. * @example * var features = turf.featureCollection([ * turf.point([26, 37], {foo: 'bar'}), * turf.point([36, 53], {hello: 'world'}) * ]); * * turf.geomReduce(features, function (previousValue, currentGeometry, featureIndex, currentProperties) { * //=previousValue * //=currentGeometry * //=featureIndex * //=currentProperties * return currentGeometry * }); */ function geomReduce(geojson, callback, initialValue) { var previousValue = initialValue; geomEach(geojson, function (currentGeometry, currentIndex, currentProperties) { if (currentIndex === 0 && initialValue === undefined) previousValue = currentGeometry;else previousValue = callback(previousValue, currentGeometry, currentIndex, currentProperties); }); return previousValue; } /** * Callback for flattenEach * * @callback flattenEachCallback * @param {Feature} currentFeature The current flattened feature being processed. * @param {number} featureIndex The index of the current element being processed in the * array. Starts at index 0, if an initialValue is provided, and at index 1 otherwise. * @param {number} featureSubIndex The subindex of the current element being processed in the * array. Starts at index 0 and increases if the flattened feature was a multi-geometry. */ /** * Iterate over flattened features in any GeoJSON object, similar to * Array.forEach. * * @name flattenEach * @param {(FeatureCollection|Feature|Geometry)} geojson any GeoJSON object * @param {Function} callback a method that takes (currentFeature, featureIndex, featureSubIndex) * @example * var features = turf.featureCollection([ * turf.point([26, 37], {foo: 'bar'}), * turf.multiPoint([[40, 30], [36, 53]], {hello: 'world'}) * ]); * * turf.flattenEach(features, function (currentFeature, featureIndex, featureSubIndex) { * //=currentFeature * //=featureIndex * //=featureSubIndex * }); */ function flattenEach(geojson, callback) { geomEach(geojson, function (geometry, featureIndex, properties) { // Callback for single geometry var type = geometry === null ? null : geometry.type; switch (type) { case null: case 'Point': case 'LineString': case 'Polygon': callback(feature(geometry, properties), featureIndex, 0); return; } var geomType; // Callback for multi-geometry switch (type) { case 'MultiPoint': geomType = 'Point'; break; case 'MultiLineString': geomType = 'LineString'; break; case 'MultiPolygon': geomType = 'Polygon'; break; } geometry.coordinates.forEach(function (coordinate, featureSubIndex) { var geom = { type: geomType, coordinates: coordinate }; callback(feature(geom, properties), featureIndex, featureSubIndex); }); }); } /** * Callback for flattenReduce * * The first time the callback function is called, the values provided as arguments depend * on whether the reduce method has an initialValue argument. * * If an initialValue is provided to the reduce method: * - The previousValue argument is initialValue. * - The currentValue argument is the value of the first element present in the array. * * If an initialValue is not provided: * - The previousValue argument is the value of the first element present in the array. * - The currentValue argument is the value of the second element present in the array. * * @callback flattenReduceCallback * @param {*} previousValue The accumulated value previously returned in the last invocation * of the callback, or initialValue, if supplied. * @param {Feature} currentFeature The current Feature being processed. * @param {number} featureIndex The index of the current element being processed in the * array.Starts at index 0, if an initialValue is provided, and at index 1 otherwise. * @param {number} featureSubIndex The subindex of the current element being processed in the * array. Starts at index 0 and increases if the flattened feature was a multi-geometry. */ /** * Reduce flattened features in any GeoJSON object, similar to Array.reduce(). * * @name flattenReduce * @param {(FeatureCollection|Feature|Geometry)} geojson any GeoJSON object * @param {Function} callback a method that takes (previousValue, currentFeature, featureIndex, featureSubIndex) * @param {*} [initialValue] Value to use as the first argument to the first call of the callback. * @returns {*} The value that results from the reduction. * @example * var features = turf.featureCollection([ * turf.point([26, 37], {foo: 'bar'}), * turf.multiPoint([[40, 30], [36, 53]], {hello: 'world'}) * ]); * * turf.flattenReduce(features, function (previousValue, currentFeature, featureIndex, featureSubIndex) { * //=previousValue * //=currentFeature * //=featureIndex * //=featureSubIndex * return currentFeature * }); */ function flattenReduce(geojson, callback, initialValue) { var previousValue = initialValue; flattenEach(geojson, function (currentFeature, featureIndex, featureSubIndex) { if (featureIndex === 0 && featureSubIndex === 0 && initialValue === undefined) previousValue = currentFeature;else previousValue = callback(previousValue, currentFeature, featureIndex, featureSubIndex); }); return previousValue; } /** * Callback for segmentEach * * @callback segmentEachCallback * @param {Feature<LineString>} currentSegment The current segment being processed. * @param {number} featureIndex The featureIndex currently being processed, starts at index 0. * @param {number} featureSubIndex The featureSubIndex currently being processed, starts at index 0. * @param {number} segmentIndex The segmentIndex currently being processed, starts at index 0. * @returns {void} */ /** * Iterate over 2-vertex line segment in any GeoJSON object, similar to Array.forEach() * (Multi)Point geometries do not contain segments therefore they are ignored during this operation. * * @param {(FeatureCollection|Feature|Geometry)} geojson any GeoJSON * @param {Function} callback a method that takes (currentSegment, featureIndex, featureSubIndex) * @returns {void} * @example * var polygon = turf.polygon([[[-50, 5], [-40, -10], [-50, -10], [-40, 5], [-50, 5]]]); * * // Iterate over GeoJSON by 2-vertex segments * turf.segmentEach(polygon, function (currentSegment, featureIndex, featureSubIndex, segmentIndex) { * //= currentSegment * //= featureIndex * //= featureSubIndex * //= segmentIndex * }); * * // Calculate the total number of segments * var total = 0; * turf.segmentEach(polygon, function () { * total++; * }); */ function segmentEach(geojson, callback) { flattenEach(geojson, function (feature, featureIndex, featureSubIndex) { var segmentIndex = 0; // Exclude null Geometries if (!feature.geometry) return; // (Multi)Point geometries do not contain segments therefore they are ignored during this operation. var type = feature.geometry.type; if (type === 'Point' || type === 'MultiPoint') return; // Generate 2-vertex line segments coordReduce(feature, function (previousCoords, currentCoord) { var currentSegment = lineString([previousCoords, currentCoord], feature.properties); callback(currentSegment, featureIndex, featureSubIndex, segmentIndex); segmentIndex++; return currentCoord; }); }); } /** * Callback for segmentReduce * * The first time the callback function is called, the values provided as arguments depend * on whether the reduce method has an initialValue argument. * * If an initialValue is provided to the reduce method: * - The previousValue argument is initialValue. * - The currentValue argument is the value of the first element present in the array. * * If an initialValue is not provided: * - The previousValue argument is the value of the first element present in the array. * - The currentValue argument is the value of the second element present in the array. * * @callback segmentReduceCallback * @param {*} [previousValue] The accumulated value previously returned in the last invocation * of the callback, or initialValue, if supplied. * @param {Feature<LineString>} [currentSegment] The current segment being processed. * @param {number} featureIndex The featureIndex currently being processed, starts at index 0. * @param {number} featureSubIndex The featureSubIndex currently being processed, starts at index 0. * @param {number} segmentIndex The segmentIndex currently being processed, starts at index 0. */ /** * Reduce 2-vertex line segment in any GeoJSON object, similar to Array.reduce() * (Multi)Point geometries do not contain segments therefore they are ignored during this operation. * * @param {(FeatureCollection|Feature|Geometry)} geojson any GeoJSON * @param {Function} callback a method that takes (previousValue, currentSegment, currentIndex) * @param {*} [initialValue] Value to use as the first argument to the first call of the callback. * @returns {void} * @example * var polygon = turf.polygon([[[-50, 5], [-40, -10], [-50, -10], [-40, 5], [-50, 5]]]); * * // Iterate over GeoJSON by 2-vertex segments * turf.segmentReduce(polygon, function (previousSegment, currentSegment, featureIndex, featureSubIndex, segmentIndex) { * //= previousSegment * //= currentSegment * //= featureIndex * //= featureSubIndex * //= segmentInex * return currentSegment * }); * * // Calculate the total number of segments * var initialValue = 0 * var total = turf.segmentReduce(polygon, function (previousValue) { * previousValue++; * return previousValue; * }, initialValue); */ function segmentReduce(geojson, callback, initialValue) { var previousValue = initialValue; var started = false; segmentEach(geojson, function (currentSegment, featureIndex, featureSubIndex, segmentIndex) { if (started === false && initialValue === undefined) previousValue = currentSegment;else previousValue = callback(previousValue, currentSegment, featureIndex, featureSubIndex, segmentIndex); started = true; }); return previousValue; } /** * Create Feature * * @private * @param {Geometry} geometry GeoJSON Geometry * @param {Object} properties Properties * @returns {Feature} GeoJSON Feature */ function feature(geometry, properties) { if (geometry === undefined) throw new Error('No geometry passed'); return { type: 'Feature', properties: properties || {}, geometry: geometry }; } /** * Create LineString * * @private * @param {Array<Array<number>>} coordinates Line Coordinates * @param {Object} properties Properties * @returns {Feature<LineString>} GeoJSON LineString Feature */ function lineString(coordinates, properties) { if (!coordinates) throw new Error('No coordinates passed'); if (coordinates.length < 2) throw new Error('Coordinates must be an array of two or more positions'); return { type: 'Feature', properties: properties || {}, geometry: { type: 'LineString', coordinates: coordinates } }; } /** * Callback for lineEach * * @callback lineEachCallback * @param {Feature<LineString>} currentLine The current LineString|LinearRing being processed. * @param {number} lineIndex The index of the current element being processed in the array, starts at index 0. * @param {number} lineSubIndex The sub-index of the current line being processed at index 0 */ /** * Iterate over line or ring coordinates in LineString, Polygon, MultiLineString, MultiPolygon Features or Geometries, * similar to Array.forEach. * * @name lineEach * @param {Geometry|Feature<LineString|Polygon|MultiLineString|MultiPolygon>} geojson object * @param {Function} callback a method that takes (currentLine, lineIndex, lineSubIndex) * @example * var mtLn = turf.multiLineString([ * turf.lineString([[26, 37], [35, 45]]), * turf.lineString([[36, 53], [38, 50], [41, 55]]) * ]); * * turf.lineEach(mtLn, function (currentLine, lineIndex) { * //=currentLine * //=lineIndex * }); */ function lineEach(geojson, callback) { // validation if (!geojson) throw new Error('geojson is required'); var type = geojson.geometry ? geojson.geometry.type : geojson.type; if (!type) throw new Error('invalid geojson'); if (type === 'FeatureCollection') throw new Error('FeatureCollection is not supported'); if (type === 'GeometryCollection') throw new Error('GeometryCollection is not supported'); var coordinates = geojson.geometry ? geojson.geometry.coordinates : geojson.coordinates; if (!coordinates) throw new Error('geojson must contain coordinates'); switch (type) { case 'LineString': callback(coordinates, 0, 0); return; case 'Polygon': case 'MultiLineString': var subIndex = 0; for (var line = 0; line < coordinates.length; line++) { if (type === 'MultiLineString') subIndex = line; callback(coordinates[line], line, subIndex); } return; case 'MultiPolygon': for (var multi = 0; multi < coordinates.length; multi++) { for (var ring = 0; ring < coordinates[multi].length; ring++) { callback(coordinates[multi][ring], ring, multi); } } return; default: throw new Error(type + ' geometry not supported'); } } /** * Callback for lineReduce * * The first time the callback function is called, the values provided as arguments depend * on whether the reduce method has an initialValue argument. * * If an initialValue is provided to the reduce method: * - The previousValue argument is initialValue. * - The currentValue argument is the value of the first element present in the array. * * If an initialValue is not provided: * - The previousValue argument is the value of the first element present in the array. * - The currentValue argument is the value of the second element present in the array. * * @callback lineReduceCallback * @param {*} previousValue The accumulated value previously returned in the last invocation * of the callback, or initialValue, if supplied. * @param {Feature<LineString>} currentLine The current LineString|LinearRing being processed. * @param {number} lineIndex The index of the current element being processed in the * array. Starts at index 0, if an initialValue is provided, and at index 1 otherwise. * @param {number} lineSubIndex The sub-index of the current line being processed at index 0 */ /** * Reduce features in any GeoJSON object, similar to Array.reduce(). * * @name lineReduce * @param {Geometry|Feature<LineString|Polygon|MultiLineString|MultiPolygon>} geojson object * @param {Function} callback a method that takes (previousValue, currentFeature, featureIndex) * @param {*} [initialValue] Value to use as the first argument to the first call of the callback. * @returns {*} The value that results from the reduction. * @example * var mtp = turf.multiPolygon([ * turf.polygon([[[12,48],[2,41],[24,38],[12,48]], [[9,44],[13,41],[13,45],[9,44]]]), * turf.polygon([[[5, 5], [0, 0], [2, 2], [4, 4], [5, 5]]]) * ]); * * turf.lineReduce(mtp, function (previousValue, currentLine, lineIndex, lineSubIndex) { * //=previousValue * //=currentLine * //=lineIndex * //=lineSubIndex * return currentLine * }, 2); */ function lineReduce(geojson, callback, initialValue) { var previousValue = initialValue; lineEach(geojson, function (currentLine, lineIndex, lineSubIndex) { if (lineIndex === 0 && initialValue === undefined) previousValue = currentLine;else previousValue = callback(previousValue, currentLine, lineIndex, lineSubIndex); }); return previousValue; } var index$3 = Object.freeze({ coordEach: coordEach$1, coordReduce: coordReduce, propEach: propEach, propReduce: propReduce, featureEach: featureEach$1, featureReduce: featureReduce, coordAll: coordAll, geomEach: geomEach, geomReduce: geomReduce, flattenEach: flattenEach, flattenReduce: flattenReduce, segmentEach: segmentEach, segmentReduce: segmentReduce, feature: feature, lineString: lineString, lineEach: lineEach, lineReduce: lineReduce }); var require$$1 = ( index$3 && undefined ) || index$3; var rbush = index$1; var meta = require$$1; var featureEach = meta.featureEach; var coordEach = meta.coordEach; /** * GeoJSON implementation of [RBush](https://github.com/mourner/rbush#rbush) spatial index. * * @name rbush * @param {number} [maxEntries=9] defines the maximum number of entries in a tree node. 9 (used by default) is a * reasonable choice for most applications. Higher value means faster insertion and slower search, and vice versa. * @returns {RBush} GeoJSON RBush * @example * var rbush = require('geojson-rbush') * var tree = rbush() */ var index = function index(maxEntries) { var tree = rbush(maxEntries); /** * [insert](https://github.com/mourner/rbush#data-format) * * @param {Feature<any>} feature insert single GeoJSON Feature * @returns {RBush} GeoJSON RBush * @example * var polygon = { * "type": "Feature", * "properties": {}, * "geometry": { * "type": "Polygon", * "coordinates": [[[-78, 41], [-67, 41], [-67, 48], [-78, 48], [-78, 41]]] * } * } * tree.insert(polygon) */ tree.insert = function (feature) { if (Array.isArray(feature)) { var bbox = feature; feature = bboxPolygon(bbox); feature.bbox = bbox; } else { feature.bbox = feature.bbox ? feature.bbox : turfBBox(feature); } return rbush.prototype.insert.call(this, feature); }; /** * [load](https://github.com/mourner/rbush#bulk-inserting-data) * * @param {BBox[]|FeatureCollection<any>} features load entire GeoJSON FeatureCollection * @returns {RBush} GeoJSON RBush * @example * var polygons = { * "type": "FeatureCollection", * "features": [ * { * "type": "Feature", * "properties": {}, * "geometry": { * "type": "Polygon", * "coordinates": [[[-78, 41], [-67, 41], [-67, 48], [-78, 48], [-78, 41]]] * } * }, * { * "type": "Feature", * "properties": {}, * "geometry": { * "type": "Polygon", * "coordinates": [[[-93, 32], [-83, 32], [-83, 39], [-93, 39], [-93, 32]]] * } * } * ] * } * tree.load(polygons) */ tree.load = function (features) { var load = []; // Load an Array of BBox if (Array.isArray(features)) { features.forEach(function (bbox) { var feature = bboxPolygon(bbox); feature.bbox = bbox; load.push(feature); }); } else { // Load FeatureCollection featureEach(features, function (feature) { feature.bbox = feature.bbox ? feature.bbox : turfBBox(feature); load.push(feature); }); } return rbush.prototype.load.call(this, load); }; /** * [remove](https://github.com/mourner/rbush#removing-data) * * @param {BBox|Feature<any>} feature remove single GeoJSON Feature * @returns {RBush} GeoJSON RBush * @example * var polygon = { * "type": "Feature", * "properties": {}, * "geometry": { * "type": "Polygon", * "coordinates": [[[-78, 41], [-67, 41], [-67, 48], [-78, 48], [-78, 41]]] * } * } * tree.remove(polygon) */ tree.remove = function (feature) { if (Array.isArray(feature)) { var bbox = feature; feature = bboxPolygon(bbox); feature.bbox = bbox; } return rbush.prototype.remove.call(this, feature); }; /** * [clear](https://github.com/mourner/rbush#removing-data) * * @returns {RBush} GeoJSON Rbush * @example * tree.clear() */ tree.clear = function () { return rbush.prototype.clear.call(this); }; /** * [search](https://github.com/mourner/rbush#search) * * @param {BBox|FeatureCollection|Feature<any>} geojson search with GeoJSON * @returns {FeatureCollection<any>} all features that intersects with the given GeoJSON. * @example * var polygon = { * "type": "Feature", * "properties": {}, * "geometry": { * "type": "Polygon", * "coordinates": [[[-78, 41], [-67, 41], [-67, 48], [-78, 48], [-78, 41]]] * } * } * tree.search(polygon) */ tree.search = function (geojson) { var features = rbush.prototype.search.call(this, this.toBBox(geojson)); return { type: 'FeatureCollection', features: features }; }; /** * [collides](https://github.com/mourner/rbush#collisions) * * @param {BBox|FeatureCollection|Feature<any>} geojson collides with GeoJSON * @returns {boolean} true if there are any items intersecting the given GeoJSON, otherwise false. * @example * var polygon = { * "type": "Feature", * "properties": {}, * "geometry": { * "type": "Polygon", * "coordinates": [[[-78, 41], [-67, 41], [-67, 48], [-78, 48], [-78, 41]]] * } * } * tree.collides(polygon) */ tree.collides = function (geojson) { return rbush.prototype.collides.call(this, this.toBBox(geojson)); }; /** * [all](https://github.com/mourner/rbush#search) * * @returns {FeatureCollection<any>} all the features in RBush * @example * tree.all() * //=FeatureCollection */ tree.all = function () { var features = rbush.prototype.all.call(this); return { type: 'FeatureCollection', features: features }; }; /** * [toJSON](https://github.com/mourner/rbush#export-and-import) * * @returns {any} export data as JSON object * @example * var exported = tree.toJSON() * //=JSON object */ tree.toJSON = function () { return rbush.prototype.toJSON.call(this); }; /** * [fromJSON](https://github.com/mourner/rbush#export-and-import) * * @param {any} json import previously exported data * @returns {RBush} GeoJSON RBush * @example * var exported = { * "children": [ * { * "type": "Feature", * "geometry": { * "type": "Point", * "coordinates": [110, 50] * }, * "properties": {}, * "bbox": [110, 50, 110, 50] * } * ], * "height": 1, * "leaf": true, * "minX": 110, * "minY": 50, * "maxX": 110, * "maxY": 50 * } * tree.fromJSON(exported) */ tree.fromJSON = function (json) { return rbush.prototype.fromJSON.call(this, json); }; /** * Converts GeoJSON to {minX, minY, maxX, maxY} schema * * @private * @param {BBox|FeatureCollectio|Feature<any>} geojson feature(s) to retrieve BBox from * @returns {Object} converted to {minX, minY, maxX, maxY} */ tree.toBBox = function (geojson) { var bbox; if (geojson.bbox) bbox = geojson.bbox;else if (Array.isArray(geojson) && geojson.length === 4) bbox = geojson;else bbox = turfBBox(geojson); return { minX: bbox[0], minY: bbox[1], maxX: bbox[2], maxY: bbox[3] }; }; return tree; }; /** * Takes a bbox and returns an equivalent {@link Polygon|polygon}. * * @private * @name bboxPolygon * @param {Array<number>} bbox extent in [minX, minY, maxX, maxY] order * @returns {Feature<Polygon>} a Polygon representation of the bounding box * @example * var bbox = [0, 0, 10, 10]; * * var poly = turf.bboxPolygon(bbox); * * //addToMap * var addToMap = [poly] */ function bboxPolygon(bbox) { var lowLeft = [bbox[0], bbox[1]]; var topLeft = [bbox[0], bbox[3]]; var topRight = [bbox[2], bbox[3]]; var lowRight = [bbox[2], bbox[1]]; var coordinates = [[lowLeft, lowRight, topRight, topLeft, lowLeft]]; return { type: 'Feature', bbox: bbox, properties: {}, geometry: { type: 'Polygon', coordinates: coordinates } }; } /** * Takes a set of features, calculates the bbox of all input features, and returns a bounding box. * * @private * @name bbox * @param {FeatureCollection|Feature<any>} geojson input features * @returns {Array<number>} bbox extent in [minX, minY, maxX, maxY] order * @example * var line = turf.lineString([[-74, 40], [-78, 42], [-82, 35]]); * var bbox = turf.bbox(line); * var bboxPolygon = turf.bboxPolygon(bbox); * * //addToMap * var addToMap = [line, bboxPolygon] */ function turfBBox(geojson) { var bbox = [Infinity, Infinity, -Infinity, -Infinity]; coordEach(geojson, function (coord) { if (bbox[0] > coord[0]) bbox[0] = coord[0]; if (bbox[1] > coord[1]) bbox[1] = coord[1]; if (bbox[2] < coord[0]) bbox[2] = coord[0]; if (bbox[3] < coord[1]) bbox[3] = coord[1]; }); return bbox; } function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults(subClass, superClass); } var options = { 'mode': 'line', 'tolerance': 10, 'symbol': { 'markerType': 'ellipse', 'markerFill': '#0f89f5', 'markerLineColor': '#fff', 'markerLineWidth': 2, 'markerLineOpacity': 1, 'markerWidth': 15, 'markerHeight': 15 } }; /** * A snap tool used for mouse point to adsorb geometries, it extends maptalks.Class. * * Thanks to rbush's author, this pluging has used the rbush to inspect surrounding geometries within tolerance(https://github.com/mourner/rbush) * * @author liubgithub(https://github.com/liubgithub) * * MIT License */ var SnapTool = function (_maptalks$Class) { _inherits(SnapTool, _maptalks$Class); function SnapTool(options) { _classCallCheck(this, SnapTool); var _this = _possibleConstructorReturn(this, _maptalks$Class.call(this, options)); _this.tree = index(); return _this; } SnapTool.prototype.getMode = function getMode() { this._mode = !this._mode ? this.options['mode'] : this._mode; if (this._checkMode(this._mode)) { return this._mode; } else { throw new Error('snap mode is invalid'); } }; SnapTool.prototype.setMode = function setMode(mode) { if (this._checkMode(this._mode)) { this._mode = mode; if (this.snaplayer) { if (this.snaplayer instanceof Array) { var _ref; this.allLayersGeometries = []; this.snaplayer.forEach(function (tempLayer, index$$1) { var tempGeometries = tempLayer.getGeometries(); this.allLayersGeometries[index$$1] = this._compositGeometries(tempGeometries); }.bind(this)); this.allGeometries = (_ref = []).concat.apply(_ref, this.allLayersGeometries); } else { var geometries = this.snaplayer.getGeometries(); this.allGeometries = this._compositGeometries(geometries); } } } else { throw new Error('snap mode is invalid'); } }; /** * @param {Map} map object * When using the snap tool, you should add it to a map firstly.the enable method excute default */ SnapTool.prototype.addTo = function addTo(map) { var id = maptalks.INTERNAL_LAYER_PREFIX + '_snapto'; this._mousemoveLayer = new maptalks.VectorLayer(id).addTo(map); this._map = map; this.allGeometries = []; this.enable(); }; SnapTool.prototype.remove = function remove() { this.disable(); if (this._mousemoveLayer) { this._mousemoveLayer.remove(); delete this._mousemoveLayer; } }; SnapTool.prototype.getMap = function getMap() { return this._map; }; /** * @param {String} snap mode * mode should be either 'point' or 'line' */ SnapTool.prototype._checkMode = function _checkMode(mode) { if (mode === 'point' || mode === 'line') { return true; } else { return false; } }; /** * Start snap interaction */ SnapTool.prototype.enable = function enable() { var map = this.getMap(); if (this.snaplayer) { if (this.snaplayer instanceof Array) { var _ref2; this.allLayersGeometries = []; this.snaplayer.forEach(function (tempLayer, index$$1) { var tempGeometries = tempLayer.getGeometries(); this.allLayersGeometries[index$$1] = this._compositGeometries(tempGeometries); }.bind(this)); this.allGeometries = (_ref2 = []).concat.apply(_ref2, this.allLayersGeometries); } else { var geometries = this.snaplayer.getGeometries(); this.allGeometries = this._compositGeometries(geometries); } } if (this.allGeometries) { if (!this._mousemove) { this._registerEvents(map); } if (this._mousemoveLayer) { this._mousemoveLayer.show(); } } else { throw new Error('you should set geometries which are snapped to firstly!'); } }; /** * End snap interaction */ SnapTool.prototype.disable = function disable() { var map = this.getMap(); map.off('mousemove touchstart', this._mousemove); map.off('mousedown', this._mousedown, this); map.off('mouseup', this._mouseup, this); if (this._mousemoveLayer) { this._mousemoveLayer.hide(); } delete this._mousemove; this.allGeometries = []; }; /** * @param {Geometry||Array<Geometry>} geometries to snap to * Set geomeries to an array for snapping to */ SnapTool.prototype.setGeometries = function setGeometries(geometries) { geometries = geometries instanceof Array ? geometries : [geometries]; this.allGeometries = this._compositGeometries(geometries); }; /** * @param {Layer||maptalk.VectorLayer||Array.<Layer>||Array.<maptalk.VectorLayer>} layer to snap to * Set layer for snapping to */ SnapTool.prototype.setLayer = function setLayer(layer) { if (layer instanceof Array) { var _ref5; this.snaplayer = []; this.allLayersGeometries = []; layer.forEach(function (tempLayer, index$$1) { if (tempLayer instanceof maptalks.VectorLayer) { this.snaplayer.push(tempLayer); var tempGeometries = tempLayer.getGeometries(); this.allLayersGeometries[index$$1] = this._compositGeometries(tempGeometries); tempLayer.on('addgeo', function () { var _ref3; var tempGeometries = this.snaplayer[index$$1].getGeometries(); this.allLayersGeometries[index$$1] = this._compositGeometries(tempGeometries); this.allGeometries = (_ref3 = []).concat.apply(_ref3, this.allLayersGeometries); }, this); tempLayer.on('clear', function () { var _ref4; this.allLayersGeometries.splice(index$$1, 1); this.allGeometries = (_ref4 = []).concat.apply(_ref4, this.allLayersGeometries); }, this); } }.bind(this)); this.allGeometries = (_ref5 = []).concat.apply(_ref5, this.allLayersGeometries); this._mousemoveLayer.bringToFront(); } else if (layer instanceof maptalks.VectorLayer) { var geometries = layer.getGeometries(); this.snaplayer = layer; this.allGeometries = this._compositGeometries(geometries); layer.on('addgeo', function () { var geometries = this.snaplayer.getGeometries(); this.allGeometries = this._compositGeometries(geometries); }, this); this.snaplayer.on('clear', function () { this._clearGeometries(); }, this); this._mousemoveLayer.bringToFront(); } }; /** * @param {drawTool||maptalks.DrawTool} drawing tool * When interacting with a drawtool, you should bind the drawtool object to this snapto tool */ SnapTool.prototype.bindDrawTool = function bindDrawTool(drawTool) { var _this2 = this; if (drawTool instanceof maptalks.DrawTool) { drawTool.on('drawstart', function (e) { if (_this2.snapPoint) { _this2._resetCoordinates(e.target._geometry, _this2.snapPoint); _this2._resetClickPoint(e.target._clickCoords, _this2.snapPoint); } }, this); drawTool.on('mousemove', function (e) { if (_this2.snapPoint) { var mode = e.target.getMode(); var map = e.target.getMap(); if (mode === 'circle' || mode === 'freeHandCircle') { var radius = map.computeLength(e.target._geometry.getCenter(), _this2.snapPoint); e.target._geometry.setRadius(radius); } else if (mode === 'ellipse' || mode === 'freeHandEllipse') { var center = e.target._geometry.getCenter(); var rx = map.computeLength(center, new maptalks.Coordinate({ x: _this2.snapPoint.x, y: center.y })); var ry = map.computeLength(center, new maptalks.Coordinate({ x: center.x, y: _this2.snapPoint.y })); e.target._geometry.setWidth(rx * 2); e.target._geometry.setHeight(ry * 2); } else if (mode === 'rectangle' || mode === 'freeHandRectangle') { var containerPoint = map.coordToContainerPoint(new maptalks.Coordinate({ x: _this2.snapPoint.x, y: _this2.snapPoint.y })); var firstClick = map.coordToContainerPoint(e.target._geometry.getFirstCoordinate()); var ring = [[firstClick.x, firstClick.y], [containerPoint.x, firstClick.y], [containerPoint.x, containerPoint.y], [firstClick.x, containerPoint.y]]; e.target._geometry.setCoordinates(ring.map(function (c) { return map.containerPointToCoord(new maptalks.Point(c)); })); } else { _this2._resetCoordinates(e.target._geometry, _this2.snapPoint); } } }, this); drawTool.on('drawvertex', function (e) { if (_this2.snapPoint) { _this2._resetCoordinates(e.target._geometry, _this2.snapPoint); _this2._resetClickPoint(e.target._clickCoords, _this2.snapPoint); } }, this); drawTool.on('drawend', function (e) { if (_this2.snapPoint) { var mode = e.target.getMode(); var map = e.target.getMap(); var geometry = e.geometry; if (mode === 'circle' || mode === 'freeHandCircle') { var radius = map.computeLength(e.target._geometry.getCenter(), _this2.snapPoint); geometry.setRadius(radius); } else if (mode === 'ellipse' || mode === 'freeHandEllipse') { var center = geometry.getCenter(); var rx = map.computeLength(center, new maptalks.Coordinate({ x: _this2.snapPoint.x, y: center.y })); var ry = map.computeLength(center, new maptalks.Coordinate({ x: center.x, y: _this2.snapPoint.y })); geometry.setWidth(rx * 2); geometry.setHeight(ry * 2); } else if (mode === 'rectangle' || mode === 'freeHandRectangle') { var containerPoint = map.coordToContainerPoint(new maptalks.Coordinate({ x: _this2.snapPoint.x, y: _this2.snapPoint.y })); var firstClick = map.coordToContainerPoint(geometry.getFirstCoordinate()); var ring = [[firstClick.x, firstClick.y], [containerPoint.x, firstClick.y], [containerPoint.x, containerPoint.y], [firstClick.x, containerPoint.y]]; geometry.setCoordinates(ring.map(function (c) { return map.containerPointToCoord(new maptalks.Point(c)); })); } else { _this2._resetCoordinates(geometry, _this2.snapPoint); } } }, this); } }; SnapTool.prototype._resetCoordinates = function _resetCoordinates(geometry, snapPoint) { if (!geometry) return geometry; var coords = geometry.getCoordinates(); if (geometry instanceof maptalks.Polygon) { if (geometry instanceof maptalks.Circle) { return geometry; } var coordinates = coords[0]; if (coordinates instanceof Array && coordinates.length > 2) { coordinates[coordinates.length - 2].x = snapPoint.x; coordinates[coordinates.length - 2].y = snapPoint.y; } } else if (coords instanceof Array) { coords[coords.length - 1].x = snapPoint.x; coords[coords.length - 1].y = snapPoint.y; } else if (coords instanceof maptalks.Coordinate) { coords.x = snapPoint.x; coords.y = snapPoint.y; } geometry.setCoordinates(coords); return geometry; }; SnapTool.prototype._resetClickPoint = function _resetClickPoint(clickCoords, snapPoint) { if (!clickCoords) return; clickCoords[clickCoords.length - 1].x = snapPoint.x; clickCoords[clickCoords.length - 1].y = snapPoint.y; }; SnapTool.prototype._addGeometries = function _addGeometries(geometries) { geometries = geometries instanceof Array ? geometries : [geometries]; var addGeometries = this._compositGeometries(geometries); this.allGeometries = this.allGeometries.concat(addGeometries); }; SnapTool.prototype._clearGeometries = function _clearGeometries() { this.addGeometries = []; }; /** * @param {Coordinate} mouse's coordinate on map * Using a point to inspect the surrounding geometries */ SnapTool.prototype._prepareGeometries = function _prepareGeometries(coordinate) { if (this.allGeometries) { var allGeoInGeojson = this.allGeometries; this.tree.clear(); this.tree.load({ 'type': 'FeatureCollection', 'features': allGeoInGeojson }); this.inspectExtent = this._createInspectExtent(coordinate); var availGeometries = this.tree.search(this.inspectExtent); return availGeometries; } return null; }; SnapTool.prototype._compositGeometries = function _compositGeometries(geometries) { var geos = []; var mode = this.getMode(); if (mode === 'point') { geos = this._compositToPoints(geometries); } else if (mode === 'line') { geos = this._compositToLines(geometries); } return geos; }; SnapTool.prototype._compositToPoints = function _compositToPoints(geometries) { var geos = []; geometries.forEach(function (geo) { geos = geos.concat(this._parserToPoints(geo)); }.bind(this)); return geos; }; SnapTool.prototype._createMarkers = function _createMarkers(coords) { var markers = []; coords.forEach(function (coord) { if (coord instanceof Array) { coord.forEach(function (_coord) { var _geo = new maptalks.Marker(_coord, { properties: {} }); _geo = _geo.toGeoJSON(); markers.push(_geo); }); } else { var _geo = new maptalks.Marker(coord, { properties: {} }); _geo = _geo.toGeoJSON(); markers.push(_geo); } }); return markers; }; SnapTool.prototype._parserToPoints = function _parserToPoints(geo) { var type = geo.getType(); var coordinates = null; if (type === 'Circle' || type === 'Ellipse') { coordinates = geo.getShell(); } else coordinates = geo.getCoordinates(); var geos = []; //two cases,one is single geometry,and another is multi geometries if (coordinates[0] instanceof Array) { coordinates.forEach(function (coords) { var _markers = this._createMarkers(coords); geos = geos.concat(_markers); }.bind(this)); } else { if (!(coordinates instanceof Array)) { coordinates = [coordinates]; } var _markers = this._createMarkers(coordinates); geos = geos.concat(_markers); } return geos; }; SnapTool.prototype._compositToLines = function _compositToLines(geometries) { var geos = []; geometries.forEach(function (geo) { switch (geo.getType()) { case 'Point': { var _geo = geo.toGeoJSON(); _geo.properties = {}; geos.push(_geo); } break; case 'LineString': case 'Polygon': geos = geos.concat(this._parserGeometries(geo, 1)); break; default: break; } }.bind(this)); return geos; }; SnapTool.prototype._parserGeometries = function _parserGeometries(geo, _len) { var coordinates = geo.getCoordinates(); var geos = []; //two cases,one is single geometry,and another is multi geometries if (coordinates[0] instanceof Array) { coordinates.forEach(function (coords) { var _lines = this._createLine(coords, _len, geo); geos = geos.concat(_lines); }.bind(this)); } else { var _lines = this._createLine(coordinates, _len, geo); geos = geos.concat(_lines); } return geos; }; SnapTool.prototype._createLine = function _createLine(coordinates, _length, geo) { var lines = []; var len = coordinates.length - _length; for (var i = 0; i < len; i++) { var line = new maptalks.LineString([coordinates[i], coordinates[i + 1]], { properties: { obj: geo } }); lines.push(line.toGeoJSON()); } return lines; }; SnapTool.prototype._createInspectExtent = function _createInspectExtent(coordinate) { var tolerance = !this.options['tolerance'] ? 10 : this.options['tolerance']; var map = this.getMap(); var zoom = map.getZoom(); var screenPoint = map.coordinateToPoint(coordinate, zoom); var lefttop = map.pointToCoordinate(new maptalks.Point([screenPoint.x - tolerance, screenPoint.y - tolerance]), zoom); var righttop = map.pointToCoordinate(new maptalks.Point([screenPoint.x + tolerance, screenPoint.y - tolerance]), zoom); var leftbottom = map.pointToCoordinate(new maptalks.Point([screenPoint.x - tolerance, screenPoint.y + tolerance]), zoom); var rightbottom = map.pointToCoordinate(new maptalks.Point([screenPoint.x + tolerance, screenPoint.y + tolerance]), zoom); return { 'type': 'Feature', 'properties': {}, 'geometry': { 'type': 'Polygon', 'coordinates': [[[lefttop.x, lefttop.y], [righttop.x, righttop.y], [rightbottom.x, rightbottom.y], [leftbottom.x, leftbottom.y]]] } }; }; /** * @param {Map} * Register mousemove event */ SnapTool.prototype._registerEvents = function _registerEvents(map) { this._needFindGeometry = true; this._mousemove = function (e) { this.mousePoint = e.coordinate; if (!this._marker) { this._marker = new maptalks.Marker(e.coordinate, { 'symbol': this.options['symbol'] }).addTo(this._mousemoveLayer); } else { this._marker.setCoordinates(e.coordinate); } //indicate find geometry if (!this._needFindGeometry) return; var availGeometries = this._findGeometry(e.coordinate); if (availGeometries.features.length > 0) { this.snapPoint = this._getSnapPoint(availGeometries); if (this.snapPoint) { this._marker.setCoordinates([this.snapPoint.x, this.snapPoint.y]); } } else { this.snapPoint = null; } }; this._mousedown = function () { this._needFindGeometry = false; }; this._mouseup = function () { this._needFindGeometry = true; }; map.on('mousemove touchstart', this._mousemove, this); map.on('mousedown', this._mousedown, this); map.on('mouseup', this._mouseup, this); }; /** * @param {Array<geometry>} available geometries which are surrounded * Calculate the distance from mouse point to every geometry */ SnapTool.prototype._setDistance = function _setDistance(geos) { var geoObjects = []; for (var i = 0; i < geos.length; i++) { var geo = geos[i]; if (geo.geometry.type === 'LineString') { var distance = this._distToPolyline(this.mousePoint, geo); //geo.properties.distance = distance; geoObjects.push({ geoObject: geo, distance: distance }); } else if (geo.geometry.type === 'Point') { var _distance = this._distToPoint(this.mousePoint, geo); //Composite an object including geometry and distance geoObjects.push({ geoObject: geo, distance: _distance }); } } return geoObjects; }; SnapTool.prototype._findNearestGeometries = function _findNearestGeometries(geos) { var geoObjects = this._setDistance(geos); geoObjects = geoObjects.sort(this._compare(geoObjects, 'distance')); return geoObjects[0]; }; SnapTool.prototype._findGeometry = function _findGeometry(coordinate) { var availGeimetries = this._prepareGeometries(coordinate); return availGeimetries; }; SnapTool.prototype._getSnapPoint = function _getSnapPoint(availGeometries) { var _nearestGeometry = this._findNearestGeometries(availGeometries.features); var snapPoint = null; if (!this._validDistance(_nearestGeometry.distance)) { return null; } //when it's point, return itself if (_nearestGeometry.geoObject.geometry.type === 'Point') { snapPoint = { x: _nearestGeometry.geoObject.geometry.coordinates[0], y: _nearestGeometry.geoObject.geometry.coordinates[1] }; } else if (_nearestGeometry.geoObject.geometry.type === 'LineString') { //when it's line,return the vertical insect point var nearestLine = this._setEquation(_nearestGeometry.geoObject); //whether k exists if (nearestLine.A === 0) { snapPoint = { x: this.mousePoint.x, y: _nearestGeometry.geoObject.geometry.coordinates[0][1] }; } else if (nearestLine.A === Infinity) { snapPoint = { x: _nearestGeometry.geoObject.geometry.coordinates[0][0], y: this.mousePoint.y }; } else { var k = nearestLine.B / nearestLine.A; var verticalLine = this._setVertiEquation(k, this.mousePoint); snapPoint = this._solveEquation(nearestLine, verticalLine); } } return snapPoint; }; //Calculate the distance from a point to a line SnapTool.prototype._distToPolyline = function _distToPolyline(point, line) { var equation = this._setEquation(line); var A = equation.A; var B = equation.B; var C = equation.C; var distance = Math.abs((A * point.x + B * point.y + C) / Math.sqrt(Math.pow(A, 2) + Math.pow(B, 2))); return distance; }; SnapTool.prototype._validDistance = function _validDistance(distance) { var map = this.getMap(); var resolution = map.getResolution(); var tolerance = this.options['tolerance']; if (distance / resolution > tolerance) { return false; } else { return true; } }; SnapTool.prototype._distToPoint = function _distToPoint(mousePoint, toPoint) { var from = [mousePoint.x, mousePoint.y]; var to = toPoint.geometry.coordinates; return Math.sqrt(Math.pow(from[0] - to[0], 2) + Math.pow(from[1] - to[1], 2)); }; //create a line's equation SnapTool.prototype._setEquation = function _setEquation(line) { var coords = line.geometry.coordinates; var from = coords[0]; var to = coords[1]; var k = Number((from[1] - to[1]) / (from[0] - to[0]).toString()); var A = k; var B = -1; var C = from[1] - k * from[0]; return { A: A, B: B, C: C }; }; SnapTool.prototype._setVertiEquation = function _setVertiEquation(k, point) { var b = point.y - k * point.x; var A = k; var B = -1; var C = b; return { A: A, B: B, C: C }; }; SnapTool.prototype._solveEquation = function _solveEquation(equationW, equationU) { var A1 = equationW.A, B1 = equationW.B, C1 = equationW.C; var A2 = equationU.A, B2 = equationU.B, C2 = equationU.C; var x = (B1 * C2 - C1 * B2) / (A1 * B2 - A2 * B1); var y = (A1 * C2 - A2 * C1) / (B1 * A2 - B2 * A1); return { x: x, y: y }; }; SnapTool.prototype._compare = function _compare(data, propertyName) { return function (object1, object2) { var value1 = object1[propertyName]; var value2 = object2[propertyName]; if (value2 < value1) { return 1; } else if (value2 > value1) { return -1; } else { return 0; } }; }; return SnapTool; }(maptalks.Class); SnapTool.mergeOptions(options); exports.SnapTool = SnapTool; Object.defineProperty(exports, '__esModule', { value: true }); typeof console !== 'undefined' && console.log('maptalks.snapto v0.1.11, requires maptalks@^0.33.1.'); })));
const webpack = require("webpack"); const path = require("path"); const CopyWebpackPlugin = require("copy-webpack-plugin"); const MiniCssExtractPlugin = require("mini-css-extract-plugin"); const AssetsPlugin = require("assets-webpack-plugin"); module.exports = { entry: { main: path.join(__dirname, "src", "index.js") }, output: { path: path.join(__dirname, "dist") }, module: { rules: [ { test: /\.((png)|(eot)|(woff)|(woff2)|(ttf)|(svg)|(gif))(\?v=\d+\.\d+\.\d+)?$/, loader: "file-loader?name=/[hash].[ext]" }, {test: /\.json$/, loader: "json-loader"}, { loader: "babel-loader", test: /\.js?$/, exclude: /node_modules/, query: {cacheDirectory: true} }, { test: /\.(sa|sc|c)ss$/, exclude: /node_modules/, use: ["style-loader", MiniCssExtractPlugin.loader, "css-loader", "postcss-loader", "sass-loader"] } ] }, plugins: [ new webpack.ProvidePlugin({ fetch: "imports-loader?this=>global!exports-loader?global.fetch!whatwg-fetch" }), new AssetsPlugin({ filename: "webpack.json", path: path.join(process.cwd(), "site/data"), prettyPrint: true }), // new CopyWebpackPlugin([ // { // from: "./src/fonts/", // to: "fonts/", // flatten: true // } // ]) ] };
window.onload=function() { var start = document.getElementById('start'); start.onclick = function () { var name = document.getElementById('Name').value; var id = document.getElementById('Id').value; var tel = document.getElementById("Tel").value; if (name == "") { alert("请输入名字"); return false; } if (!isName(name)) { alert("请输入正确的姓名") return false; } if (id =="") { alert("请输入学号"); return false; } if (!isId(id)) { alert("请输入正确学号"); return false; } if (tel == "") { alert("请输入电话号码"); return false; } if (!isTelephone(tel)) { alert("请输入正确的手机号码"); return false; } else { start.submit(); // document.getElementById("myform").submit(); // window.open("answer.html","_self"); } } function isName(obj) { var nameReg = /[\u4E00-\u9FA5]+$/; return nameReg.test(obj); } function isId(obj) { var emailReg = /^2017\d{8}$/; return emailReg.test(obj); } function isTelephone(obj) { reg = /^1[34578]\d{9}$/; return reg.test(obj); } }
(function (){ "use strict"; (function() { var $bordered = $('.bordered'); window.setInterval(function() { var top = window.pageYOffset || document.documentElement.scrollTop; if(top > 0) { $bordered.fadeOut('fast'); } else if(top == 0 && !$bordered.is(':visible')) { $bordered.fadeIn("fast"); } }, 200); })(); $(function() { $('.scroll').click(function(e) { e.preventDefault(); if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) { var target = $(this.hash); target = target.length ? target : $('[name=' + this.hash.slice(1) +']'); if (target.length) { $('html,body').animate({ scrollTop: target.offset().top }, 1000); return false; } } }); }); (function () { var $hash = $(location.hash); if ($hash.hasClass('modal')) { $hash.modal('show'); } })(); // // carousels intervals and disabled the keyboard support // $(document).ready(function(){ $('#backgroundCarousel').carousel({ interval: 10000000, // TODO just one slide for now keyboard : false }); $('#partnersCarousel').carousel({ interval: 4000, keyboard : false }); }); })(); (function(){ "use strict"; // // toggle popups from pricing dialog to the partners dialog // var cennik = $("#cennik"); var ponuka = $("#ponuka"); function toggle(){ cennik.modal("toggle"); ponuka.modal("toggle"); } $("#cennik button").on("click", toggle); })(); (function(){ "use strict"; // // deep linking for tracking google analytics // requested by michael, should not be also standard deep linking // function setDeeplinking(event){ window.location.hash = $(event.target).data("target"); } function clearDeeplinking(event){ window.location.hash = ""; } $("nav .menu").on("click", setDeeplinking); $("#try").on("click", setDeeplinking); $('#cennik').on('hidden.bs.modal', clearDeeplinking); $('#ponuka').on('hidden.bs.modal', clearDeeplinking); $('#kontakt').on('hidden.bs.modal', clearDeeplinking); })(); (function(){ "use strict"; // // sending emails via the rest api // $("#form1").on("click", function(e){ e.preventDefault(); sendContent( $("#formName1")[0].value, $("#formEmail1")[0].value, $("#formNote1")[0].value, $($("#events1")[0]).prop('checked'), function(){ $("#formName1").css("display", "none"); $("#form1").css("display", "none"); $("#formEmail1").css("display", "none"); $("#formNote1").css("display", "none"); $("#events1").css("display", "none"); $(".events-align label").css("display", "none"); $("#mobilethanks").css("display", "block"); } ); }); $("#form2").on("click", function(e){ e.preventDefault(); sendContent( $("#formName2")[0].value, $("#formEmail2")[0].value, $("#formNote2")[0].value, $($("#events2")[0]).prop('checked'), function emptyCallback(){} ); }); function sendContent(name, email, note, newsletter, callback){ var EMAIL_RECIPIENT = "[email protected]"; var NAME_RECIPIENT = "HalmiSpace"; var SND_EMAIL_RECIPIENT = "[email protected]"; var SND_NAME_RECIPIENT = "Lolovia"; if (!email){ email = ":( Uchádzač nespokytol žiadny email."; } if (!note){ note = ":( Uchádzač neposlal žiadnu poznámku."; } if (!name){ name = "Uchádzač"; } console.log("newsletter", newsletter); var wantsReceiveEmail = newsletter ? "Áno, mám záujem o newsletter." : "Nemám záujem o newsletter."; var toParam = { "email": EMAIL_RECIPIENT, "name": NAME_RECIPIENT, "type": "to" }; var message = ""; message += "Uchádzač: " + name + "<br/>"; message += "Email: " + email + "<br/>"; message += "Poznámka: " + note + "<br/>"; message += "Newsletter: " + wantsReceiveEmail + "<br/>"; var messageParam = { "from_email": "[email protected]", "to": [toParam, { "email": SND_EMAIL_RECIPIENT, "name": SND_NAME_RECIPIENT, "type": "to" }], "headers": { "Reply-To": email }, "autotext": "true", "subject": "Uchádzač o coworking: " + name, "html": message }; var opts = { url: "https://mandrillapp.com/api/1.0/messages/send.json", data: { "key": "9WZGkQuvFHBbuy-p8ZOPjQ", "message": messageParam }, type: "POST", crossDomain: true, success: function(msg){ console.info("success email message", msg[0]); }, error : function(){ alert("Vyskytla sa chyba, kontaktuj nas na [email protected]!") } }; $.ajax(opts).done(function(){ $("#formName1")[0].value = ""; $("#formEmail1")[0].value = ""; $("#formNote1")[0].value = ""; $("#formName2")[0].value = ""; $("#formEmail2")[0].value = ""; $("#formNote2")[0].value = ""; $("#thanks").addClass("active"); callback(); }); } })();
describe('$materialPopup service', function() { beforeEach(module('material.services.popup', 'ngAnimateMock')); function setup(options) { var popup; inject(function($materialPopup, $rootScope) { $materialPopup(options).then(function(p) { popup = p; }); $rootScope.$apply(); }); return popup; } describe('enter()', function() { it('should append to options.appendTo', inject(function($animate, $rootScope) { var parent = angular.element('<div id="parent">'); var popup = setup({ appendTo: parent, template: '<div id="element"></div>' }); popup.enter(); $rootScope.$digest(); expect($animate.queue.shift().event).toBe('enter'); expect(popup.element.parent()[0]).toBe(parent[0]); //fails })); it('should append to $rootElement by default', inject(function($rootScope, $document, $rootElement) { var popup = setup({ template: '<div id="element"></div>' }); popup.enter(); $rootScope.$digest(); expect(popup.element.parent()[0]).toBe($rootElement[0]); })); }); describe('destroy()', function() { it('should leave and then destroy scope', inject(function($rootScope, $animate) { var popup = setup({ template: '<div>' }); popup.enter(); $rootScope.$apply(); var scope = popup.element.scope(); spyOn($animate, 'leave').andCallFake(function(element, cb) { cb(); }); spyOn(scope, '$destroy'); popup.destroy(); expect($animate.leave).toHaveBeenCalled(); expect(scope.$destroy).toHaveBeenCalled(); })); }); });
/** * Created by Samuel Schmid on 23.03.14. * * Class for Database Handling * * Containing * - App Config * - Database Information * * @type {Database} */ module.exports = Database; Array.prototype.contains = function(obj) { var i = this.length; while (i--) { if (this[i] === obj) { return true; } } return false; } String.prototype.replaceAll = function(target, replacement) { return this.split(target).join(replacement); }; function Database(grunt) { this.grunt = grunt; this.appconfig = grunt.config().appconfig; this.db = this.appconfig.db; } /** * delete Database Schemes of Docs * * @param docs */ Database.prototype.deleteSchemes = function(docs) { var grunt = this.grunt; grunt.log.debug("start "); if(docs.docs.length > 0) { var firstDoc = docs.docs[0]; var rootfolder = firstDoc.schemefolder.split("/")[0]; grunt.log.debug("Database: delete files in folder:" + rootfolder); grunt.file.delete(rootfolder); } else { grunt.log.debug("Empty"); return; } } /** * create Database Schemes for Docs * * @param docs */ Database.prototype.createSchemes = function(docs) { var grunt = this.grunt; if(this.db.name === "mongodb") { if(this.db.provider === "mongoose") { grunt.log.write("start writing schemes for database " + this.db.name + " and provider "+this.db.provider + "."); var Provider = require('./providers/mongoose/mongoose-provider.js'); var provider = new Provider(grunt); for(var i=0;i<docs.docs.length;i++) { var doc = docs.docs[i]; if(doc.json.type.endsWith('.abstract')) { provider.writeAbstractScheme(doc); } } for(var i=0;i<docs.docs.length;i++) { var doc = docs.docs[i]; if(!doc.json.type.endsWith('.apidescription') && !doc.json.type.endsWith('.abstract')) { provider.writeScheme(doc); } } provider.writeLib(); } else { grunt.log.write("cannot create schemes for database " + this.db.name + ", because there we can't use the provider "+this.db.provider+" for it."); } } else { grunt.log.write("cannot create schemes for database " + this.db.name + ", because there is no provider for it."); } }
Test.expect(reverseWords('The quick brown fox jumps over the lazy dog.') === 'ehT kciuq nworb xof spmuj revo eht yzal .god'); Test.expect(reverseWords('apple') === 'elppa'); Test.expect(reverseWords('a b c d') === 'a b c d'); Test.expect(reverseWords('double spaced words') === 'elbuod decaps sdrow');
'use strict'; import { gl } from './Context'; import { mat4 } from 'gl-matrix'; import Camera from './Camera'; class OrthographicCamera extends Camera { constructor( { path, uniforms, background, translucence, right, top, name = 'orthographic.camera', left = -1, bottom = -1, near = 0.1, far = 1 } = {}) { super({ name, path, uniforms, background, translucence }); this.left = left; this.right = right; this.bottom = bottom; this.top = top; this.near = near; this.far = far; this.inheritance = ['Entity', 'Structure', 'Camera', 'OrthographicCamera']; this.configure(); } get left() { return this._left; } set left(left) { this._left = left; } get right() { return this._right; } set right(right) { this._right = right; } get bottom() { return this._bottom; } set bottom(bottom) { this._bottom = bottom; } get top() { return this._top; } set top(top) { this._top = top; } get near() { return this._near; } set near(near) { this._near = near; } get far() { return this._far; } set far(far) { this._far = far; } configure() { super.configure(); mat4.ortho(this.projectionMatrix, this.left, this.right, this.bottom, this.top, this.near, this.far); mat4.identity(this.modelViewMatrix); } bind(program) { super.bind(program); gl.disable(gl.DEPTH_TEST); gl.viewport(0, 0, this.right, this.top); } } export default OrthographicCamera;
// Karma configuration // Generated on Wed Feb 17 2016 10:45:47 GMT+0100 (CET) module.exports = function(config) { config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) basePath: './', // frameworks to use // available frameworks: https://npmjs.org/browse/keyword/karma-adapter frameworks: ['systemjs', 'jasmine'], // list of files / patterns to load in the browser files: [ 'app/**/*spec.js' ], systemjs: { // Point out where the SystemJS config file is configFile: 'app/systemjs.config.js', serveFiles: [ 'app/**/*.js' ] }, plugins: [ 'karma-systemjs', 'karma-chrome-launcher', 'karma-firefox-launcher', 'karma-phantomjs-launcher', 'karma-jasmine', 'karma-junit-reporter', 'karma-coverage' ], // list of files to exclude exclude: [], // preprocess matching files before serving them to the browser // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor preprocessors: { 'app/**/!(*spec).js': ['coverage'] }, // test results reporter to use // possible values: 'dots', 'progress' // available reporters: https://npmjs.org/browse/keyword/karma-reporter reporters: ['progress', 'coverage'], coverageReporter: { reporters:[ {type: 'lcov', subdir: 'report-lcov'}, {type: 'json', subdir: 'report-json', file: 'coverage-final.json'}, ] }, // web server port port: 9876, // enable / disable colors in the output (reporters and logs) colors: true, // level of logging // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes autoWatch: true, // start these browsers // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher browsers: ['PhantomJS'], // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits singleRun: true, // Concurrency level // how many browser should be started simultaneous concurrency: Infinity }) }
'use strict' // create a net-peer compatible object based on a UDP datagram socket module.exports = function udpAdapter(udpSocket, udpDestinationHost, udpDestinationPort) { const _listeners = [] udpSocket.on('message', (msg, rinfo) => { //console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`) for(let i=0; i < _listeners.length; i++) { _listeners[i](msg) } }) let on = function(event, fn) { if (event === 'data') { _listeners.push(fn) } } let send = function(message) { udpSocket.send(Buffer.from(message.buffer), udpDestinationPort, udpDestinationHost, (err) => { }) } return Object.freeze({ on, send }) }
var Filter = require('broccoli-filter') module.exports = WrapFilter; WrapFilter.prototype = Object.create(Filter.prototype); WrapFilter.prototype.constructor = WrapFilter; function WrapFilter (inputTree, options) { if (!(this instanceof WrapFilter)) return new WrapFilter(inputTree, options) Filter.call(this, inputTree, options) this.options = options || {}; this.options.extensions = this.options.extensions || ['js']; this.extensions = this.options.extensions; } WrapFilter.prototype.processString = function (string) { var wrapper = this.options.wrapper; if ( !(wrapper instanceof Array) ) { return string; } var startWith = wrapper[0] || ''; var endWith = wrapper[1] || ''; return [startWith, string, endWith].join('') }
Template.formeditprofile.events({ 'submit #editform': function(event){ event.preventDefault(); var firstNameVar = event.target.firstname.value; var lastNameVar = event.target.lastname.value; var classVar = event.target.classvar.value; Profiles.insert({ uid:Meteor.userId(), firstname: firstNameVar, lastname: lastNameVar, classvar: classVar }); alert("Done!"); } }); Template.addprofile.rendered = function(){ this.$('.ui.dropdown').dropdown(); }
var expect = require('expect.js'); var EventEmitter = require('events').EventEmitter; var fixtures = require('../fixtures'); var Detector = require('../../lib/detector.js'); describe('Detector', function() { // Used to test emitted events var found; var listener = function(magicNumber) { found.push(magicNumber); }; beforeEach(function() { found = []; }); describe('constructor', function() { it('inherits from EventEmitter', function() { expect(new Detector()).to.be.an(EventEmitter); }); it('accepts an array of file paths', function() { var filePaths = ['path1.js', 'path2.js']; var detector = new Detector(filePaths); expect(detector._filePaths).to.be(filePaths); }); it('accepts a boolean to enforce the use of const', function() { var detector = new Detector([], { enforceConst: true }); expect(detector._enforceConst).to.be(true); }); it('accepts an array of numbers to ignore', function() { var ignore = [1, 2, 3.4]; var detector = new Detector([], { ignore: ignore }); expect(detector._ignore).to.be(ignore); }); }); describe('run', function() { it('is compatible with callbacks', function(done) { var detector = new Detector([fixtures.emptyFile]); detector.run(function(err) { done(err); }); }); it('is compatible with promises', function(done) { var detector = new Detector([fixtures.emptyFile]); detector.run().then(function() { done(); }).catch(done); }); it('returns an Error if not given an array of file paths', function(done) { var detector = new Detector(); detector.run().catch(function(err) { expect(err).to.be.an(Error); expect(err.message).to.be('filePaths must be a non-empty array of paths'); done(); }); }); }); it('emits end on completion, passing the number of files parsed', function(done) { var detector = new Detector([fixtures.emptyFile, fixtures.singleVariable]); detector.on('end', function(numFiles) { expect(numFiles).to.be(2); done(); }); detector.run().catch(done); }); it('emits no events when parsing an empty file', function(done) { var detector = new Detector([fixtures.emptyFile]); detector.on('found', listener); detector.run().then(function() { expect(found).to.be.empty(); done(); }).catch(done); }); it('emits no events when the file contains only named constants', function(done) { var detector = new Detector([fixtures.singleVariable]); detector.on('found', listener); detector.run().then(function() { expect(found).to.be.empty(); done(); }).catch(done); }); it('emits no events for literals assigned to object properties', function(done) { var detector = new Detector([fixtures.objectProperties]); detector.on('found', listener); detector.run().then(function() { expect(found).to.have.length(2); expect(found[0].value).to.be('4'); expect(found[1].value).to.be('5'); done(); }).catch(done); }); it('emits no events for literals used in AssignmentExpressions', function(done) { var detector = new Detector([fixtures.assignmentExpressions]); detector.on('found', listener); detector.run().then(function() { expect(found).to.have.length(0); done(); }).catch(done); }); it('emits no events for numbers marked by ignore:line', function(done) { var detector = new Detector([fixtures.lineIgnore]); detector.on('found', listener); detector.run().then(function() { expect(found).to.be.empty(); done(); }).catch(done); }); it('emits no events between ignore:start / ignore:end', function(done) { var detector = new Detector([fixtures.blockIgnore]); detector.on('found', listener); detector.run().then(function() { expect(found).to.be.empty(); done(); }).catch(done); }); it('emits a "found" event containing a magic number, when found', function(done) { var detector = new Detector([fixtures.secondsInMinute]); detector.on('found', listener); detector.run().then(function() { expect(found).to.have.length(1); expect(found[0].value).to.be('60'); expect(found[0].file.substr(-18)).to.be('secondsInMinute.js'); expect(found[0].startColumn).to.be(9); expect(found[0].endColumn).to.be(11); expect(found[0].fileLength).to.be(4); expect(found[0].lineNumber).to.be(2); expect(found[0].lineSource).to.be(' return 60;'); expect(found[0].contextLines).to.eql([ 'function getSecondsInMinute() {', ' return 60;', '}' ]); expect(found[0].contextIndex).to.eql(1); done(); }).catch(done); }); it('correctly emits hex and octal values', function(done) { var detector = new Detector([fixtures.hexOctal]); detector.on('found', listener); detector.run().then(function() { expect(found).to.have.length(3); expect(found[0].value).to.be('0x1A'); expect(found[1].value).to.be('0x02'); expect(found[2].value).to.be('071'); done(); }).catch(done); }); it('skips unnamed constants within the ignore list', function(done) { var detector = new Detector([fixtures.ignore], { ignore: [0] }); detector.on('found', listener); detector.run().then(function() { expect(found).to.have.length(1); expect(found[0].value).to.be('1'); done(); }).catch(done); }); it('ignores the shebang at the start of a file', function(done) { var detector = new Detector([fixtures.shebang]); detector.on('found', listener); detector.run().then(function() { expect(found).to.have.length(1); expect(found[0].lineNumber).to.be(4); expect(found[0].value).to.be('100'); done(); }).catch(done); }); describe('with detectObjects set to true', function() { it('emits a "found" event for object literals', function(done) { var detector = new Detector([fixtures.objectLiterals], { detectObjects: true }); detector.on('found', listener); detector.run().then(function() { expect(found).to.have.length(1); expect(found[0].value).to.be('42'); done(); }).catch(done); }); it('emits a "found" event for property assignments', function(done) { var detector = new Detector([fixtures.objectProperties], { detectObjects: true }); detector.on('found', listener); detector.run().then(function() { expect(found).to.have.length(4); expect(found[0].value).to.be('2'); expect(found[1].value).to.be('3'); expect(found[2].value).to.be('4'); expect(found[3].value).to.be('5'); done(); }).catch(done); }); }); describe('with enforceConst set to true', function() { it('emits a "found" event for variable declarations', function(done) { var detector = new Detector([fixtures.constVariable], { enforceConst: true }); detector.on('found', listener); detector.run().then(function() { expect(found).to.have.length(1); expect(found[0].value).to.be('10'); done(); }).catch(done); }); it('emits a "found" event for object expressions', function(done) { var detector = new Detector([fixtures.constObject], { enforceConst: true }); detector.on('found', listener); detector.run().then(function() { expect(found).to.have.length(1); expect(found[0].value).to.be('10'); done(); }).catch(done); }); }); });
import React, { PropTypes } from 'react'; import { connect } from 'react-redux'; import './PostListView.scss'; import { toastr } from 'react-redux-toastr'; import { bindActionCreators } from 'redux'; import { fetchPostsFromApi, selectPostCategory, clearPostsErrors, clearPostsMessages } from '../../../actions/actionCreators'; import CategoryFilterContainer from '../../CategoryFilterContainer/CategoryFilterContainer'; import { PostList, LoadingIndicator, Divider, MessagesSection } from '../../../components'; import NoPostsFound from '../Misc/NoPostsFound'; // containsCategory :: Object -> Object -> Bool const containsCategory = (post, category) => { const categories = post.categories.filter( (cat) => cat._id == category.id ); return categories.length > 0; }; // getFilteredPosts :: Object -> [Object] -> [Object] const getFilteredPosts = ( category, posts ) => { if (category === null || category.name === 'All') { return posts; } return posts.filter((post) => { if (containsCategory(post, category)) { return post; } return undefined; }); }; /* Only used internally and it's so small so not worth creating a new component */ const SectionSubTitle = ({ title }) => ( <h4 className="section-sub-title"> {title} </h4> ); SectionSubTitle.propTypes = { title: PropTypes.string.isRequired }; class PostListView extends React.Component { constructor(props) { super(props); this.handleSelectCategory = this.handleSelectCategory.bind(this); this.handleChangePage = this.handleChangePage.bind(this); this.handleClose = this.handleClose.bind(this); } componentDidMount() { const { posts, fetchPosts } = this.props; if (!posts.items || posts.items.length === 0) { fetchPosts(); } } handleChangePage() { //TODO: Implement me!! } handleSelectCategory(category) { const { selectPostCat } = this.props; selectPostCat(category); } showMessage(message) { toastr.info(message); } handleClose(sender) { const { clearErrors, clearMessages } = this.props; const theElement = sender.target.id; if (theElement === 'button-close-error-panel') { clearErrors(); } else if (theElement === 'button-close-messages-panel') { clearMessages(); } } render() { const { posts, isFetching, postCategories, selectedCategory, errors, messages } = this.props; const items = posts.items; const visiblePosts = getFilteredPosts(selectedCategory, items); return ( <LoadingIndicator isLoading={isFetching}> <div className="post-list-view__wrapper"> <MessagesSection messages={messages} errors={errors} onClose={this.handleClose} /> <h1 className="section-header">From the Blog</h1> <SectionSubTitle title={selectedCategory.name == 'All' ? // eslint-disable-line 'All Posts' : `Selected Category: ${selectedCategory.name}` } /> <Divider /> <CategoryFilterContainer categories={postCategories} onSelectCategory={this.handleSelectCategory} selectedCategory={selectedCategory} /> {visiblePosts !== undefined && visiblePosts.length > 0 ? <PostList posts={visiblePosts} onChangePage={this.handleChangePage} /> : <NoPostsFound selectedCategory={selectedCategory} /> } </div> </LoadingIndicator> ); } } PostListView.propTypes = { dispatch: PropTypes.func.isRequired, errors: PropTypes.array.isRequired, messages: PropTypes.array.isRequired, posts: PropTypes.object.isRequired, isFetching: PropTypes.bool.isRequired, fetchPosts: PropTypes.func.isRequired, selectPostCat: PropTypes.func.isRequired, postCategories: PropTypes.array.isRequired, selectedCategory: PropTypes.object.isRequired, clearMessages: PropTypes.func.isRequired, clearErrors: PropTypes.func.isRequired }; // mapStateToProps :: {State} -> {Props} const mapStateToProps = (state) => ({ posts: state.posts, postCategories: state.posts.categories, selectedCategory: state.posts.selectedCategory, messages: state.messages.posts, errors: state.errors.posts, isFetching: state.posts.isFetching }); // mapDispatchToProps :: {Dispatch} -> {Props} const mapDispatchToProps = (dispatch) => bindActionCreators({ fetchPosts: () => fetchPostsFromApi(), selectPostCat: (category) => selectPostCategory(category), clearMessages: () => clearPostsMessages(), clearErrors: () => clearPostsErrors() }, dispatch); export default connect( mapStateToProps, mapDispatchToProps )(PostListView);
version https://git-lfs.github.com/spec/v1 oid sha256:4a4e80129485fe848fa53149568184f09fa2da8648b6476b750ef97344bd4c5b size 10959
/** * Module dependencies. */ var util = require('sails-util'), uuid = require('node-uuid'), path = require('path'), generateSecret = require('./generateSecret'), cookie = require('express/node_modules/cookie'), parseSignedCookie = require('cookie-parser').signedCookie, ConnectSession = require('express/node_modules/connect').middleware.session.Session; module.exports = function(sails) { ////////////////////////////////////////////////////////////////////////////// // TODO: // // All of this craziness can be replaced by making the socket.io interpreter // 100% connect-compatible (it's close!). Then, the connect cookie parser // can be used directly with Sails' simulated req and res objects. // ////////////////////////////////////////////////////////////////////////////// /** * Prototype for the connect session store wrapper used by the sockets hook. * Includes a save() method to persist the session data. */ function SocketIOSession(options) { var sid = options.sid, data = options.data; this.save = function(cb) { if (!sid) { sails.log.error('Trying to save session, but could not determine session ID.'); sails.log.error('This probably means a requesting socket did not send a cookie.'); sails.log.error('Usually, this happens when a socket from an old browser tab ' + ' tries to reconnect.'); sails.log.error('(this can also occur when trying to connect a cross-origin socket.)'); if (cb) cb('Could not save session.'); return; } // Merge data directly into instance to allow easy access on `req.session` later util.defaults(this, data); // Persist session Session.set(sid, sails.util.cloneDeep(this), function(err) { if (err) { sails.log.error('Could not save session:'); sails.log.error(err); } if (cb) cb(err); }); }; // Set the data on this object, since it will be used as req.session util.extend(this, options.data); } // Session hook var Session = { defaults: { session: { adapter: 'memory', key: "sails.sid" } }, /** * Normalize and validate configuration for this hook. * Then fold any modifications back into `sails.config` */ configure: function() { // Validate config // Ensure that secret is specified if a custom session store is used if (sails.config.session) { if (!util.isObject(sails.config.session)) { throw new Error('Invalid custom session store configuration!\n' + '\n' + 'Basic usage ::\n' + '{ session: { adapter: "memory", secret: "someVerySecureString", /* ...if applicable: host, port, etc... */ } }' + '\n\nCustom usage ::\n' + '{ session: { store: { /* some custom connect session store instance */ }, secret: "someVerySecureString", /* ...custom settings.... */ } }' ); } } // If session config is set, but secret is undefined, set a secure, one-time use secret if (!sails.config.session || !sails.config.session.secret) { sails.log.verbose('Session secret not defined-- automatically generating one for now...'); if (sails.config.environment === 'production') { sails.log.warn('Session secret must be identified!'); sails.log.warn('Automatically generating one for now...'); sails.log.error('This generated session secret is NOT OK for production!'); sails.log.error('It will change each time the server starts and break multi-instance deployments.'); sails.log.blank(); sails.log.error('To set up a session secret, add or update it in `config/session.js`:'); sails.log.error('module.exports.session = { secret: "keyboardcat" }'); sails.log.blank(); } sails.config.session.secret = generateSecret(); } // Backwards-compatibility / shorthand notation // (allow mongo or redis session stores to be specified directly) if (sails.config.session.adapter === 'redis') { sails.config.session.adapter = 'connect-redis'; } else if (sails.config.session.adapter === 'mongo') { sails.config.session.adapter = 'connect-mongo'; } }, /** * Create a connection to the configured session store * and keep it around * * @api private */ initialize: function(cb) { var sessionConfig = sails.config.session; // Intepret session adapter config and "new up" a session store if (util.isObject(sessionConfig) && !util.isObject(sessionConfig.store)) { // Unless the session is explicitly disabled, require the appropriate adapter if (sessionConfig.adapter) { // 'memory' is a special case if (sessionConfig.adapter === 'memory') { var MemoryStore = require('express').session.MemoryStore; sessionConfig.store = new MemoryStore(); } // Try and load the specified adapter from the local sails project, // or catch and return error: else { var COULD_NOT_REQUIRE_CONNECT_ADAPTER_ERR = function (adapter, packagejson, e) { var errMsg; if (e && typeof e === 'object' && e instanceof Error) { errMsg = e.stack; } else { errMsg = util.inspect(e); } var output = 'Could not load Connect session adapter :: ' + adapter + '\n'; if (packagejson && !packagejson.main) { output+='(If this is your module, make sure that the module has a "main" configuration in its package.json file)'; } output+='\nError from adapter:\n'+ errMsg+'\n\n'; // Recommend installation of the session adapter: output += 'Do you have the Connect session adapter installed in this project?\n'; output += 'Try running the following command in your project\'s root directory:\n'; var installRecommendation = 'npm install '; if (adapter === 'connect-redis') { installRecommendation += '[email protected]'; installRecommendation += '\n(Note that `[email protected]` introduced breaking changes- make sure you have v1.4.5 installed!)'; } else { installRecommendation += adapter; installRecommendation +='\n(Note: Make sure the version of the Connect adapter you install is compatible with Express 3/Sails v0.10)'; } installRecommendation += '\n'; output += installRecommendation; return output; }; try { // Determine the path to the adapter by using the "main" described in its package.json file: var pathToAdapterDependency; var pathToAdapterPackage = path.resolve(sails.config.appPath, 'node_modules', sessionConfig.adapter ,'package.json'); var adapterPackage; try { adapterPackage = require(pathToAdapterPackage); pathToAdapterDependency = path.resolve(sails.config.appPath, 'node_modules', sessionConfig.adapter, adapterPackage.main); } catch (e) { return cb(COULD_NOT_REQUIRE_CONNECT_ADAPTER_ERR(sessionConfig.adapter, adapterPackage, e)); } var SessionAdapter = require(pathToAdapterDependency); var CustomStore = SessionAdapter(require('express')); sessionConfig.store = new CustomStore(sessionConfig); } catch (e) { // TODO: negotiate error return cb(COULD_NOT_REQUIRE_CONNECT_ADAPTER_ERR(sessionConfig.adapter, adapterPackage, e)); } } } } // Save reference in `sails.session` sails.session = Session; return cb(); }, /** * Create a new sid and build an empty session for it. * * @param {Object} handshake - a socket "handshake" -- basically, this is like `req` * @param {Function} cb * @returns live session, with `id` property === new sid */ generate: function(handshake, cb) { // Generate a session object w/ sid // This is important since we need this sort of object as the basis for the data // we'll save directly into the session store. // (handshake is a pretend `req` object, and 2nd argument is cookie config) var session = new ConnectSession(handshake, { cookie: { // Prevent access from client-side javascript httpOnly: true, // Restrict to path path: '/' } }); // Next, persist the new session Session.set(session.id, session, function(err) { if (err) return cb(err); sails.log.verbose('Generated new session (', session.id, ') for socket....'); // Pass back final session object return cb(null, session); }); }, /** * @param {String} sessionId * @param {Function} cb * * @api private */ get: function(sessionId, cb) { if (!util.isFunction(cb)) { throw new Error('Invalid usage :: `Session.get(sessionId, cb)`'); } return sails.config.session.store.get(sessionId, cb); }, /** * @param {String} sessionId * @param {} data * @param {Function} [cb] - optional * * @api private */ set: function(sessionId, data, cb) { cb = util.optional(cb); return sails.config.session.store.set(sessionId, data, cb); }, /** * Create a session transaction * * Load the Connect session data using the sessionID in the socket.io handshake object * Mix-in the session.save() method for persisting the data back to the session store. * * Functionally equivalent to connect's sessionStore middleware. */ fromSocket: function(socket, cb) { // If a socket makes it here, even though its associated session is not specified, // it's authorized as far as the app is concerned, so no need to do that again. // Instead, use the cookie to look up the sid, and then the sid to look up the session data // If sid doesn't exit in socket, we have to do a little work first to get it // (or generate a new one-- and therefore a new empty session as well) if (!socket.handshake.sessionID && !socket.handshake.headers.cookie) { // If no cookie exists, generate a random one (this will create a new session!) var generatedCookie = sails.config.session.key + '=' + uuid.v1(); socket.handshake.headers.cookie = generatedCookie; sails.log.verbose('Could not fetch session, since connecting socket (', socket.id, ') has no cookie.'); sails.log.verbose('Is this a cross-origin socket..?)'); sails.log.verbose('Generated a one-time-use cookie:', generatedCookie); sails.log.verbose('This will result in an empty session, i.e. (req.session === {})'); // Convert cookie into `sid` using session secret // Maintain sid in socket so that the session can be queried before processing each incoming message socket.handshake.cookie = cookie.parse(generatedCookie); // Parse and decrypt cookie and save it in the socket.handshake socket.handshake.sessionID = parseSignedCookie(socket.handshake.cookie[sails.config.session.key], sails.config.session.secret); // Generate and persist a new session in the store Session.generate(socket.handshake, function(err, sessionData) { if (err) return cb(err); sails.log.silly('socket.handshake.sessionID is now :: ', socket.handshake.sessionID); // Provide access to adapter-agnostic `.save()` return cb(null, new SocketIOSession({ sid: sessionData.id, data: sessionData })); }); return; } try { // Convert cookie into `sid` using session secret // Maintain sid in socket so that the session can be queried before processing each incoming message socket.handshake.cookie = cookie.parse(socket.handshake.headers.cookie); // Parse and decrypt cookie and save it in the socket.handshake socket.handshake.sessionID = parseSignedCookie(socket.handshake.cookie[sails.config.session.key], sails.config.session.secret); } catch (e) { sails.log.error('Could not load session for socket #' + socket.id); sails.log.error('The socket\'s cookie could not be parsed into a sessionID.'); sails.log.error('Unless you\'re overriding the `authorization` function, make sure ' + 'you pass in a valid `' + sails.config.session.key + '` cookie'); sails.log.error('(or omit the cookie altogether to have a new session created and an ' + 'encrypted cookie sent in the response header to your socket.io upgrade request)'); return cb(e); } // If sid DOES exist, it's easy to look up in the socket var sid = socket.handshake.sessionID; // Cache the handshake in case it gets wiped out during the call to Session.get var handshake = socket.handshake; // Retrieve session data from store Session.get(sid, function(err, sessionData) { if (err) { sails.log.error('Error retrieving session from socket.'); return cb(err); } // sid is not known-- the session secret probably changed // Or maybe server restarted and it was: // (a) using an auto-generated secret, or // (b) using the session memory store // and so it doesn't recognize the socket's session ID. else if (!sessionData) { sails.log.verbose('A socket (' + socket.id + ') is trying to connect with an invalid or expired session ID (' + sid + ').'); sails.log.verbose('Regnerating empty session...'); Session.generate(handshake, function(err, sessionData) { if (err) return cb(err); // Provide access to adapter-agnostic `.save()` return cb(null, new SocketIOSession({ sid: sessionData.id, data: sessionData })); }); } // Otherwise session exists and everything is ok. // Instantiate SocketIOSession (provides .save() method) // And extend it with session data else return cb(null, new SocketIOSession({ data: sessionData, sid: sid })); }); } }; return Session; };
function showErrorMessage(errorMessage) { $("#authorize-prompt") .addClass("error-prompt") .removeClass("success-prompt") .html(errorMessage); } function showSuccessMessage(message) { $("#authorize-prompt") .removeClass("error-prompt") .addClass("success-prompt") .html(message); } function shake() { var l = 10; var original = -150; for( var i = 0; i < 8; i++ ) { var computed; if (i % 2 > 0.51) { computed = original - l; } else { computed = original + l; } $("#login-box").animate({ "left": computed + "px" }, 100); } $("#login-box").animate({ "left": "-150px" }, 50); } function handleAuthSuccess(data) { showSuccessMessage(data.message); $("#login-button").prop("disabled", true); setTimeout(function() { location.href = data.redirectUri; }, 1000); } function handleAuthFailure(data) { showErrorMessage(data.responseJSON.message); shake(); } $(function () { $('[data-toggle="tooltip"]').tooltip() }) function handleGrantAuthorization() { var csrf_token = $("#csrf_token").val(); var client_id = $("#client_id").val(); $.ajax("/oauth/authorize", { "method": "POST", "data": { client_id, csrf_token }, "success": handleAuthSuccess, "error": handleAuthFailure }); }
module.exports = [ 'M6 2 L26 2 L26 30', 'L16 24 L6 30 Z' ].join(' ');
// DATA_TEMPLATE: empty_table oTest.fnStart("5396 - fnUpdate with 2D arrays for a single row"); $(document).ready(function () { $('#example thead tr').append('<th>6</th>'); $('#example thead tr').append('<th>7</th>'); $('#example thead tr').append('<th>8</th>'); $('#example thead tr').append('<th>9</th>'); $('#example thead tr').append('<th>10</th>'); var aDataSet = [ [ "1", "홍길동", "1154315", "etc1", [ [ "[email protected]", "2011-03-04" ], [ "[email protected]", "2009-07-06" ], [ "[email protected]", ",hide" ], [ "[email protected]", "" ] ], "2011-03-04", "show" ], [ "2", "홍길순", "2154315", "etc2", [ [ "[email protected]", "2009-09-26" ], [ "[email protected]", "2009-05-21,hide" ], [ "[email protected]", "2010-03-05" ], [ "[email protected]", ",hide" ], [ "[email protected]", "2010-03-05" ] ], "2010-03-05", "show" ] ] var oTable = $('#example').dataTable({ "aaData": aDataSet, "aoColumns": [ { "mData": "0"}, { "mData": "1"}, { "mData": "2"}, { "mData": "3"}, { "mData": "4.0.0"}, { "mData": "4.0.1"}, { "mData": "4.1.0"}, { "mData": "4.1.1"}, { "mData": "5"}, { "mData": "6"} ] }); oTest.fnTest( "Initialisation", null, function () { return $('#example tbody tr:eq(0) td:eq(0)').html() == '1'; } ); oTest.fnTest( "Update row", function () { $('#example').dataTable().fnUpdate([ "0", "홍길순", "2154315", "etc2", [ [ "[email protected]", "2009-09-26" ], [ "[email protected]", "2009-05-21,hide" ], [ "[email protected]", "2010-03-05" ], [ "[email protected]", ",hide" ], [ "[email protected]", "2010-03-05" ] ], "2010-03-05", "show" ], 1); }, function () { return $('#example tbody tr:eq(0) td:eq(0)').html() == '0'; } ); oTest.fnTest( "Original row preserved", null, function () { return $('#example tbody tr:eq(1) td:eq(0)').html() == '1'; } ); oTest.fnComplete(); });
/* * jQuery Touch Optimized Sliders "R"Us * HTML media * * Copyright (c) Fred Heusschen * www.frebsite.nl */ !function(i){var n="tosrus",e="html";i[n].media[e]={filterAnchors:function(n){return"#"==n.slice(0,1)&&i(n).is("div")},initAnchors:function(e,t){i('<div class="'+i[n]._c("html")+'" />').append(i(t)).appendTo(e),e.removeClass(i[n]._c.loading).trigger(i[n]._e.loaded)},filterSlides:function(i){return i.is("div")},initSlides:function(){}}}(jQuery);
/** * Knook-mailer * https://github.com/knook/knook.git * Auhtors: Alexandre Lagrange-Cetto, Olivier Graziano, Olivier Marin * Created on 15/04/2016. * version 0.1.0 */ 'use strict'; module.exports = { Accounts: require('./src/Accounts'), Email: require('./src/Email'), Init: require('./src/Init'), Prefs: require('./src/Prefs'), Security: require('./src/Security') };
module.exports = { KeyQ: { printable: true, keyCode: 81, Default: 'ქ', Shift: '', CapsLock: 'Ⴕ', Shift_CapsLock: '', Alt: '', Alt_Shift: '' }, KeyW: { printable: true, keyCode: 87, Default: 'წ', Shift: 'ჭ', CapsLock: 'Ⴜ', Shift_CapsLock: 'Ⴝ', Alt: '∑', Alt_Shift: '„' }, KeyE: { printable: true, keyCode: 69, Default: 'ე', Shift: '', CapsLock: 'Ⴄ', Shift_CapsLock: '', Alt: '´', Alt_Shift: '´' }, KeyR: { printable: true, keyCode: 82, Default: 'რ', Shift: 'ღ', CapsLock: 'Ⴐ', Shift_CapsLock: 'Ⴖ', Alt: '®', Alt_Shift: '‰' }, KeyT: { printable: true, keyCode: 84, Default: 'ტ', Shift: 'თ', CapsLock: 'Ⴒ', Shift_CapsLock: 'Ⴇ', Alt: '†', Alt_Shift: 'ˇ' }, KeyY: { printable: true, keyCode: 89, Default: 'ყ', Shift: '', CapsLock: 'Ⴗ', Shift_CapsLock: '', Alt: '¥', Alt_Shift: 'Á' }, KeyU: { printable: true, keyCode: 85, Default: 'უ', Shift: '', CapsLock: 'Ⴓ', Shift_CapsLock: '', Alt: '', Alt_Shift: '' }, KeyI: { printable: true, keyCode: 73, Default: 'ი', Shift: '', CapsLock: 'Ⴈ', Shift_CapsLock: '', Alt: 'ˆ', Alt_Shift: 'ˆ' }, KeyO: { printable: true, keyCode: 79, Default: 'ო', Shift: '`', CapsLock: 'Ⴍ', Shift_CapsLock: '', Alt: 'ø', Alt_Shift: 'Ø' }, KeyP: { printable: true, keyCode: 80, Default: 'პ', Shift: '~', CapsLock: 'Ⴎ', Shift_CapsLock: '', Alt: 'π', Alt_Shift: '∏' }, KeyA: { printable: true, keyCode: 65, Default: 'ა', Shift: '', CapsLock: 'Ⴀ', Shift_CapsLock: '', Alt: 'å', Alt_Shift: 'Å' }, KeyS: { printable: true, keyCode: 83, Default: 'ს', Shift: 'შ', CapsLock: 'Ⴑ', Shift_CapsLock: 'Ⴘ', Alt: 'ß', Alt_Shift: 'Í' }, KeyD: { printable: true, keyCode: 68, Default: 'დ', Shift: '', CapsLock: 'Ⴃ', Shift_CapsLock: '', Alt: '∂', Alt_Shift: 'Î' }, KeyF: { printable: true, keyCode: 70, Default: 'ფ', Shift: '', CapsLock: 'Ⴔ', Shift_CapsLock: '', Alt: 'ƒ', Alt_Shift: 'Ï' }, KeyG: { printable: true, keyCode: 71, Default: 'გ', Shift: '', CapsLock: 'Ⴂ', Shift_CapsLock: '', Alt: '˙', Alt_Shift: '˝' }, KeyH: { printable: true, keyCode: 72, Default: 'ჰ', Shift: '', CapsLock: 'Ⴠ', Shift_CapsLock: '', Alt: '∆', Alt_Shift: 'Ó' }, KeyJ: { printable: true, keyCode: 74, Default: 'ჯ', Shift: 'ჟ', CapsLock: 'Ⴟ', Shift_CapsLock: 'Ⴏ', Alt: '˚', Alt_Shift: 'Ô' }, KeyK: { printable: true, keyCode: 75, Default: 'კ', Shift: '', CapsLock: 'Ⴉ', Shift_CapsLock: '', Alt: '¬', Alt_Shift: '' }, KeyL: { printable: true, keyCode: 76, Default: 'ლ', Shift: '', CapsLock: 'Ⴊ', Shift_CapsLock: '', Alt: 'Ω', Alt_Shift: 'Ò' }, KeyZ: { printable: true, keyCode: 90, Default: 'ზ', Shift: 'ძ', CapsLock: 'Ⴆ', Shift_CapsLock: '', Alt: '≈', Alt_Shift: '¸' }, KeyX: { printable: true, keyCode: 88, Default: 'ხ', Shift: '', CapsLock: 'Ⴞ', Shift_CapsLock: '', Alt: 'ç', Alt_Shift: '˛' }, KeyC: { printable: true, keyCode: 67, Default: 'ც', Shift: 'ჩ', CapsLock: 'Ⴚ', Shift_CapsLock: 'Ⴙ', Alt: '√', Alt_Shift: 'Ç' }, KeyV: { printable: true, keyCode: 86, Default: 'ვ', Shift: '', CapsLock: 'Ⴅ', Shift_CapsLock: '', Alt: '∫', Alt_Shift: '◊' }, KeyB: { printable: true, keyCode: 66, Default: 'ბ', Shift: '', CapsLock: 'Ⴁ', Shift_CapsLock: '', Alt: '˜', Alt_Shift: 'ı' }, KeyN: { printable: true, keyCode: 78, Default: 'ნ', Shift: '', CapsLock: 'Ⴌ', Shift_CapsLock: '', Alt: 'µ', Alt_Shift: '˜' }, KeyM: { printable: true, keyCode: 77, Default: 'მ', Shift: '', CapsLock: 'Ⴋ', Shift_CapsLock: '', Alt: 'µ', Alt_Shift: 'Â' }, // digits Digit1: { printable: true, keyCode: 49, Default: '1', Shift: '!', CapsLock: '1', Shift_CapsLock: '!', Alt_Shift: '⁄', Alt: '¡' }, Digit2: { printable: true, keyCode: 50, Default: '2', Shift: '@', CapsLock: '2', Shift_CapsLock: '@', Alt_Shift: '€', Alt: '™' }, Digit3: { printable: true, keyCode: 51, Default: '3', Shift: '#', CapsLock: '3', Shift_CapsLock: '#', Alt_Shift: '‹', Alt: '£' }, Digit4: { printable: true, keyCode: 52, Default: '4', Shift: '$', CapsLock: '4', Shift_CapsLock: '$', Alt_Shift: '›', Alt: '¢' }, Digit5: { printable: true, keyCode: 53, Default: '5', Shift: '%', CapsLock: '5', Shift_CapsLock: '%', Alt_Shift: 'fi', Alt: '∞' }, Digit6: { printable: true, keyCode: 54, Default: '6', Shift: '^', CapsLock: '6', Shift_CapsLock: '^', Alt_Shift: 'fl', Alt: '§' }, Digit7: { printable: true, keyCode: 55, Default: '7', Shift: '&', CapsLock: '7', Shift_CapsLock: '&', Alt_Shift: '‡', Alt: '¶' }, Digit8: { printable: true, keyCode: 56, Default: '8', Shift: '*', CapsLock: '8', Shift_CapsLock: '*', Alt_Shift: '°', Alt: '•' }, Digit9: { printable: true, keyCode: 57, Default: '9', Shift: '(', CapsLock: '9', Shift_CapsLock: '(', Alt_Shift: '·', Alt: 'º' }, Digit0: { printable: true, keyCode: 48, Default: '0', Shift: ')', CapsLock: '0', Shift_CapsLock: ')', Alt_Shift: '‚', Alt: 'º' }, // symbols IntlBackslash: { printable: true, keyCode: 192, Default: '§', Shift: '±', CapsLock: '§', Shift_CapsLock: '±', Alt: '§', }, Minus: { printable: true, keyCode: 189, Default: '-', Shift: '_', CapsLock: '-', Shift_CapsLock: '_', Alt: '–', }, Equal: { printable: true, keyCode: 187, Default: '=', Shift: '+', CapsLock: '=', Shift_CapsLock: '+', Alt: '≠' }, BracketLeft: { printable: true, keyCode: 219, Default: '[', Shift: '{', CapsLock: '[', Shift_CapsLock: '{', Alt: '“' }, BracketRight: { printable: true, keyCode: 221, Default: ']', Shift: '}', CapsLock: ']', Shift_CapsLock: '}', Alt: '‘' }, Semicolon: { printable: true, keyCode: 186, Default: ';', Shift: ':', CapsLock: ';', Shift_CapsLock: ':', Alt: '…' }, Quote: { printable: true, keyCode: 222, Default: '\'', Shift: '"', CapsLock: '\'', Shift_CapsLock: '"', Alt: 'æ' }, Backslash: { printable: true, keyCode: 220, Default: '\\', Shift: '|', CapsLock: '\\', Shift_CapsLock: '|', Alt: '«' }, Backquote: { printable: true, keyCode: 192, Default: '`', Shift: '~', CapsLock: '`', Shift_CapsLock: '~', Alt: '`' }, Comma: { printable: true, keyCode: 188, Default: ',', Shift: '<', CapsLock: ',', Shift_CapsLock: '<', Alt: '≤' }, Period: { printable: true, keyCode: 190, Default: '.', Shift: '>', CapsLock: '.', Shift_CapsLock: '>', Alt: '≥' }, Slash: { printable: true, keyCode: 191, Default: '/', Shift: '?', CapsLock: '/', Shift_CapsLock: '?', Alt: '÷' }, // space keys Tab: { printable: true, keyCode: 9 }, Enter: { keyCode: 13 }, Space: { printable: true, keyCode: 32 }, // helper keys Escape: { keyCode: 27 }, Backspace: { keyCode: 8 }, CapsLock: { keyCode: 20 }, ShiftLeft: { keyCode: 16 }, ShiftRight: { keyCode: 16 }, ControlLeft: { keyCode: 17 }, AltLeft: { keyCode: 18 }, OSLeft: { keyCode: 91 }, Space: { keyCode: 32 }, OSRight: { keyCode: 93 }, AltRight: { keyCode: 18 }, // arrows ArrowLeft: { keyCode: 37 }, ArrowDown: { keyCode: 40 }, ArrowUp: { keyCode: 38 }, ArrowRight: { keyCode: 39 } }
window.Boid = (function(){ function Boid(x, y, settings){ this.location = new Vector(x, y); this.acceleration = new Vector(0, 0); this.velocity = new Vector(Helper.getRandomInt(-1,1), Helper.getRandomInt(-1,1)); this.settings = settings || {}; this.show_connections = settings.show_connections || true; this.r = settings.r || 3.0; this.maxspeed = settings.maxspeed || 2; this.maxforce = settings.maxforce || 0.5; this.perchSite = settings.perchSite || [h - 100, h - 50]; this.laziness_level = settings.laziness_level || 0.7; this.min_perch = settings.min_perch || 1; this.max_perch = settings.max_perch || 100; this.perching = settings.perching || false; this.perchTimer = settings.perchTimer || 100; this.separation_multiple = settings.separation || 0.2; this.cohesion_multiple = settings.cohesion || 2.0; this.alignment_multiple = settings.alignment || 1.0; this.separation_neighbor_dist = (settings.separation_neighbor_dis || 10) * 10; this.cohesion_neighbor_dist = settings.cohesion_neighbor_dis || 200; this.alignment_neighbor_dist = settings.alignment_neighbor_dis || 200; } Boid.prototype = { constructor: Boid, update: function(){ if (this.perching) { this.perchTimer--; if (this.perchTimer < 0){ this.perching = false; } } else { this.velocity.add(this.acceleration); this.velocity.limit(this.maxspeed); this.location.add(this.velocity); this.acceleration.multiply(0); } }, applyForce: function(force){ this.acceleration.add(force); }, tired: function(){ var x = Math.random(); if (x < this.laziness_level){ return false; } else { return true; } }, seek: function(target) { var desired = Vector.subtract(target, this.location); desired.normalize(); desired.multiply(this.maxspeed); var steer = Vector.subtract(desired, this.velocity); steer.limit(this.maxforce); return steer; }, //Leaving this function here for experiments //You can replace "seek" inside cohesion() //For a more fish-like behaviour arrive: function(target) { var desired = Vector.subtract(target, this.location); var dMag = desired.magnitude(); desired.normalize(); // closer than 100 pixels? if (dMag < 100) { var m = Helper.map(dMag,0,100,0,this.maxspeed); desired.multiply(m); } else { desired.multiply(this.maxspeed); } var steer = Vector.subtract(desired, this.velocity); steer.limit(this.maxforce); return steer; }, align: function(boids){ var sum = new Vector(); var count = 0; for (var i = 0; i < boids.length; i++){ if (boids[i].perching == false) { var distance = Vector.distance(this.location, boids[i].location); //if ((distance > 0) && (distance < this.align_neighbor_dist)) { sum.add(boids[i].velocity); count++; //} } } if (count > 0) { sum.divide(count); sum.normalize(); sum.multiply(this.maxspeed); var steer = Vector.subtract(sum,this.velocity); steer.limit(this.maxforce); return steer; } else { return new Vector(0,0); } }, cohesion: function(boids){ var sum = new Vector(); var count = 0; for (var i = 0; i < boids.length; i++){ if (boids[i].perching == false) { var distance = Vector.distance(this.location, boids[i].location); //if ((distance > 0) && (distance < this.cohesion_neighbor_dist)) { sum.add(boids[i].location); count++; //} } } if (count > 0) { sum.divide(count); return this.seek(sum); } else { return new Vector(0,0); } }, separate: function(boids) { var sum = new Vector(); var count = 0; for (var i=0; i< boids.length; i++){ var distance = Vector.distance(this.location, boids[i].location); if ((distance > 0) && (distance < this.separation_neighbor_dist)) { var diff = Vector.subtract(this.location, boids[i].location); diff.normalize(); diff.divide(distance); sum.add(diff); count++; } } if(count > 0){ sum.divide(count); sum.normalize(); sum.multiply(this.maxspeed); var steer = Vector.subtract(sum, this.velocity); steer.limit(this.maxforce); } return sum; }, borders: function() { //We are allowing boids to fly a bit outside //the view and then return. var offset = 20; var isTired = this.tired(); if (this.onPerchSite() && isTired ){ this.perching = true; } else { if (this.location.x < -offset) this.location.x += 5; if (this.location.x > w + offset) this.location.x -= 5; if (this.location.y > h + offset) this.location.y -= 5; if (this.location.y < -offset) this.location.y += 5; } }, onPerchSite: function(){ for (var i = 0; i < this.perchSite.length; i++){ if( this.location.y > this.perchSite[i] -2 && this.location.y < this.perchSite[i] + 2 ) return true; } return false; }, borders2: function() { var offset = 20; var isTired = this.tired(); if (this.location.y > this.perchSite - 2 && this.location.y < this.perchSite + 2 && isTired ){ this.perching = true; } else { if (this.location.x < -this.r) this.location.x = w+this.r; if (this.location.y < -this.r) this.location.y = h+this.r; if (this.location.x > w+this.r) this.location.x = -this.r; if (this.location.y > h+this.r) this.location.y = -this.r; } }, render: function() { var theta = this.velocity.heading() + Math.PI/2; context.stroke(); context.save(); context.translate(this.location.x, this.location.y); context.rotate(theta); if(this.settings.boid_shape){ this.settings.boid_shape(); } else { this.default_boid_shape(); } context.restore(); }, default_boid_shape: function(){ var radius = 5; context.fillStyle = "#636570"; context.beginPath(); context.arc(0, 0, radius, 0, 2 * Math.PI, false); context.closePath(); context.fill(); }, flock: function(boids){ var separate = this.separate(boids); var align = this.align(boids); var cohesion = this.cohesion(boids); separate.multiply(this.separation_multiple); align.multiply(this.alignment_multiple); cohesion.multiply(this.cohesion_multiple); this.applyForce(separate); this.applyForce(align); this.applyForce(cohesion); }, run: function(boids){ if (this.perching){ this.perchTimer--; if(this.perchTimer < 0 ) { this.perching = false; this.perchTimer = Helper.getRandomInt(this.min_perch,this.max_perch); } } else { this.flock(boids); this.update(); this.borders(); } } }; return Boid; })();
/*global window*/ (function($){ 'use strict'; var Observable = function(){ this.observers = {}; }; Observable.prototype.on = function(event, observer){ (this.observers[event] = this.observers[event] || []).push(observer); }; Observable.prototype.emit = function(event){ var args = Array.prototype.slice.call(arguments, 1); (this.observers[event] || []).forEach(function(observer){ observer.apply(this, args); }.bind(this)); }; var Model = $.Model = function(alpha){ Observable.call(this); this._alpha = alpha || 30; }; Model.prototype = Object.create(Observable.prototype); Model.prototype.constructor = Model; Model.prototype.alpha = function(alpha){ this._alpha = alpha || this._alpha; if (alpha !== undefined) { this.emit('alpha', this._alpha); } return this._alpha; }; var Step = function(){}; Step.prototype.description = function(){ return this.type + this.x + ',' + this.y; }; var MoveTo = function(x, y){ Step.call(this); this.type = 'M'; this.x = x; this.y = y; }; MoveTo.prototype = Object.create(Step.prototype); MoveTo.prototype.constructor = MoveTo; var LineTo = function(x, y){ Step.call(this); this.type = 'L'; this.x = x; this.y = y; }; LineTo.prototype = Object.create(Step.prototype); LineTo.prototype.constructor = LineTo; var HalfCircleTo = function(x, y, r, direction) { Step.call(this); this.type = 'A'; this.x = x; this.y = y; this.r = r; this.direction = direction; }; HalfCircleTo.prototype = Object.create(Step.prototype); HalfCircleTo.prototype.constructor = HalfCircleTo; HalfCircleTo.prototype.description = function(){ return [ this.type, this.r + ',' + this.r, 0, '0,' + (this.direction === -1 ? 1: 0), this.x + ',' + this.y ].join(' '); }; var ControlPoints = $.ControlPoints = function(model, direction, x, y){ Observable.call(this); this.model = model; this.direction = direction; this.x = x; this.y = y; this.model.on('alpha', this.signal.bind(this)); }; ControlPoints.prototype = Object.create(Observable.prototype); ControlPoints.prototype.constructor = ControlPoints; ControlPoints.prototype.signal = function(){ this.emit('controlpoints', this.controlPoints()); }; ControlPoints.prototype.controlPoints = function(){ var alpha = this.model.alpha() * Math.PI / 180; var sinAlpha = Math.sin(alpha); var coefficient = 1/2 * sinAlpha * (1 - sinAlpha); var ab = this.y/(1 + coefficient); var w = ab * 1/2 * Math.sin(2 * alpha); var h = ab * 1/2 * Math.cos(2 * alpha); var r = ab * 1/2 * sinAlpha; var points = [ new MoveTo(this.x, this.y), new LineTo(this.x + this.direction * w, this.y - ab/2 - h), new HalfCircleTo(this.x, this.y - ab, r, this.direction), ]; var n=10; var ds = ab/n; var dw = ds * 1/2 * Math.tan(alpha); for (var index = 0; index < n; index++) { points.push(new LineTo(this.x + dw, this.y - ab + (index + 1/2) * ds)); points.push(new LineTo(this.x, this.y - ab + (index + 1) * ds)); } return points; }; var View = $.View = function(model, path){ this.model = model; this.path = path; this.update(); }; View.prototype.update = function(){ this.path.setAttribute('d', this.description()); }; View.prototype.description = function(){ return this.model.controlPoints().map(function(point){ return point.description(); }).join(''); }; })(window.heart = window.heart || {});
import root from './_root.js'; import toString from './toString.js'; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeParseInt = root.parseInt; /** * Converts `string` to an integer of the specified radix. If `radix` is * `undefined` or `0`, a `radix` of `10` is used unless `value` is a * hexadecimal, in which case a `radix` of `16` is used. * * **Note:** This method aligns with the * [ES5 implementation](https://es5.github.io/#x15.1.2.2) of `parseInt`. * * @static * @memberOf _ * @since 1.1.0 * @category String * @param {string} string The string to convert. * @param {number} [radix=10] The radix to interpret `value` by. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {number} Returns the converted integer. * @example * * _.parseInt('08'); * // => 8 * * _.map(['6', '08', '10'], _.parseInt); * // => [6, 8, 10] */ function parseInt(string, radix, guard) { if (guard || radix == null) { radix = 0; } else if (radix) { radix = +radix; } return nativeParseInt(toString(string), radix || 0); } export default parseInt;
import $ from 'jquery'; module.exports = function(root) { root = root ? root : global; root.expect = root.chai.expect; root.$ = $; beforeEach(() => { // Using these globally-available Sinon features is preferrable, as they're // automatically restored for you in the subsequent `afterEach` root.sandbox = root.sinon.sandbox.create(); root.stub = root.sandbox.stub.bind(root.sandbox); root.spy = root.sandbox.spy.bind(root.sandbox); root.mock = root.sandbox.mock.bind(root.sandbox); root.useFakeTimers = root.sandbox.useFakeTimers.bind(root.sandbox); root.useFakeXMLHttpRequest = root.sandbox.useFakeXMLHttpRequest.bind(root.sandbox); root.useFakeServer = root.sandbox.useFakeServer.bind(root.sandbox); }); afterEach(() => { delete root.stub; delete root.spy; root.sandbox.restore(); }); };
const mongoose = require('mongoose'); const UserModel = mongoose.model('User'); module.exports = { login: (email, password) => { return UserModel.findOne({email, password}); } };
module.exports = { login: function(user, req) { // Parse detailed information from user-agent string var r = require('ua-parser').parse(req.headers['user-agent']); // Create new UserLogin row to database sails.models.loglogin.create({ ip: req.ip, host: req.host, agent: req.headers['user-agent'], browser: r.ua.toString(), browserVersion: r.ua.toVersionString(), browserFamily: r.ua.family, os: r.os.toString(), osVersion: r.os.toVersionString(), osFamily: r.os.family, device: r.device.family, user: user.id }) .exec(function(err, created) { if(err) sails.log(err); created.user = user; sails.models.loglogin.publishCreate(created); }); }, request: function(log, req, resp) { //var userId = -1; // if (req.token) { // userId = req.token; // } else { // userId = -1; // } sails.models.logrequest.create({ ip: log.ip, protocol: log.protocol, method: log.method, url: log.diagnostic.url, headers: req.headers || {}, parameters: log.diagnostic.routeParams, body: log.diagnostic.bodyParams, query: log.diagnostic.queryParams, responseTime: log.responseTime || 0, middlewareLatency: log.diagnostic.middlewareLatency || 0, user: req.token || 0 }) .exec(function(err, created) { if(err) sails.log(err); sails.models.logrequest.publishCreate(created); }); } };
const isObjectId = objectId => objectId && /^[0-9a-fA-F]{24}$/.test(objectId) const isEmail = email => email && /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(email.trim()) const isNick = nick => nick && /^[\u4E00-\u9FA5\uF900-\uFA2DA-Za-z0-9\-\_]{2,40}$/.test(nick.trim()) const isUrl = url => url && /^(http(?:|s)\:)*\/\/([^\/]+)/.test(url.trim()) export { isObjectId, isEmail, isNick, isUrl }
var Command = require("../Command"); var RealDirection = require("../../RealDirection"); var MessageCategory = require("../../MessageCategory"); var _dir = RealDirection.NORTHEAST; class Northeast extends Command{ constructor(){ super(); this.rule = /^n(?:orth)?e(?:ast)?$/g; } exec(){ if(this.step(_dir)){ this.showRoom(); } else { this.sendMessage("Alas, you can't go that way.", MessageCategory.COMMAND); } } } module.exports = Northeast;
import VueRouter from 'vue-router' import { mount } from '@vue/test-utils' import { waitNT, waitRAF } from '../../../tests/utils' import { Vue } from '../../vue' import { BPaginationNav } from './pagination-nav' Vue.use(VueRouter) // The majority of tests for the core of pagination mixin are performed // in pagination.spec.js. Here we just test the differences that // <pagination-nav> has // We use a (currently) undocumented wrapper method `destroy()` at the end // of each test to remove the VM and DOM from the JSDOM document, as // the wrapper's and instances remain after each test completes describe('pagination-nav', () => { it('renders with correct basic structure for root elements', async () => { const wrapper = mount(BPaginationNav, { propsData: { numberOfPages: 1, value: 1 } }) await waitNT(wrapper.vm) await waitRAF() // <pagination-nav> has an outer wrapper of nav expect(wrapper.element.tagName).toBe('NAV') const $ul = wrapper.find('ul.pagination') expect($ul.exists()).toBe(true) // NAV Attributes expect(wrapper.attributes('aria-hidden')).toBe('false') expect(wrapper.attributes('aria-label')).toBe('Pagination') // UL Classes expect($ul.classes()).toContain('pagination') expect($ul.classes()).toContain('b-pagination') expect($ul.classes()).not.toContain('pagination-sm') expect($ul.classes()).not.toContain('pagination-lg') expect($ul.classes()).not.toContain('justify-content-center') expect($ul.classes()).not.toContain('justify-content-end') // UL Attributes expect($ul.attributes('role')).not.toBe('menubar') expect($ul.attributes('aria-disabled')).toBe('false') expect($ul.attributes('aria-label')).not.toBe('Pagination') wrapper.destroy() }) it('renders with correct default HREF', async () => { const wrapper = mount(BPaginationNav, { propsData: { numberOfPages: 5, value: 3, limit: 10 } }) await waitNT(wrapper.vm) await waitRAF() expect(wrapper.element.tagName).toBe('NAV') const $links = wrapper.findAll('a.page-link') expect($links.length).toBe(9) // Default base URL is '/', and link will be the page number expect($links.at(0).attributes('href')).toBe('/1') expect($links.at(1).attributes('href')).toBe('/2') expect($links.at(2).attributes('href')).toBe('/1') expect($links.at(3).attributes('href')).toBe('/2') expect($links.at(4).attributes('href')).toBe('/3') expect($links.at(5).attributes('href')).toBe('/4') expect($links.at(6).attributes('href')).toBe('/5') expect($links.at(7).attributes('href')).toBe('/4') expect($links.at(8).attributes('href')).toBe('/5') wrapper.destroy() }) it('renders with correct default page button text', async () => { const wrapper = mount(BPaginationNav, { propsData: { numberOfPages: 5, value: 3, limit: 10 } }) await waitNT(wrapper.vm) await waitRAF() expect(wrapper.element.tagName).toBe('NAV') const $links = wrapper.findAll('a.page-link') expect($links.length).toBe(9) expect($links.at(2).text()).toBe('1') expect($links.at(3).text()).toBe('2') expect($links.at(4).text()).toBe('3') expect($links.at(5).text()).toBe('4') expect($links.at(6).text()).toBe('5') wrapper.destroy() }) it('disabled renders correct', async () => { const wrapper = mount(BPaginationNav, { propsData: { numberOfPages: 1, value: 1, disabled: true } }) await waitNT(wrapper.vm) await waitRAF() // <pagination-nav> has an outer wrapper of nav expect(wrapper.element.tagName).toBe('NAV') const $ul = wrapper.find('ul.pagination') expect($ul.exists()).toBe(true) // NAV Attributes expect(wrapper.attributes('aria-hidden')).toBe('true') expect(wrapper.attributes('aria-disabled')).toBe('true') // UL Classes expect($ul.classes()).toContain('pagination') expect($ul.classes()).toContain('b-pagination') // UL Attributes expect($ul.attributes('role')).not.toBe('menubar') expect($ul.attributes('aria-disabled')).toBe('true') // LI classes expect(wrapper.findAll('li').length).toBe(5) expect(wrapper.findAll('li.page-item').length).toBe(5) expect(wrapper.findAll('li.disabled').length).toBe(5) // LI Inner should be span elements expect(wrapper.findAll('li > span').length).toBe(5) expect(wrapper.findAll('li > span.page-link').length).toBe(5) expect(wrapper.findAll('li > span[aria-disabled="true"').length).toBe(5) wrapper.destroy() }) it('reacts to changes in number-of-pages', async () => { const wrapper = mount(BPaginationNav, { propsData: { numberOfPages: 3, value: 2, limit: 10 } }) await waitNT(wrapper.vm) await waitRAF() expect(wrapper.element.tagName).toBe('NAV') let $links = wrapper.findAll('a.page-link') expect($links.length).toBe(7) await wrapper.setProps({ numberOfPages: 5 }) await waitNT(wrapper.vm) $links = wrapper.findAll('a.page-link') expect($links.length).toBe(9) wrapper.destroy() }) it('renders with correct HREF when base-url specified', async () => { const wrapper = mount(BPaginationNav, { propsData: { numberOfPages: 5, value: 3, limit: 10, baseUrl: '/foo/' } }) await waitNT(wrapper.vm) await waitRAF() expect(wrapper.element.tagName).toBe('NAV') const $links = wrapper.findAll('a.page-link') expect($links.length).toBe(9) // Default base URL is '/', and link will be the page number expect($links.at(0).attributes('href')).toBe('/foo/1') expect($links.at(1).attributes('href')).toBe('/foo/2') expect($links.at(2).attributes('href')).toBe('/foo/1') expect($links.at(3).attributes('href')).toBe('/foo/2') expect($links.at(4).attributes('href')).toBe('/foo/3') expect($links.at(5).attributes('href')).toBe('/foo/4') expect($links.at(6).attributes('href')).toBe('/foo/5') expect($links.at(7).attributes('href')).toBe('/foo/4') expect($links.at(8).attributes('href')).toBe('/foo/5') wrapper.destroy() }) it('renders with correct HREF when link-gen function provided', async () => { const wrapper = mount(BPaginationNav, { propsData: { numberOfPages: 5, value: 3, limit: 10, linkGen: page => `?${page}` } }) await waitNT(wrapper.vm) await waitRAF() expect(wrapper.element.tagName).toBe('NAV') const $links = wrapper.findAll('a.page-link') expect($links.length).toBe(9) // Default base URL is '/', and link will be the page number expect($links.at(0).attributes('href')).toBe('?1') expect($links.at(1).attributes('href')).toBe('?2') expect($links.at(2).attributes('href')).toBe('?1') expect($links.at(3).attributes('href')).toBe('?2') expect($links.at(4).attributes('href')).toBe('?3') expect($links.at(5).attributes('href')).toBe('?4') expect($links.at(6).attributes('href')).toBe('?5') expect($links.at(7).attributes('href')).toBe('?4') expect($links.at(8).attributes('href')).toBe('?5') wrapper.destroy() }) it('renders with correct HREF when link-gen function returns object', async () => { const wrapper = mount(BPaginationNav, { propsData: { numberOfPages: 5, value: 3, limit: 10, linkGen: page => ({ path: `/baz?${page}` }) } }) await waitNT(wrapper.vm) await waitRAF() expect(wrapper.element.tagName).toBe('NAV') const $links = wrapper.findAll('a.page-link') expect($links.length).toBe(9) // Default base URL is '/', and link will be the page number expect($links.at(0).attributes('href')).toBe('/baz?1') expect($links.at(1).attributes('href')).toBe('/baz?2') expect($links.at(2).attributes('href')).toBe('/baz?1') expect($links.at(3).attributes('href')).toBe('/baz?2') expect($links.at(4).attributes('href')).toBe('/baz?3') expect($links.at(5).attributes('href')).toBe('/baz?4') expect($links.at(6).attributes('href')).toBe('/baz?5') expect($links.at(7).attributes('href')).toBe('/baz?4') expect($links.at(8).attributes('href')).toBe('/baz?5') wrapper.destroy() }) it('renders with correct page button text when page-gen function provided', async () => { const wrapper = mount(BPaginationNav, { propsData: { numberOfPages: 5, value: 3, limit: 10, pageGen: page => `Page ${page}` } }) await waitNT(wrapper.vm) await waitRAF() expect(wrapper.element.tagName).toBe('NAV') const $links = wrapper.findAll('a.page-link') expect($links.length).toBe(9) expect($links.at(2).text()).toBe('Page 1') expect($links.at(3).text()).toBe('Page 2') expect($links.at(4).text()).toBe('Page 3') expect($links.at(5).text()).toBe('Page 4') expect($links.at(6).text()).toBe('Page 5') wrapper.destroy() }) it('renders with correct HREF when array of links set via pages prop', async () => { const wrapper = mount(BPaginationNav, { propsData: { value: 3, limit: 10, pages: ['/baz?1', '/baz?2', '/baz?3', '/baz?4', '/baz?5'] } }) await waitNT(wrapper.vm) await waitRAF() expect(wrapper.element.tagName).toBe('NAV') const $links = wrapper.findAll('a.page-link') expect($links.length).toBe(9) // Default base URL is '/', and link will be the page number expect($links.at(0).attributes('href')).toBe('/baz?1') expect($links.at(1).attributes('href')).toBe('/baz?2') expect($links.at(2).attributes('href')).toBe('/baz?1') expect($links.at(3).attributes('href')).toBe('/baz?2') expect($links.at(4).attributes('href')).toBe('/baz?3') expect($links.at(5).attributes('href')).toBe('/baz?4') expect($links.at(6).attributes('href')).toBe('/baz?5') expect($links.at(7).attributes('href')).toBe('/baz?4') expect($links.at(8).attributes('href')).toBe('/baz?5') // Page buttons have correct content expect($links.at(2).text()).toBe('1') expect($links.at(3).text()).toBe('2') expect($links.at(4).text()).toBe('3') expect($links.at(5).text()).toBe('4') expect($links.at(6).text()).toBe('5') wrapper.destroy() }) it('renders with correct HREF when array of links and text set via pages prop', async () => { const wrapper = mount(BPaginationNav, { propsData: { value: 3, limit: 10, pages: [ { link: '/baz?1', text: 'one' }, { link: '/baz?2', text: 'two' }, { link: '/baz?3', text: 'three' }, { link: '/baz?4', text: 'four' }, { link: '/baz?5', text: 'five' } ] } }) await waitNT(wrapper.vm) await waitRAF() expect(wrapper.element.tagName).toBe('NAV') const $links = wrapper.findAll('a.page-link') expect($links.length).toBe(9) // Default base URL is '/', and link will be the page number expect($links.at(0).attributes('href')).toBe('/baz?1') expect($links.at(1).attributes('href')).toBe('/baz?2') expect($links.at(2).attributes('href')).toBe('/baz?1') expect($links.at(3).attributes('href')).toBe('/baz?2') expect($links.at(4).attributes('href')).toBe('/baz?3') expect($links.at(5).attributes('href')).toBe('/baz?4') expect($links.at(6).attributes('href')).toBe('/baz?5') expect($links.at(7).attributes('href')).toBe('/baz?4') expect($links.at(8).attributes('href')).toBe('/baz?5') // Page buttons have correct content expect($links.at(2).text()).toBe('one') expect($links.at(3).text()).toBe('two') expect($links.at(4).text()).toBe('three') expect($links.at(5).text()).toBe('four') expect($links.at(6).text()).toBe('five') wrapper.destroy() }) it('reacts to changes in pages array length', async () => { const wrapper = mount(BPaginationNav, { propsData: { value: 2, limit: 10, pages: ['/baz?1', '/baz?2', '/baz?3'] } }) await waitNT(wrapper.vm) await waitRAF() expect(wrapper.element.tagName).toBe('NAV') let $links = wrapper.findAll('a.page-link') expect($links.length).toBe(7) expect($links.at(0).attributes('href')).toBe('/baz?1') expect($links.at(1).attributes('href')).toBe('/baz?1') expect($links.at(2).attributes('href')).toBe('/baz?1') expect($links.at(3).attributes('href')).toBe('/baz?2') expect($links.at(4).attributes('href')).toBe('/baz?3') expect($links.at(5).attributes('href')).toBe('/baz?3') expect($links.at(6).attributes('href')).toBe('/baz?3') // Add extra page await wrapper.setProps({ pages: ['/baz?1', '/baz?2', '/baz?3', '/baz?4'] }) await waitNT(wrapper.vm) $links = wrapper.findAll('a.page-link') expect($links.length).toBe(8) expect($links.at(0).attributes('href')).toBe('/baz?1') expect($links.at(1).attributes('href')).toBe('/baz?1') expect($links.at(2).attributes('href')).toBe('/baz?1') expect($links.at(3).attributes('href')).toBe('/baz?2') expect($links.at(4).attributes('href')).toBe('/baz?3') expect($links.at(5).attributes('href')).toBe('/baz?4') expect($links.at(6).attributes('href')).toBe('/baz?3') expect($links.at(7).attributes('href')).toBe('/baz?4') wrapper.destroy() }) it('clicking buttons updates the v-model', async () => { const App = { compatConfig: { MODE: 3, RENDER_FUNCTION: 'suppress-warning' }, methods: { onPageClick(bvEvent, page) { // Prevent 3rd page from being selected if (page === 3) { bvEvent.preventDefault() } } }, render(h) { return h(BPaginationNav, { props: { baseUrl: '#', // Needed to prevent JSDOM errors numberOfPages: 5, value: 1, limit: 10 }, on: { 'page-click': this.onPageClick } }) } } const wrapper = mount(App) expect(wrapper).toBeDefined() const paginationNav = wrapper.findComponent(BPaginationNav) expect(paginationNav).toBeDefined() expect(paginationNav.element.tagName).toBe('NAV') // Grab the page links const lis = paginationNav.findAll('li') expect(lis.length).toBe(9) expect(paginationNav.vm.computedCurrentPage).toBe(1) expect(paginationNav.emitted('input')).toBeUndefined() expect(paginationNav.emitted('change')).toBeUndefined() expect(paginationNav.emitted('page-click')).toBeUndefined() // Click on current (1st) page link (does nothing) await lis .at(2) .find('a') .trigger('click') await waitRAF() expect(paginationNav.vm.computedCurrentPage).toBe(1) expect(paginationNav.emitted('input')).toBeUndefined() expect(paginationNav.emitted('change')).toBeUndefined() expect(paginationNav.emitted('page-click')).toBeUndefined() // Click on 2nd page link await lis .at(3) .find('a') .trigger('click') await waitRAF() expect(paginationNav.vm.computedCurrentPage).toBe(2) expect(paginationNav.emitted('input')).toBeDefined() expect(paginationNav.emitted('change')).toBeDefined() expect(paginationNav.emitted('page-click')).toBeDefined() expect(paginationNav.emitted('input')[0][0]).toBe(2) expect(paginationNav.emitted('change')[0][0]).toBe(2) expect(paginationNav.emitted('page-click').length).toBe(1) // Click goto last page link await lis .at(8) .find('a') .trigger('click') await waitRAF() expect(paginationNav.vm.computedCurrentPage).toBe(5) expect(paginationNav.emitted('input')[1][0]).toBe(5) expect(paginationNav.emitted('change')[1][0]).toBe(5) expect(paginationNav.emitted('page-click').length).toBe(2) // Click prev page link await lis .at(1) .find('a') .trigger('click') await waitRAF() expect(paginationNav.vm.computedCurrentPage).toBe(4) expect(paginationNav.emitted('input')[2][0]).toBe(4) expect(paginationNav.emitted('change')[2][0]).toBe(4) expect(paginationNav.emitted('page-click').length).toBe(3) // Click on 3rd page link (prevented) await lis .at(4) .find('a') .trigger('click') await waitRAF() expect(paginationNav.vm.computedCurrentPage).toBe(4) expect(paginationNav.emitted('input').length).toBe(3) expect(paginationNav.emitted('change').length).toBe(3) expect(paginationNav.emitted('page-click').length).toBe(4) wrapper.destroy() }) describe('auto-detect page', () => { // Note: JSDOM only works with hash URL updates out of the box beforeEach(() => { // Make sure theJSDOM is at '/', as JSDOM instances for each test! window.history.pushState({}, '', '/') }) it('detects current page without $router', async () => { const wrapper = mount(BPaginationNav, { propsData: { numberOfPages: 3, value: null, linkGen: page => (page === 2 ? '/' : `/#${page}`) } }) await waitNT(wrapper.vm) await waitRAF() await waitNT(wrapper.vm) expect(wrapper.vm.$router).toBeUndefined() expect(wrapper.vm.$route).toBeUndefined() expect(wrapper.element.tagName).toBe('NAV') const $ul = wrapper.find('ul.pagination') expect($ul.exists()).toBe(true) // Emitted current page (2) expect(wrapper.emitted('input')).toBeDefined() expect(wrapper.emitted('input').length).toBe(1) expect(wrapper.emitted('input')[0][0]).toBe(2) // Page 2, URL = '' wrapper.destroy() }) it('works with $router to detect path and linkGen returns location object', async () => { const App = { compatConfig: { MODE: 3, COMPONENT_FUNCTIONAL: 'suppress-warning' }, components: { BPaginationNav }, methods: { linkGen(page) { // We make page #2 "home" for testing // We return a to prop to auto trigger use of $router // if using strings, we would need to set use-router=true return page === 2 ? { path: '/' } : { path: '/' + page } } }, template: ` <div> <b-pagination-nav :number-of-pages="3" :link-gen="linkGen"></b-pagination-nav> <router-view></router-view> </div> ` } // Our router view component const FooRoute = { compatConfig: { MODE: 3, RENDER_FUNCTION: 'suppress-warning' }, render(h) { return h('div', { class: 'foo-content' }, ['stub']) } } // Create router instance const router = new VueRouter({ routes: [{ path: '/', component: FooRoute }, { path: '/:page', component: FooRoute }] }) const wrapper = mount(App, { router }) expect(wrapper).toBeDefined() // Wait for the router to initialize await new Promise(resolve => router.onReady(resolve)) // Wait for the guessCurrentPage to complete await waitNT(wrapper.vm) await waitRAF() await waitNT(wrapper.vm) // The pagination-nav component should exist expect(wrapper.findComponent(BPaginationNav).exists()).toBe(true) // And should be on page 2 expect(wrapper.findComponent(BPaginationNav).vm.currentPage).toBe(2) // Push router to a new page wrapper.vm.$router.push('/3') // Wait for the guessCurrentPage to complete await waitNT(wrapper.vm) await waitRAF() await waitNT(wrapper.vm) // The pagination-nav component should exist expect(wrapper.findComponent(BPaginationNav).exists()).toBe(true) // And should be on page 3 expect(wrapper.findComponent(BPaginationNav).vm.currentPage).toBe(3) wrapper.destroy() }) it('works with $router to detect path and use-router set and linkGen returns string', async () => { const App = { compatConfig: { MODE: 3, COMPONENT_FUNCTIONAL: 'suppress-warning' }, components: { BPaginationNav }, methods: { linkGen(page) { // We make page #2 "home" for testing // We return a to prop to auto trigger use of $router // if using strings, we would need to set use-router=true return page === 2 ? '/' : `/${page}` } }, template: ` <div> <b-pagination-nav :number-of-pages="3" :link-gen="linkGen" use-router></b-pagination-nav> <router-view></router-view> </div> ` } // Our router view component const FooRoute = { compatConfig: { MODE: 3, RENDER_FUNCTION: 'suppress-warning' }, render(h) { return h('div', { class: 'foo-content' }, ['stub']) } } // Create router instance const router = new VueRouter({ routes: [{ path: '/', component: FooRoute }, { path: '/:page', component: FooRoute }] }) const wrapper = mount(App, { router }) expect(wrapper).toBeDefined() // Wait for the router to initialize await new Promise(resolve => router.onReady(resolve)) // Wait for the guessCurrentPage to complete await waitNT(wrapper.vm) await waitRAF() await waitNT(wrapper.vm) // The <pagination-nav> component should exist expect(wrapper.findComponent(BPaginationNav).exists()).toBe(true) // And should be on page 2 expect(wrapper.findComponent(BPaginationNav).vm.currentPage).toBe(2) // Push router to a new page wrapper.vm.$router.push('/3') // Wait for the guessCurrentPage to complete await waitNT(wrapper.vm) await waitRAF() await waitNT(wrapper.vm) // The pagination-nav component should exist expect(wrapper.findComponent(BPaginationNav).exists()).toBe(true) // And should be on page 3 expect(wrapper.findComponent(BPaginationNav).vm.currentPage).toBe(3) wrapper.destroy() }) }) })
module.exports = (name, node) => ( name === "apply" && node.type === "CallExpression" && node.callee.type === "Identifier");
/* * The MIT License (MIT) * * Copyright (c) 2016-2017 The Regents of the University of California * Author: Jim Robinson * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import {loadIndex} from "./indexFactory.js" import AlignmentContainer from "./alignmentContainer.js" import BamUtils from "./bamUtils.js" import {BGZip, igvxhr} from "../../node_modules/igv-utils/src/index.js" import {buildOptions} from "../util/igvUtils.js" /** * Class for reading a bam file * * @param config * @constructor */ class BamReader { constructor(config, genome) { this.config = config this.genome = genome this.bamPath = config.url this.baiPath = config.indexURL BamUtils.setReaderDefaults(this, config) } async readAlignments(chr, bpStart, bpEnd) { const chrToIndex = await this.getChrIndex() const queryChr = this.chrAliasTable.hasOwnProperty(chr) ? this.chrAliasTable[chr] : chr const chrId = chrToIndex[queryChr] const alignmentContainer = new AlignmentContainer(chr, bpStart, bpEnd, this.config) if (chrId === undefined) { return alignmentContainer } else { const bamIndex = await this.getIndex() const chunks = bamIndex.blocksForRange(chrId, bpStart, bpEnd) if (!chunks || chunks.length === 0) { return alignmentContainer } let counter = 1 for (let c of chunks) { let lastBlockSize if (c.maxv.offset === 0) { lastBlockSize = 0 // Don't need to read the last block. } else { const bsizeOptions = buildOptions(this.config, {range: {start: c.maxv.block, size: 26}}) const abuffer = await igvxhr.loadArrayBuffer(this.bamPath, bsizeOptions) lastBlockSize = BGZip.bgzBlockSize(abuffer) } const fetchMin = c.minv.block const fetchMax = c.maxv.block + lastBlockSize const range = {start: fetchMin, size: fetchMax - fetchMin + 1} const compressed = await igvxhr.loadArrayBuffer(this.bamPath, buildOptions(this.config, {range: range})) var ba = BGZip.unbgzf(compressed) //new Uint8Array(BGZip.unbgzf(compressed)); //, c.maxv.block - c.minv.block + 1)); const done = BamUtils.decodeBamRecords(ba, c.minv.offset, alignmentContainer, this.indexToChr, chrId, bpStart, bpEnd, this.filter) if (done) { // console.log(`Loaded ${counter} chunks out of ${chunks.length}`); break } counter++ } alignmentContainer.finish() return alignmentContainer } } async getHeader() { if (!this.header) { const genome = this.genome const index = await this.getIndex() let start let len if (index.firstBlockPosition) { const bsizeOptions = buildOptions(this.config, {range: {start: index.firstBlockPosition, size: 26}}) const abuffer = await igvxhr.loadArrayBuffer(this.bamPath, bsizeOptions) const bsize = BGZip.bgzBlockSize(abuffer) len = index.firstBlockPosition + bsize // Insure we get the complete compressed block containing the header } else { len = 64000 } const options = buildOptions(this.config, {range: {start: 0, size: len}}) this.header = await BamUtils.readHeader(this.bamPath, options, genome) } return this.header } async getIndex() { const genome = this.genome if (!this.index) { this.index = await loadIndex(this.baiPath, this.config, genome) } return this.index } async getChrIndex() { if (this.chrToIndex) { return this.chrToIndex } else { const header = await this.getHeader() this.chrToIndex = header.chrToIndex this.indexToChr = header.chrNames this.chrAliasTable = header.chrAliasTable return this.chrToIndex } } } export default BamReader
var should = require("should"); var Mat3x3 = require("./Mat3x3"); var Barycentric3 = require("./Barycentric3"); var Logger = require("./Logger"); (function(exports) { var verboseLogger = new Logger({ logLevel: "debug" }); ////////////////// constructor function XYZ(x, y, z, options) { var that = this; if (typeof x === "number") { that.x = x; that.y = y; that.z = z; should && y.should.Number && z.should.Number && isNaN(x).should.False && isNaN(y).should.False && isNaN(z).should.False; } else { var xyz = x; should && xyz.x.should.Number && xyz.y.should.Number && xyz.z.should.Number; that.x = xyz.x; that.y = xyz.y; that.z = xyz.z; if (options == null) { options = y; } } options = options || {}; if (options.verbose) { that.verbose = options.verbose; } return that; } XYZ.prototype.nearest = function(a, b) { var that = this; var adx = a.x - that.x; var ady = a.y - that.y; var adz = a.z - that.z; var bdx = b.x - that.x; var bdy = b.y - that.y; var bdz = b.z - that.z; var ad2 = adx * adx + ady * ady + adz * adz; var bd2 = bdx * bdx + bdy * bdy + bdz * bdz; return ad2 <= bd2 ? a : b; } XYZ.prototype.dot = function(xyz) { var that = this; return that.x * xyz.x + that.y * xyz.y + that.z * xyz.z; } XYZ.prototype.cross = function(xyz) { var that = this; return new XYZ( that.y * xyz.z - that.z * xyz.y, -(that.x * xyz.z - that.z * xyz.x), that.x * xyz.y - that.y * xyz.x, that); } XYZ.prototype.interpolate = function(xyz, p) { var that = this; p = p == null ? 0.5 : p; var p1 = 1 - p; should && xyz.should.exist && xyz.x.should.Number && xyz.y.should.Number && xyz.z.should.Number; return new XYZ( p * xyz.x + p1 * that.x, p * xyz.y + p1 * that.y, p * xyz.z + p1 * that.z, that); } XYZ.prototype.invalidate = function() { var that = this; delete that._norm; } XYZ.prototype.normSquared = function() { var that = this; return that.x * that.x + that.y * that.y + that.z * that.z; } XYZ.prototype.norm = function() { var that = this; if (that._norm == null) { that._norm = Math.sqrt(that.normSquared()); } return that._norm; } XYZ.prototype.minus = function(value) { var that = this; should && value.x.should.Number && value.y.should.Number && value.z.should.Number; return new XYZ(that.x - value.x, that.y - value.y, that.z - value.z, that); } XYZ.prototype.plus = function(value) { var that = this; should && value.x.should.Number && value.y.should.Number && value.z.should.Number; return new XYZ(that.x + value.x, that.y + value.y, that.z + value.z, that); } XYZ.prototype.equal = function(value, tolerance) { var that = this; if (value == null) { that.verbose && console.log("XYZ.equal(null) => false"); return false; } if (value.x == null) { that.verbose && console.log("XYZ.equal(value.x is null) => false"); return false; } if (value.y == null) { that.verbose && console.log("XYZ.equal(value.y is null) => false"); return false; } if (value.z == null) { that.verbose && console.log("XYZ.equal(value.z is null) => false"); return false; } tolerance = tolerance || 0; var result = value.x - tolerance <= that.x && that.x <= value.x + tolerance && value.y - tolerance <= that.y && that.y <= value.y + tolerance && value.z - tolerance <= that.z && that.z <= value.z + tolerance; that.verbose && !result && verboseLogger.debug("XYZ", that, ".equal(", value, ") => false"); return result; } XYZ.prototype.toString = function() { var that = this; var scale = 1000; return "[" + Math.round(that.x * scale) / scale + "," + Math.round(that.y * scale) / scale + "," + Math.round(that.z * scale) / scale + "]"; } XYZ.prototype.multiply = function(m) { var that = this; if (m instanceof Mat3x3) { return new XYZ( m.get(0, 0) * that.x + m.get(0, 1) * that.y + m.get(0, 2) * that.z, m.get(1, 0) * that.x + m.get(1, 1) * that.y + m.get(1, 2) * that.z, m.get(2, 0) * that.x + m.get(2, 1) * that.y + m.get(2, 2) * that.z, that); } should && m.should.Number; return new XYZ( m * that.x, m * that.y, m * that.z, that); } /////////// class XYZ.of = function(xyz, options) { options = options || {}; if (xyz instanceof XYZ) { return xyz; } if (options.strict) { should && xyz.x.should.Number && xyz.y.should.Number && xyz.z.should.Number; } else { if (!xyz.x instanceof Number) { return null; } if (!xyz.y instanceof Number) { return null; } if (!xyz.z instanceof Number) { return null; } } return new XYZ(xyz.x, xyz.y, xyz.z, options); } XYZ.precisionDriftComparator = function(v1, v2) { // comparator order will reveal // any long-term precision drift // as a horizontal visual break along x-axis var s1 = v1.y < 0 ? -1 : 1; var s2 = v2.y < 0 ? -1 : 1; var cmp = s1 - s2; cmp === 0 && (cmp = Math.round(v2.y) - Math.round(v1.y)); if (cmp === 0) { var v1x = Math.round(v1.x); var v2x = Math.round(v2.x); cmp = v1.y < 0 ? v1x - v2x : v2x - v1x; } cmp === 0 && (cmp = v1.z - v2.z); return cmp; } module.exports = exports.XYZ = XYZ; })(typeof exports === "object" ? exports : (exports = {})); // mocha -R min --inline-diffs *.js (typeof describe === 'function') && describe("XYZ", function() { var XYZ = require("./XYZ"); var options = { verbose: true }; it("XYZ(1,2,3) should create an XYZ coordinate", function() { var xyz = new XYZ(1, 2, 3); xyz.should.instanceOf(XYZ); xyz.x.should.equal(1); xyz.y.should.equal(2); xyz.z.should.equal(3); }) it("XYZ({x:1,y:2,z:3) should create an XYZ coordinate", function() { var xyz = new XYZ(1, 2, 3); var xyz2 = new XYZ(xyz); xyz2.should.instanceOf(XYZ); xyz2.x.should.equal(1); xyz2.y.should.equal(2); xyz2.z.should.equal(3); var xyz3 = new XYZ({ x: 1, y: 2, z: 3 }); xyz2.should.instanceOf(XYZ); xyz2.x.should.equal(1); xyz2.y.should.equal(2); xyz2.z.should.equal(3); }) it("equal(value, tolerance) should return true if coordinates are same within tolerance", function() { var xyz = new XYZ(1, 2, 3); var xyz2 = new XYZ(xyz); xyz.equal(xyz2).should.True; xyz2.x = xyz.x - 0.00001; xyz.equal(xyz2).should.False; xyz.equal(xyz2, 0.00001).should.True; xyz.equal(xyz2, 0.000001).should.False; xyz2.x = xyz.x + 0.00001; xyz.equal(xyz2).should.False; xyz.equal(xyz2, 0.00001).should.True; xyz.equal(xyz2, 0.000001).should.False; }) it("norm() should return true the vector length", function() { var e = 0.000001; new XYZ(1, 2, 3).norm().should.within(3.741657 - e, 3.741657 + e); new XYZ(-1, 2, 3).norm().should.within(3.741657 - e, 3.741657 + e); new XYZ(1, -2, 3).norm().should.within(3.741657 - e, 3.741657 + e); new XYZ(1, -2, -3).norm().should.within(3.741657 - e, 3.741657 + e); new XYZ(1, 0, 1).norm().should.within(1.414213 - e, 1.414213 + e); new XYZ(0, 1, 1).norm().should.within(1.414213 - e, 1.414213 + e); new XYZ(1, 1, 0).norm().should.within(1.414213 - e, 1.414213 + e); }) it("normSquared() should return norm squared", function() { var xyz = new XYZ(1, 2, 3); xyz.norm().should.equal(Math.sqrt(xyz.normSquared())); }) it("minus(value) should return vector difference", function() { var xyz1 = new XYZ(1, 2, 3); var xyz2 = new XYZ(10, 20, 30); var xyz3 = xyz1.minus(xyz2); xyz3.equal({ x: -9, y: -18, z: -27 }).should.True; }) it("plus(value) should return vector sum", function() { var xyz1 = new XYZ(1, 2, 3); var xyz2 = new XYZ(10, 20, 30); var xyz3 = xyz1.plus(xyz2); xyz3.equal({ x: 11, y: 22, z: 33 }).should.True; }) it("interpolate(xyz,p) should interpolate to given point for p[0,1]", function() { var pt1 = new XYZ(1, 1, 1, { verbose: true }); var pt2 = new XYZ(10, 20, 30, { verbose: true }); pt1.interpolate(pt2, 0).equal(pt1).should.True; pt1.interpolate(pt2, 1).equal(pt2).should.True; pt1.interpolate(pt2, 0.1).equal({ x: 1.9, y: 2.9, z: 3.9 }).should.True; }); it("XYZ.of(pt) should return an XYZ object for given point", function() { var xyz = XYZ.of({ x: 1, y: 2, z: 3 }); xyz.should.instanceOf.XYZ; var xyz2 = XYZ.of(xyz); xyz2.should.equal(xyz); }); it("cross(xyz) returns cross product with xyz", function() { var v1 = new XYZ(1, 2, 3, options); var v2 = new XYZ(4, 5, 6, options); var cross = v1.cross(v2); var e = 0; cross.equal({ x: -3, y: 6, z: -3, e }).should.True; }); it("teString() returns concise string representation", function() { new XYZ(1, 2, 3).toString().should.equal("[1,2,3]"); new XYZ(1.001, 2.0001, -3.001).toString().should.equal("[1.001,2,-3.001]"); new XYZ(1.001, 2.0001, -3.001).toString().should.equal("[1.001,2,-3.001]"); }) it("dot(xyz) returns dot product with xyz", function() { var v1 = new XYZ(1, 2, 3, options); var v2 = new XYZ(4, 5, 6, options); var dot = v1.dot(v2); dot.should.equal(32); }); it("nearest(a,b) returns nearest point", function() { var vx = new XYZ(1, 0, 0); var vy = new XYZ(0, 1, 0); var vz = new XYZ(0, 0, 1); new XYZ(2, 0, 0).nearest(vx, vy).should.equal(vx); new XYZ(0, 0, 2).nearest(vx, vy).should.equal(vx); new XYZ(0, 2, 0).nearest(vx, vy).should.equal(vy); new XYZ(0, 2, 0).nearest(vz, vy).should.equal(vy); new XYZ(0, 0, 2).nearest(vy, vz).should.equal(vz); new XYZ(0, 0, 2).nearest(vx, vz).should.equal(vz); }); it("precisionDriftComparator(v1,v2) sorts scanned vertices to reveal long-term precision drift", function() { XYZ.precisionDriftComparator(new XYZ(1, 2, 3), new XYZ(1, 2, 3)).should.equal(0); XYZ.precisionDriftComparator(new XYZ(1, -2, 3), new XYZ(1, -2, 3)).should.equal(0); XYZ.precisionDriftComparator(new XYZ(1, -2, 3), new XYZ(1, 2, 3)).should.below(0); XYZ.precisionDriftComparator(new XYZ(1, 2, 3), new XYZ(1, -2, 3)).should.above(0); XYZ.precisionDriftComparator(new XYZ(1, -2, 3), new XYZ(1, -3, 3)).should.below(0); XYZ.precisionDriftComparator(new XYZ(1, -2, 3), new XYZ(2, -2, 3)).should.below(0); XYZ.precisionDriftComparator(new XYZ(1, 2, 3), new XYZ(2, 2, 3)).should.above(0); XYZ.precisionDriftComparator(new XYZ(1, 2, 3), new XYZ(1, 3, 3)).should.above(0); }); })
/** * This file is part of the Unit.js testing framework. * * (c) Nicolas Tallefourtane <[email protected]> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code * or visit {@link http://unitjs.com|Unit.js}. * * @author Nicolas Tallefourtane <[email protected]> */ 'use strict'; var test = require('../../../'); describe('Asserter object()', function(){ describe('object() behavior', function(){ it('Does not contains assertions from the assertions containers', function(){ test .value(test.object({}).hasHeader) .isUndefined() .value(test.object({}).isError) .isUndefined() .value(test.object({}).hasMessage) .isUndefined() .value(test.object({}).isInfinite) .isUndefined() ; }); it('Assert that the tested value is an `object`', function(){ var Foo = function Foo(){}; test .object({}) .object([]) .object(new Date()) .object(new RegExp()) .object(new Foo()) .case('Test failure', function(){ test .exception(function(){ test.object('Foo'); }) .exception(function(){ test.object(Foo); }) .exception(function(){ test.object(1); }) .exception(function(){ test.object(undefined); }) .exception(function(){ test.object(true); }) .exception(function(){ test.object(false); }) .exception(function(){ test.object(null); }) .exception(function(){ test.object(function(){}); }) ; }) ; }); }); describe('Assertions of object()', function(){ it('is(expected)', function(){ test .object({fluent: 'is awesome', deep: [0, 1]}) .is({fluent: 'is awesome', deep: [0, 1]}) .exception(function(){ test.object({fluent: 'is awesome', deep: [0, 1]}) .is({fluent: 'is awesome', deep: [0, 2]}); }) ; }); it('isNot(expected)', function(){ test .object({fluent: 'is awesome', deep: [0, 1]}) .isNot({fluent: 'is awesome', deep: [0, '1']}) .exception(function(){ test.object({fluent: 'is awesome', deep: [0, 1]}) .isNot({fluent: 'is awesome', deep: [0, 1]}); }) ; }); it('isIdenticalTo(expected)', function(){ var obj = {}, obj2 = obj ; test .object(obj) .isIdenticalTo(obj2) .exception(function(){ test.object(obj).isIdenticalTo({}); }) ; }); it('isNotIdenticalTo(expected)', function(){ var obj = {}, obj2 = obj ; test .object(obj) .isNotIdenticalTo({}) .exception(function(){ test.object(obj).isNotIdenticalTo(obj2); }) ; }); it('isEqualTo(expected)', function(){ var obj = {}, obj2 = obj ; test .object(obj) .isEqualTo(obj2) .exception(function(){ test.object(obj).isEqualTo({}); }) ; }); it('isNotEqualTo(expected)', function(){ var obj = {foo: 'bar'}, obj2 = obj ; test .object(obj) .isNotEqualTo({foo: 'bar', baz: 'bar'}) .exception(function(){ test.object(obj).isNotEqualTo(obj2); }) ; }); it('match(expected)', function(){ test .object({hello: 'world'}) .match(function(obj){ return obj.hello == 'world'; }) .exception(function(){ test.object({hello: 'world'}) .match(function(obj){ return obj.hello == 'foo'; }); }) ; }); it('notMatch(expected)', function(){ test .object({hello: 'world'}) .notMatch(function(obj){ return obj.hello == 'E.T'; }) .exception(function(){ test.object({hello: 'world'}) .notMatch(function(obj){ return obj.hello == 'world'; }) }) ; }); it('isValid(expected)', function(){ test .object({hello: 'world'}) .isValid(function(obj){ return obj.hello == 'world'; }) .exception(function(){ test.object({hello: 'world'}) .isValid(function(obj){ return obj.hello == 'foo'; }); }) ; }); it('isNotValid(expected)', function(){ test .object({hello: 'world'}) .isNotValid(function(obj){ return obj.hello == 'E.T'; }) .exception(function(){ test.object({hello: 'world'}) .isNotValid(function(obj){ return obj.hello == 'world'; }) }) ; }); it('matchEach(expected)', function(){ test .object({foo: 'bar', hey: 'you', joker:1}) .matchEach(function(it, key) { if(key == 'joker'){ return (typeof it == 'number'); } return (typeof it == 'string'); }) .exception(function(){ // error if one or several does not match test.object({foo: 'bar', hey: 'you', joker:1}) .matchEach(function(it, key) { return (typeof it == 'string'); }) }) ; }); it('notMatchEach(expected)', function(){ test .object({foo: 'bar', hey: 'you', joker:1}) .notMatchEach(function(it, key) { if(key == 'other'){ return true; } }) .exception(function(){ // error if one or several does not match test.object({foo: 'bar', hey: 'you', joker:1}) .notMatchEach(function(it, key) { if(key == 'foo'){ return true; } }) }) .exception(function(){ // error if one or several does not match test.object({foo: 'bar', hey: 'you', joker:1}) .notMatchEach(function(it, key) { return (typeof it == 'string'); }) }) ; }); it('isArray()', function(){ test .object([]) .isArray() .exception(function(){ test.object({}).isArray(); }) .exception(function(){ test.object(new Date()).isArray(); }) ; }); it('isRegExp()', function(){ test .object(/[0-9]+/) .isRegExp() .exception(function(){ test.object({}).isRegExp(); }) .exception(function(){ test.object(new Date()).isRegExp(); }) ; }); it('isNotRegExp()', function(){ test .object(new Date()) .isNotRegExp() .exception(function(){ test.object(/[0-9]+/).isNotRegExp(); }) ; }); it('isDate()', function(){ test .object(new Date()) .isDate() .exception(function(){ test.object({}).isDate(); }) .exception(function(){ test.object(/[0-9]+/).isDate(); }) ; }); it('isNotDate()', function(){ test .object(/[0-9]+/) .isNotDate() .exception(function(){ test.object(new Date()).isNotDate(); }) ; }); it('isArguments()', function(){ var fn = function(){ var args = arguments; test.object(arguments).isArguments(); test.object(args).isArguments(); }; fn(1, 2, 3); test.exception(function(){ test.object({0: 'a'}).isArguments(); }); }); it('isNotArguments()', function(){ var fn = function(){ test .object(arguments) .isArguments() .object([1, 2, 3]) .isNotArguments() .object({0:1, 1:2, 2:3}) .isNotArguments() ; }; fn(1, 2, 3); test.exception(function(){ test.object(arguments).isNotArguments(); }); }); it('isEmpty()', function(){ test .object({}) .isEmpty() .exception(function(){ test.object({0: 'a'}).isEmpty(); }) ; }); it('isNotEmpty()', function(){ test .object({hello: 'Nico'}) .isNotEmpty() .exception(function(){ test.object({}).isNotEmpty(); }) ; }); it('hasLength(expected)', function(){ test .object({foo: 'bar', other: 'baz'}) .hasLength(2) .exception(function(){ test.object({foo: 'bar', other: 'baz'}) .hasLength(3); }) ; }); it('hasNotLength(expected)', function(){ test .object({foo: 'bar', other: 'baz'}) .hasNotLength(4) .exception(function(){ test.object({foo: 'bar', other: 'baz'}) .hasNotLength(2); }) ; }); it('isEnumerable(property)', function(){ test .object({prop: 'foobar'}) .isEnumerable('prop') .exception(function(){ test.object({prop: 'foobar'}) .isEnumerable('length'); }) ; }); it('isNotEnumerable(property)', function(){ test .object(Object.create({}, {prop: {enumerable: 0}})) .isNotEnumerable('prop') .exception(function(){ test.object({prop: 'foobar'}) .isNotEnumerable('prop'); }) ; }); it('isFrozen()', function(){ test .object(Object.freeze({})) .isFrozen() .exception(function(){ test.object({}) .isFrozen(); }) ; }); it('isNotFrozen()', function(){ test .object({}) .isNotFrozen() .exception(function(){ test.object(Object.freeze({})) .isNotFrozen(); }) ; }); it('isInstanceOf(expected)', function(){ test .object(new Date()) .isInstanceOf(Date) .exception(function(){ test.object(new Date()) .isInstanceOf(Error); }) ; }); it('isNotInstanceOf(expected)', function(){ test .object(new Date()) .isNotInstanceOf(RegExp) .exception(function(){ test.object(new Date()) .isNotInstanceOf(Object); }) .exception(function(){ test.object(new Date()) .isNotInstanceOf(Date); }) ; }); it('hasProperty(property [, value])', function(){ test .object({foo: 'bar'}) .hasProperty('foo') .object({foo: 'bar'}) .hasProperty('foo', 'bar') .exception(function(){ test.object({foo: 'bar'}) .hasProperty('bar'); }) .exception(function(){ test.object({foo: 'bar'}) .hasProperty('foo', 'ba'); }) ; }); it('hasNotProperty(property [, value])', function(){ test .object({foo: 'bar'}) .hasNotProperty('bar') .object({foo: 'bar'}) .hasNotProperty('foo', 'baz') .exception(function(){ test.object({foo: 'bar'}) .hasNotProperty('foo'); }) .exception(function(){ test.object({foo: 'bar'}) .hasNotProperty('foo', 'bar'); }) ; }); it('hasOwnProperty(property [, value])', function(){ test .object({foo: 'bar'}) .hasOwnProperty('foo') .object({foo: 'bar'}) .hasOwnProperty('foo', 'bar') .exception(function(){ test.object({foo: 'bar'}) .hasOwnProperty('bar'); }) .exception(function(){ test.object({foo: 'bar'}) .hasOwnProperty('foo', 'ba'); }) ; }); it('hasNotOwnProperty(property [, value])', function(){ test .object({foo: 'bar'}) .hasNotOwnProperty('bar') .object({foo: 'bar'}) .hasNotOwnProperty('foo', 'baz') .exception(function(){ test.object({foo: 'bar'}) .hasNotOwnProperty('foo'); }) .exception(function(){ test.object({foo: 'bar'}) .hasNotOwnProperty('foo', 'bar'); }) ; }); it('hasProperties(properties)', function(){ test .object({foo: 'bar', bar: 'huhu', other: 'vroom'}) .hasProperties(['other', 'bar', 'foo']) .exception(function(){ test.object({foo: 'bar', bar: 'huhu', other: 'vroom'}) .hasProperties(['other', 'bar']); }) ; }); it('hasNotProperties(properties)', function(){ test .object({foo: 'bar', bar: 'huhu', other: 'vroom'}) .hasNotProperties(['other', 'foo']) .exception(function(){ test.object({foo: 'bar', bar: 'huhu', other: 'vroom'}) .hasNotProperties(['bar', 'other', 'foo']); }) ; }); it('hasOwnProperties(properties)', function(){ test .object({foo: 'bar', bar: 'huhu', other: 'vroom'}) .hasOwnProperties(['other', 'bar', 'foo']) .exception(function(){ test.object({foo: 'bar', bar: 'huhu', other: 'vroom'}) .hasOwnProperties(['other', 'bar']); }) ; }); it('hasKey(key [, value])', function(){ test .object({foo: 'bar'}) .hasKey('foo') .object({foo: 'bar'}) .hasKey('foo', 'bar') .exception(function(){ test.object({foo: 'bar'}) .hasKey('bar'); }) .exception(function(){ test.object({foo: 'bar'}) .hasKey('foo', 'ba'); }) ; }); it('notHasKey(key [, value])', function(){ test .object({foo: 'bar'}) .notHasKey('bar') .object({foo: 'bar'}) .notHasKey('foo', 'baz') .exception(function(){ test.object({foo: 'bar'}) .notHasKey('foo'); }) .exception(function(){ test.object({foo: 'bar'}) .notHasKey('foo', 'bar'); }) ; }); it('hasKeys(keys)', function(){ test .object({foo: 'bar', bar: 'huhu', other: 'vroom'}) .hasKeys(['other', 'bar', 'foo']) .exception(function(){ test.object({foo: 'bar', bar: 'huhu', other: 'vroom'}) .hasKeys(['other', 'bar']); }) ; }); it('notHasKeys(keys)', function(){ test .object({foo: 'bar', bar: 'huhu', other: 'vroom'}) .notHasKeys(['other', 'foo']) .exception(function(){ test.object({foo: 'bar', bar: 'huhu', other: 'vroom'}) .notHasKeys(['bar', 'other', 'foo']); }) ; }); it('hasValue(expected)', function(){ test .object({life: 42, love: 69}) .hasValue(42) .exception(function(){ test.object({life: 42, love: 69}) .hasValue('42'); }) ; }); it('notHasValue(expected)', function(){ test .object({life: 42, love: 69}) .notHasValue(4) .exception(function(){ test.object({life: 42, love: 69}) .notHasValue(42); }) ; }); it('hasValues(expected)', function(){ test .object({life: 42, love: 69}) .hasValues([42, 69]) .exception(function(){ test.object([1, 42, 3]) .hasValues([42, 3.01]); }) ; }); it('notHasValues(expected)', function(){ test .object({life: 42, love: 69}) .notHasValues([43, 68]) .exception(function(){ test.object([1, 42, 3]) .notHasValues([1, 42, 3]); }) ; }); it('contains(expected [, ...])', function(){ test .object({ a: { b: 10 }, b: { c: 10, d: 11, a: { b: 10, c: 11} }}) .contains({ a: { b: 10 }, b: { c: 10, a: { c: 11 }}}) .object({a: 'a', b: {c: 'c'}}) .contains({b: {c: 'c'}}) .contains({b: {c: 'c'}}, {a: 'a'}) .exception(function(){ test.object({foo: {a: 'a'}, bar: {b: 'b', c: 'c'}}) .contains({foo: {a: 'a'}}, {bar: {b: 'c'}}); }) ; }); it('notContains(expected [, ...])', function(){ test .object({a: 'a'}, {b: 'b', c: 'c'}) .notContains({c: 'b'}) .exception(function(){ test.object({foo: {a: 'a'}, bar: {b: 'b', c: 'c'}}) .notContains({foo: {a: 'a'}, bar: {c: 'c'}}); }) ; }); it('hasName(expected)', function(){ test .object(new Date(2010, 5, 28)) .hasName('Date') .exception(function(){ test.object(new Date(2010, 5, 28)) .hasName('date'); }) ; }); }); });
var mongoose = require('mongoose'); var Shape = require('./Shape'); var User = require('./User'); // Create a session model, _id will be assigned by Mongoose var CanvasSessionSchema = new mongoose.Schema( { _id: String, users: [User], dateCreated: Date, dateUpdated: Date, // canDraw: Boolean, // canChat: Boolean, // maxUsers: Number, sessionProperties: { canDraw: Boolean, canChat: Boolean, maxUsers: Number }, //canvasModel: { type: Object }, canvasShapes: { type: Array, unique: true, index: true }, messages: Array }, { autoIndex: false } ); // Make Session available to rest of the application module.exports = mongoose.model('Session', CanvasSessionSchema);
import config from '../components/configLoader'; import { addToDefaultPluginDOM } from '../components/helpers'; const pluginConfig = config.plugins.find(obj => obj.name === 'age'); // DOM setup const pluginId = 'js-plugin-age'; addToDefaultPluginDOM(pluginId); const ageDOM = document.getElementById(pluginId); const renderAge = () => { const { birthday, goal } = pluginConfig; // Inspired by: // Alex MacCaw https://github.com/maccman/motivation const now = new Date(); const age = (now - new Date(birthday)) / 3.1556952e+10; // divided by 1 year in ms let remainder = 100 - (age / goal * 100); let goalPrefix = 'left until'; if (remainder < 0) { goalPrefix = 'over goal of'; remainder = -remainder; } ageDOM.innerHTML = `Age: ${age.toFixed(5)}, ${remainder.toFixed(2)}% ${goalPrefix} ${goal}`; }; // Initialize plugin export const init = () => renderAge(); // eslint-disable-line import/prefer-default-export
Meteor.startup(function () { }); Deps.autorun(function(){ Meteor.subscribe('userData'); });
// will this be needed? var getMotionEventName = function(type) { var t; var el = document.createElement('fakeelement'); var map = {}; if (type == 'transition') { map = { 'transition': 'transitionend', 'OTransition': 'oTransitionEnd', 'MozTransition': 'transitionend', 'WebkitTransition': 'webkitTransitionEnd' }; } else if (type == 'animation') { map = { 'animation': 'animationend', 'OAnimation': 'oAnimationEnd', 'MozAnimation': 'animationend', 'WebkitAnimation': 'webkitAnimationEnd' }; }; for (t in map) { if (el.style[t] !== undefined) { return map[t]; } } };
// Include gulp import gulp from 'gulp'; import fs from 'fs'; // Include Our Plugins import eslint from 'gulp-eslint'; import mocha from 'gulp-mocha'; import browserSyncJs from 'browser-sync'; import sassJs from 'gulp-sass'; import sassCompiler from 'sass'; import rename from "gulp-rename"; import uglify from 'gulp-uglify'; import postcss from 'gulp-postcss'; import replace from 'gulp-replace'; import autoprefixer from 'autoprefixer'; import gulpStylelint from '@ronilaukkarinen/gulp-stylelint'; const browserSync = browserSyncJs.create(); const pkg = JSON.parse(fs.readFileSync('./package.json')); const sass = sassJs(sassCompiler); const doEslint = function() { return gulp.src( [ '*.js', pkg.directories.bin + '/**/*', pkg.directories.lib + '/**/*.js', pkg.directories.test + '/**/*.js' ]) .pipe(eslint()) .pipe(eslint.format()) // .pipe(eslint.failAfterError()) ; }; const doMocha = function() { return gulp.src(pkg.directories.test + '/**/*.js', {read: false}) .pipe(mocha({ reporter: 'dot' })) ; }; const buildJs = function() { return gulp.src(pkg.directories.theme + '/**/js-src/*.js') .pipe(eslint()) .pipe(eslint.format()) //.pipe(eslint.failAfterError()) .pipe(rename(function(path){ path.dirname = path.dirname.replace(/js-src/, 'js'); })) .pipe(uglify({output: { max_line_len: 9000 }})) .pipe(gulp.dest(pkg.directories.theme)) ; }; const buildCss = function() { return gulp.src(pkg.directories.theme + '/**/*.scss') .pipe(gulpStylelint({ reporters: [ {formatter: 'string', console: true} ] })) .pipe(sass().on('error', sass.logError)) .pipe(postcss([ autoprefixer() ])) .pipe(rename(function(path){ path.dirname = path.dirname.replace(/sass/, 'css'); })) .pipe(replace(/(\n)\s*\n/g, '$1')) .pipe(gulp.dest(pkg.directories.theme)) ; }; const serve = function() { browserSync.init({ server: pkg.directories.htdocs, port: 8080 }); gulp.watch(pkg.directories.htdocs + '/**/*').on('change', browserSync.reload); }; // Watch Files For Changes const watch = function() { gulp.watch(['gulpfile.js', 'package.json'], process.exit); gulp.watch( [ '*.js', pkg.directories.bin + '/**/*', pkg.directories.lib + '/**/*.js', pkg.directories.test + '/**/*.js' ], test ); gulp.watch(pkg.directories.theme + '/**/*.js', buildJs); gulp.watch(pkg.directories.theme + '/**/*.scss', buildCss); }; // Bundle tasks const test = gulp.parallel(doEslint, doMocha); const build = gulp.parallel(buildJs, buildCss); const defaultTask = gulp.parallel(serve, watch); // Expose tasks export {doEslint, doMocha, buildJs, buildCss, serve, watch, test, build}; export default defaultTask;
// // Jala Project [http://opensvn.csie.org/traccgi/jala] // // Copyright 2004 ORF Online und Teletext GmbH // // 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. // // $Revision: 213 $ // $LastChangedBy: tobi $ // $LastChangedDate: 2007-05-08 16:12:32 +0200 (Die, 08 Mai 2007) $ // $HeadURL: http://dev.orf.at/source/jala/trunk/code/AsyncRequest.js $ // /** * @fileoverview Fields and methods of the jala.AsyncRequest class. */ // Define the global namespace for Jala modules if (!global.jala) { global.jala = {}; } /** * Creates a new AsyncRequest instance. * @class This class is used to create requests of type "INTERNAL" * (like cron-jobs) that are processed in a separate thread and * therefor asynchronous. * @param {Object} obj Object in whose context the method should be called * @param {String} funcName Name of the function to call * @param {Array} args Array containing the arguments that should be passed * to the function (optional). This option is <em>deprecated</em>, instead * pass the arguments directly to the {@link #run} method. * @constructor * @returns A new instance of AsyncRequest * @type AsyncRequest * @deprecated Use the {@link http://helma.zumbrunn.net/reference/core/app.html#invokeAsync * app.invokeAsync} method instead (built-in into Helma as * of version 1.6) */ jala.AsyncRequest = function(obj, funcName, args) { app.logger.warn("Use of jala.AsyncRequest is deprecated in this version."); app.logger.warn("This module will probably be removed in a " + "future version of Jala."); /** * Contains a reference to the thread started by this AsyncRequest * @type java.lang.Thread * @private */ var thread; /** * Contains the timeout defined for this AsyncRequest (in milliseconds) * @type Number * @private */ var timeout; /** * Contains the number of milliseconds to wait before starting * the asynchronous request. * @type Number * @private */ var delay; /** * Run method necessary to implement java.lang.Runnable. * @private */ var runner = function() { // evaluator that will handle the request var ev = app.__app__.getEvaluator(); if (delay != null) { java.lang.Thread.sleep(delay); } try { if (args === undefined || args === null || args.constructor != Array) { args = []; } if (timeout != null) { ev.invokeInternal(obj, funcName, args, timeout); } else { ev.invokeInternal(obj, funcName, args); } } catch (e) { // ignore it, but log it app.log("[Runner] Caught Exception: " + e); } finally { // release the ev in any case app.__app__.releaseEvaluator(ev); // remove reference to underlying thread thread = null; } return; }; /** * Sets the timeout of this asynchronous request. * @param {Number} seconds Thread-timeout. */ this.setTimeout = function(seconds) { timeout = seconds * 1000; return; }; /** * Defines the delay to wait before evaluating this asynchronous request. * @param {Number} millis Milliseconds to wait */ this.setDelay = function(millis) { delay = millis; return; }; /** * Starts this asynchronous request. Any arguments passed to * this method will be passed to the method executed by * this AsyncRequest instance. */ this.run = function() { if (arguments.length > 0) { // convert arguments object into array args = Array.prototype.slice.call(arguments, 0, arguments.length); } thread = (new java.lang.Thread(new java.lang.Runnable({"run": runner}))); thread.start(); return; }; /** * Starts this asynchronous request. * @deprecated Use {@link #run} instead */ this.evaluate = function() { this.run.apply(this, arguments); return; }; /** * Returns true if the underlying thread is alive * @returns True if the underlying thread is alive, * false otherwise. * @type Boolean */ this.isAlive = function() { return thread != null && thread.isAlive(); } /** @ignore */ this.toString = function() { return "[jala.AsyncRequest]"; }; /** * Main constructor body */ if (!obj || !funcName) throw "jala.AsyncRequest: insufficient arguments."; return this; }
const OFF = 0; const WARN = 1; const ERROR = 2; module.exports = { extends: "../.eslintrc.js", rules: { "max-len": [ ERROR, 100 ], }, env: { "es6": true, "node": true, "mocha": true, }, };
const webdriver = require('selenium-webdriver'); const setupDriver = (browser) => { const driver = new webdriver .Builder() .usingServer('http://localhost:9515/') .withCapabilities({ browserName: browser, }) .build(); return driver; }; module.exports = { setupDriver };
'use strict'; module.exports = function(grunt) { // Please see the Grunt documentation for more information regarding task // creation: http://gruntjs.com/creating-tasks function random(min, max) { min = min || 0; max = max || 1; var result; if(min === 0 && max === 1) { result = Math.random(); } else { result = Math.floor((Math.random() * max) + min); } return result; } grunt.registerMultiTask('random', 'Your task description goes here.', function() { // Merge task-specific and/or target-specific options with these defaults. var options = this.options({min:0,max:1}); grunt.log.writeln('Random: ' + random(options.min, options.max)); }); };
'use strict'; angular .module('facebookMe', [ ]) ;